diff --git a/wpilibc/wpilibC++/include/Base.h b/wpilibc/wpilibC++/include/Base.h index 2aaa4ee223..168d140953 100644 --- a/wpilibc/wpilibC++/include/Base.h +++ b/wpilibc/wpilibC++/include/Base.h @@ -16,4 +16,3 @@ #define DISALLOW_COPY_AND_ASSIGN(TypeName) \ TypeName(const TypeName&); \ void operator=(const TypeName&) - diff --git a/wpilibc/wpilibC++/include/Buttons/Button.h b/wpilibc/wpilibC++/include/Buttons/Button.h index c4911118ab..8897569b11 100644 --- a/wpilibc/wpilibC++/include/Buttons/Button.h +++ b/wpilibc/wpilibC++/include/Buttons/Button.h @@ -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 diff --git a/wpilibc/wpilibC++/include/Buttons/ButtonScheduler.h b/wpilibc/wpilibC++/include/Buttons/ButtonScheduler.h index 96d0a0ee11..7accbc9e36 100644 --- a/wpilibc/wpilibC++/include/Buttons/ButtonScheduler.h +++ b/wpilibc/wpilibC++/include/Buttons/ButtonScheduler.h @@ -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 diff --git a/wpilibc/wpilibC++/include/Buttons/CancelButtonScheduler.h b/wpilibc/wpilibC++/include/Buttons/CancelButtonScheduler.h index 0491213164..ea5f8ff2d0 100644 --- a/wpilibc/wpilibC++/include/Buttons/CancelButtonScheduler.h +++ b/wpilibc/wpilibC++/include/Buttons/CancelButtonScheduler.h @@ -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 diff --git a/wpilibc/wpilibC++/include/Buttons/HeldButtonScheduler.h b/wpilibc/wpilibC++/include/Buttons/HeldButtonScheduler.h index 3bca0d5417..f68bcd70e7 100644 --- a/wpilibc/wpilibC++/include/Buttons/HeldButtonScheduler.h +++ b/wpilibc/wpilibC++/include/Buttons/HeldButtonScheduler.h @@ -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 diff --git a/wpilibc/wpilibC++/include/Buttons/InternalButton.h b/wpilibc/wpilibC++/include/Buttons/InternalButton.h index e61cf0a636..5f54d34818 100644 --- a/wpilibc/wpilibC++/include/Buttons/InternalButton.h +++ b/wpilibc/wpilibC++/include/Buttons/InternalButton.h @@ -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 diff --git a/wpilibc/wpilibC++/include/Buttons/JoystickButton.h b/wpilibc/wpilibC++/include/Buttons/JoystickButton.h index cb5f0c482c..f34f36561a 100644 --- a/wpilibc/wpilibC++/include/Buttons/JoystickButton.h +++ b/wpilibc/wpilibC++/include/Buttons/JoystickButton.h @@ -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 diff --git a/wpilibc/wpilibC++/include/Buttons/NetworkButton.h b/wpilibc/wpilibC++/include/Buttons/NetworkButton.h index 874a768a48..6ec0c1ea79 100644 --- a/wpilibc/wpilibC++/include/Buttons/NetworkButton.h +++ b/wpilibc/wpilibC++/include/Buttons/NetworkButton.h @@ -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 -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 diff --git a/wpilibc/wpilibC++/include/Buttons/PressedButtonScheduler.h b/wpilibc/wpilibC++/include/Buttons/PressedButtonScheduler.h index a69320bdc7..4acb1a1498 100644 --- a/wpilibc/wpilibC++/include/Buttons/PressedButtonScheduler.h +++ b/wpilibc/wpilibC++/include/Buttons/PressedButtonScheduler.h @@ -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 diff --git a/wpilibc/wpilibC++/include/Buttons/ReleasedButtonScheduler.h b/wpilibc/wpilibC++/include/Buttons/ReleasedButtonScheduler.h index 198a1d3eb7..e0fceeaf6c 100644 --- a/wpilibc/wpilibC++/include/Buttons/ReleasedButtonScheduler.h +++ b/wpilibc/wpilibC++/include/Buttons/ReleasedButtonScheduler.h @@ -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 diff --git a/wpilibc/wpilibC++/include/Buttons/ToggleButtonScheduler.h b/wpilibc/wpilibC++/include/Buttons/ToggleButtonScheduler.h index e0987e5a7d..42d52bd15a 100644 --- a/wpilibc/wpilibC++/include/Buttons/ToggleButtonScheduler.h +++ b/wpilibc/wpilibC++/include/Buttons/ToggleButtonScheduler.h @@ -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 diff --git a/wpilibc/wpilibC++/include/Buttons/Trigger.h b/wpilibc/wpilibC++/include/Buttons/Trigger.h index d6ca1707a9..056042f16d 100644 --- a/wpilibc/wpilibC++/include/Buttons/Trigger.h +++ b/wpilibc/wpilibC++/include/Buttons/Trigger.h @@ -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 diff --git a/wpilibc/wpilibC++/include/Commands/Command.h b/wpilibc/wpilibC++/include/Commands/Command.h index 42edef7e1e..0eccd3c40d 100644 --- a/wpilibc/wpilibC++/include/Commands/Command.h +++ b/wpilibc/wpilibC++/include/Commands/Command.h @@ -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. * - *

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.

+ *

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.

* - *

If a command uses a {@link Subsystem}, then it should specify that it does so by + *

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.

* - *

If a command is running and a new command with shared requirements is started, + *

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.

+ * other one will not even be started, and the active one will continue + * functioning.

* * @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 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 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. - * - *

It may be useful for a team to reference the {@link Command#isTimedOut() isTimedOut()} method - * for time-sensitive commands.

- * @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. - * - *

This is where you may want - * to wrap up loose ends, like shutting off a motor that was being used - * in the command.

- * - *

Generally, it is useful to simply call the {@link Command#end() end()} method - * within this method

- */ - 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. + * + *

It may be useful for a team to reference the {@link Command#isTimedOut() + * isTimedOut()} method + * for time-sensitive commands.

+ * @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. + * + *

This is where you may want + * to wrap up loose ends, like shutting off a motor that was being used + * in the command.

+ * + *

Generally, it is useful to simply call the {@link Command#end() end()} + * method + * within this method

+ */ + 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 diff --git a/wpilibc/wpilibC++/include/Commands/CommandGroup.h b/wpilibc/wpilibC++/include/Commands/CommandGroup.h index 9a7005bd62..302d9c6c1a 100644 --- a/wpilibc/wpilibC++/include/Commands/CommandGroup.h +++ b/wpilibc/wpilibC++/include/Commands/CommandGroup.h @@ -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. * - *

Commands in a {@link CommandGroup} are added using the {@link CommandGroup#AddSequential(Command) AddSequential(...)} method + *

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}.

* - *

{@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(...)} + *

{@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.

* *

CommandGroups can also execute commands in parallel, simply by adding them * using {@link CommandGroup#AddParallel(Command) AddParallel(...)}.

- * + * * @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 CommandVector; - /** The commands in this group (stored in entries) */ - CommandVector m_commands; - typedef std::list 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 CommandVector; + /** The commands in this group (stored in entries) */ + CommandVector m_commands; + typedef std::list 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 diff --git a/wpilibc/wpilibC++/include/Commands/CommandGroupEntry.h b/wpilibc/wpilibC++/include/Commands/CommandGroupEntry.h index 1b652b857d..4a0d96058c 100644 --- a/wpilibc/wpilibC++/include/Commands/CommandGroupEntry.h +++ b/wpilibc/wpilibC++/include/Commands/CommandGroupEntry.h @@ -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 diff --git a/wpilibc/wpilibC++/include/Commands/PIDCommand.h b/wpilibc/wpilibC++/include/Commands/PIDCommand.h index 6430eaf0df..0e09c7b7b1 100644 --- a/wpilibc/wpilibC++/include/Commands/PIDCommand.h +++ b/wpilibc/wpilibC++/include/Commands/PIDCommand.h @@ -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 - diff --git a/wpilibc/wpilibC++/include/Commands/PIDSubsystem.h b/wpilibc/wpilibC++/include/Commands/PIDSubsystem.h index e2ea9d6778..63a771c861 100644 --- a/wpilibc/wpilibC++/include/Commands/PIDSubsystem.h +++ b/wpilibc/wpilibC++/include/Commands/PIDSubsystem.h @@ -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). * - *

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 + *

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.

* */ -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 diff --git a/wpilibc/wpilibC++/include/Commands/PrintCommand.h b/wpilibc/wpilibC++/include/Commands/PrintCommand.h index b6342f5014..f36d16d942 100644 --- a/wpilibc/wpilibC++/include/Commands/PrintCommand.h +++ b/wpilibc/wpilibC++/include/Commands/PrintCommand.h @@ -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 -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 diff --git a/wpilibc/wpilibC++/include/Commands/Scheduler.h b/wpilibc/wpilibC++/include/Commands/Scheduler.h index 668a1c74a1..c9e81a4f1c 100644 --- a/wpilibc/wpilibC++/include/Commands/Scheduler.h +++ b/wpilibc/wpilibC++/include/Commands/Scheduler.h @@ -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 ButtonVector; - ButtonVector m_buttons; - typedef std::vector CommandVector; - MUTEX_ID m_additionsLock; - CommandVector m_additions; - typedef std::set 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 ButtonVector; + ButtonVector m_buttons; + typedef std::vector CommandVector; + MUTEX_ID m_additionsLock; + CommandVector m_additions; + typedef std::set CommandSet; + CommandSet m_commands; + bool m_adding; + bool m_enabled; + StringArray *commands; + NumberArray *ids; + NumberArray *toCancel; + ITable *m_table; + bool m_runningCommandsChanged; }; #endif - diff --git a/wpilibc/wpilibC++/include/Commands/StartCommand.h b/wpilibc/wpilibC++/include/Commands/StartCommand.h index 1ea6dcf429..3e612d2b21 100644 --- a/wpilibc/wpilibC++/include/Commands/StartCommand.h +++ b/wpilibc/wpilibC++/include/Commands/StartCommand.h @@ -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 diff --git a/wpilibc/wpilibC++/include/Commands/Subsystem.h b/wpilibc/wpilibC++/include/Commands/Subsystem.h index 30fccea83e..a6973d230c 100644 --- a/wpilibc/wpilibC++/include/Commands/Subsystem.h +++ b/wpilibc/wpilibC++/include/Commands/Subsystem.h @@ -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 - 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 diff --git a/wpilibc/wpilibC++/include/Commands/WaitCommand.h b/wpilibc/wpilibC++/include/Commands/WaitCommand.h index 036bae80b1..7a61968bd2 100644 --- a/wpilibc/wpilibC++/include/Commands/WaitCommand.h +++ b/wpilibc/wpilibC++/include/Commands/WaitCommand.h @@ -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 diff --git a/wpilibc/wpilibC++/include/Commands/WaitForChildren.h b/wpilibc/wpilibC++/include/Commands/WaitForChildren.h index 2f4e3eae9b..17435ce36c 100644 --- a/wpilibc/wpilibC++/include/Commands/WaitForChildren.h +++ b/wpilibc/wpilibC++/include/Commands/WaitForChildren.h @@ -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 diff --git a/wpilibc/wpilibC++/include/Commands/WaitUntilCommand.h b/wpilibc/wpilibC++/include/Commands/WaitUntilCommand.h index b816ccf73c..dbd08a0873 100644 --- a/wpilibc/wpilibC++/include/Commands/WaitUntilCommand.h +++ b/wpilibc/wpilibC++/include/Commands/WaitUntilCommand.h @@ -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 diff --git a/wpilibc/wpilibC++/include/Controller.h b/wpilibc/wpilibC++/include/Controller.h index 99eba88055..1b25c2516a 100644 --- a/wpilibc/wpilibC++/include/Controller.h +++ b/wpilibc/wpilibC++/include/Controller.h @@ -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; +}; diff --git a/wpilibc/wpilibC++/include/Error.h b/wpilibc/wpilibC++/include/Error.h index 4fbe0f016b..9fde78ec28 100644 --- a/wpilibc/wpilibC++/include/Error.h +++ b/wpilibc/wpilibC++/include/Error.h @@ -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); }; diff --git a/wpilibc/wpilibC++/include/ErrorBase.h b/wpilibc/wpilibC++/include/ErrorBase.h index c4e3cea924..5b0dbce081 100644 --- a/wpilibc/wpilibC++/include/ErrorBase.h +++ b/wpilibc/wpilibC++/include/ErrorBase.h @@ -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); }; diff --git a/wpilibc/wpilibC++/include/GenericHID.h b/wpilibc/wpilibC++/include/GenericHID.h index 88a6e78a1b..84f0f76f74 100644 --- a/wpilibc/wpilibC++/include/GenericHID.h +++ b/wpilibc/wpilibC++/include/GenericHID.h @@ -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; }; diff --git a/wpilibc/wpilibC++/include/HLUsageReporting.h b/wpilibc/wpilibC++/include/HLUsageReporting.h index 359b149e9a..991125b3a2 100644 --- a/wpilibc/wpilibC++/include/HLUsageReporting.h +++ b/wpilibc/wpilibC++/include/HLUsageReporting.h @@ -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(); }; diff --git a/wpilibc/wpilibC++/include/LiveWindow/LiveWindow.h b/wpilibc/wpilibC++/include/LiveWindow/LiveWindow.h index 3e9e26ebff..a50c9f99f3 100644 --- a/wpilibc/wpilibC++/include/LiveWindow/LiveWindow.h +++ b/wpilibc/wpilibC++/include/LiveWindow/LiveWindow.h @@ -7,60 +7,62 @@ #include #include -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 m_sensors; - std::map m_components; + std::vector m_sensors; + std::map 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 diff --git a/wpilibc/wpilibC++/include/LiveWindow/LiveWindowSendable.h b/wpilibc/wpilibC++/include/LiveWindow/LiveWindowSendable.h index abc4f7ed4c..4f2023a113 100644 --- a/wpilibc/wpilibC++/include/LiveWindow/LiveWindowSendable.h +++ b/wpilibc/wpilibC++/include/LiveWindow/LiveWindowSendable.h @@ -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_ */ diff --git a/wpilibc/wpilibC++/include/LiveWindow/LiveWindowStatusListener.h b/wpilibc/wpilibC++/include/LiveWindow/LiveWindowStatusListener.h index 7c701e3fce..22e4f9935b 100644 --- a/wpilibc/wpilibC++/include/LiveWindow/LiveWindowStatusListener.h +++ b/wpilibc/wpilibC++/include/LiveWindow/LiveWindowStatusListener.h @@ -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 diff --git a/wpilibc/wpilibC++/include/Notifier.h b/wpilibc/wpilibC++/include/Notifier.h index 3cb2fda1c5..06e3c87c97 100644 --- a/wpilibc/wpilibC++/include/Notifier.h +++ b/wpilibc/wpilibC++/include/Notifier.h @@ -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(); }; diff --git a/wpilibc/wpilibC++/include/PIDController.h b/wpilibc/wpilibC++/include/PIDController.h index a224632c95..19da382cbe 100644 --- a/wpilibc/wpilibC++/include/PIDController.h +++ b/wpilibc/wpilibC++/include/PIDController.h @@ -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); }; diff --git a/wpilibc/wpilibC++/include/PIDInterface.h b/wpilibc/wpilibC++/include/PIDInterface.h index 3bde03b590..049668f373 100644 --- a/wpilibc/wpilibC++/include/PIDInterface.h +++ b/wpilibc/wpilibC++/include/PIDInterface.h @@ -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; }; diff --git a/wpilibc/wpilibC++/include/PIDOutput.h b/wpilibc/wpilibC++/include/PIDOutput.h index a2e2c95de6..40421d0822 100644 --- a/wpilibc/wpilibC++/include/PIDOutput.h +++ b/wpilibc/wpilibC++/include/PIDOutput.h @@ -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; }; diff --git a/wpilibc/wpilibC++/include/PIDSource.h b/wpilibc/wpilibC++/include/PIDSource.h index de7a228f6d..6f5df76d0c 100644 --- a/wpilibc/wpilibC++/include/PIDSource.h +++ b/wpilibc/wpilibC++/include/PIDSource.h @@ -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; }; diff --git a/wpilibc/wpilibC++/include/Resource.h b/wpilibc/wpilibC++/include/Resource.h index fcb9b486e7..8c8033ffc9 100644 --- a/wpilibc/wpilibC++/include/Resource.h +++ b/wpilibc/wpilibC++/include/Resource.h @@ -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); }; diff --git a/wpilibc/wpilibC++/include/RobotState.h b/wpilibc/wpilibC++/include/RobotState.h index 1a2f834acf..82dcd3242b 100644 --- a/wpilibc/wpilibC++/include/RobotState.h +++ b/wpilibc/wpilibC++/include/RobotState.h @@ -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(); }; - - diff --git a/wpilibc/wpilibC++/include/SensorBase.h b/wpilibc/wpilibC++/include/SensorBase.h index a629e1864b..3f6f95873f 100644 --- a/wpilibc/wpilibC++/include/SensorBase.h +++ b/wpilibc/wpilibC++/include/SensorBase.h @@ -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; }; diff --git a/wpilibc/wpilibC++/include/SmartDashboard/NamedSendable.h b/wpilibc/wpilibC++/include/SmartDashboard/NamedSendable.h index 8be059b3f0..e6171b58f9 100644 --- a/wpilibc/wpilibC++/include/SmartDashboard/NamedSendable.h +++ b/wpilibc/wpilibC++/include/SmartDashboard/NamedSendable.h @@ -8,22 +8,21 @@ #ifndef NAMEDSENDABLE_H_ #define NAMEDSENDABLE_H_ - #include #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_ */ diff --git a/wpilibc/wpilibC++/include/SmartDashboard/Sendable.h b/wpilibc/wpilibC++/include/SmartDashboard/Sendable.h index f350f26855..ad0899b8cc 100644 --- a/wpilibc/wpilibC++/include/SmartDashboard/Sendable.h +++ b/wpilibc/wpilibC++/include/SmartDashboard/Sendable.h @@ -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 #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 diff --git a/wpilibc/wpilibC++/include/SmartDashboard/SendableChooser.h b/wpilibc/wpilibC++/include/SmartDashboard/SendableChooser.h index f8570ccc61..46d6ccbe08 100644 --- a/wpilibc/wpilibC++/include/SmartDashboard/SendableChooser.h +++ b/wpilibc/wpilibC++/include/SmartDashboard/SendableChooser.h @@ -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 /** - * 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}. * - *

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 + *

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.

* * @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 m_choices; - ITable *m_table; + private: + std::string m_defaultChoice; + std::map m_choices; + ITable *m_table; }; #endif diff --git a/wpilibc/wpilibC++/include/SmartDashboard/SmartDashboard.h b/wpilibc/wpilibC++/include/SmartDashboard/SmartDashboard.h index c4ab91ca0f..ce490a6388 100644 --- a/wpilibc/wpilibC++/include/SmartDashboard/SmartDashboard.h +++ b/wpilibc/wpilibC++/include/SmartDashboard/SmartDashboard.h @@ -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 m_tablesToData; + /** + * A map linking tables in the SmartDashboard to the {@link + * SmartDashboardData} objects + * they came from. + */ + static std::map m_tablesToData; }; #endif diff --git a/wpilibc/wpilibC++/include/Task.h b/wpilibc/wpilibC++/include/Task.h index 76aba6cf28..123e3224cb 100644 --- a/wpilibc/wpilibC++/include/Task.h +++ b/wpilibc/wpilibC++/include/Task.h @@ -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); }; - diff --git a/wpilibc/wpilibC++/include/Timer.h b/wpilibc/wpilibC++/include/Timer.h index 6f0eb26f9a..0a8b69c68d 100644 --- a/wpilibc/wpilibC++/include/Timer.h +++ b/wpilibc/wpilibC++/include/Timer.h @@ -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); }; diff --git a/wpilibc/wpilibC++/include/Utility.h b/wpilibc/wpilibC++/include/Utility.h index f0814898ae..9b2f1d4f84 100644 --- a/wpilibc/wpilibC++/include/Utility.h +++ b/wpilibc/wpilibC++/include/Utility.h @@ -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 #include -#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); diff --git a/wpilibc/wpilibC++/include/WPIErrors.h b/wpilibc/wpilibC++/include/WPIErrors.h index cc018e7806..1a751b631f 100644 --- a/wpilibc/wpilibC++/include/WPIErrors.h +++ b/wpilibc/wpilibC++/include/WPIErrors.h @@ -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 diff --git a/wpilibc/wpilibC++/include/interfaces/Accelerometer.h b/wpilibc/wpilibC++/include/interfaces/Accelerometer.h index 609e9bcffc..9c024f1dc6 100644 --- a/wpilibc/wpilibC++/include/interfaces/Accelerometer.h +++ b/wpilibc/wpilibC++/include/interfaces/Accelerometer.h @@ -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; }; diff --git a/wpilibc/wpilibC++/include/interfaces/Potentiometer.h b/wpilibc/wpilibC++/include/interfaces/Potentiometer.h index e8562c19d0..f89da062af 100644 --- a/wpilibc/wpilibC++/include/interfaces/Potentiometer.h +++ b/wpilibc/wpilibC++/include/interfaces/Potentiometer.h @@ -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 diff --git a/wpilibc/wpilibC++/src/Buttons/Button.cpp b/wpilibc/wpilibC++/src/Buttons/Button.cpp index ba1489fd93..b57fd89e7f 100644 --- a/wpilibc/wpilibC++/src/Buttons/Button.cpp +++ b/wpilibc/wpilibC++/src/Buttons/Button.cpp @@ -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); } diff --git a/wpilibc/wpilibC++/src/Buttons/ButtonScheduler.cpp b/wpilibc/wpilibC++/src/Buttons/ButtonScheduler.cpp index e7f71b983a..ddc9025fe4 100644 --- a/wpilibc/wpilibC++/src/Buttons/ButtonScheduler.cpp +++ b/wpilibc/wpilibC++/src/Buttons/ButtonScheduler.cpp @@ -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); } diff --git a/wpilibc/wpilibC++/src/Buttons/CancelButtonScheduler.cpp b/wpilibc/wpilibC++/src/Buttons/CancelButtonScheduler.cpp index 5562158d17..1d2b6ccc48 100644 --- a/wpilibc/wpilibC++/src/Buttons/CancelButtonScheduler.cpp +++ b/wpilibc/wpilibC++/src/Buttons/CancelButtonScheduler.cpp @@ -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; + } } - diff --git a/wpilibc/wpilibC++/src/Buttons/HeldButtonScheduler.cpp b/wpilibc/wpilibC++/src/Buttons/HeldButtonScheduler.cpp index fbe4a9f3fd..04c8e3bb2c 100644 --- a/wpilibc/wpilibC++/src/Buttons/HeldButtonScheduler.cpp +++ b/wpilibc/wpilibC++/src/Buttons/HeldButtonScheduler.cpp @@ -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(); + } + } } diff --git a/wpilibc/wpilibC++/src/Buttons/InternalButton.cpp b/wpilibc/wpilibC++/src/Buttons/InternalButton.cpp index 0bd322dd48..932c943ce1 100644 --- a/wpilibc/wpilibC++/src/Buttons/InternalButton.cpp +++ b/wpilibc/wpilibC++/src/Buttons/InternalButton.cpp @@ -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; } diff --git a/wpilibc/wpilibC++/src/Buttons/JoystickButton.cpp b/wpilibc/wpilibC++/src/Buttons/JoystickButton.cpp index 3dace65873..c2bdf627d0 100644 --- a/wpilibc/wpilibC++/src/Buttons/JoystickButton.cpp +++ b/wpilibc/wpilibC++/src/Buttons/JoystickButton.cpp @@ -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); } diff --git a/wpilibc/wpilibC++/src/Buttons/NetworkButton.cpp b/wpilibc/wpilibC++/src/Buttons/NetworkButton.cpp index 5b67c2aac8..4c5f05ae92 100644 --- a/wpilibc/wpilibC++/src/Buttons/NetworkButton.cpp +++ b/wpilibc/wpilibC++/src/Buttons/NetworkButton.cpp @@ -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); } diff --git a/wpilibc/wpilibC++/src/Buttons/PressedButtonScheduler.cpp b/wpilibc/wpilibC++/src/Buttons/PressedButtonScheduler.cpp index 3cf25ba6a0..5a0c506ffe 100644 --- a/wpilibc/wpilibC++/src/Buttons/PressedButtonScheduler.cpp +++ b/wpilibc/wpilibC++/src/Buttons/PressedButtonScheduler.cpp @@ -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; + } } diff --git a/wpilibc/wpilibC++/src/Buttons/ReleasedButtonScheduler.cpp b/wpilibc/wpilibC++/src/Buttons/ReleasedButtonScheduler.cpp index 8715573f2c..e7131e613d 100644 --- a/wpilibc/wpilibC++/src/Buttons/ReleasedButtonScheduler.cpp +++ b/wpilibc/wpilibC++/src/Buttons/ReleasedButtonScheduler.cpp @@ -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(); + } + } } diff --git a/wpilibc/wpilibC++/src/Buttons/ToggleButtonScheduler.cpp b/wpilibc/wpilibC++/src/Buttons/ToggleButtonScheduler.cpp index ed72160df7..c4048d267f 100644 --- a/wpilibc/wpilibC++/src/Buttons/ToggleButtonScheduler.cpp +++ b/wpilibc/wpilibC++/src/Buttons/ToggleButtonScheduler.cpp @@ -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; + } } - diff --git a/wpilibc/wpilibC++/src/Buttons/Trigger.cpp b/wpilibc/wpilibC++/src/Buttons/Trigger.cpp index e633df4573..d605cc2a8a 100644 --- a/wpilibc/wpilibC++/src/Buttons/Trigger.cpp +++ b/wpilibc/wpilibC++/src/Buttons/Trigger.cpp @@ -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; } diff --git a/wpilibc/wpilibC++/src/Commands/Command.cpp b/wpilibc/wpilibC++/src/Commands/Command.cpp index 23c9a20116..d465681d07 100644 --- a/wpilibc/wpilibC++/src/Commands/Command.cpp +++ b/wpilibc/wpilibC++/src/Commands/Command.cpp @@ -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. * - *

Note that the recommended way to call this method is in the constructor.

+ *

Note that the recommended way to call this method is in the + * constructor.

* * @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. - *

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.

+ *

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.

*/ -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. - *

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, + *

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.

*

A command can not be canceled - * if it is a part of a command group, you must cancel the command group instead.

+ * if it is a part of a command group, you must cancel the command group + * instead.

*/ -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. * - *

By default a command will not run when the robot is disabled, and will in fact be canceled.

+ *

By default a command will not run when the robot is disabled, and will in + * fact be canceled.

* @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(); + } } diff --git a/wpilibc/wpilibC++/src/Commands/CommandGroup.cpp b/wpilibc/wpilibC++/src/Commands/CommandGroup.cpp index 14763fc008..d1058feb63 100644 --- a/wpilibc/wpilibC++/src/Commands/CommandGroup.cpp +++ b/wpilibc/wpilibC++/src/Commands/CommandGroup.cpp @@ -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}. * - *

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 + *

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.

* *

It is recommended that this method be called in the constructor.

- * + * * @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. * - *

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 + *

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.

* - *

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 + *

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.

* *

It is recommended that this method be called in the constructor.

@@ -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}. * - *

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 + *

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.

* - *

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 + *

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.

* *

It is recommended that this method be called in the constructor.

* * @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}. * - *

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 + *

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.

* - *

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 + *

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.

* - *

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 + *

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.

* *

It is recommended that this method be called in the constructor.

@@ -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(); } diff --git a/wpilibc/wpilibC++/src/Commands/CommandGroupEntry.cpp b/wpilibc/wpilibC++/src/Commands/CommandGroupEntry.cpp index b3ca63f3da..10a36dbc3a 100644 --- a/wpilibc/wpilibC++/src/Commands/CommandGroupEntry.cpp +++ b/wpilibc/wpilibC++/src/Commands/CommandGroupEntry.cpp @@ -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; } diff --git a/wpilibc/wpilibC++/src/Commands/PIDCommand.cpp b/wpilibc/wpilibC++/src/Commands/PIDCommand.cpp index 33b3d368b2..e4b832617c 100644 --- a/wpilibc/wpilibC++/src/Commands/PIDCommand.cpp +++ b/wpilibc/wpilibC++/src/Commands/PIDCommand.cpp @@ -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); } diff --git a/wpilibc/wpilibC++/src/Commands/PIDSubsystem.cpp b/wpilibc/wpilibC++/src/Commands/PIDSubsystem.cpp index 312e8c2159..e6c341ddb5 100644 --- a/wpilibc/wpilibC++/src/Commands/PIDSubsystem.cpp +++ b/wpilibc/wpilibC++/src/Commands/PIDSubsystem.cpp @@ -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); } diff --git a/wpilibc/wpilibC++/src/Commands/PrintCommand.cpp b/wpilibc/wpilibC++/src/Commands/PrintCommand.cpp index 646db72b12..51145de850 100644 --- a/wpilibc/wpilibC++/src/Commands/PrintCommand.cpp +++ b/wpilibc/wpilibC++/src/Commands/PrintCommand.cpp @@ -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 -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() {} diff --git a/wpilibc/wpilibC++/src/Commands/Scheduler.cpp b/wpilibc/wpilibC++/src/Commands/Scheduler.cpp index 1af895f624..eb030eaae7 100644 --- a/wpilibc/wpilibC++/src/Commands/Scheduler.cpp +++ b/wpilibc/wpilibC++/src/Commands/Scheduler.cpp @@ -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: * *
    @@ -128,66 +128,67 @@ void Scheduler::ProcessCommandAddition(Command *command) { *
*/ 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; } diff --git a/wpilibc/wpilibC++/src/Commands/StartCommand.cpp b/wpilibc/wpilibC++/src/Commands/StartCommand.cpp index 4e04514069..60db054fce 100644 --- a/wpilibc/wpilibC++/src/Commands/StartCommand.cpp +++ b/wpilibc/wpilibC++/src/Commands/StartCommand.cpp @@ -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; } diff --git a/wpilibc/wpilibC++/src/Commands/Subsystem.cpp b/wpilibc/wpilibC++/src/Commands/Subsystem.cpp index d1f5299702..45ced0bdf6 100644 --- a/wpilibc/wpilibC++/src/Commands/Subsystem.cpp +++ b/wpilibc/wpilibC++/src/Commands/Subsystem.cpp @@ -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. * - *

WARNING: This should NOT be called in a constructor if the subsystem is a + *

WARNING: This should NOT be called in a constructor if the + * subsystem is a * singleton.

* * @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; } diff --git a/wpilibc/wpilibC++/src/Commands/WaitCommand.cpp b/wpilibc/wpilibC++/src/Commands/WaitCommand.cpp index 508db04471..d11c915605 100644 --- a/wpilibc/wpilibC++/src/Commands/WaitCommand.cpp +++ b/wpilibc/wpilibC++/src/Commands/WaitCommand.cpp @@ -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 -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() {} diff --git a/wpilibc/wpilibC++/src/Commands/WaitForChildren.cpp b/wpilibc/wpilibC++/src/Commands/WaitForChildren.cpp index e16851332c..527f11ed2d 100644 --- a/wpilibc/wpilibC++/src/Commands/WaitForChildren.cpp +++ b/wpilibc/wpilibC++/src/Commands/WaitForChildren.cpp @@ -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; } diff --git a/wpilibc/wpilibC++/src/Commands/WaitUntilCommand.cpp b/wpilibc/wpilibC++/src/Commands/WaitUntilCommand.cpp index 5eed6e42cb..989047966a 100644 --- a/wpilibc/wpilibC++/src/Commands/WaitUntilCommand.cpp +++ b/wpilibc/wpilibC++/src/Commands/WaitUntilCommand.cpp @@ -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() {} diff --git a/wpilibc/wpilibC++/src/Error.cpp b/wpilibc/wpilibC++/src/Error.cpp index f64c4fe966..fd11ba5ae4 100644 --- a/wpilibc/wpilibC++/src/Error.cpp +++ b/wpilibc/wpilibC++/src/Error.cpp @@ -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; } diff --git a/wpilibc/wpilibC++/src/ErrorBase.cpp b/wpilibc/wpilibC++/src/ErrorBase.cpp index f9151dbd46..363ae9d94c 100644 --- a/wpilibc/wpilibC++/src/ErrorBase.cpp +++ b/wpilibc/wpilibC++/src/ErrorBase.cpp @@ -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; } diff --git a/wpilibc/wpilibC++/src/HLUsageReporting.cpp b/wpilibc/wpilibC++/src/HLUsageReporting.cpp index c0032984b7..94cd7088f2 100644 --- a/wpilibc/wpilibC++/src/HLUsageReporting.cpp +++ b/wpilibc/wpilibC++/src/HLUsageReporting.cpp @@ -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(); + } } diff --git a/wpilibc/wpilibC++/src/LiveWindow/LiveWindow.cpp b/wpilibc/wpilibC++/src/LiveWindow/LiveWindow.cpp index fa0206d62d..7243c182a4 100644 --- a/wpilibc/wpilibC++/src/LiveWindow/LiveWindow.cpp +++ b/wpilibc/wpilibC++/src/LiveWindow/LiveWindow.cpp @@ -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::iterator it = - m_components.begin(); it != m_components.end(); ++it) - { - it->first->StartLiveWindowMode(); - } - } - else - { - for (std::map::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::iterator it = + m_components.begin(); + it != m_components.end(); ++it) { + it->first->StartLiveWindowMode(); + } + } else { + for (std::map::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::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::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); + } + } } diff --git a/wpilibc/wpilibC++/src/LiveWindow/LiveWindowStatusListener.cpp b/wpilibc/wpilibC++/src/LiveWindow/LiveWindowStatusListener.cpp index 5a80f902e8..1c03e7c809 100644 --- a/wpilibc/wpilibC++/src/LiveWindow/LiveWindowStatusListener.cpp +++ b/wpilibc/wpilibC++/src/LiveWindow/LiveWindowStatusListener.cpp @@ -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) {} diff --git a/wpilibc/wpilibC++/src/Resource.cpp b/wpilibc/wpilibC++/src/Resource.cpp index 858d239f11..6246f08ad6 100644 --- a/wpilibc/wpilibC++/src/Resource.cpp +++ b/wpilibc/wpilibC++/src/Resource.cpp @@ -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; } diff --git a/wpilibc/wpilibC++/src/RobotState.cpp b/wpilibc/wpilibC++/src/RobotState.cpp index 747000aaab..0e368dfa7d 100644 --- a/wpilibc/wpilibC++/src/RobotState.cpp +++ b/wpilibc/wpilibC++/src/RobotState.cpp @@ -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; } diff --git a/wpilibc/wpilibC++/src/SmartDashboard/SendableChooser.cpp b/wpilibc/wpilibC++/src/SmartDashboard/SendableChooser.cpp index 05fd8ca699..bad9d14fd2 100644 --- a/wpilibc/wpilibC++/src/SmartDashboard/SendableChooser.cpp +++ b/wpilibc/wpilibC++/src/SmartDashboard/SendableChooser.cpp @@ -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::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::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"; } diff --git a/wpilibc/wpilibC++/src/SmartDashboard/SmartDashboard.cpp b/wpilibc/wpilibC++/src/SmartDashboard/SmartDashboard.cpp index 163a8c3959..15321352b4 100644 --- a/wpilibc/wpilibC++/src/SmartDashboard/SmartDashboard.cpp +++ b/wpilibc/wpilibC++/src/SmartDashboard/SmartDashboard.cpp @@ -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 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; iGetString(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); } diff --git a/wpilibc/wpilibC++Devices/include/ADXL345_I2C.h b/wpilibc/wpilibC++Devices/include/ADXL345_I2C.h index 723c1017a1..f3f537a4a7 100644 --- a/wpilibc/wpilibC++Devices/include/ADXL345_I2C.h +++ b/wpilibc/wpilibC++Devices/include/ADXL345_I2C.h @@ -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; }; diff --git a/wpilibc/wpilibC++Devices/include/ADXL345_SPI.h b/wpilibc/wpilibC++Devices/include/ADXL345_SPI.h index fb50699916..974cb7b3e5 100644 --- a/wpilibc/wpilibC++Devices/include/ADXL345_SPI.h +++ b/wpilibc/wpilibC++Devices/include/ADXL345_SPI.h @@ -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; }; diff --git a/wpilibc/wpilibC++Devices/include/AnalogAccelerometer.h b/wpilibc/wpilibC++Devices/include/AnalogAccelerometer.h index 3e011e9758..56de0b165c 100644 --- a/wpilibc/wpilibC++Devices/include/AnalogAccelerometer.h +++ b/wpilibc/wpilibC++Devices/include/AnalogAccelerometer.h @@ -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; }; diff --git a/wpilibc/wpilibC++Devices/include/AnalogInput.h b/wpilibc/wpilibC++Devices/include/AnalogInput.h index 6e857f2a46..a1c8cae810 100644 --- a/wpilibc/wpilibC++Devices/include/AnalogInput.h +++ b/wpilibc/wpilibC++Devices/include/AnalogInput.h @@ -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; }; diff --git a/wpilibc/wpilibC++Devices/include/AnalogOutput.h b/wpilibc/wpilibC++Devices/include/AnalogOutput.h index 7ff4e56073..bccf8598bb 100644 --- a/wpilibc/wpilibC++Devices/include/AnalogOutput.h +++ b/wpilibc/wpilibC++Devices/include/AnalogOutput.h @@ -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; }; diff --git a/wpilibc/wpilibC++Devices/include/AnalogPotentiometer.h b/wpilibc/wpilibC++Devices/include/AnalogPotentiometer.h index 42a7b69687..67920721dd 100644 --- a/wpilibc/wpilibC++Devices/include/AnalogPotentiometer.h +++ b/wpilibc/wpilibC++Devices/include/AnalogPotentiometer.h @@ -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); }; diff --git a/wpilibc/wpilibC++Devices/include/AnalogTrigger.h b/wpilibc/wpilibC++Devices/include/AnalogTrigger.h index 9b18a33b61..1f6c7aeba5 100644 --- a/wpilibc/wpilibC++Devices/include/AnalogTrigger.h +++ b/wpilibc/wpilibC++Devices/include/AnalogTrigger.h @@ -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; }; diff --git a/wpilibc/wpilibC++Devices/include/AnalogTriggerOutput.h b/wpilibc/wpilibC++Devices/include/AnalogTriggerOutput.h index 1f7214fcf9..1e0c54f60f 100644 --- a/wpilibc/wpilibC++Devices/include/AnalogTriggerOutput.h +++ b/wpilibc/wpilibC++Devices/include/AnalogTriggerOutput.h @@ -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; }; diff --git a/wpilibc/wpilibC++Devices/include/BuiltInAccelerometer.h b/wpilibc/wpilibC++Devices/include/BuiltInAccelerometer.h index 7f2ce58a6a..5dc997af39 100644 --- a/wpilibc/wpilibC++Devices/include/BuiltInAccelerometer.h +++ b/wpilibc/wpilibC++Devices/include/BuiltInAccelerometer.h @@ -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; }; diff --git a/wpilibc/wpilibC++Devices/include/CAN/can_proto.h b/wpilibc/wpilibC++Devices/include/CAN/can_proto.h index 5113b02a0f..c2737d7854 100644 --- a/wpilibc/wpilibC++Devices/include/CAN/can_proto.h +++ b/wpilibc/wpilibC++Devices/include/CAN/can_proto.h @@ -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__ diff --git a/wpilibc/wpilibC++Devices/include/CANJaguar.h b/wpilibc/wpilibC++Devices/include/CANJaguar.h index 3c065927ba..0ddae45d27 100644 --- a/wpilibc/wpilibC++Devices/include/CANJaguar.h +++ b/wpilibc/wpilibC++Devices/include/CANJaguar.h @@ -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.
Passed as the "tag" when setting the control mode.*/ - static const struct EncoderStruct {} Encoder; - /** Sets a quadrature encoder as the position and speed reference.
Passed as the "tag" when setting the control mode.*/ - static const struct QuadEncoderStruct {} QuadEncoder; - /** Sets a potentiometer as the position reference only.
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.
Passed as the "tag" when + * setting the control mode.*/ + static const struct EncoderStruct { + } Encoder; + /** Sets a quadrature encoder as the position and speed reference.
Passed + * as the "tag" when setting the control mode.*/ + static const struct QuadEncoderStruct { + } QuadEncoder; + /** Sets a potentiometer as the position reference only.
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 m_receivedStatusMessage0; - mutable std::atomic m_receivedStatusMessage1; - mutable std::atomic 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 m_receivedStatusMessage0; + mutable std::atomic m_receivedStatusMessage1; + mutable std::atomic 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; }; diff --git a/wpilibc/wpilibC++Devices/include/CANSpeedController.h b/wpilibc/wpilibC++Devices/include/CANSpeedController.h index 5de86bd915..376aaad754 100644 --- a/wpilibc/wpilibC++Devices/include/CANSpeedController.h +++ b/wpilibc/wpilibC++Devices/include/CANSpeedController.h @@ -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; }; diff --git a/wpilibc/wpilibC++Devices/include/CANTalon.h b/wpilibc/wpilibC++Devices/include/CANTalon.h index 5668c1e149..b8f08af1cf 100644 --- a/wpilibc/wpilibC++Devices/include/CANTalon.h +++ b/wpilibc/wpilibC++Devices/include/CANTalon.h @@ -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; }; diff --git a/wpilibc/wpilibC++Devices/include/CameraServer.h b/wpilibc/wpilibC++Devices/include/CameraServer.h index 8359ca366a..046224a7db 100644 --- a/wpilibc/wpilibC++Devices/include/CameraServer.h +++ b/wpilibc/wpilibC++Devices/include/CameraServer.h @@ -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 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 imageData); + void SetImageData(uint8_t* data, unsigned int size, unsigned int start = 0, + bool imaqData = false); + void FreeImageData( + std::tuple 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. diff --git a/wpilibc/wpilibC++Devices/include/Compressor.h b/wpilibc/wpilibC++Devices/include/Compressor.h index a8a38393d4..e13bd962c9 100644 --- a/wpilibc/wpilibC++Devices/include/Compressor.h +++ b/wpilibc/wpilibC++Devices/include/Compressor.h @@ -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_ */ diff --git a/wpilibc/wpilibC++Devices/include/ControllerPower.h b/wpilibc/wpilibC++Devices/include/ControllerPower.h index 654cfb5035..7384e60650 100644 --- a/wpilibc/wpilibC++Devices/include/ControllerPower.h +++ b/wpilibc/wpilibC++Devices/include/ControllerPower.h @@ -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 \ No newline at end of file diff --git a/wpilibc/wpilibC++Devices/include/Counter.h b/wpilibc/wpilibC++Devices/include/Counter.h index 11e8451100..ce8bcaec28 100644 --- a/wpilibc/wpilibC++Devices/include/Counter.h +++ b/wpilibc/wpilibC++Devices/include/Counter.h @@ -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; }; diff --git a/wpilibc/wpilibC++Devices/include/CounterBase.h b/wpilibc/wpilibC++Devices/include/CounterBase.h index a9a38ae339..921ea0c997 100644 --- a/wpilibc/wpilibC++Devices/include/CounterBase.h +++ b/wpilibc/wpilibC++Devices/include/CounterBase.h @@ -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; }; diff --git a/wpilibc/wpilibC++Devices/include/DigitalInput.h b/wpilibc/wpilibC++Devices/include/DigitalInput.h index 39cb4f8374..b43ad071f2 100644 --- a/wpilibc/wpilibC++Devices/include/DigitalInput.h +++ b/wpilibc/wpilibC++Devices/include/DigitalInput.h @@ -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,35 +11,37 @@ /** * Class to read a digital input. - * This class will read digital inputs and return the current value on the channel. Other devices - * such as encoders, gear tooth sensors, etc. that are implemented elsewhere will automatically - * allocate digital inputs and outputs as required. This class is only for devices like switches + * This class will read digital inputs and return the current value on the + * channel. Other devices + * such as encoders, gear tooth sensors, etc. that are implemented elsewhere + * will automatically + * allocate digital inputs and outputs as required. This class is only for + * devices like switches * etc. that aren't implemented anywhere else. */ -class DigitalInput : public DigitalSource, public LiveWindowSendable -{ -public: - explicit DigitalInput(uint32_t channel); - virtual ~DigitalInput(); - bool Get() const; - uint32_t GetChannel() const; +class DigitalInput : public DigitalSource, public LiveWindowSendable { + public: + explicit DigitalInput(uint32_t channel); + virtual ~DigitalInput(); + bool Get() const; + uint32_t GetChannel() const; - // Digital Source Interface - virtual uint32_t GetChannelForRouting() const; - virtual uint32_t GetModuleForRouting() const; - virtual bool GetAnalogTriggerForRouting() const; + // Digital Source Interface + virtual uint32_t GetChannelForRouting() const; + virtual uint32_t GetModuleForRouting() const; + virtual bool GetAnalogTriggerForRouting() const; - void UpdateTable(); - void StartLiveWindowMode(); - void StopLiveWindowMode(); - std::string GetSmartDashboardType() const; - void InitTable(ITable *subTable); - ITable * GetTable() const; + void UpdateTable(); + void StartLiveWindowMode(); + void StopLiveWindowMode(); + std::string GetSmartDashboardType() const; + void InitTable(ITable *subTable); + ITable *GetTable() const; -private: - void InitDigitalInput(uint32_t channel); - uint32_t m_channel; - bool m_lastValue; + private: + void InitDigitalInput(uint32_t channel); + uint32_t m_channel; + bool m_lastValue; - ITable *m_table; + ITable *m_table; }; diff --git a/wpilibc/wpilibC++Devices/include/DigitalOutput.h b/wpilibc/wpilibC++Devices/include/DigitalOutput.h index d398caac38..b1cf76d16d 100644 --- a/wpilibc/wpilibC++Devices/include/DigitalOutput.h +++ b/wpilibc/wpilibC++Devices/include/DigitalOutput.h @@ -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,41 +12,44 @@ /** * Class to write to digital outputs. - * Write values to the digital output channels. Other devices implemented elsewhere will allocate + * Write values to the digital output channels. Other devices implemented + * elsewhere will allocate * channels automatically so for those devices it shouldn't be done here. */ -class DigitalOutput : public DigitalSource, public ITableListener, public LiveWindowSendable -{ -public: - explicit DigitalOutput(uint32_t channel); - virtual ~DigitalOutput(); - void Set(uint32_t value); - uint32_t GetChannel() const; - void Pulse(float length); - bool IsPulsing() const; - void SetPWMRate(float rate); - void EnablePWM(float initialDutyCycle); - void DisablePWM(); - void UpdateDutyCycle(float dutyCycle); +class DigitalOutput : public DigitalSource, + public ITableListener, + public LiveWindowSendable { + public: + explicit DigitalOutput(uint32_t channel); + virtual ~DigitalOutput(); + void Set(uint32_t value); + uint32_t GetChannel() const; + void Pulse(float length); + bool IsPulsing() const; + void SetPWMRate(float rate); + void EnablePWM(float initialDutyCycle); + void DisablePWM(); + void UpdateDutyCycle(float dutyCycle); - // Digital Source Interface - virtual uint32_t GetChannelForRouting() const; - virtual uint32_t GetModuleForRouting() const; - virtual bool GetAnalogTriggerForRouting() const; + // Digital Source Interface + virtual uint32_t GetChannelForRouting() const; + virtual uint32_t GetModuleForRouting() const; + virtual bool GetAnalogTriggerForRouting() const; - virtual void ValueChanged(ITable* source, const std::string& key, EntryValue value, bool isNew); - void UpdateTable(); - void StartLiveWindowMode(); - void StopLiveWindowMode(); - std::string GetSmartDashboardType() const; - void InitTable(ITable *subTable); - ITable * GetTable() const; + virtual void ValueChanged(ITable *source, const std::string &key, + EntryValue value, bool isNew); + void UpdateTable(); + void StartLiveWindowMode(); + void StopLiveWindowMode(); + std::string GetSmartDashboardType() const; + void InitTable(ITable *subTable); + ITable *GetTable() const; -private: - void InitDigitalOutput(uint32_t channel); + private: + void InitDigitalOutput(uint32_t channel); - uint32_t m_channel; - void *m_pwmGenerator; + uint32_t m_channel; + void *m_pwmGenerator; - ITable *m_table; + ITable *m_table; }; diff --git a/wpilibc/wpilibC++Devices/include/DigitalSource.h b/wpilibc/wpilibC++Devices/include/DigitalSource.h index 39497dcbe1..9e0985ab7f 100644 --- a/wpilibc/wpilibC++Devices/include/DigitalSource.h +++ b/wpilibc/wpilibC++Devices/include/DigitalSource.h @@ -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,16 +10,18 @@ /** * DigitalSource Interface. - * The DigitalSource represents all the possible inputs for a counter or a quadrature encoder. The source may be - * either a digital input or an analog input. If the caller just provides a channel, then a digital input will be - * constructed and freed when finished for the source. The source can either be a digital input or analog trigger + * The DigitalSource represents all the possible inputs for a counter or a + * quadrature encoder. The source may be + * either a digital input or an analog input. If the caller just provides a + * channel, then a digital input will be + * constructed and freed when finished for the source. The source can either be + * a digital input or analog trigger * but not both. */ -class DigitalSource : public InterruptableSensorBase -{ -public: - virtual ~DigitalSource(); - virtual uint32_t GetChannelForRouting() const = 0; - virtual uint32_t GetModuleForRouting() const = 0; - virtual bool GetAnalogTriggerForRouting() const = 0; +class DigitalSource : public InterruptableSensorBase { + public: + virtual ~DigitalSource(); + virtual uint32_t GetChannelForRouting() const = 0; + virtual uint32_t GetModuleForRouting() const = 0; + virtual bool GetAnalogTriggerForRouting() const = 0; }; diff --git a/wpilibc/wpilibC++Devices/include/DoubleSolenoid.h b/wpilibc/wpilibC++Devices/include/DoubleSolenoid.h index e966baeae6..4c310c11e9 100644 --- a/wpilibc/wpilibC++Devices/include/DoubleSolenoid.h +++ b/wpilibc/wpilibC++Devices/include/DoubleSolenoid.h @@ -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,39 +17,37 @@ * The DoubleSolenoid class is typically used for pneumatics solenoids that * have two positions controlled by two separate channels. */ -class DoubleSolenoid : public SolenoidBase, public LiveWindowSendable, public ITableListener -{ -public: - enum Value - { - kOff, - kForward, - kReverse - }; +class DoubleSolenoid : public SolenoidBase, + public LiveWindowSendable, + public ITableListener { + public: + enum Value { kOff, kForward, kReverse }; - explicit DoubleSolenoid(uint32_t forwardChannel, uint32_t reverseChannel); - DoubleSolenoid(uint8_t moduleNumber, uint32_t forwardChannel, uint32_t reverseChannel); - virtual ~DoubleSolenoid(); - virtual void Set(Value value); - virtual Value Get() const; - bool IsFwdSolenoidBlackListed() const; - bool IsRevSolenoidBlackListed() const; + explicit DoubleSolenoid(uint32_t forwardChannel, uint32_t reverseChannel); + DoubleSolenoid(uint8_t moduleNumber, uint32_t forwardChannel, + uint32_t reverseChannel); + virtual ~DoubleSolenoid(); + virtual void Set(Value value); + virtual Value Get() const; + bool IsFwdSolenoidBlackListed() const; + bool IsRevSolenoidBlackListed() const; - void ValueChanged(ITable* source, const std::string& key, EntryValue value, bool isNew); - void UpdateTable(); - void StartLiveWindowMode(); - void StopLiveWindowMode(); - std::string GetSmartDashboardType() const; - void InitTable(ITable *subTable); - ITable * GetTable() const; + void ValueChanged(ITable* source, const std::string& key, EntryValue value, + bool isNew); + void UpdateTable(); + void StartLiveWindowMode(); + void StopLiveWindowMode(); + std::string GetSmartDashboardType() const; + void InitTable(ITable* subTable); + ITable* GetTable() const; -private: - virtual void InitSolenoid(); + private: + virtual void InitSolenoid(); - uint32_t m_forwardChannel; ///< The forward channel on the module to control. - uint32_t m_reverseChannel; ///< The reverse channel on the module to control. - uint8_t m_forwardMask; ///< The mask for the forward channel. - uint8_t m_reverseMask; ///< The mask for the reverse channel. + uint32_t m_forwardChannel; ///< The forward channel on the module to control. + uint32_t m_reverseChannel; ///< The reverse channel on the module to control. + uint8_t m_forwardMask; ///< The mask for the forward channel. + uint8_t m_reverseMask; ///< The mask for the reverse channel. - ITable *m_table; + ITable* m_table; }; diff --git a/wpilibc/wpilibC++Devices/include/DriverStation.h b/wpilibc/wpilibC++Devices/include/DriverStation.h index 40e0df3cd9..8d8c912d77 100644 --- a/wpilibc/wpilibC++Devices/include/DriverStation.h +++ b/wpilibc/wpilibC++Devices/include/DriverStation.h @@ -14,107 +14,98 @@ struct HALControlWord; class AnalogInput; /** - * Provide access to the network communication data to / from the Driver Station. + * Provide access to the network communication data to / from the Driver + * Station. */ -class DriverStation : public SensorBase, public RobotStateInterface -{ -public: - enum Alliance - { - kRed, - kBlue, - kInvalid - }; +class DriverStation : public SensorBase, public RobotStateInterface { + public: + enum Alliance { kRed, kBlue, kInvalid }; - virtual ~DriverStation(); - static DriverStation *GetInstance(); - static void ReportError(std::string error); + virtual ~DriverStation(); + static DriverStation *GetInstance(); + static void ReportError(std::string error); - static const uint32_t kJoystickPorts = 6; + static const uint32_t kJoystickPorts = 6; - float GetStickAxis(uint32_t stick, uint32_t axis); - int GetStickPOV(uint32_t stick, uint32_t pov); - uint32_t GetStickButtons(uint32_t stick) const; - bool GetStickButton(uint32_t stick, uint8_t button); + float GetStickAxis(uint32_t stick, uint32_t axis); + int GetStickPOV(uint32_t stick, uint32_t pov); + uint32_t GetStickButtons(uint32_t stick) const; + bool GetStickButton(uint32_t stick, uint8_t button); - int GetStickAxisCount(uint32_t stick) const; - int GetStickPOVCount(uint32_t stick) const; - int GetStickButtonCount(uint32_t stick) const; + int GetStickAxisCount(uint32_t stick) const; + int GetStickPOVCount(uint32_t stick) const; + int GetStickButtonCount(uint32_t stick) const; - bool GetJoystickIsXbox(uint32_t stick) const; - int GetJoystickType(uint32_t stick) const; - std::string GetJoystickName(uint32_t stick) const; - int GetJoystickAxisType(uint32_t stick, uint8_t axis) const; + bool GetJoystickIsXbox(uint32_t stick) const; + int GetJoystickType(uint32_t stick) const; + std::string GetJoystickName(uint32_t stick) const; + int GetJoystickAxisType(uint32_t stick, uint8_t axis) const; - bool IsEnabled() const override; - bool IsDisabled() const override; - bool IsAutonomous() const override; - bool IsOperatorControl() const override; - bool IsTest() const override; - bool IsDSAttached() const; - bool IsNewControlData() const; - bool IsFMSAttached() const; - bool IsSysActive() const; - bool IsSysBrownedOut() const; - - Alliance GetAlliance() const; - uint32_t GetLocation() const; - void WaitForData(); - double GetMatchTime() const; - float GetBatteryVoltage() const; + bool IsEnabled() const override; + bool IsDisabled() const override; + bool IsAutonomous() const override; + bool IsOperatorControl() const override; + bool IsTest() const override; + bool IsDSAttached() const; + bool IsNewControlData() const; + bool IsFMSAttached() const; + bool IsSysActive() const; + bool IsSysBrownedOut() const; - /** Only to be used to tell the Driver Station what code you claim to be executing - * for diagnostic purposes only - * @param entering If true, starting disabled code; if false, leaving disabled code */ - void InDisabled(bool entering) - { - m_userInDisabled = entering; - } - /** Only to be used to tell the Driver Station what code you claim to be executing - * for diagnostic purposes only - * @param entering If true, starting autonomous code; if false, leaving autonomous code */ - void InAutonomous(bool entering) - { - m_userInAutonomous = entering; - } - /** Only to be used to tell the Driver Station what code you claim to be executing - * for diagnostic purposes only - * @param entering If true, starting teleop code; if false, leaving teleop code */ - void InOperatorControl(bool entering) - { - m_userInTeleop = entering; - } - /** Only to be used to tell the Driver Station what code you claim to be executing - * for diagnostic purposes only - * @param entering If true, starting test code; if false, leaving test code */ - void InTest(bool entering) - { - m_userInTest = entering; - } + Alliance GetAlliance() const; + uint32_t GetLocation() const; + void WaitForData(); + double GetMatchTime() const; + float GetBatteryVoltage() const; -protected: - DriverStation(); + /** Only to be used to tell the Driver Station what code you claim to be + * executing + * for diagnostic purposes only + * @param entering If true, starting disabled code; if false, leaving disabled + * code */ + void InDisabled(bool entering) { m_userInDisabled = entering; } + /** Only to be used to tell the Driver Station what code you claim to be + * executing + * for diagnostic purposes only + * @param entering If true, starting autonomous code; if false, leaving + * autonomous code */ + void InAutonomous(bool entering) { m_userInAutonomous = entering; } + /** Only to be used to tell the Driver Station what code you claim to be + * executing + * for diagnostic purposes only + * @param entering If true, starting teleop code; if false, leaving teleop + * code */ + void InOperatorControl(bool entering) { m_userInTeleop = entering; } + /** Only to be used to tell the Driver Station what code you claim to be + * executing + * for diagnostic purposes only + * @param entering If true, starting test code; if false, leaving test code */ + void InTest(bool entering) { m_userInTest = entering; } - void GetData(); -private: - static void InitTask(DriverStation *ds); - static DriverStation *m_instance; - void ReportJoystickUnpluggedError(std::string message); - void Run(); + protected: + DriverStation(); - HALJoystickAxes m_joystickAxes[kJoystickPorts]; - HALJoystickPOVs m_joystickPOVs[kJoystickPorts]; - HALJoystickButtons m_joystickButtons[kJoystickPorts]; - HALJoystickDescriptor m_joystickDescriptor[kJoystickPorts]; - Task m_task; - SEMAPHORE_ID m_newControlData; - MULTIWAIT_ID m_packetDataAvailableMultiWait; - MUTEX_ID m_packetDataAvailableMutex; - MULTIWAIT_ID m_waitForDataSem; - MUTEX_ID m_waitForDataMutex; - bool m_userInDisabled; - bool m_userInAutonomous; - bool m_userInTeleop; - bool m_userInTest; - double m_nextMessageTime; + void GetData(); + + private: + static void InitTask(DriverStation *ds); + static DriverStation *m_instance; + void ReportJoystickUnpluggedError(std::string message); + void Run(); + + HALJoystickAxes m_joystickAxes[kJoystickPorts]; + HALJoystickPOVs m_joystickPOVs[kJoystickPorts]; + HALJoystickButtons m_joystickButtons[kJoystickPorts]; + HALJoystickDescriptor m_joystickDescriptor[kJoystickPorts]; + Task m_task; + SEMAPHORE_ID m_newControlData; + MULTIWAIT_ID m_packetDataAvailableMultiWait; + MUTEX_ID m_packetDataAvailableMutex; + MULTIWAIT_ID m_waitForDataSem; + MUTEX_ID m_waitForDataMutex; + bool m_userInDisabled; + bool m_userInAutonomous; + bool m_userInTeleop; + bool m_userInTest; + double m_nextMessageTime; }; diff --git a/wpilibc/wpilibC++Devices/include/Encoder.h b/wpilibc/wpilibC++Devices/include/Encoder.h index 0a06b5ee2f..ce4b0e04c2 100644 --- a/wpilibc/wpilibC++Devices/include/Encoder.h +++ b/wpilibc/wpilibC++Devices/include/Encoder.h @@ -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,80 +17,93 @@ class DigitalSource; /** * Class to read quad encoders. - * Quadrature encoders are devices that count shaft rotation and can sense direction. The output of - * the QuadEncoder class is an integer that can count either up or down, and can go negative for - * reverse direction counting. When creating QuadEncoders, a direction is supplied that changes the - * sense of the output to make code more readable if the encoder is mounted such that forward movement - * generates negative values. Quadrature encoders have two digital outputs, an A Channel and a B Channel - * that are out of phase with each other to allow the FPGA to do direction sensing. + * Quadrature encoders are devices that count shaft rotation and can sense + * direction. The output of + * the QuadEncoder class is an integer that can count either up or down, and can + * go negative for + * reverse direction counting. When creating QuadEncoders, a direction is + * supplied that changes the + * sense of the output to make code more readable if the encoder is mounted such + * that forward movement + * generates negative values. Quadrature encoders have two digital outputs, an A + * Channel and a B Channel + * that are out of phase with each other to allow the FPGA to do direction + * sensing. * * All encoders will immediately start counting - Reset() them if you need them * to be zeroed before use. */ -class Encoder : public SensorBase, public CounterBase, public PIDSource, public LiveWindowSendable -{ -public: - enum IndexingType { kResetWhileHigh, kResetWhileLow, kResetOnFallingEdge, kResetOnRisingEdge }; +class Encoder : public SensorBase, + public CounterBase, + public PIDSource, + public LiveWindowSendable { + public: + enum IndexingType { + kResetWhileHigh, + kResetWhileLow, + kResetOnFallingEdge, + kResetOnRisingEdge + }; - Encoder(uint32_t aChannel, uint32_t bChannel, bool reverseDirection = false, - EncodingType encodingType = k4X); - Encoder(DigitalSource *aSource, DigitalSource *bSource, bool reverseDirection = false, - EncodingType encodingType = k4X); - Encoder(DigitalSource &aSource, DigitalSource &bSource, bool reverseDirection = false, - EncodingType encodingType = k4X); - virtual ~Encoder(); + Encoder(uint32_t aChannel, uint32_t bChannel, bool reverseDirection = false, + EncodingType encodingType = k4X); + Encoder(DigitalSource *aSource, DigitalSource *bSource, + bool reverseDirection = false, EncodingType encodingType = k4X); + Encoder(DigitalSource &aSource, DigitalSource &bSource, + bool reverseDirection = false, EncodingType encodingType = k4X); + virtual ~Encoder(); - // CounterBase interface - int32_t Get() const override; - int32_t GetRaw() const; - int32_t GetEncodingScale() const; - void Reset() override; - double GetPeriod() const override; - void SetMaxPeriod(double maxPeriod) override; - bool GetStopped() const override; - bool GetDirection() const override; + // CounterBase interface + int32_t Get() const override; + int32_t GetRaw() const; + int32_t GetEncodingScale() const; + void Reset() override; + double GetPeriod() const override; + void SetMaxPeriod(double maxPeriod) override; + bool GetStopped() const override; + bool GetDirection() const override; - double GetDistance() const; - double GetRate() const; - void SetMinRate(double minRate); - void SetDistancePerPulse(double distancePerPulse); - void SetReverseDirection(bool reverseDirection); - void SetSamplesToAverage(int samplesToAverage); - int GetSamplesToAverage() const; - void SetPIDSourceParameter(PIDSourceParameter pidSource); - double PIDGet() const override; + double GetDistance() const; + double GetRate() const; + void SetMinRate(double minRate); + void SetDistancePerPulse(double distancePerPulse); + void SetReverseDirection(bool reverseDirection); + void SetSamplesToAverage(int samplesToAverage); + int GetSamplesToAverage() const; + void SetPIDSourceParameter(PIDSourceParameter pidSource); + double PIDGet() const override; - void SetIndexSource(uint32_t channel, IndexingType type = kResetOnRisingEdge); - void SetIndexSource(DigitalSource *source, IndexingType type = kResetOnRisingEdge); - void SetIndexSource(DigitalSource &source, IndexingType type = kResetOnRisingEdge); + void SetIndexSource(uint32_t channel, IndexingType type = kResetOnRisingEdge); + void SetIndexSource(DigitalSource *source, + IndexingType type = kResetOnRisingEdge); + void SetIndexSource(DigitalSource &source, + IndexingType type = kResetOnRisingEdge); - 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; - int32_t GetFPGAIndex() const - { - return m_index; - } + int32_t GetFPGAIndex() const { return m_index; } -private: - void InitEncoder(bool _reverseDirection, EncodingType encodingType); - double DecodingScaleFactor() const; + private: + void InitEncoder(bool _reverseDirection, EncodingType encodingType); + double DecodingScaleFactor() const; - DigitalSource *m_aSource; // the A phase of the quad encoder - DigitalSource *m_bSource; // the B phase of the quad encoder - bool m_allocatedASource; // was the A source allocated locally? - bool m_allocatedBSource; // was the B source allocated locally? - void* m_encoder; - int32_t m_index; // The encoder's FPGA index. - double m_distancePerPulse; // distance of travel for each encoder tick - Counter *m_counter; // Counter object for 1x and 2x encoding - EncodingType m_encodingType; // Encoding type - int32_t m_encodingScale; // 1x, 2x, or 4x, per the encodingType - PIDSourceParameter m_pidSource; // Encoder parameter that sources a PID controller + DigitalSource *m_aSource; // the A phase of the quad encoder + DigitalSource *m_bSource; // the B phase of the quad encoder + bool m_allocatedASource; // was the A source allocated locally? + bool m_allocatedBSource; // was the B source allocated locally? + void *m_encoder; + int32_t m_index; // The encoder's FPGA index. + double m_distancePerPulse; // distance of travel for each encoder tick + Counter *m_counter; // Counter object for 1x and 2x encoding + EncodingType m_encodingType; // Encoding type + int32_t m_encodingScale; // 1x, 2x, or 4x, per the encodingType + PIDSourceParameter + m_pidSource; // Encoder parameter that sources a PID controller - ITable *m_table; + ITable *m_table; }; diff --git a/wpilibc/wpilibC++Devices/include/GearTooth.h b/wpilibc/wpilibC++Devices/include/GearTooth.h index 17a4b0c06a..7d531060f9 100644 --- a/wpilibc/wpilibC++Devices/include/GearTooth.h +++ b/wpilibc/wpilibC++Devices/include/GearTooth.h @@ -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,20 +10,21 @@ /** * Alias for counter class. - * Implement the gear tooth sensor supplied by FIRST. Currently there is no reverse sensing on - * the gear tooth sensor, but in future versions we might implement the necessary timing in the + * Implement the gear tooth sensor supplied by FIRST. Currently there is no + * reverse sensing on + * the gear tooth sensor, but in future versions we might implement the + * necessary timing in the * FPGA to sense direction. */ -class GearTooth : public Counter -{ -public: - /// 55 uSec for threshold - static constexpr double kGearToothThreshold = 55e-6; - GearTooth(uint32_t channel, bool directionSensitive = false); - GearTooth(DigitalSource *source, bool directionSensitive = false); - GearTooth(DigitalSource &source, bool directionSensitive = false); - virtual ~GearTooth(); - void EnableDirectionSensing(bool directionSensitive); +class GearTooth : public Counter { + public: + /// 55 uSec for threshold + static constexpr double kGearToothThreshold = 55e-6; + GearTooth(uint32_t channel, bool directionSensitive = false); + GearTooth(DigitalSource *source, bool directionSensitive = false); + GearTooth(DigitalSource &source, bool directionSensitive = false); + virtual ~GearTooth(); + void EnableDirectionSensing(bool directionSensitive); - virtual std::string GetSmartDashboardType() const override; + virtual std::string GetSmartDashboardType() const override; }; diff --git a/wpilibc/wpilibC++Devices/include/Gyro.h b/wpilibc/wpilibC++Devices/include/Gyro.h index ddb0a09a0b..6845a8f62b 100644 --- a/wpilibc/wpilibC++Devices/include/Gyro.h +++ b/wpilibc/wpilibC++Devices/include/Gyro.h @@ -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,54 +14,59 @@ class AnalogInput; /** * Use a rate gyro to return the robots heading relative to a starting position. - * The Gyro class tracks the robots heading based on the starting position. As the robot - * rotates the new heading is computed by integrating the rate of rotation returned - * by the sensor. When the class is instantiated, it does a short calibration routine - * where it samples the gyro while at rest to determine the default offset. This is - * subtracted from each sample to determine the heading. This gyro class must be used - * with a channel that is assigned one of the Analog accumulators from the FPGA. See + * The Gyro class tracks the robots heading based on the starting position. As + * the robot + * rotates the new heading is computed by integrating the rate of rotation + * returned + * by the sensor. When the class is instantiated, it does a short calibration + * routine + * where it samples the gyro while at rest to determine the default offset. This + * is + * subtracted from each sample to determine the heading. This gyro class must be + * used + * with a channel that is assigned one of the Analog accumulators from the FPGA. + * See * AnalogInput for the current accumulator assignments. */ -class Gyro : public SensorBase, public PIDSource, public LiveWindowSendable -{ -public: - static const uint32_t kOversampleBits = 10; - static const uint32_t kAverageBits = 0; - static constexpr float kSamplesPerSecond = 50.0; - static constexpr float kCalibrationSampleTime = 5.0; - static constexpr float kDefaultVoltsPerDegreePerSecond = 0.007; +class Gyro : public SensorBase, public PIDSource, public LiveWindowSendable { + public: + static const uint32_t kOversampleBits = 10; + static const uint32_t kAverageBits = 0; + static constexpr float kSamplesPerSecond = 50.0; + static constexpr float kCalibrationSampleTime = 5.0; + static constexpr float kDefaultVoltsPerDegreePerSecond = 0.007; - explicit Gyro(int32_t channel); - explicit Gyro(AnalogInput *channel); - explicit Gyro(AnalogInput &channel); - virtual ~Gyro(); - virtual float GetAngle() const; - virtual double GetRate() const; - void SetSensitivity(float voltsPerDegreePerSecond); - void SetDeadband(float volts); - void SetPIDSourceParameter(PIDSourceParameter pidSource); - virtual void Reset(); - void InitGyro(); + explicit Gyro(int32_t channel); + explicit Gyro(AnalogInput *channel); + explicit Gyro(AnalogInput &channel); + virtual ~Gyro(); + virtual float GetAngle() const; + virtual double GetRate() const; + void SetSensitivity(float voltsPerDegreePerSecond); + void SetDeadband(float volts); + void SetPIDSourceParameter(PIDSourceParameter pidSource); + virtual void Reset(); + void InitGyro(); - // PIDSource interface - double PIDGet() const override; + // PIDSource interface + 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; -protected: - AnalogInput *m_analog; + protected: + AnalogInput *m_analog; -private: - float m_voltsPerDegreePerSecond; - float m_offset; - bool m_channelAllocated; - uint32_t m_center; - PIDSourceParameter m_pidSource; + private: + float m_voltsPerDegreePerSecond; + float m_offset; + bool m_channelAllocated; + uint32_t m_center; + PIDSourceParameter m_pidSource; - ITable *m_table; + ITable *m_table; }; diff --git a/wpilibc/wpilibC++Devices/include/I2C.h b/wpilibc/wpilibC++Devices/include/I2C.h index a90e4c62e9..e6dee47eed 100644 --- a/wpilibc/wpilibC++Devices/include/I2C.h +++ b/wpilibc/wpilibC++Devices/include/I2C.h @@ -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. */ /*----------------------------------------------------------------------------*/ @@ -14,25 +15,25 @@ * It probably should not be used directly. * */ -class I2C : SensorBase -{ -public: - enum Port {kOnboard, kMXP}; +class I2C : SensorBase { + public: + enum Port { kOnboard, kMXP }; - I2C(Port port, uint8_t deviceAddress); - virtual ~I2C(); + I2C(Port port, uint8_t deviceAddress); + virtual ~I2C(); - bool Transaction(uint8_t *dataToSend, uint8_t sendSize, uint8_t *dataReceived, - uint8_t receiveSize); - bool AddressOnly(); - bool Write(uint8_t registerAddress, uint8_t data); - bool WriteBulk(uint8_t* data, uint8_t count); - bool Read(uint8_t registerAddress, uint8_t count, uint8_t *data); - bool ReadOnly(uint8_t count, uint8_t *buffer); - void Broadcast(uint8_t registerAddress, uint8_t data); - bool VerifySensor(uint8_t registerAddress, uint8_t count, const uint8_t *expected); -private: + bool Transaction(uint8_t *dataToSend, uint8_t sendSize, uint8_t *dataReceived, + uint8_t receiveSize); + bool AddressOnly(); + bool Write(uint8_t registerAddress, uint8_t data); + bool WriteBulk(uint8_t *data, uint8_t count); + bool Read(uint8_t registerAddress, uint8_t count, uint8_t *data); + bool ReadOnly(uint8_t count, uint8_t *buffer); + void Broadcast(uint8_t registerAddress, uint8_t data); + bool VerifySensor(uint8_t registerAddress, uint8_t count, + const uint8_t *expected); - Port m_port; - uint8_t m_deviceAddress; + private: + Port m_port; + uint8_t m_deviceAddress; }; diff --git a/wpilibc/wpilibC++Devices/include/Internal/HardwareHLReporting.h b/wpilibc/wpilibC++Devices/include/Internal/HardwareHLReporting.h index aa7ebc8dd9..a91a20d9db 100644 --- a/wpilibc/wpilibC++Devices/include/Internal/HardwareHLReporting.h +++ b/wpilibc/wpilibC++Devices/include/Internal/HardwareHLReporting.h @@ -1,9 +1,8 @@ #include "HLUsageReporting.h" -class HardwareHLReporting : public HLUsageReportingInterface -{ -public: - virtual void ReportScheduler(); - virtual void ReportSmartDashboard(); +class HardwareHLReporting : public HLUsageReportingInterface { + public: + virtual void ReportScheduler(); + virtual void ReportSmartDashboard(); }; diff --git a/wpilibc/wpilibC++Devices/include/InterruptableSensorBase.h b/wpilibc/wpilibC++Devices/include/InterruptableSensorBase.h index 358e082c35..b2225fb8de 100644 --- a/wpilibc/wpilibC++Devices/include/InterruptableSensorBase.h +++ b/wpilibc/wpilibC++Devices/include/InterruptableSensorBase.h @@ -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,34 +10,41 @@ #include "SensorBase.h" #include "Resource.h" -class InterruptableSensorBase : public SensorBase -{ -public: - enum WaitResult { - kTimeout = 0x0, - kRisingEdge = 0x1, - kFallingEdge = 0x100, - kBoth = 0x101, - }; +class InterruptableSensorBase : public SensorBase { + public: + enum WaitResult { + kTimeout = 0x0, + kRisingEdge = 0x1, + kFallingEdge = 0x100, + kBoth = 0x101, + }; - InterruptableSensorBase(); - virtual ~InterruptableSensorBase(); - virtual uint32_t GetChannelForRouting() const = 0; - virtual uint32_t GetModuleForRouting() const = 0; - virtual bool GetAnalogTriggerForRouting() const = 0; - virtual void RequestInterrupts(InterruptHandlerFunction handler, void *param); ///< Asynchronus handler version. - virtual void RequestInterrupts(); ///< Synchronus Wait version. - virtual void CancelInterrupts(); ///< Free up the underlying chipobject functions. - virtual WaitResult WaitForInterrupt(float timeout, bool ignorePrevious = true); ///< Synchronus version. - virtual void EnableInterrupts(); ///< Enable interrupts - after finishing setup. - virtual void DisableInterrupts(); ///< Disable, but don't deallocate. - virtual double ReadRisingTimestamp();///< Return the timestamp for the rising interrupt that occurred. - virtual double ReadFallingTimestamp();///< Return the timestamp for the falling interrupt that occurred. - virtual void SetUpSourceEdge(bool risingEdge, bool fallingEdge); -protected: - void* m_interrupt; - uint32_t m_interruptIndex; - void AllocateInterrupts(bool watcher); + InterruptableSensorBase(); + virtual ~InterruptableSensorBase(); + virtual uint32_t GetChannelForRouting() const = 0; + virtual uint32_t GetModuleForRouting() const = 0; + virtual bool GetAnalogTriggerForRouting() const = 0; + virtual void RequestInterrupts( + InterruptHandlerFunction handler, + void *param); ///< Asynchronus handler version. + virtual void RequestInterrupts(); ///< Synchronus Wait version. + virtual void + CancelInterrupts(); ///< Free up the underlying chipobject functions. + virtual WaitResult WaitForInterrupt( + float timeout, bool ignorePrevious = true); ///< Synchronus version. + virtual void + EnableInterrupts(); ///< Enable interrupts - after finishing setup. + virtual void DisableInterrupts(); ///< Disable, but don't deallocate. + virtual double ReadRisingTimestamp(); ///< Return the timestamp for the + ///rising interrupt that occurred. + virtual double ReadFallingTimestamp(); ///< Return the timestamp for the + ///falling interrupt that occurred. + virtual void SetUpSourceEdge(bool risingEdge, bool fallingEdge); - static Resource *m_interrupts; + protected: + void *m_interrupt; + uint32_t m_interruptIndex; + void AllocateInterrupts(bool watcher); + + static Resource *m_interrupts; }; diff --git a/wpilibc/wpilibC++Devices/include/IterativeRobot.h b/wpilibc/wpilibC++Devices/include/IterativeRobot.h index 76a1cc08aa..79f4c8e544 100644 --- a/wpilibc/wpilibC++Devices/include/IterativeRobot.h +++ b/wpilibc/wpilibC++Devices/include/IterativeRobot.h @@ -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,65 +10,74 @@ #include "RobotBase.h" /** - * IterativeRobot implements a specific type of Robot Program framework, extending the RobotBase class. - * - * The IterativeRobot class is intended to be subclassed by a user creating a robot program. - * - * This class is intended to implement the "old style" default code, by providing - * the following functions which are called by the main loop, StartCompetition(), at the appropriate times: - * + * IterativeRobot implements a specific type of Robot Program framework, + * extending the RobotBase class. + * + * The IterativeRobot class is intended to be subclassed by a user creating a + * robot program. + * + * This class is intended to implement the "old style" default code, by + * providing + * the following functions which are called by the main loop, + * StartCompetition(), at the appropriate times: + * * RobotInit() -- provide for initialization at robot power-on - * + * * Init() functions -- each of the following functions is called once when the * appropriate mode is entered: * - DisabledInit() -- called only when first disabled - * - AutonomousInit() -- called each and every time autonomous is entered from another mode - * - TeleopInit() -- called each and every time teleop is entered from another mode - * - TestInit() -- called each and every time test is entered from another mode - * + * - AutonomousInit() -- called each and every time autonomous is entered from + * another mode + * - TeleopInit() -- called each and every time teleop is entered from + * another mode + * - TestInit() -- called each and every time test is entered from + * another mode + * * Periodic() functions -- each of these functions is called iteratively at the - * appropriate periodic rate (aka the "slow loop"). The default period of - * the iterative robot is synced to the driver station control packets, - * giving a periodic frequency of about 50Hz (50 times per second). + * appropriate periodic rate (aka the "slow loop"). The + * default period of + * the iterative robot is synced to the driver station + * control packets, + * giving a periodic frequency of about 50Hz (50 times + * per second). * - DisabledPeriodic() * - AutonomousPeriodic() * - TeleopPeriodic() * - TestPeriodic() - * + * */ -class IterativeRobot : public RobotBase -{ -public: - /* - * The default period for the periodic function calls (seconds) - * Setting the period to 0.0 will cause the periodic functions to follow - * the Driver Station packet rate of about 50Hz. - */ - static constexpr double kDefaultPeriod = 0.0; +class IterativeRobot : public RobotBase { + public: + /* + * The default period for the periodic function calls (seconds) + * Setting the period to 0.0 will cause the periodic functions to follow + * the Driver Station packet rate of about 50Hz. + */ + static constexpr double kDefaultPeriod = 0.0; - virtual void StartCompetition(); + virtual void StartCompetition(); - virtual void RobotInit(); - virtual void DisabledInit(); - virtual void AutonomousInit(); - virtual void TeleopInit(); - virtual void TestInit(); + virtual void RobotInit(); + virtual void DisabledInit(); + virtual void AutonomousInit(); + virtual void TeleopInit(); + virtual void TestInit(); - virtual void DisabledPeriodic(); - virtual void AutonomousPeriodic(); - virtual void TeleopPeriodic(); - virtual void TestPeriodic(); + virtual void DisabledPeriodic(); + virtual void AutonomousPeriodic(); + virtual void TeleopPeriodic(); + virtual void TestPeriodic(); -protected: - virtual void Prestart(); + protected: + virtual void Prestart(); - virtual ~IterativeRobot(); - IterativeRobot(); + virtual ~IterativeRobot(); + IterativeRobot(); -private: - bool m_disabledInitialized; - bool m_autonomousInitialized; - bool m_teleopInitialized; - bool m_testInitialized; + private: + bool m_disabledInitialized; + bool m_autonomousInitialized; + bool m_teleopInitialized; + bool m_testInitialized; }; diff --git a/wpilibc/wpilibC++Devices/include/Jaguar.h b/wpilibc/wpilibC++Devices/include/Jaguar.h index d7f8698714..cf47e69034 100644 --- a/wpilibc/wpilibC++Devices/include/Jaguar.h +++ b/wpilibc/wpilibC++Devices/include/Jaguar.h @@ -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,19 +13,19 @@ /** * Luminary Micro / Vex Robotics Jaguar Speed Controller with PWM control */ -class Jaguar : public SafePWM, public SpeedController -{ -public: - explicit Jaguar(uint32_t channel); - virtual ~Jaguar(); - virtual void Set(float value, uint8_t syncGroup = 0); - virtual float Get() const; - virtual void Disable(); +class Jaguar : public SafePWM, public SpeedController { + public: + explicit Jaguar(uint32_t channel); + virtual ~Jaguar(); + virtual void Set(float value, uint8_t syncGroup = 0); + virtual float Get() const; + virtual void Disable(); - virtual void PIDWrite(float output) override; + virtual void PIDWrite(float output) override; virtual void SetInverted(bool isInverted) override; - virtual bool GetInverted() const override; -private: - void InitJaguar(); - bool m_isInverted; + virtual bool GetInverted() const override; + + private: + void InitJaguar(); + bool m_isInverted; }; diff --git a/wpilibc/wpilibC++Devices/include/Joystick.h b/wpilibc/wpilibC++Devices/include/Joystick.h index c63618319b..66d8af142e 100644 --- a/wpilibc/wpilibC++Devices/include/Joystick.h +++ b/wpilibc/wpilibC++Devices/include/Joystick.h @@ -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,88 +16,101 @@ class DriverStation; /** * Handle input from standard Joysticks connected to the Driver Station. - * This class handles standard input that comes from the Driver Station. Each time a value is requested - * the most recent value is returned. There is a single class instance for each joystick and the mapping + * This class handles standard input that comes from the Driver Station. Each + * time a value is requested + * the most recent value is returned. There is a single class instance for each + * joystick and the mapping * of ports to hardware buttons depends on the code in the driver station. */ -class Joystick : public GenericHID, public ErrorBase -{ -public: - static const uint32_t kDefaultXAxis = 0; - static const uint32_t kDefaultYAxis = 1; - static const uint32_t kDefaultZAxis = 2; - static const uint32_t kDefaultTwistAxis = 2; - static const uint32_t kDefaultThrottleAxis = 3; - typedef enum - { - kXAxis, kYAxis, kZAxis, kTwistAxis, kThrottleAxis, kNumAxisTypes - } AxisType; - static const uint32_t kDefaultTriggerButton = 1; - static const uint32_t kDefaultTopButton = 2; - typedef enum - { - kTriggerButton, kTopButton, kNumButtonTypes - } ButtonType; - typedef enum - { - kLeftRumble, kRightRumble - } RumbleType; - typedef enum - { - kUnknown = -1, kXInputUnknown = 0, kXInputGamepad = 1, kXInputWheel = 2, kXInputArcadeStick = 3, kXInputFlightStick = 4, kXInputDancePad = 5, kXInputGuitar = 6, kXInputGuitar2 = 7, - kXInputDrumKit = 8, kXInputGuitar3 = 11, kXInputArcadePad = 19, kHIDJoystick = 20, kHIDGamepad = 21, kHIDDriving = 22, kHIDFlight = 23, kHID1stPerson = 24 - } HIDType; - explicit Joystick(uint32_t port); - Joystick(uint32_t port, uint32_t numAxisTypes, uint32_t numButtonTypes); - virtual ~Joystick(); +class Joystick : public GenericHID, public ErrorBase { + public: + static const uint32_t kDefaultXAxis = 0; + static const uint32_t kDefaultYAxis = 1; + static const uint32_t kDefaultZAxis = 2; + static const uint32_t kDefaultTwistAxis = 2; + static const uint32_t kDefaultThrottleAxis = 3; + typedef enum { + kXAxis, + kYAxis, + kZAxis, + kTwistAxis, + kThrottleAxis, + kNumAxisTypes + } AxisType; + static const uint32_t kDefaultTriggerButton = 1; + static const uint32_t kDefaultTopButton = 2; + typedef enum { kTriggerButton, kTopButton, kNumButtonTypes } ButtonType; + typedef enum { kLeftRumble, kRightRumble } RumbleType; + typedef enum { + kUnknown = -1, + kXInputUnknown = 0, + kXInputGamepad = 1, + kXInputWheel = 2, + kXInputArcadeStick = 3, + kXInputFlightStick = 4, + kXInputDancePad = 5, + kXInputGuitar = 6, + kXInputGuitar2 = 7, + kXInputDrumKit = 8, + kXInputGuitar3 = 11, + kXInputArcadePad = 19, + kHIDJoystick = 20, + kHIDGamepad = 21, + kHIDDriving = 22, + kHIDFlight = 23, + kHID1stPerson = 24 + } HIDType; + explicit Joystick(uint32_t port); + Joystick(uint32_t port, uint32_t numAxisTypes, uint32_t numButtonTypes); + virtual ~Joystick(); - uint32_t GetAxisChannel(AxisType axis) const; - void SetAxisChannel(AxisType axis, uint32_t channel); + uint32_t GetAxisChannel(AxisType axis) const; + void SetAxisChannel(AxisType axis, uint32_t channel); - virtual float GetX(JoystickHand hand = kRightHand) const override; - virtual float GetY(JoystickHand hand = kRightHand) const override; - virtual float GetZ() const override; - virtual float GetTwist() const override; - virtual float GetThrottle() const override; - virtual float GetAxis(AxisType axis) const; - float GetRawAxis(uint32_t axis) const override; + virtual float GetX(JoystickHand hand = kRightHand) const override; + virtual float GetY(JoystickHand hand = kRightHand) const override; + virtual float GetZ() const override; + virtual float GetTwist() const override; + virtual float GetThrottle() const override; + virtual float GetAxis(AxisType axis) const; + float GetRawAxis(uint32_t axis) const override; - virtual bool GetTrigger(JoystickHand hand = kRightHand) const override; - virtual bool GetTop(JoystickHand hand = kRightHand) const override; - virtual bool GetBumper(JoystickHand hand = kRightHand) const override; - virtual bool GetRawButton(uint32_t button) const override; - virtual int GetPOV(uint32_t pov = 0) const override; - bool GetButton(ButtonType button) const; - static Joystick* GetStickForPort(uint32_t port); + virtual bool GetTrigger(JoystickHand hand = kRightHand) const override; + virtual bool GetTop(JoystickHand hand = kRightHand) const override; + virtual bool GetBumper(JoystickHand hand = kRightHand) const override; + virtual bool GetRawButton(uint32_t button) const override; + virtual int GetPOV(uint32_t pov = 0) const override; + bool GetButton(ButtonType button) const; + static Joystick *GetStickForPort(uint32_t port); - virtual float GetMagnitude() const; - virtual float GetDirectionRadians() const; - virtual float GetDirectionDegrees() const; + virtual float GetMagnitude() const; + virtual float GetDirectionRadians() const; + virtual float GetDirectionDegrees() const; - bool GetIsXbox() const; - Joystick::HIDType GetType() const; - std::string GetName() const; - int GetAxisType(uint8_t axis) const; - - int GetAxisCount() const; - int GetButtonCount() const; - int GetPOVCount() const; - - void SetRumble(RumbleType type, float value); - void SetOutput(uint8_t outputNumber, bool value); - void SetOutputs(uint32_t value); + bool GetIsXbox() const; + Joystick::HIDType GetType() const; + std::string GetName() const; + int GetAxisType(uint8_t axis) const; -private: - DISALLOW_COPY_AND_ASSIGN(Joystick); - void InitJoystick(uint32_t numAxisTypes, uint32_t numButtonTypes); + int GetAxisCount() const; + int GetButtonCount() const; + int GetPOVCount() const; - DriverStation *m_ds; - uint32_t m_port; - uint32_t *m_axes; - uint32_t *m_buttons; - uint32_t m_outputs; - uint16_t m_leftRumble; - uint16_t m_rightRumble; + void SetRumble(RumbleType type, float value); + void SetOutput(uint8_t outputNumber, bool value); + void SetOutputs(uint32_t value); + + private: + DISALLOW_COPY_AND_ASSIGN(Joystick); + void InitJoystick(uint32_t numAxisTypes, uint32_t numButtonTypes); + + DriverStation *m_ds; + uint32_t m_port; + uint32_t *m_axes; + uint32_t *m_buttons; + uint32_t m_outputs; + uint16_t m_leftRumble; + uint16_t m_rightRumble; }; #endif diff --git a/wpilibc/wpilibC++Devices/include/MotorSafety.h b/wpilibc/wpilibC++Devices/include/MotorSafety.h index 00820be541..e7e8c8b945 100644 --- a/wpilibc/wpilibC++Devices/include/MotorSafety.h +++ b/wpilibc/wpilibC++Devices/include/MotorSafety.h @@ -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,14 +8,13 @@ #define DEFAULT_SAFETY_EXPIRATION 0.1 -class MotorSafety -{ -public: - virtual void SetExpiration(float timeout) = 0; - virtual float GetExpiration() const = 0; - virtual bool IsAlive() const = 0; - virtual void StopMotor() = 0; - virtual void SetSafetyEnabled(bool enabled) = 0; - virtual bool IsSafetyEnabled() const = 0; - virtual void GetDescription(char *desc) const = 0; +class MotorSafety { + public: + virtual void SetExpiration(float timeout) = 0; + virtual float GetExpiration() const = 0; + virtual bool IsAlive() const = 0; + virtual void StopMotor() = 0; + virtual void SetSafetyEnabled(bool enabled) = 0; + virtual bool IsSafetyEnabled() const = 0; + virtual void GetDescription(char *desc) const = 0; }; diff --git a/wpilibc/wpilibC++Devices/include/MotorSafetyHelper.h b/wpilibc/wpilibC++Devices/include/MotorSafetyHelper.h index bea8e02d8e..173734da87 100644 --- a/wpilibc/wpilibC++Devices/include/MotorSafetyHelper.h +++ b/wpilibc/wpilibC++Devices/include/MotorSafetyHelper.h @@ -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,26 +11,30 @@ class MotorSafety; -class MotorSafetyHelper : public ErrorBase -{ -public: - MotorSafetyHelper(MotorSafety *safeObject); - ~MotorSafetyHelper(); - void Feed(); - void SetExpiration(float expirationTime); - float GetExpiration() const; - bool IsAlive() const; - void Check(); - void SetSafetyEnabled(bool enabled); - bool IsSafetyEnabled() const; - static void CheckMotors(); -private: - double m_expiration; // the expiration time for this object - bool m_enabled; // true if motor safety is enabled for this motor - double m_stopTime; // the FPGA clock value when this motor has expired - mutable ReentrantSemaphore m_syncMutex; // protect accesses to the state for this object - MotorSafety *m_safeObject; // the object that is using the helper - MotorSafetyHelper *m_nextHelper; // next object in the list of MotorSafetyHelpers - static MotorSafetyHelper *m_headHelper; // the head of the list of MotorSafetyHelper objects - static ReentrantSemaphore m_listMutex; // protect accesses to the list of helpers +class MotorSafetyHelper : public ErrorBase { + public: + MotorSafetyHelper(MotorSafety *safeObject); + ~MotorSafetyHelper(); + void Feed(); + void SetExpiration(float expirationTime); + float GetExpiration() const; + bool IsAlive() const; + void Check(); + void SetSafetyEnabled(bool enabled); + bool IsSafetyEnabled() const; + static void CheckMotors(); + + private: + double m_expiration; // the expiration time for this object + bool m_enabled; // true if motor safety is enabled for this motor + double m_stopTime; // the FPGA clock value when this motor has expired + mutable ReentrantSemaphore + m_syncMutex; // protect accesses to the state for this object + MotorSafety *m_safeObject; // the object that is using the helper + MotorSafetyHelper * + m_nextHelper; // next object in the list of MotorSafetyHelpers + static MotorSafetyHelper * + m_headHelper; // the head of the list of MotorSafetyHelper objects + static ReentrantSemaphore + m_listMutex; // protect accesses to the list of helpers }; diff --git a/wpilibc/wpilibC++Devices/include/NIIMAQdx.h b/wpilibc/wpilibC++Devices/include/NIIMAQdx.h index 4940063ae8..2aba89da21 100644 --- a/wpilibc/wpilibC++Devices/include/NIIMAQdx.h +++ b/wpilibc/wpilibC++Devices/include/NIIMAQdx.h @@ -1,142 +1,141 @@ //============================================================================== // // Title : NIIMAQdx.h -// Created : 1403685834 seconds after 1/1/1970 12:00:00 UTC -// Copyright : © Copyright 2006, National Instruments Corporation, All rights reserved +// Created : 1403685834 seconds after 1/1/1970 12:00:00 UTC +// Copyright : © Copyright 2006, National Instruments Corporation, All rights +// reserved // Purpose : Include file for NI-IMAQdx library support. // //============================================================================== #ifndef ___niimaqdx_h___ #define ___niimaqdx_h___ - #ifdef __cplusplus extern "C" { #endif - #if !defined(niimaqdx_types) #define niimaqdx_types #ifdef _CVI_ - #pragma EnableLibraryRuntimeChecking +#pragma EnableLibraryRuntimeChecking #endif //============================================================================== // Typedefs //============================================================================== #ifndef _NI_uInt8_DEFINED_ - #define _NI_uInt8_DEFINED_ - typedef unsigned char uInt8; +#define _NI_uInt8_DEFINED_ +typedef unsigned char uInt8; #endif #ifndef _NI_uInt16_DEFINED_ - #define _NI_uInt16_DEFINED_ - typedef unsigned short int uInt16; +#define _NI_uInt16_DEFINED_ +typedef unsigned short int uInt16; #endif #ifndef _NI_uInt32_DEFINED_ - #define _NI_uInt32_DEFINED_ - #if defined(_MSC_VER) - typedef unsigned long uInt32; - #elif __GNUC__ - #if __x86_64__ - typedef unsigned int uInt32; - #else - typedef unsigned long uInt32; - #endif - #endif +#define _NI_uInt32_DEFINED_ +#if defined(_MSC_VER) +typedef unsigned long uInt32; +#elif __GNUC__ +#if __x86_64__ +typedef unsigned int uInt32; +#else +typedef unsigned long uInt32; +#endif +#endif #endif #ifndef _NI_uInt64_DEFINED_ - #define _NI_uInt64_DEFINED_ - #if defined(_MSC_VER) || _CVI_ >= 700 - typedef unsigned __int64 uInt64; - #elif __GNUC__ - typedef unsigned long long uInt64; - #endif +#define _NI_uInt64_DEFINED_ +#if defined(_MSC_VER) || _CVI_ >= 700 +typedef unsigned __int64 uInt64; +#elif __GNUC__ +typedef unsigned long long uInt64; +#endif #endif #ifndef _NI_Int8_DEFINED_ - #define _NI_Int8_DEFINED_ - typedef char Int8; +#define _NI_Int8_DEFINED_ +typedef char Int8; #endif #ifndef _NI_Int16_DEFINED_ - #define _NI_Int16_DEFINED_ - typedef short int Int16; +#define _NI_Int16_DEFINED_ +typedef short int Int16; #endif #ifndef _NI_Int32_DEFINED_ - #define _NI_Int32_DEFINED_ - #if defined(_MSC_VER) - typedef long Int32; - #elif __GNUC__ - #if __x86_64__ - typedef int Int32; - #else - typedef long Int32; - #endif - #endif -#endif +#define _NI_Int32_DEFINED_ +#if defined(_MSC_VER) +typedef long Int32; +#elif __GNUC__ +#if __x86_64__ +typedef int Int32; +#else +typedef long Int32; +#endif +#endif +#endif #ifndef _NI_Int64_DEFINED_ - #define _NI_Int64_DEFINED_ - #if defined(_MSC_VER) || _CVI_ >= 700 - typedef __int64 Int64; - #elif __GNUC__ - typedef long long int Int64; - #endif +#define _NI_Int64_DEFINED_ +#if defined(_MSC_VER) || _CVI_ >= 700 +typedef __int64 Int64; +#elif __GNUC__ +typedef long long int Int64; +#endif #endif #ifndef _NI_float32_DEFINED_ - #define _NI_float32_DEFINED_ - typedef float float32; +#define _NI_float32_DEFINED_ +typedef float float32; #endif #ifndef _NI_float64_DEFINED_ - #define _NI_float64_DEFINED_ - typedef double float64; +#define _NI_float64_DEFINED_ +typedef double float64; #endif #ifndef TRUE - #define TRUE (1L) +#define TRUE (1L) #endif #ifndef FALSE - #define FALSE (0L) +#define FALSE (0L) #endif #ifndef _NI_GUIDHNDL_DEFINED - typedef uInt32 GUIHNDL; +typedef uInt32 GUIHNDL; #endif #if (defined(_MSC_VER) || defined(_CVI_)) - #ifndef _NI_FUNC_DEFINED - #define NI_FUNC __stdcall - #endif - - #ifndef _NI_FUNCC_DEFINED - #define NI_FUNCC __cdecl - #endif +#ifndef _NI_FUNC_DEFINED +#define NI_FUNC __stdcall +#endif + +#ifndef _NI_FUNCC_DEFINED +#define NI_FUNCC __cdecl +#endif #elif defined(__GNUC__) - #ifndef _NI_FUNC_DEFINED - #define NI_FUNC - #endif - - #ifndef _NI_FUNCC_DEFINED - #define NI_FUNCC - #endif +#ifndef _NI_FUNC_DEFINED +#define NI_FUNC +#endif + +#ifndef _NI_FUNCC_DEFINED +#define NI_FUNCC +#endif #endif #ifndef _NI_bool32_DEFINED_ - #define _NI_bool32_DEFINED_ - typedef uInt32 bool32; +#define _NI_bool32_DEFINED_ +typedef uInt32 bool32; #endif #ifndef _NI_IMAQdxSession_DEFINED_ - #define _NI_IMAQdxSession_DEFINED_ - typedef uInt32 IMAQdxSession; +#define _NI_IMAQdxSession_DEFINED_ +typedef uInt32 IMAQdxSession; #endif #define IMAQDX_MAX_API_STRING_LENGTH 512 @@ -146,501 +145,806 @@ extern "C" { //============================================================================== typedef struct Image_struct Image; - //============================================================================== // Error Codes Enumeration //============================================================================== typedef enum IMAQdxError_enum { - IMAQdxErrorSuccess = 0x0, // Success - IMAQdxErrorSystemMemoryFull = 0xBFF69000, // Not enough memory - IMAQdxErrorInternal, // Internal error - IMAQdxErrorInvalidParameter, // Invalid parameter - IMAQdxErrorInvalidPointer, // Invalid pointer - IMAQdxErrorInvalidInterface, // Invalid camera session - IMAQdxErrorInvalidRegistryKey, // Invalid registry key - IMAQdxErrorInvalidAddress, // Invalid address - IMAQdxErrorInvalidDeviceType, // Invalid device type - IMAQdxErrorNotImplemented, // Not implemented - IMAQdxErrorCameraNotFound, // Camera not found - IMAQdxErrorCameraInUse, // Camera is already in use. - IMAQdxErrorCameraNotInitialized, // Camera is not initialized. - IMAQdxErrorCameraRemoved, // Camera has been removed. - IMAQdxErrorCameraRunning, // Acquisition in progress. - IMAQdxErrorCameraNotRunning, // No acquisition in progress. - IMAQdxErrorAttributeNotSupported, // Attribute not supported by the camera. - IMAQdxErrorAttributeNotSettable, // Unable to set attribute. - IMAQdxErrorAttributeNotReadable, // Unable to get attribute. - IMAQdxErrorAttributeOutOfRange, // Attribute value is out of range. - IMAQdxErrorBufferNotAvailable, // Requested buffer is unavailable. - IMAQdxErrorBufferListEmpty, // Buffer list is empty. Add one or more buffers. - IMAQdxErrorBufferListLocked, // Buffer list is already locked. Reconfigure acquisition and try again. - IMAQdxErrorBufferListNotLocked, // No buffer list. Reconfigure acquisition and try again. - IMAQdxErrorResourcesAllocated, // Transfer engine resources already allocated. Reconfigure acquisition and try again. - IMAQdxErrorResourcesUnavailable, // Insufficient transfer engine resources. - IMAQdxErrorAsyncWrite, // Unable to perform asychronous register write. - IMAQdxErrorAsyncRead, // Unable to perform asychronous register read. - IMAQdxErrorTimeout, // Timeout. - IMAQdxErrorBusReset, // Bus reset occurred during a transaction. - IMAQdxErrorInvalidXML, // Unable to load camera's XML file. - IMAQdxErrorFileAccess, // Unable to read/write to file. - IMAQdxErrorInvalidCameraURLString, // Camera has malformed URL string. - IMAQdxErrorInvalidCameraFile, // Invalid camera file. - IMAQdxErrorGenICamError, // Unknown Genicam error. - IMAQdxErrorFormat7Parameters, // For format 7: The combination of speed, image position, image size, and color coding is incorrect. - IMAQdxErrorInvalidAttributeType, // The attribute type is not compatible with the passed variable type. - IMAQdxErrorDLLNotFound, // The DLL could not be found. - IMAQdxErrorFunctionNotFound, // The function could not be found. - IMAQdxErrorLicenseNotActivated, // License not activated. - IMAQdxErrorCameraNotConfiguredForListener, // The camera is not configured properly to support a listener. - IMAQdxErrorCameraMulticastNotAvailable, // Unable to configure the system for multicast support. - IMAQdxErrorBufferHasLostPackets, // The requested buffer has lost packets and the user requested an error to be generated. - IMAQdxErrorGiGEVisionError, // Unknown GiGE Vision error. - IMAQdxErrorNetworkError, // Unknown network error. - IMAQdxErrorCameraUnreachable, // Unable to connect to the camera. - IMAQdxErrorHighPerformanceNotSupported, // High performance acquisition is not supported on the specified network interface. Connect the camera to a network interface running the high performance driver. - IMAQdxErrorInterfaceNotRenamed, // Unable to rename interface. Invalid or duplicate name specified. - IMAQdxErrorNoSupportedVideoModes, // The camera does not have any video modes which are supported. - IMAQdxErrorSoftwareTriggerOverrun, // Software trigger overrun. - IMAQdxErrorTestPacketNotReceived, // The system did not receive a test packet from the camera. The packet size may be too large for the network configuration or a firewall may be enabled. - IMAQdxErrorCorruptedImageReceived, // The camera returned a corrupted image. - IMAQdxErrorCameraConfigurationHasChanged, // The camera did not return an image of the correct type it was configured for previously. - IMAQdxErrorCameraInvalidAuthentication, // The camera is configured with password authentication and either the user name and password were not configured or they are incorrect. - IMAQdxErrorUnknownHTTPError, // The camera returned an unknown HTTP error. - IMAQdxErrorKernelDriverUnavailable, // Unable to attach to the kernel mode driver. - IMAQdxErrorPixelFormatDecoderUnavailable, // No decoder available for selected pixel format. - IMAQdxErrorFirmwareUpdateNeeded, // The acquisition hardware needs a firmware update before it can be used. - IMAQdxErrorFirmwareUpdateRebootNeeded, // The firmware on the acquisition hardware has been updated and the system must be rebooted before use. - IMAQdxErrorLightingCurrentOutOfRange, // The requested current level from the lighting controller is not possible. - IMAQdxErrorUSB3VisionError, // Unknown USB3 Vision error. - IMAQdxErrorInvalidU3VUSBDescriptor, // The camera has a USB descriptor that is incompatible with the USB3 Vision specification. - IMAQdxErrorU3VInvalidControlInterface, // The USB3 Vision control interface is not implemented or is invalid on this camera. - IMAQdxErrorU3VControlInterfaceError, // There was an error from the control interface of the USB3 Vision camera. - IMAQdxErrorU3VInvalidEventInterface, // The USB3 Vision event interface is not implemented or is invalid on this camera. - IMAQdxErrorU3VEventInterfaceError, // There was an error from the event interface of the USB3 Vision camera. - IMAQdxErrorU3VInvalidStreamInterface, // The USB3 Vision stream interface is not implemented or is invalid on this camera. - IMAQdxErrorU3VStreamInterfaceError, // There was an error from the stream interface of the USB3 Vision camera. - IMAQdxErrorU3VUnsupportedConnectionSpeed, // The USB connection speed is not supported by the camera. Check whether the camera is plugged into a USB 2.0 port instead of a USB 3.0 port. If so, verify that the camera supports this use case. - IMAQdxErrorU3VInsufficientPower, // The USB3 Vision camera requires more current than can be supplied by the USB port in use. - IMAQdxErrorU3VInvalidMaxCurrent, // The U3V_MaximumCurrentUSB20_mA registry value is not valid for the connected USB3 Vision camera. - IMAQdxErrorBufferIncompleteData, // The requested buffer has incomplete data and the user requested an error to be generated. - IMAQdxErrorCameraAcquisitionConfigFailed, // The camera returned an error starting the acquisition. - IMAQdxErrorCameraClosePending, // The camera still has outstanding references and will be closed when these operations complete. - IMAQdxErrorSoftwareFault, // An unexpected software error occurred. - IMAQdxErrorCameraPropertyInvalid, // The value for an invalid camera property was requested. - IMAQdxErrorJumboFramesNotEnabled, // Jumbo frames are not enabled on the host. Maximum packet size is 1500 bytes. - IMAQdxErrorBayerPixelFormatNotSelected, // This operation requires that the camera has a Bayer pixel format selected. - IMAQdxErrorGuard = 0xFFFFFFFF, + IMAQdxErrorSuccess = 0x0, // Success + IMAQdxErrorSystemMemoryFull = 0xBFF69000, // Not enough memory + IMAQdxErrorInternal, // Internal error + IMAQdxErrorInvalidParameter, // Invalid parameter + IMAQdxErrorInvalidPointer, // Invalid pointer + IMAQdxErrorInvalidInterface, // Invalid camera session + IMAQdxErrorInvalidRegistryKey, // Invalid registry key + IMAQdxErrorInvalidAddress, // Invalid address + IMAQdxErrorInvalidDeviceType, // Invalid device type + IMAQdxErrorNotImplemented, // Not implemented + IMAQdxErrorCameraNotFound, // Camera not found + IMAQdxErrorCameraInUse, // Camera is already in use. + IMAQdxErrorCameraNotInitialized, // Camera is not initialized. + IMAQdxErrorCameraRemoved, // Camera has been removed. + IMAQdxErrorCameraRunning, // Acquisition in progress. + IMAQdxErrorCameraNotRunning, // No acquisition in progress. + IMAQdxErrorAttributeNotSupported, // Attribute not supported by the camera. + IMAQdxErrorAttributeNotSettable, // Unable to set attribute. + IMAQdxErrorAttributeNotReadable, // Unable to get attribute. + IMAQdxErrorAttributeOutOfRange, // Attribute value is out of range. + IMAQdxErrorBufferNotAvailable, // Requested buffer is unavailable. + IMAQdxErrorBufferListEmpty, // Buffer list is empty. Add one or more buffers. + IMAQdxErrorBufferListLocked, // Buffer list is already locked. Reconfigure + // acquisition and try again. + IMAQdxErrorBufferListNotLocked, // No buffer list. Reconfigure acquisition + // and try again. + IMAQdxErrorResourcesAllocated, // Transfer engine resources already + // allocated. Reconfigure acquisition and try + // again. + IMAQdxErrorResourcesUnavailable, // Insufficient transfer engine resources. + IMAQdxErrorAsyncWrite, // Unable to perform asychronous register write. + IMAQdxErrorAsyncRead, // Unable to perform asychronous register read. + IMAQdxErrorTimeout, // Timeout. + IMAQdxErrorBusReset, // Bus reset occurred during a transaction. + IMAQdxErrorInvalidXML, // Unable to load camera's XML file. + IMAQdxErrorFileAccess, // Unable to read/write to file. + IMAQdxErrorInvalidCameraURLString, // Camera has malformed URL string. + IMAQdxErrorInvalidCameraFile, // Invalid camera file. + IMAQdxErrorGenICamError, // Unknown Genicam error. + IMAQdxErrorFormat7Parameters, // For format 7: The combination of speed, + // image position, image size, and color coding + // is incorrect. + IMAQdxErrorInvalidAttributeType, // The attribute type is not compatible with + // the passed variable type. + IMAQdxErrorDLLNotFound, // The DLL could not be found. + IMAQdxErrorFunctionNotFound, // The function could not be found. + IMAQdxErrorLicenseNotActivated, // License not activated. + IMAQdxErrorCameraNotConfiguredForListener, // The camera is not configured + // properly to support a listener. + IMAQdxErrorCameraMulticastNotAvailable, // Unable to configure the system for + // multicast support. + IMAQdxErrorBufferHasLostPackets, // The requested buffer has lost packets and + // the user requested an error to be + // generated. + IMAQdxErrorGiGEVisionError, // Unknown GiGE Vision error. + IMAQdxErrorNetworkError, // Unknown network error. + IMAQdxErrorCameraUnreachable, // Unable to connect to the camera. + IMAQdxErrorHighPerformanceNotSupported, // High performance acquisition is + // not supported on the specified + // network interface. Connect the + // camera to a network interface + // running the high performance + // driver. + IMAQdxErrorInterfaceNotRenamed, // Unable to rename interface. Invalid or + // duplicate name specified. + IMAQdxErrorNoSupportedVideoModes, // The camera does not have any video modes + // which are supported. + IMAQdxErrorSoftwareTriggerOverrun, // Software trigger overrun. + IMAQdxErrorTestPacketNotReceived, // The system did not receive a test packet + // from the camera. The packet size may be + // too large for the network configuration + // or a firewall may be enabled. + IMAQdxErrorCorruptedImageReceived, // The camera returned a corrupted image. + IMAQdxErrorCameraConfigurationHasChanged, // The camera did not return an + // image of the correct type it was + // configured for previously. + IMAQdxErrorCameraInvalidAuthentication, // The camera is configured with + // password authentication and either + // the user name and password were + // not configured or they are + // incorrect. + IMAQdxErrorUnknownHTTPError, // The camera returned an unknown HTTP error. + IMAQdxErrorKernelDriverUnavailable, // Unable to attach to the kernel mode + // driver. + IMAQdxErrorPixelFormatDecoderUnavailable, // No decoder available for + // selected pixel format. + IMAQdxErrorFirmwareUpdateNeeded, // The acquisition hardware needs a firmware + // update before it can be used. + IMAQdxErrorFirmwareUpdateRebootNeeded, // The firmware on the acquisition + // hardware has been updated and the + // system must be rebooted before use. + IMAQdxErrorLightingCurrentOutOfRange, // The requested current level from the + // lighting controller is not possible. + IMAQdxErrorUSB3VisionError, // Unknown USB3 Vision error. + IMAQdxErrorInvalidU3VUSBDescriptor, // The camera has a USB descriptor that + // is incompatible with the USB3 Vision + // specification. + IMAQdxErrorU3VInvalidControlInterface, // The USB3 Vision control interface + // is not implemented or is invalid on + // this camera. + IMAQdxErrorU3VControlInterfaceError, // There was an error from the control + // interface of the USB3 Vision camera. + IMAQdxErrorU3VInvalidEventInterface, // The USB3 Vision event interface is + // not implemented or is invalid on this + // camera. + IMAQdxErrorU3VEventInterfaceError, // There was an error from the event + // interface of the USB3 Vision camera. + IMAQdxErrorU3VInvalidStreamInterface, // The USB3 Vision stream interface is + // not implemented or is invalid on + // this camera. + IMAQdxErrorU3VStreamInterfaceError, // There was an error from the stream + // interface of the USB3 Vision camera. + IMAQdxErrorU3VUnsupportedConnectionSpeed, // The USB connection speed is not + // supported by the camera. Check + // whether the camera is plugged + // into a USB 2.0 port instead of a + // USB 3.0 port. If so, verify + // that the camera supports this + // use case. + IMAQdxErrorU3VInsufficientPower, // The USB3 Vision camera requires more + // current than can be supplied by the USB + // port in use. + IMAQdxErrorU3VInvalidMaxCurrent, // The U3V_MaximumCurrentUSB20_mA registry + // value is not valid for the connected USB3 + // Vision camera. + IMAQdxErrorBufferIncompleteData, // The requested buffer has incomplete data + // and the user requested an error to be + // generated. + IMAQdxErrorCameraAcquisitionConfigFailed, // The camera returned an error + // starting the acquisition. + IMAQdxErrorCameraClosePending, // The camera still has outstanding references + // and will be closed when these operations + // complete. + IMAQdxErrorSoftwareFault, // An unexpected software error occurred. + IMAQdxErrorCameraPropertyInvalid, // The value for an invalid camera property + // was requested. + IMAQdxErrorJumboFramesNotEnabled, // Jumbo frames are not enabled on the + // host. Maximum packet size is 1500 + // bytes. + IMAQdxErrorBayerPixelFormatNotSelected, // This operation requires that the + // camera has a Bayer pixel format + // selected. + IMAQdxErrorGuard = 0xFFFFFFFF, } IMAQdxError; - //============================================================================== // Bus Type Enumeration //============================================================================== typedef enum IMAQdxBusType_enum { - IMAQdxBusTypeFireWire = 0x31333934, - IMAQdxBusTypeEthernet = 0x69707634, - IMAQdxBusTypeSimulator = 0x2073696D, - IMAQdxBusTypeDirectShow = 0x64736877, - IMAQdxBusTypeIP = 0x4950636D, - IMAQdxBusTypeSmartCam2 = 0x53436132, - IMAQdxBusTypeUSB3Vision = 0x55534233, - IMAQdxBusTypeUVC = 0x55564320, - IMAQdxBusTypeGuard = 0xFFFFFFFF, + IMAQdxBusTypeFireWire = 0x31333934, + IMAQdxBusTypeEthernet = 0x69707634, + IMAQdxBusTypeSimulator = 0x2073696D, + IMAQdxBusTypeDirectShow = 0x64736877, + IMAQdxBusTypeIP = 0x4950636D, + IMAQdxBusTypeSmartCam2 = 0x53436132, + IMAQdxBusTypeUSB3Vision = 0x55534233, + IMAQdxBusTypeUVC = 0x55564320, + IMAQdxBusTypeGuard = 0xFFFFFFFF, } IMAQdxBusType; - //============================================================================== // Camera Control Mode Enumeration //============================================================================== typedef enum IMAQdxCameraControlMode_enum { - IMAQdxCameraControlModeController, - IMAQdxCameraControlModeListener, - IMAQdxCameraControlModeGuard = 0xFFFFFFFF, + IMAQdxCameraControlModeController, + IMAQdxCameraControlModeListener, + IMAQdxCameraControlModeGuard = 0xFFFFFFFF, } IMAQdxCameraControlMode; - //============================================================================== // Buffer Number Mode Enumeration //============================================================================== typedef enum IMAQdxBufferNumberMode_enum { - IMAQdxBufferNumberModeNext, - IMAQdxBufferNumberModeLast, - IMAQdxBufferNumberModeBufferNumber, - IMAQdxBufferNumberModeGuard = 0xFFFFFFFF, + IMAQdxBufferNumberModeNext, + IMAQdxBufferNumberModeLast, + IMAQdxBufferNumberModeBufferNumber, + IMAQdxBufferNumberModeGuard = 0xFFFFFFFF, } IMAQdxBufferNumberMode; - //============================================================================== // Plug n Play Event Enumeration //============================================================================== typedef enum IMAQdxPnpEvent_enum { - IMAQdxPnpEventCameraAttached, - IMAQdxPnpEventCameraDetached, - IMAQdxPnpEventBusReset, - IMAQdxPnpEventGuard = 0xFFFFFFFF, + IMAQdxPnpEventCameraAttached, + IMAQdxPnpEventCameraDetached, + IMAQdxPnpEventBusReset, + IMAQdxPnpEventGuard = 0xFFFFFFFF, } IMAQdxPnpEvent; - //============================================================================== // Bayer Pattern Enumeration //============================================================================== typedef enum IMAQdxBayerPattern_enum { - IMAQdxBayerPatternNone, - IMAQdxBayerPatternGB, - IMAQdxBayerPatternGR, - IMAQdxBayerPatternBG, - IMAQdxBayerPatternRG, - IMAQdxBayerPatternHardware, - IMAQdxBayerPatternGuard = 0xFFFFFFFF, + IMAQdxBayerPatternNone, + IMAQdxBayerPatternGB, + IMAQdxBayerPatternGR, + IMAQdxBayerPatternBG, + IMAQdxBayerPatternRG, + IMAQdxBayerPatternHardware, + IMAQdxBayerPatternGuard = 0xFFFFFFFF, } IMAQdxBayerPattern; - //============================================================================== // Bayer Decode Algorithm Enumeration //============================================================================== typedef enum IMAQdxBayerAlgorithm_enum { - IMAQdxBayerAlgorithmBilinear, - IMAQdxBayerAlgorithmVNG, - IMAQdxBayerAlgorithmGuard = 0xFFFFFFFF, + IMAQdxBayerAlgorithmBilinear, + IMAQdxBayerAlgorithmVNG, + IMAQdxBayerAlgorithmGuard = 0xFFFFFFFF, } IMAQdxBayerAlgorithm; - //============================================================================== // Output Image Types -- Values match Vision Development Module image types //============================================================================== typedef enum IMAQdxOutputImageType_enum { - IMAQdxOutputImageTypeU8 = 0, - IMAQdxOutputImageTypeI16 = 1, - IMAQdxOutputImageTypeU16 = 7, - IMAQdxOutputImageTypeRGB32 = 4, - IMAQdxOutputImageTypeRGB64 = 6, - IMAQdxOutputImageTypeAuto = 0x7FFFFFFF, - IMAQdxOutputImageTypeGuard = 0xFFFFFFFF, + IMAQdxOutputImageTypeU8 = 0, + IMAQdxOutputImageTypeI16 = 1, + IMAQdxOutputImageTypeU16 = 7, + IMAQdxOutputImageTypeRGB32 = 4, + IMAQdxOutputImageTypeRGB64 = 6, + IMAQdxOutputImageTypeAuto = 0x7FFFFFFF, + IMAQdxOutputImageTypeGuard = 0xFFFFFFFF, } IMAQdxOutputImageType; - //============================================================================== // Controller Destination Mode Enumeration //============================================================================== typedef enum IMAQdxDestinationMode_enum { - IMAQdxDestinationModeUnicast, - IMAQdxDestinationModeBroadcast, - IMAQdxDestinationModeMulticast, - IMAQdxDestinationModeGuard = 0xFFFFFFFF, + IMAQdxDestinationModeUnicast, + IMAQdxDestinationModeBroadcast, + IMAQdxDestinationModeMulticast, + IMAQdxDestinationModeGuard = 0xFFFFFFFF, } IMAQdxDestinationMode; - //============================================================================== // Attribute Type Enumeration //============================================================================== -typedef enum IMAQdxAttributeType_enum { - IMAQdxAttributeTypeU32, - IMAQdxAttributeTypeI64, - IMAQdxAttributeTypeF64, - IMAQdxAttributeTypeString, - IMAQdxAttributeTypeEnum, - IMAQdxAttributeTypeBool, - IMAQdxAttributeTypeCommand, - IMAQdxAttributeTypeBlob, - IMAQdxAttributeTypeGuard = 0xFFFFFFFF, +typedef enum IMAQdxAttributeType_enum { + IMAQdxAttributeTypeU32, + IMAQdxAttributeTypeI64, + IMAQdxAttributeTypeF64, + IMAQdxAttributeTypeString, + IMAQdxAttributeTypeEnum, + IMAQdxAttributeTypeBool, + IMAQdxAttributeTypeCommand, + IMAQdxAttributeTypeBlob, + IMAQdxAttributeTypeGuard = 0xFFFFFFFF, } IMAQdxAttributeType; - //============================================================================== // Value Type Enumeration //============================================================================== -typedef enum IMAQdxValueType_enum { - IMAQdxValueTypeU32, - IMAQdxValueTypeI64, - IMAQdxValueTypeF64, - IMAQdxValueTypeString, - IMAQdxValueTypeEnumItem, - IMAQdxValueTypeBool, - IMAQdxValueTypeDisposableString, - IMAQdxValueTypeGuard = 0xFFFFFFFF, +typedef enum IMAQdxValueType_enum { + IMAQdxValueTypeU32, + IMAQdxValueTypeI64, + IMAQdxValueTypeF64, + IMAQdxValueTypeString, + IMAQdxValueTypeEnumItem, + IMAQdxValueTypeBool, + IMAQdxValueTypeDisposableString, + IMAQdxValueTypeGuard = 0xFFFFFFFF, } IMAQdxValueType; - //============================================================================== // Interface File Flags Enumeration //============================================================================== typedef enum IMAQdxInterfaceFileFlags_enum { - IMAQdxInterfaceFileFlagsConnected = 0x1, - IMAQdxInterfaceFileFlagsDirty = 0x2, - IMAQdxInterfaceFileFlagsGuard = 0xFFFFFFFF, + IMAQdxInterfaceFileFlagsConnected = 0x1, + IMAQdxInterfaceFileFlagsDirty = 0x2, + IMAQdxInterfaceFileFlagsGuard = 0xFFFFFFFF, } IMAQdxInterfaceFileFlags; - //============================================================================== // Overwrite Mode Enumeration //============================================================================== typedef enum IMAQdxOverwriteMode_enum { - IMAQdxOverwriteModeGetOldest = 0x0, - IMAQdxOverwriteModeFail = 0x2, - IMAQdxOverwriteModeGetNewest = 0x3, - IMAQdxOverwriteModeGuard = 0xFFFFFFFF, + IMAQdxOverwriteModeGetOldest = 0x0, + IMAQdxOverwriteModeFail = 0x2, + IMAQdxOverwriteModeGetNewest = 0x3, + IMAQdxOverwriteModeGuard = 0xFFFFFFFF, } IMAQdxOverwriteMode; - //============================================================================== // Incomplete Buffer Mode Enumeration //============================================================================== typedef enum IMAQdxIncompleteBufferMode_enum { - IMAQdxIncompleteBufferModeIgnore, - IMAQdxIncompleteBufferModeFail, - IMAQdxIncompleteBufferModeGuard = 0xFFFFFFFF, + IMAQdxIncompleteBufferModeIgnore, + IMAQdxIncompleteBufferModeFail, + IMAQdxIncompleteBufferModeGuard = 0xFFFFFFFF, } IMAQdxIncompleteBufferMode; - //============================================================================== // Lost Packet Mode Enumeration //============================================================================== typedef enum IMAQdxLostPacketMode_enum { - IMAQdxLostPacketModeIgnore, - IMAQdxLostPacketModeFail, - IMAQdxLostPacketModeGuard = 0xFFFFFFFF, + IMAQdxLostPacketModeIgnore, + IMAQdxLostPacketModeFail, + IMAQdxLostPacketModeGuard = 0xFFFFFFFF, } IMAQdxLostPacketMode; - //============================================================================== // Attribute Visibility Enumeration //============================================================================== typedef enum IMAQdxAttributeVisibility_enum { - IMAQdxAttributeVisibilitySimple = 0x00001000, - IMAQdxAttributeVisibilityIntermediate = 0x00002000, - IMAQdxAttributeVisibilityAdvanced = 0x00004000, - IMAQdxAttributeVisibilityGuard = 0xFFFFFFFF, + IMAQdxAttributeVisibilitySimple = 0x00001000, + IMAQdxAttributeVisibilityIntermediate = 0x00002000, + IMAQdxAttributeVisibilityAdvanced = 0x00004000, + IMAQdxAttributeVisibilityGuard = 0xFFFFFFFF, } IMAQdxAttributeVisibility; - //============================================================================== // Stream Channel Mode Enumeration //============================================================================== typedef enum IMAQdxStreamChannelMode_enum { - IMAQdxStreamChannelModeAutomatic, - IMAQdxStreamChannelModeManual, - IMAQdxStreamChannelModeGuard = 0xFFFFFFFF, + IMAQdxStreamChannelModeAutomatic, + IMAQdxStreamChannelModeManual, + IMAQdxStreamChannelModeGuard = 0xFFFFFFFF, } IMAQdxStreamChannelMode; - //============================================================================== // Pixel Signedness Enumeration //============================================================================== typedef enum IMAQdxPixelSignedness_enum { - IMAQdxPixelSignednessUnsigned, - IMAQdxPixelSignednessSigned, - IMAQdxPixelSignednessHardware, - IMAQdxPixelSignednessGuard = 0xFFFFFFFF, + IMAQdxPixelSignednessUnsigned, + IMAQdxPixelSignednessSigned, + IMAQdxPixelSignednessHardware, + IMAQdxPixelSignednessGuard = 0xFFFFFFFF, } IMAQdxPixelSignedness; - //============================================================================== // USB Connection Speed Enumeration //============================================================================== typedef enum IMAQdxUSBConnectionSpeed_enum { - IMAQdxUSBConnectionSpeedLow = 1, - IMAQdxUSBConnectionSpeedFull = 2, - IMAQdxUSBConnectionSpeedHigh = 4, - IMAQdxUSBConnectionSpeedSuper = 8, - IMAQdxUSBConnectionSpeedGuard = 0xFFFFFFFF, + IMAQdxUSBConnectionSpeedLow = 1, + IMAQdxUSBConnectionSpeedFull = 2, + IMAQdxUSBConnectionSpeedHigh = 4, + IMAQdxUSBConnectionSpeedSuper = 8, + IMAQdxUSBConnectionSpeedGuard = 0xFFFFFFFF, } IMAQdxUSBConnectionSpeed; - //============================================================================== // CVI Structures //============================================================================== #pragma pack(push, 4) - //============================================================================== // Camera Information Structure //============================================================================== typedef struct IMAQdxCameraInformation_struct { - uInt32 Type; - uInt32 Version; - uInt32 Flags; - uInt32 SerialNumberHi; - uInt32 SerialNumberLo; - IMAQdxBusType BusType; - char InterfaceName[IMAQDX_MAX_API_STRING_LENGTH]; - char VendorName[IMAQDX_MAX_API_STRING_LENGTH]; - char ModelName[IMAQDX_MAX_API_STRING_LENGTH]; - char CameraFileName[IMAQDX_MAX_API_STRING_LENGTH]; - char CameraAttributeURL[IMAQDX_MAX_API_STRING_LENGTH]; + uInt32 Type; + uInt32 Version; + uInt32 Flags; + uInt32 SerialNumberHi; + uInt32 SerialNumberLo; + IMAQdxBusType BusType; + char InterfaceName[IMAQDX_MAX_API_STRING_LENGTH]; + char VendorName[IMAQDX_MAX_API_STRING_LENGTH]; + char ModelName[IMAQDX_MAX_API_STRING_LENGTH]; + char CameraFileName[IMAQDX_MAX_API_STRING_LENGTH]; + char CameraAttributeURL[IMAQDX_MAX_API_STRING_LENGTH]; } IMAQdxCameraInformation; - //============================================================================== // Camera File Structure //============================================================================== typedef struct IMAQdxCameraFile_struct { - uInt32 Type; - uInt32 Version; - char FileName[IMAQDX_MAX_API_STRING_LENGTH]; + uInt32 Type; + uInt32 Version; + char FileName[IMAQDX_MAX_API_STRING_LENGTH]; } IMAQdxCameraFile; - //============================================================================== // Attribute Information Structure //============================================================================== typedef struct IMAQdxAttributeInformation_struct { - IMAQdxAttributeType Type; - bool32 Readable; - bool32 Writable; - char Name[IMAQDX_MAX_API_STRING_LENGTH]; + IMAQdxAttributeType Type; + bool32 Readable; + bool32 Writable; + char Name[IMAQDX_MAX_API_STRING_LENGTH]; } IMAQdxAttributeInformation; - //============================================================================== // Enumeration Item Structure //============================================================================== typedef struct IMAQdxEnumItem_struct { - uInt32 Value; - uInt32 Reserved; - char Name[IMAQDX_MAX_API_STRING_LENGTH]; + uInt32 Value; + uInt32 Reserved; + char Name[IMAQDX_MAX_API_STRING_LENGTH]; } IMAQdxEnumItem; - //============================================================================== // Camera Information Structure //============================================================================== typedef IMAQdxEnumItem IMAQdxVideoMode; - #pragma pack(pop) - //============================================================================== // Callbacks //============================================================================== -typedef uInt32 (NI_FUNC *FrameDoneEventCallbackPtr)(IMAQdxSession id, uInt32 bufferNumber, void* callbackData); -typedef uInt32 (NI_FUNC *PnpEventCallbackPtr)(IMAQdxSession id, IMAQdxPnpEvent pnpEvent, void* callbackData); -typedef void (NI_FUNC *AttributeUpdatedEventCallbackPtr)(IMAQdxSession id, const char* name, void* callbackData); +typedef uInt32(NI_FUNC* FrameDoneEventCallbackPtr)(IMAQdxSession id, + uInt32 bufferNumber, + void* callbackData); +typedef uInt32(NI_FUNC* PnpEventCallbackPtr)(IMAQdxSession id, + IMAQdxPnpEvent pnpEvent, + void* callbackData); +typedef void(NI_FUNC* AttributeUpdatedEventCallbackPtr)(IMAQdxSession id, + const char* name, + void* callbackData); -#endif //niimaqdx_types +#endif // niimaqdx_types //============================================================================== // Attributes //============================================================================== -#define IMAQdxAttributeBaseAddress "CameraInformation::BaseAddress" // Read only. Gets the base address of the camera registers. -#define IMAQdxAttributeBusType "CameraInformation::BusType" // Read only. Gets the bus type of the camera. -#define IMAQdxAttributeModelName "CameraInformation::ModelName" // Read only. Returns the model name. -#define IMAQdxAttributeSerialNumberHigh "CameraInformation::SerialNumberHigh" // Read only. Gets the upper 32-bits of the camera 64-bit serial number. -#define IMAQdxAttributeSerialNumberLow "CameraInformation::SerialNumberLow" // Read only. Gets the lower 32-bits of the camera 64-bit serial number. -#define IMAQdxAttributeVendorName "CameraInformation::VendorName" // Read only. Returns the vendor name. -#define IMAQdxAttributeHostIPAddress "CameraInformation::HostIPAddress" // Read only. Returns the host adapter IP address. -#define IMAQdxAttributeIPAddress "CameraInformation::IPAddress" // Read only. Returns the IP address. -#define IMAQdxAttributePrimaryURLString "CameraInformation::PrimaryURLString" // Read only. Gets the camera's primary URL string. -#define IMAQdxAttributeSecondaryURLString "CameraInformation::SecondaryURLString" // Read only. Gets the camera's secondary URL string. -#define IMAQdxAttributeAcqInProgress "StatusInformation::AcqInProgress" // Read only. Gets the current state of the acquisition. TRUE if acquiring; otherwise FALSE. -#define IMAQdxAttributeLastBufferCount "StatusInformation::LastBufferCount" // Read only. Gets the number of transferred buffers. -#define IMAQdxAttributeLastBufferNumber "StatusInformation::LastBufferNumber" // Read only. Gets the last cumulative buffer number transferred. -#define IMAQdxAttributeLostBufferCount "StatusInformation::LostBufferCount" // Read only. Gets the number of lost buffers during an acquisition session. -#define IMAQdxAttributeLostPacketCount "StatusInformation::LostPacketCount" // Read only. Gets the number of lost packets during an acquisition session. -#define IMAQdxAttributeRequestedResendPackets "StatusInformation::RequestedResendPacketCount" // Read only. Gets the number of packets requested to be resent during an acquisition session. -#define IMAQdxAttributeReceivedResendPackets "StatusInformation::ReceivedResendPackets" // Read only. Gets the number of packets that were requested to be resent during an acquisition session and were completed. -#define IMAQdxAttributeHandledEventCount "StatusInformation::HandledEventCount" // Read only. Gets the number of handled events during an acquisition session. -#define IMAQdxAttributeLostEventCount "StatusInformation::LostEventCount" // Read only. Gets the number of lost events during an acquisition session. -#define IMAQdxAttributeBayerGainB "AcquisitionAttributes::Bayer::GainB" // Sets/gets the white balance gain for the blue component of the Bayer conversion. -#define IMAQdxAttributeBayerGainG "AcquisitionAttributes::Bayer::GainG" // Sets/gets the white balance gain for the green component of the Bayer conversion. -#define IMAQdxAttributeBayerGainR "AcquisitionAttributes::Bayer::GainR" // Sets/gets the white balance gain for the red component of the Bayer conversion. -#define IMAQdxAttributeBayerPattern "AcquisitionAttributes::Bayer::Pattern" // Sets/gets the Bayer pattern to use. -#define IMAQdxAttributeStreamChannelMode "AcquisitionAttributes::Controller::StreamChannelMode" // Gets/sets the mode for allocating a FireWire stream channel. -#define IMAQdxAttributeDesiredStreamChannel "AcquisitionAttributes::Controller::DesiredStreamChannel" // Gets/sets the stream channel to manually allocate. -#define IMAQdxAttributeFrameInterval "AcquisitionAttributes::FrameInterval" // Read only. Gets the duration in milliseconds between successive frames. -#define IMAQdxAttributeIgnoreFirstFrame "AcquisitionAttributes::IgnoreFirstFrame" // Gets/sets the video delay of one frame between starting the camera and receiving the video feed. -#define IMAQdxAttributeOffsetX "OffsetX" // Gets/sets the left offset of the image. -#define IMAQdxAttributeOffsetY "OffsetY" // Gets/sets the top offset of the image. -#define IMAQdxAttributeWidth "Width" // Gets/sets the width of the image. -#define IMAQdxAttributeHeight "Height" // Gets/sets the height of the image. -#define IMAQdxAttributePixelFormat "PixelFormat" // Gets/sets the pixel format of the source sensor. -#define IMAQdxAttributePacketSize "PacketSize" // Gets/sets the packet size in bytes. -#define IMAQdxAttributePayloadSize "PayloadSize" // Gets/sets the frame size in bytes. -#define IMAQdxAttributeSpeed "AcquisitionAttributes::Speed" // Gets/sets the transfer speed in Mbps for a FireWire packet. -#define IMAQdxAttributeShiftPixelBits "AcquisitionAttributes::ShiftPixelBits" // Gets/sets the alignment of 16-bit cameras. Downshift the pixel bits if the camera returns most significant bit-aligned data. -#define IMAQdxAttributeSwapPixelBytes "AcquisitionAttributes::SwapPixelBytes" // Gets/sets the endianness of 16-bit cameras. Swap the pixel bytes if the camera returns little endian data. -#define IMAQdxAttributeOverwriteMode "AcquisitionAttributes::OverwriteMode" // Gets/sets the overwrite mode, used to determine acquisition when an image transfer cannot be completed due to an overwritten internal buffer. -#define IMAQdxAttributeTimeout "AcquisitionAttributes::Timeout" // Gets/sets the timeout value in milliseconds, used to abort an acquisition when the image transfer cannot be completed within the delay. -#define IMAQdxAttributeVideoMode "AcquisitionAttributes::VideoMode" // Gets/sets the video mode for a camera. -#define IMAQdxAttributeBitsPerPixel "AcquisitionAttributes::BitsPerPixel" // Gets/sets the actual bits per pixel. For 16-bit components, this represents the actual bit depth (10-, 12-, 14-, or 16-bit). -#define IMAQdxAttributePixelSignedness "AcquisitionAttributes::PixelSignedness" // Gets/sets the signedness of the pixel. For 16-bit components, this represents the actual pixel signedness (Signed, or Unsigned). -#define IMAQdxAttributeReserveDualPackets "AcquisitionAttributes::ReserveDualPackets" // Gets/sets if dual packets will be reserved for a very large FireWire packet. -#define IMAQdxAttributeReceiveTimestampMode "AcquisitionAttributes::ReceiveTimestampMode" // Gets/sets the mode for timestamping images received by the driver. -#define IMAQdxAttributeActualPeakBandwidth "AcquisitionAttributes::AdvancedEthernet::BandwidthControl::ActualPeakBandwidth" // Read only. Returns the actual maximum peak bandwidth the camera will be configured to use. -#define IMAQdxAttributeDesiredPeakBandwidth "AcquisitionAttributes::AdvancedEthernet::BandwidthControl::DesiredPeakBandwidth" // Gets/sets the desired maximum peak bandwidth the camera should use. -#define IMAQdxAttributeDestinationMode "AcquisitionAttributes::AdvancedEthernet::Controller::DestinationMode" // Gets/Sets where the camera is instructed to send the image stream. -#define IMAQdxAttributeDestinationMulticastAddress "AcquisitionAttributes::AdvancedEthernet::Controller::DestinationMulticastAddress" // Gets/Sets the multicast address the camera should send data in multicast mode. -#define IMAQdxAttributeEventsEnabled "AcquisitionAttributes::AdvancedEthernet::EventParameters::EventsEnabled" // Gets/Sets if events will be handled. -#define IMAQdxAttributeMaxOutstandingEvents "AcquisitionAttributes::AdvancedEthernet::EventParameters::MaxOutstandingEvents" // Gets/Sets the maximum number of outstanding events to queue. -#define IMAQdxAttributeTestPacketEnabled "AcquisitionAttributes::AdvancedEthernet::TestPacketParameters::TestPacketEnabled" // Gets/Sets whether the driver will validate the image streaming settings using test packets prior to an acquisition -#define IMAQdxAttributeTestPacketTimeout "AcquisitionAttributes::AdvancedEthernet::TestPacketParameters::TestPacketTimeout" // Gets/Sets the timeout for validating test packet reception (if enabled) -#define IMAQdxAttributeMaxTestPacketRetries "AcquisitionAttributes::AdvancedEthernet::TestPacketParameters::MaxTestPacketRetries" // Gets/Sets the number of retries for validating test packet reception (if enabled) -#define IMAQdxAttributeChunkDataDecodingEnabled "AcquisitionAttributes::ChunkDataDecoding::ChunkDataDecodingEnabled" // Gets/Sets whether the driver will decode any chunk data in the image stream -#define IMAQdxAttributeChunkDataDecodingMaxElementSize "AcquisitionAttributes::ChunkDataDecoding::MaximumChunkCopySize" // Gets/Sets the maximum size of any single chunk data element that will be made available -#define IMAQdxAttributeLostPacketMode "AcquisitionAttributes::AdvancedEthernet::LostPacketMode" // Gets/sets the behavior when the user extracts a buffer that has missing packets. -#define IMAQdxAttributeMemoryWindowSize "AcquisitionAttributes::AdvancedEthernet::ResendParameters::MemoryWindowSize" // Gets/sets the size of the memory window of the camera in kilobytes. Should match the camera's internal buffer size. -#define IMAQdxAttributeResendsEnabled "AcquisitionAttributes::AdvancedEthernet::ResendParameters::ResendsEnabled" // Gets/sets if resends will be issued for missing packets. -#define IMAQdxAttributeResendThresholdPercentage "AcquisitionAttributes::AdvancedEthernet::ResendParameters::ResendThresholdPercentage" // Gets/sets the threshold of the packet processing window that will trigger packets to be resent. -#define IMAQdxAttributeResendBatchingPercentage "AcquisitionAttributes::AdvancedEthernet::ResendParameters::ResendBatchingPercentage" // Gets/sets the percent of the packet resend threshold that will be issued as one group past the initial threshold sent in a single request. -#define IMAQdxAttributeMaxResendsPerPacket "AcquisitionAttributes::AdvancedEthernet::ResendParameters::MaxResendsPerPacket" // Gets/sets the maximum number of resend requests that will be issued for a missing packet. -#define IMAQdxAttributeResendResponseTimeout "AcquisitionAttributes::AdvancedEthernet::ResendParameters::ResendResponseTimeout" // Gets/sets the time to wait for a resend request to be satisfied before sending another. -#define IMAQdxAttributeNewPacketTimeout "AcquisitionAttributes::AdvancedEthernet::ResendParameters::NewPacketTimeout" // Gets/sets the time to wait for new packets to arrive in a partially completed image before assuming the rest of the image was lost. -#define IMAQdxAttributeMissingPacketTimeout "AcquisitionAttributes::AdvancedEthernet::ResendParameters::MissingPacketTimeout" // Gets/sets the time to wait for a missing packet before issuing a resend. -#define IMAQdxAttributeResendTimerResolution "AcquisitionAttributes::AdvancedEthernet::ResendParameters::ResendTimerResolution" // Gets/sets the resolution of the packet processing system that is used for all packet-related timeouts. - +#define IMAQdxAttributeBaseAddress \ + "CameraInformation::BaseAddress" // Read only. Gets the base address of the + // camera registers. +#define IMAQdxAttributeBusType \ + "CameraInformation::BusType" // Read only. Gets the bus type of the camera. +#define IMAQdxAttributeModelName \ + "CameraInformation::ModelName" // Read only. Returns the model name. +#define IMAQdxAttributeSerialNumberHigh \ + "CameraInformation::SerialNumberHigh" // Read only. Gets the upper 32-bits of + // the camera 64-bit serial number. +#define IMAQdxAttributeSerialNumberLow \ + "CameraInformation::SerialNumberLow" // Read only. Gets the lower 32-bits of + // the camera 64-bit serial number. +#define IMAQdxAttributeVendorName \ + "CameraInformation::VendorName" // Read only. Returns the vendor name. +#define IMAQdxAttributeHostIPAddress \ + "CameraInformation::HostIPAddress" // Read only. Returns the host adapter IP + // address. +#define IMAQdxAttributeIPAddress \ + "CameraInformation::IPAddress" // Read only. Returns the IP address. +#define IMAQdxAttributePrimaryURLString \ + "CameraInformation::PrimaryURLString" // Read only. Gets the camera's primary + // URL string. +#define IMAQdxAttributeSecondaryURLString \ + "CameraInformation::SecondaryURLString" // Read only. Gets the camera's + // secondary URL string. +#define IMAQdxAttributeAcqInProgress \ + "StatusInformation::AcqInProgress" // Read only. Gets the current state of + // the acquisition. TRUE if acquiring; + // otherwise FALSE. +#define IMAQdxAttributeLastBufferCount \ + "StatusInformation::LastBufferCount" // Read only. Gets the number of + // transferred buffers. +#define IMAQdxAttributeLastBufferNumber \ + "StatusInformation::LastBufferNumber" // Read only. Gets the last cumulative + // buffer number transferred. +#define IMAQdxAttributeLostBufferCount \ + "StatusInformation::LostBufferCount" // Read only. Gets the number of lost + // buffers during an acquisition + // session. +#define IMAQdxAttributeLostPacketCount \ + "StatusInformation::LostPacketCount" // Read only. Gets the number of lost + // packets during an acquisition + // session. +#define IMAQdxAttributeRequestedResendPackets \ + "StatusInformation::RequestedResendPacketCount" // Read only. Gets the number + // of packets requested to be + // resent during an + // acquisition session. +#define IMAQdxAttributeReceivedResendPackets \ + "StatusInformation::ReceivedResendPackets" // Read only. Gets the number of + // packets that were requested to + // be resent during an acquisition + // session and were completed. +#define IMAQdxAttributeHandledEventCount \ + "StatusInformation::HandledEventCount" // Read only. Gets the number of + // handled events during an + // acquisition session. +#define IMAQdxAttributeLostEventCount \ + "StatusInformation::LostEventCount" // Read only. Gets the number of lost + // events during an acquisition session. +#define IMAQdxAttributeBayerGainB \ + "AcquisitionAttributes::Bayer::GainB" // Sets/gets the white balance gain for + // the blue component of the Bayer + // conversion. +#define IMAQdxAttributeBayerGainG \ + "AcquisitionAttributes::Bayer::GainG" // Sets/gets the white balance gain for + // the green component of the Bayer + // conversion. +#define IMAQdxAttributeBayerGainR \ + "AcquisitionAttributes::Bayer::GainR" // Sets/gets the white balance gain for + // the red component of the Bayer + // conversion. +#define IMAQdxAttributeBayerPattern \ + "AcquisitionAttributes::Bayer::Pattern" // Sets/gets the Bayer pattern to + // use. +#define IMAQdxAttributeStreamChannelMode \ + "AcquisitionAttributes::Controller::StreamChannelMode" // Gets/sets the mode + // for allocating a + // FireWire stream + // channel. +#define IMAQdxAttributeDesiredStreamChannel \ + "AcquisitionAttributes::Controller::DesiredStreamChannel" // Gets/sets the + // stream channel + // to manually + // allocate. +#define IMAQdxAttributeFrameInterval \ + "AcquisitionAttributes::FrameInterval" // Read only. Gets the duration in + // milliseconds between successive + // frames. +#define IMAQdxAttributeIgnoreFirstFrame \ + "AcquisitionAttributes::IgnoreFirstFrame" // Gets/sets the video delay of one + // frame between starting the + // camera and receiving the video + // feed. +#define IMAQdxAttributeOffsetX \ + "OffsetX" // Gets/sets the left offset of the image. +#define IMAQdxAttributeOffsetY \ + "OffsetY" // Gets/sets the top offset of the image. +#define IMAQdxAttributeWidth "Width" // Gets/sets the width of the image. +#define IMAQdxAttributeHeight "Height" // Gets/sets the height of the image. +#define IMAQdxAttributePixelFormat \ + "PixelFormat" // Gets/sets the pixel format of the source sensor. +#define IMAQdxAttributePacketSize \ + "PacketSize" // Gets/sets the packet size in bytes. +#define IMAQdxAttributePayloadSize \ + "PayloadSize" // Gets/sets the frame size in bytes. +#define IMAQdxAttributeSpeed \ + "AcquisitionAttributes::Speed" // Gets/sets the transfer speed in Mbps for a + // FireWire packet. +#define IMAQdxAttributeShiftPixelBits \ + "AcquisitionAttributes::ShiftPixelBits" // Gets/sets the alignment of 16-bit + // cameras. Downshift the pixel bits + // if the camera returns most + // significant bit-aligned data. +#define IMAQdxAttributeSwapPixelBytes \ + "AcquisitionAttributes::SwapPixelBytes" // Gets/sets the endianness of 16-bit + // cameras. Swap the pixel bytes if + // the camera returns little endian + // data. +#define IMAQdxAttributeOverwriteMode \ + "AcquisitionAttributes::OverwriteMode" // Gets/sets the overwrite mode, used + // to determine acquisition when an + // image transfer cannot be completed + // due to an overwritten internal + // buffer. +#define IMAQdxAttributeTimeout \ + "AcquisitionAttributes::Timeout" // Gets/sets the timeout value in + // milliseconds, used to abort an + // acquisition when the image transfer + // cannot be completed within the delay. +#define IMAQdxAttributeVideoMode \ + "AcquisitionAttributes::VideoMode" // Gets/sets the video mode for a camera. +#define IMAQdxAttributeBitsPerPixel \ + "AcquisitionAttributes::BitsPerPixel" // Gets/sets the actual bits per pixel. + // For 16-bit components, this + // represents the actual bit depth + // (10-, 12-, 14-, or 16-bit). +#define IMAQdxAttributePixelSignedness \ + "AcquisitionAttributes::PixelSignedness" // Gets/sets the signedness of the + // pixel. For 16-bit components, + // this represents the actual pixel + // signedness (Signed, or Unsigned). +#define IMAQdxAttributeReserveDualPackets \ + "AcquisitionAttributes::ReserveDualPackets" // Gets/sets if dual packets will + // be reserved for a very large + // FireWire packet. +#define IMAQdxAttributeReceiveTimestampMode \ + "AcquisitionAttributes::ReceiveTimestampMode" // Gets/sets the mode for + // timestamping images received + // by the driver. +#define IMAQdxAttributeActualPeakBandwidth \ + "AcquisitionAttributes::AdvancedEthernet::BandwidthControl::" \ + "ActualPeakBandwidth" // Read only. Returns the actual maximum peak bandwidth + // the camera will be configured to use. +#define IMAQdxAttributeDesiredPeakBandwidth \ + "AcquisitionAttributes::AdvancedEthernet::BandwidthControl::" \ + "DesiredPeakBandwidth" // Gets/sets the desired maximum peak bandwidth the + // camera should use. +#define IMAQdxAttributeDestinationMode \ + "AcquisitionAttributes::AdvancedEthernet::Controller::DestinationMode" // Gets/Sets + // where + // the + // camera + // is + // instructed + // to + // send + // the + // image + // stream. +#define IMAQdxAttributeDestinationMulticastAddress \ + "AcquisitionAttributes::AdvancedEthernet::Controller::" \ + "DestinationMulticastAddress" // Gets/Sets the multicast address the camera + // should send data in multicast mode. +#define IMAQdxAttributeEventsEnabled \ + "AcquisitionAttributes::AdvancedEthernet::EventParameters::EventsEnabled" // Gets/Sets if events will be handled. +#define IMAQdxAttributeMaxOutstandingEvents \ + "AcquisitionAttributes::AdvancedEthernet::EventParameters::" \ + "MaxOutstandingEvents" // Gets/Sets the maximum number of outstanding events + // to queue. +#define IMAQdxAttributeTestPacketEnabled \ + "AcquisitionAttributes::AdvancedEthernet::TestPacketParameters::" \ + "TestPacketEnabled" // Gets/Sets whether the driver will validate the image + // streaming settings using test packets prior to an + // acquisition +#define IMAQdxAttributeTestPacketTimeout \ + "AcquisitionAttributes::AdvancedEthernet::TestPacketParameters::" \ + "TestPacketTimeout" // Gets/Sets the timeout for validating test packet + // reception (if enabled) +#define IMAQdxAttributeMaxTestPacketRetries \ + "AcquisitionAttributes::AdvancedEthernet::TestPacketParameters::" \ + "MaxTestPacketRetries" // Gets/Sets the number of retries for validating test + // packet reception (if enabled) +#define IMAQdxAttributeChunkDataDecodingEnabled \ + "AcquisitionAttributes::ChunkDataDecoding::ChunkDataDecodingEnabled" // Gets/Sets + // whether + // the + // driver + // will + // decode + // any + // chunk + // data + // in + // the + // image + // stream +#define IMAQdxAttributeChunkDataDecodingMaxElementSize \ + "AcquisitionAttributes::ChunkDataDecoding::MaximumChunkCopySize" // Gets/Sets + // the + // maximum + // size of + // any + // single + // chunk + // data + // element + // that will + // be made + // available +#define IMAQdxAttributeLostPacketMode \ + "AcquisitionAttributes::AdvancedEthernet::LostPacketMode" // Gets/sets the + // behavior when + // the user + // extracts a + // buffer that has + // missing packets. +#define IMAQdxAttributeMemoryWindowSize \ + "AcquisitionAttributes::AdvancedEthernet::ResendParameters::" \ + "MemoryWindowSize" // Gets/sets the size of the memory window of the camera + // in kilobytes. Should match the camera's internal buffer + // size. +#define IMAQdxAttributeResendsEnabled \ + "AcquisitionAttributes::AdvancedEthernet::ResendParameters::ResendsEnabled" // Gets/sets if resends will be issued for missing packets. +#define IMAQdxAttributeResendThresholdPercentage \ + "AcquisitionAttributes::AdvancedEthernet::ResendParameters::" \ + "ResendThresholdPercentage" // Gets/sets the threshold of the packet + // processing window that will trigger packets to + // be resent. +#define IMAQdxAttributeResendBatchingPercentage \ + "AcquisitionAttributes::AdvancedEthernet::ResendParameters::" \ + "ResendBatchingPercentage" // Gets/sets the percent of the packet resend + // threshold that will be issued as one group past + // the initial threshold sent in a single request. +#define IMAQdxAttributeMaxResendsPerPacket \ + "AcquisitionAttributes::AdvancedEthernet::ResendParameters::" \ + "MaxResendsPerPacket" // Gets/sets the maximum number of resend requests that + // will be issued for a missing packet. +#define IMAQdxAttributeResendResponseTimeout \ + "AcquisitionAttributes::AdvancedEthernet::ResendParameters::" \ + "ResendResponseTimeout" // Gets/sets the time to wait for a resend request to + // be satisfied before sending another. +#define IMAQdxAttributeNewPacketTimeout \ + "AcquisitionAttributes::AdvancedEthernet::ResendParameters::" \ + "NewPacketTimeout" // Gets/sets the time to wait for new packets to arrive in + // a partially completed image before assuming the rest of + // the image was lost. +#define IMAQdxAttributeMissingPacketTimeout \ + "AcquisitionAttributes::AdvancedEthernet::ResendParameters::" \ + "MissingPacketTimeout" // Gets/sets the time to wait for a missing packet + // before issuing a resend. +#define IMAQdxAttributeResendTimerResolution \ + "AcquisitionAttributes::AdvancedEthernet::ResendParameters::" \ + "ResendTimerResolution" // Gets/sets the resolution of the packet processing + // system that is used for all packet-related + // timeouts. //============================================================================== // Functions //============================================================================== IMAQdxError NI_FUNC IMAQdxSnap(IMAQdxSession id, Image* image); IMAQdxError NI_FUNC IMAQdxConfigureGrab(IMAQdxSession id); -IMAQdxError NI_FUNC IMAQdxGrab(IMAQdxSession id, Image* image, bool32 waitForNextBuffer, uInt32* actualBufferNumber); -IMAQdxError NI_FUNC IMAQdxSequence(IMAQdxSession id, Image* images[], uInt32 count); -IMAQdxError NI_FUNC IMAQdxDiscoverEthernetCameras(const char* address, uInt32 timeout); -IMAQdxError NI_FUNC IMAQdxEnumerateCameras(IMAQdxCameraInformation cameraInformationArray[], uInt32* count, bool32 connectedOnly); +IMAQdxError NI_FUNC IMAQdxGrab(IMAQdxSession id, Image* image, + bool32 waitForNextBuffer, + uInt32* actualBufferNumber); +IMAQdxError NI_FUNC +IMAQdxSequence(IMAQdxSession id, Image* images[], uInt32 count); +IMAQdxError NI_FUNC +IMAQdxDiscoverEthernetCameras(const char* address, uInt32 timeout); +IMAQdxError NI_FUNC +IMAQdxEnumerateCameras(IMAQdxCameraInformation cameraInformationArray[], + uInt32* count, bool32 connectedOnly); IMAQdxError NI_FUNC IMAQdxResetCamera(const char* name, bool32 resetAll); -IMAQdxError NI_FUNC IMAQdxOpenCamera(const char* name, IMAQdxCameraControlMode mode, IMAQdxSession* id); +IMAQdxError NI_FUNC IMAQdxOpenCamera(const char* name, + IMAQdxCameraControlMode mode, + IMAQdxSession* id); IMAQdxError NI_FUNC IMAQdxCloseCamera(IMAQdxSession id); -IMAQdxError NI_FUNC IMAQdxConfigureAcquisition(IMAQdxSession id, bool32 continuous, uInt32 bufferCount); +IMAQdxError NI_FUNC IMAQdxConfigureAcquisition(IMAQdxSession id, + bool32 continuous, + uInt32 bufferCount); IMAQdxError NI_FUNC IMAQdxStartAcquisition(IMAQdxSession id); -IMAQdxError NI_FUNC IMAQdxGetImage(IMAQdxSession id, Image* image, IMAQdxBufferNumberMode mode, uInt32 desiredBufferNumber, uInt32* actualBufferNumber); -IMAQdxError NI_FUNC IMAQdxGetImageData(IMAQdxSession id, void* buffer, uInt32 bufferSize, IMAQdxBufferNumberMode mode, uInt32 desiredBufferNumber, uInt32* actualBufferNumber); +IMAQdxError NI_FUNC +IMAQdxGetImage(IMAQdxSession id, Image* image, IMAQdxBufferNumberMode mode, + uInt32 desiredBufferNumber, uInt32* actualBufferNumber); +IMAQdxError NI_FUNC +IMAQdxGetImageData(IMAQdxSession id, void* buffer, uInt32 bufferSize, + IMAQdxBufferNumberMode mode, uInt32 desiredBufferNumber, + uInt32* actualBufferNumber); IMAQdxError NI_FUNC IMAQdxStopAcquisition(IMAQdxSession id); IMAQdxError NI_FUNC IMAQdxUnconfigureAcquisition(IMAQdxSession id); -IMAQdxError NI_FUNC IMAQdxEnumerateVideoModes(IMAQdxSession id, IMAQdxVideoMode videoModeArray[], uInt32* count, uInt32* currentMode); -IMAQdxError NI_FUNC IMAQdxEnumerateAttributes(IMAQdxSession id, IMAQdxAttributeInformation attributeInformationArray[], uInt32* count, const char* root); -IMAQdxError NI_FUNC IMAQdxGetAttribute(IMAQdxSession id, const char* name, IMAQdxValueType type, void* value); -IMAQdxError NI_FUNCC IMAQdxSetAttribute(IMAQdxSession id, const char* name, IMAQdxValueType type, ...); -IMAQdxError NI_FUNC IMAQdxGetAttributeMinimum(IMAQdxSession id, const char* name, IMAQdxValueType type, void* value); -IMAQdxError NI_FUNC IMAQdxGetAttributeMaximum(IMAQdxSession id, const char* name, IMAQdxValueType type, void* value); -IMAQdxError NI_FUNC IMAQdxGetAttributeIncrement(IMAQdxSession id, const char* name, IMAQdxValueType type, void* value); -IMAQdxError NI_FUNC IMAQdxGetAttributeType(IMAQdxSession id, const char* name, IMAQdxAttributeType* type); -IMAQdxError NI_FUNC IMAQdxIsAttributeReadable(IMAQdxSession id, const char* name, bool32* readable); -IMAQdxError NI_FUNC IMAQdxIsAttributeWritable(IMAQdxSession id, const char* name, bool32* writable); -IMAQdxError NI_FUNC IMAQdxEnumerateAttributeValues(IMAQdxSession id, const char* name, IMAQdxEnumItem list[], uInt32* size); -IMAQdxError NI_FUNC IMAQdxGetAttributeTooltip(IMAQdxSession id, const char* name, char* tooltip, uInt32 length); -IMAQdxError NI_FUNC IMAQdxGetAttributeUnits(IMAQdxSession id, const char* name, char* units, uInt32 length); -IMAQdxError NI_FUNC IMAQdxRegisterFrameDoneEvent(IMAQdxSession id, uInt32 bufferInterval, FrameDoneEventCallbackPtr callbackFunction, void* callbackData); -IMAQdxError NI_FUNC IMAQdxRegisterPnpEvent(IMAQdxSession id, IMAQdxPnpEvent event, PnpEventCallbackPtr callbackFunction, void* callbackData); -IMAQdxError NI_FUNC IMAQdxWriteRegister(IMAQdxSession id, uInt32 offset, uInt32 value); -IMAQdxError NI_FUNC IMAQdxReadRegister(IMAQdxSession id, uInt32 offset, uInt32* value); -IMAQdxError NI_FUNC IMAQdxWriteMemory(IMAQdxSession id, uInt32 offset, const char* values, uInt32 count); -IMAQdxError NI_FUNC IMAQdxReadMemory(IMAQdxSession id, uInt32 offset, char* values, uInt32 count); -IMAQdxError NI_FUNC IMAQdxGetErrorString(IMAQdxError error, char* message, uInt32 messageLength); -IMAQdxError NI_FUNC IMAQdxWriteAttributes(IMAQdxSession id, const char* filename); -IMAQdxError NI_FUNC IMAQdxReadAttributes(IMAQdxSession id, const char* filename); -IMAQdxError NI_FUNC IMAQdxResetEthernetCameraAddress(const char* name, const char* address, const char* subnet, const char* gateway, uInt32 timeout); -IMAQdxError NI_FUNC IMAQdxEnumerateAttributes2(IMAQdxSession id, IMAQdxAttributeInformation attributeInformationArray[], uInt32* count, const char* root, IMAQdxAttributeVisibility visibility); -IMAQdxError NI_FUNC IMAQdxGetAttributeVisibility(IMAQdxSession id, const char* name, IMAQdxAttributeVisibility* visibility); -IMAQdxError NI_FUNC IMAQdxGetAttributeDescription(IMAQdxSession id, const char* name, char* description, uInt32 length); -IMAQdxError NI_FUNC IMAQdxGetAttributeDisplayName(IMAQdxSession id, const char* name, char* displayName, uInt32 length); +IMAQdxError NI_FUNC +IMAQdxEnumerateVideoModes(IMAQdxSession id, IMAQdxVideoMode videoModeArray[], + uInt32* count, uInt32* currentMode); +IMAQdxError NI_FUNC IMAQdxEnumerateAttributes( + IMAQdxSession id, IMAQdxAttributeInformation attributeInformationArray[], + uInt32* count, const char* root); +IMAQdxError NI_FUNC IMAQdxGetAttribute(IMAQdxSession id, const char* name, + IMAQdxValueType type, void* value); +IMAQdxError NI_FUNCC IMAQdxSetAttribute(IMAQdxSession id, const char* name, + IMAQdxValueType type, ...); +IMAQdxError NI_FUNC +IMAQdxGetAttributeMinimum(IMAQdxSession id, const char* name, + IMAQdxValueType type, void* value); +IMAQdxError NI_FUNC +IMAQdxGetAttributeMaximum(IMAQdxSession id, const char* name, + IMAQdxValueType type, void* value); +IMAQdxError NI_FUNC +IMAQdxGetAttributeIncrement(IMAQdxSession id, const char* name, + IMAQdxValueType type, void* value); +IMAQdxError NI_FUNC IMAQdxGetAttributeType(IMAQdxSession id, const char* name, + IMAQdxAttributeType* type); +IMAQdxError NI_FUNC +IMAQdxIsAttributeReadable(IMAQdxSession id, const char* name, bool32* readable); +IMAQdxError NI_FUNC +IMAQdxIsAttributeWritable(IMAQdxSession id, const char* name, bool32* writable); +IMAQdxError NI_FUNC +IMAQdxEnumerateAttributeValues(IMAQdxSession id, const char* name, + IMAQdxEnumItem list[], uInt32* size); +IMAQdxError NI_FUNC IMAQdxGetAttributeTooltip(IMAQdxSession id, + const char* name, char* tooltip, + uInt32 length); +IMAQdxError NI_FUNC IMAQdxGetAttributeUnits(IMAQdxSession id, const char* name, + char* units, uInt32 length); +IMAQdxError NI_FUNC +IMAQdxRegisterFrameDoneEvent(IMAQdxSession id, uInt32 bufferInterval, + FrameDoneEventCallbackPtr callbackFunction, + void* callbackData); +IMAQdxError NI_FUNC IMAQdxRegisterPnpEvent(IMAQdxSession id, + IMAQdxPnpEvent event, + PnpEventCallbackPtr callbackFunction, + void* callbackData); +IMAQdxError NI_FUNC +IMAQdxWriteRegister(IMAQdxSession id, uInt32 offset, uInt32 value); +IMAQdxError NI_FUNC +IMAQdxReadRegister(IMAQdxSession id, uInt32 offset, uInt32* value); +IMAQdxError NI_FUNC IMAQdxWriteMemory(IMAQdxSession id, uInt32 offset, + const char* values, uInt32 count); +IMAQdxError NI_FUNC +IMAQdxReadMemory(IMAQdxSession id, uInt32 offset, char* values, uInt32 count); +IMAQdxError NI_FUNC +IMAQdxGetErrorString(IMAQdxError error, char* message, uInt32 messageLength); +IMAQdxError NI_FUNC +IMAQdxWriteAttributes(IMAQdxSession id, const char* filename); +IMAQdxError NI_FUNC +IMAQdxReadAttributes(IMAQdxSession id, const char* filename); +IMAQdxError NI_FUNC +IMAQdxResetEthernetCameraAddress(const char* name, const char* address, + const char* subnet, const char* gateway, + uInt32 timeout); +IMAQdxError NI_FUNC IMAQdxEnumerateAttributes2( + IMAQdxSession id, IMAQdxAttributeInformation attributeInformationArray[], + uInt32* count, const char* root, IMAQdxAttributeVisibility visibility); +IMAQdxError NI_FUNC +IMAQdxGetAttributeVisibility(IMAQdxSession id, const char* name, + IMAQdxAttributeVisibility* visibility); +IMAQdxError NI_FUNC +IMAQdxGetAttributeDescription(IMAQdxSession id, const char* name, + char* description, uInt32 length); +IMAQdxError NI_FUNC +IMAQdxGetAttributeDisplayName(IMAQdxSession id, const char* name, + char* displayName, uInt32 length); IMAQdxError NI_FUNC IMAQdxDispose(void* buffer); -IMAQdxError NI_FUNC IMAQdxRegisterAttributeUpdatedEvent(IMAQdxSession id, const char* name, AttributeUpdatedEventCallbackPtr callbackFunction, void* callbackData); -IMAQdxError NI_FUNC IMAQdxEnumerateAttributes3(IMAQdxSession id, IMAQdxAttributeInformation attributeInformationArray[], uInt32* count, const char* root, IMAQdxAttributeVisibility visibility); - +IMAQdxError NI_FUNC IMAQdxRegisterAttributeUpdatedEvent( + IMAQdxSession id, const char* name, + AttributeUpdatedEventCallbackPtr callbackFunction, void* callbackData); +IMAQdxError NI_FUNC IMAQdxEnumerateAttributes3( + IMAQdxSession id, IMAQdxAttributeInformation attributeInformationArray[], + uInt32* count, const char* root, IMAQdxAttributeVisibility visibility); #ifdef __cplusplus } #endif - -#endif // ___niimaqdx_h___ +#endif // ___niimaqdx_h___ diff --git a/wpilibc/wpilibC++Devices/include/NetworkCommunication/AICalibration.h b/wpilibc/wpilibC++Devices/include/NetworkCommunication/AICalibration.h index b2f366c5bd..4b459a19e8 100644 --- a/wpilibc/wpilibC++Devices/include/NetworkCommunication/AICalibration.h +++ b/wpilibc/wpilibC++Devices/include/NetworkCommunication/AICalibration.h @@ -5,15 +5,16 @@ #include #ifdef __cplusplus -extern "C" -{ +extern "C" { #endif - uint32_t FRC_NetworkCommunication_nAICalibration_getLSBWeight(const uint32_t aiSystemIndex, const uint32_t channel, int32_t *status); - int32_t FRC_NetworkCommunication_nAICalibration_getOffset(const uint32_t aiSystemIndex, const uint32_t channel, int32_t *status); +uint32_t FRC_NetworkCommunication_nAICalibration_getLSBWeight( + const uint32_t aiSystemIndex, const uint32_t channel, int32_t *status); +int32_t FRC_NetworkCommunication_nAICalibration_getOffset( + const uint32_t aiSystemIndex, const uint32_t channel, int32_t *status); #ifdef __cplusplus } #endif -#endif // __AICalibration_h__ +#endif // __AICalibration_h__ diff --git a/wpilibc/wpilibC++Devices/include/NetworkCommunication/CANInterfacePlugin.h b/wpilibc/wpilibC++Devices/include/NetworkCommunication/CANInterfacePlugin.h index 77d992cf24..1dd6404456 100644 --- a/wpilibc/wpilibC++Devices/include/NetworkCommunication/CANInterfacePlugin.h +++ b/wpilibc/wpilibC++Devices/include/NetworkCommunication/CANInterfacePlugin.h @@ -11,72 +11,99 @@ #include #define CAN_IS_FRAME_REMOTE 0x80000000 -#define CAN_IS_FRAME_11BIT 0x40000000 +#define CAN_IS_FRAME_11BIT 0x40000000 #define CAN_29BIT_MESSAGE_ID_MASK 0x1FFFFFFF #define CAN_11BIT_MESSAGE_ID_MASK 0x000007FF -class CANInterfacePlugin -{ -public: - CANInterfacePlugin() {} - virtual ~CANInterfacePlugin() {} +class CANInterfacePlugin { + public: + CANInterfacePlugin() {} + virtual ~CANInterfacePlugin() {} - /** - * This entry-point of the CANInterfacePlugin is passed a message that the driver needs to send to - * a device on the CAN bus. - * - * This function may be called from multiple contexts and must therefore be reentrant. - * - * @param messageID The 29-bit CAN message ID in the lsbs. The msb can indicate a remote frame. - * @param data A pointer to a buffer containing between 0 and 8 bytes to send with the message. May be NULL if dataSize is 0. - * @param dataSize The number of bytes to send with the message. - * @return Return any error code. On success return 0. - */ - virtual int32_t sendMessage(uint32_t messageID, const uint8_t *data, uint8_t dataSize) = 0; + /** + * This entry-point of the CANInterfacePlugin is passed a message that the + * driver needs to send to + * a device on the CAN bus. + * + * This function may be called from multiple contexts and must therefore be + * reentrant. + * + * @param messageID The 29-bit CAN message ID in the lsbs. The msb can + * indicate a remote frame. + * @param data A pointer to a buffer containing between 0 and 8 bytes to send + * with the message. May be NULL if dataSize is 0. + * @param dataSize The number of bytes to send with the message. + * @return Return any error code. On success return 0. + */ + virtual int32_t sendMessage(uint32_t messageID, const uint8_t *data, + uint8_t dataSize) = 0; - /** - * This entry-point of the CANInterfacePlugin is passed buffers which should be populated with - * any received messages from devices on the CAN bus. - * - * This function is always called by a single task in the Jaguar driver, so it need not be reentrant. - * - * This function is expected to block for some period of time waiting for a message from the CAN bus. - * It may timeout periodically (returning non-zero to indicate no message was populated) to allow for - * shutdown and unloading of the plugin. - * - * @param messageID A reference to be populated with a received 29-bit CAN message ID in the lsbs. - * @param data A pointer to a buffer of 8 bytes to be populated with data received with the message. - * @param dataSize A reference to be populated with the size of the data received (0 - 8 bytes). - * @return This should return 0 if a message was populated, non-0 if no message was not populated. - */ - virtual int32_t receiveMessage(uint32_t &messageID, uint8_t *data, uint8_t &dataSize) = 0; + /** + * This entry-point of the CANInterfacePlugin is passed buffers which should + * be populated with + * any received messages from devices on the CAN bus. + * + * This function is always called by a single task in the Jaguar driver, so it + * need not be reentrant. + * + * This function is expected to block for some period of time waiting for a + * message from the CAN bus. + * It may timeout periodically (returning non-zero to indicate no message was + * populated) to allow for + * shutdown and unloading of the plugin. + * + * @param messageID A reference to be populated with a received 29-bit CAN + * message ID in the lsbs. + * @param data A pointer to a buffer of 8 bytes to be populated with data + * received with the message. + * @param dataSize A reference to be populated with the size of the data + * received (0 - 8 bytes). + * @return This should return 0 if a message was populated, non-0 if no + * message was not populated. + */ + virtual int32_t receiveMessage(uint32_t &messageID, uint8_t *data, + uint8_t &dataSize) = 0; #if defined(__linux) - /** - * This entry-point of the CANInterfacePlugin returns status of the CAN bus. - * - * This function may be called from multiple contexts and must therefore be reentrant. - * - * This function will return detailed hardware status if available for diagnostics of the CAN interface. - * - * @param busOffCount The number of times that sendMessage failed with a busOff error indicating that messages - * are not successfully transmitted on the bus. - * @param txFullCount The number of times that sendMessage failed with a txFifoFull error indicating that messages - * are not successfully received by any CAN device. - * @param receiveErrorCount The count of receive errors as reported by the CAN driver. - * @param transmitErrorCount The count of transmit errors as reported by the CAN driver. - * @return This should return 0 if all status was retrieved successfully or an error code if not. - */ - virtual int32_t getStatus(uint32_t &busOffCount, uint32_t &txFullCount, uint32_t &receiveErrorCount, uint32_t &transmitErrorCount) {return 0;} + /** + * This entry-point of the CANInterfacePlugin returns status of the CAN bus. + * + * This function may be called from multiple contexts and must therefore be + * reentrant. + * + * This function will return detailed hardware status if available for + * diagnostics of the CAN interface. + * + * @param busOffCount The number of times that sendMessage failed with a + * busOff error indicating that messages + * are not successfully transmitted on the bus. + * @param txFullCount The number of times that sendMessage failed with a + * txFifoFull error indicating that messages + * are not successfully received by any CAN device. + * @param receiveErrorCount The count of receive errors as reported by the CAN + * driver. + * @param transmitErrorCount The count of transmit errors as reported by the + * CAN driver. + * @return This should return 0 if all status was retrieved successfully or an + * error code if not. + */ + virtual int32_t getStatus(uint32_t &busOffCount, uint32_t &txFullCount, + uint32_t &receiveErrorCount, + uint32_t &transmitErrorCount) { + return 0; + } #endif }; /** - * This function allows you to register a CANInterfacePlugin to provide access a CAN bus. - * - * @param interface A pointer to an object that inherits from CANInterfacePlugin and implements + * This function allows you to register a CANInterfacePlugin to provide access a + * CAN bus. + * + * @param interface A pointer to an object that inherits from CANInterfacePlugin + * and implements * the pure virtual interface. If NULL, unregister the current plugin. */ -void FRC_NetworkCommunication_CANSessionMux_registerInterface(CANInterfacePlugin* interface); +void FRC_NetworkCommunication_CANSessionMux_registerInterface( + CANInterfacePlugin *interface); -#endif // __CANInterfacePlugin_h__ +#endif // __CANInterfacePlugin_h__ diff --git a/wpilibc/wpilibC++Devices/include/NetworkCommunication/CANSessionMux.h b/wpilibc/wpilibC++Devices/include/NetworkCommunication/CANSessionMux.h index 3f8a6f192f..5ee4046adf 100644 --- a/wpilibc/wpilibC++Devices/include/NetworkCommunication/CANSessionMux.h +++ b/wpilibc/wpilibC++Devices/include/NetworkCommunication/CANSessionMux.h @@ -19,46 +19,67 @@ /* Flags in the upper bits of the messageID */ #define CAN_IS_FRAME_REMOTE 0x80000000 -#define CAN_IS_FRAME_11BIT 0x40000000 +#define CAN_IS_FRAME_11BIT 0x40000000 -#define ERR_CANSessionMux_InvalidBuffer -44086 +#define ERR_CANSessionMux_InvalidBuffer -44086 #define ERR_CANSessionMux_MessageNotFound -44087 -#define WARN_CANSessionMux_NoToken 44087 -#define ERR_CANSessionMux_NotAllowed -44088 -#define ERR_CANSessionMux_NotInitialized -44089 -#define ERR_CANSessionMux_SessionOverrun 44050 +#define WARN_CANSessionMux_NoToken 44087 +#define ERR_CANSessionMux_NotAllowed -44088 +#define ERR_CANSessionMux_NotInitialized -44089 +#define ERR_CANSessionMux_SessionOverrun 44050 -struct tCANStreamMessage{ - uint32_t messageID; - uint32_t timeStamp; - uint8_t data[8]; - uint8_t dataSize; +struct tCANStreamMessage { + uint32_t messageID; + uint32_t timeStamp; + uint8_t data[8]; + uint8_t dataSize; }; -namespace nCANSessionMux -{ - void sendMessage_wrapper(uint32_t messageID, const uint8_t *data, uint8_t dataSize, int32_t periodMs, int32_t *status); - void receiveMessage_wrapper(uint32_t *messageID, uint32_t messageIDMask, uint8_t *data, uint8_t *dataSize, uint32_t *timeStamp, int32_t *status); - void openStreamSession(uint32_t *sessionHandle, uint32_t messageID, uint32_t messageIDMask, uint32_t maxMessages, int32_t *status); - void closeStreamSession(uint32_t sessionHandle); - void readStreamSession(uint32_t sessionHandle, struct tCANStreamMessage *messages, uint32_t messagesToRead, uint32_t *messagesRead, int32_t *status); - void getCANStatus(float *percentBusUtilization, uint32_t *busOffCount, uint32_t *txFullCount, uint32_t *receiveErrorCount, uint32_t *transmitErrorCount, int32_t *status); +namespace nCANSessionMux { +void sendMessage_wrapper(uint32_t messageID, const uint8_t *data, + uint8_t dataSize, int32_t periodMs, int32_t *status); +void receiveMessage_wrapper(uint32_t *messageID, uint32_t messageIDMask, + uint8_t *data, uint8_t *dataSize, + uint32_t *timeStamp, int32_t *status); +void openStreamSession(uint32_t *sessionHandle, uint32_t messageID, + uint32_t messageIDMask, uint32_t maxMessages, + int32_t *status); +void closeStreamSession(uint32_t sessionHandle); +void readStreamSession(uint32_t sessionHandle, + struct tCANStreamMessage *messages, + uint32_t messagesToRead, uint32_t *messagesRead, + int32_t *status); +void getCANStatus(float *percentBusUtilization, uint32_t *busOffCount, + uint32_t *txFullCount, uint32_t *receiveErrorCount, + uint32_t *transmitErrorCount, int32_t *status); } #ifdef __cplusplus -extern "C" -{ +extern "C" { #endif - void FRC_NetworkCommunication_CANSessionMux_sendMessage(uint32_t messageID, const uint8_t *data, uint8_t dataSize, int32_t periodMs, int32_t *status); - void FRC_NetworkCommunication_CANSessionMux_receiveMessage(uint32_t *messageID, uint32_t messageIDMask, uint8_t *data, uint8_t *dataSize, uint32_t *timeStamp, int32_t *status); - void FRC_NetworkCommunication_CANSessionMux_openStreamSession(uint32_t *sessionHandle, uint32_t messageID, uint32_t messageIDMask, uint32_t maxMessages, int32_t *status); - void FRC_NetworkCommunication_CANSessionMux_closeStreamSession(uint32_t sessionHandle); - void FRC_NetworkCommunication_CANSessionMux_readStreamSession(uint32_t sessionHandle, struct tCANStreamMessage *messages, uint32_t messagesToRead, uint32_t *messagesRead, int32_t *status); - void FRC_NetworkCommunication_CANSessionMux_getCANStatus(float *percentBusUtilization, uint32_t *busOffCount, uint32_t *txFullCount, uint32_t *receiveErrorCount, uint32_t *transmitErrorCount, int32_t *status); +void FRC_NetworkCommunication_CANSessionMux_sendMessage(uint32_t messageID, + const uint8_t *data, + uint8_t dataSize, + int32_t periodMs, + int32_t *status); +void FRC_NetworkCommunication_CANSessionMux_receiveMessage( + uint32_t *messageID, uint32_t messageIDMask, uint8_t *data, + uint8_t *dataSize, uint32_t *timeStamp, int32_t *status); +void FRC_NetworkCommunication_CANSessionMux_openStreamSession( + uint32_t *sessionHandle, uint32_t messageID, uint32_t messageIDMask, + uint32_t maxMessages, int32_t *status); +void FRC_NetworkCommunication_CANSessionMux_closeStreamSession( + uint32_t sessionHandle); +void FRC_NetworkCommunication_CANSessionMux_readStreamSession( + uint32_t sessionHandle, struct tCANStreamMessage *messages, + uint32_t messagesToRead, uint32_t *messagesRead, int32_t *status); +void FRC_NetworkCommunication_CANSessionMux_getCANStatus( + float *percentBusUtilization, uint32_t *busOffCount, uint32_t *txFullCount, + uint32_t *receiveErrorCount, uint32_t *transmitErrorCount, int32_t *status); #ifdef __cplusplus } #endif -#endif // __CANSessionMux_h__ +#endif // __CANSessionMux_h__ diff --git a/wpilibc/wpilibC++Devices/include/NetworkCommunication/FRCComm.h b/wpilibc/wpilibC++Devices/include/NetworkCommunication/FRCComm.h index d7081365a5..d7eb65c45d 100644 --- a/wpilibc/wpilibC++Devices/include/NetworkCommunication/FRCComm.h +++ b/wpilibc/wpilibC++Devices/include/NetworkCommunication/FRCComm.h @@ -1,14 +1,14 @@ /************************************************************* * NOTICE - * + * * These are the only externally exposed functions to the * NetworkCommunication library - * + * * This is an implementation of FRC Spec for Comm Protocol * Revision 4.5, June 30, 2008 * * Copyright (c) National Instruments 2008. All Rights Reserved. - * + * *************************************************************/ #ifndef __FRC_COMM_H__ @@ -36,92 +36,112 @@ #define ERR_FRCSystem_NoDSConnection -44018 enum AllianceStationID_t { - kAllianceStationID_red1, - kAllianceStationID_red2, - kAllianceStationID_red3, - kAllianceStationID_blue1, - kAllianceStationID_blue2, - kAllianceStationID_blue3, + kAllianceStationID_red1, + kAllianceStationID_red2, + kAllianceStationID_red3, + kAllianceStationID_blue1, + kAllianceStationID_blue2, + kAllianceStationID_blue3, }; enum MatchType_t { - kMatchType_none, - kMatchType_practice, - kMatchType_qualification, - kMatchType_elimination, + kMatchType_none, + kMatchType_practice, + kMatchType_qualification, + kMatchType_elimination, }; struct ControlWord_t { #ifndef __vxworks - uint32_t enabled : 1; - uint32_t autonomous : 1; - uint32_t test :1; - uint32_t eStop : 1; - uint32_t fmsAttached:1; - uint32_t dsAttached:1; - uint32_t control_reserved : 26; + uint32_t enabled : 1; + uint32_t autonomous : 1; + uint32_t test : 1; + uint32_t eStop : 1; + uint32_t fmsAttached : 1; + uint32_t dsAttached : 1; + uint32_t control_reserved : 26; #else - uint32_t control_reserved : 26; - uint32_t dsAttached:1; - uint32_t fmsAttached:1; - uint32_t eStop : 1; - uint32_t test :1; - uint32_t autonomous : 1; - uint32_t enabled : 1; + uint32_t control_reserved : 26; + uint32_t dsAttached : 1; + uint32_t fmsAttached : 1; + uint32_t eStop : 1; + uint32_t test : 1; + uint32_t autonomous : 1; + uint32_t enabled : 1; #endif }; struct JoystickAxes_t { - uint16_t count; - int16_t axes[1]; + uint16_t count; + int16_t axes[1]; }; struct JoystickPOV_t { - uint16_t count; - int16_t povs[1]; + uint16_t count; + int16_t povs[1]; }; #ifdef __cplusplus extern "C" { #endif - int EXPORT_FUNC FRC_NetworkCommunication_Reserve(void *instance); +int EXPORT_FUNC FRC_NetworkCommunication_Reserve(void *instance); #ifndef SIMULATION - void EXPORT_FUNC getFPGAHardwareVersion(uint16_t *fpgaVersion, uint32_t *fpgaRevision); +void EXPORT_FUNC +getFPGAHardwareVersion(uint16_t *fpgaVersion, uint32_t *fpgaRevision); #endif - int EXPORT_FUNC setStatusData(float battery, uint8_t dsDigitalOut, uint8_t updateNumber, - const char *userDataHigh, int userDataHighLength, - const char *userDataLow, int userDataLowLength, int wait_ms); - int EXPORT_FUNC setErrorData(const char *errors, int errorsLength, int wait_ms); - +int EXPORT_FUNC setStatusData(float battery, uint8_t dsDigitalOut, + uint8_t updateNumber, const char *userDataHigh, + int userDataHighLength, const char *userDataLow, + int userDataLowLength, int wait_ms); +int EXPORT_FUNC setErrorData(const char *errors, int errorsLength, int wait_ms); + #ifdef SIMULATION - void EXPORT_FUNC setNewDataSem(HANDLE); +void EXPORT_FUNC setNewDataSem(HANDLE); #else -# if defined (__vxworks) - void EXPORT_FUNC setNewDataSem(SEM_ID); -# else - void EXPORT_FUNC setNewDataSem(pthread_cond_t *); -# endif +#if defined(__vxworks) +void EXPORT_FUNC setNewDataSem(SEM_ID); +#else +void EXPORT_FUNC setNewDataSem(pthread_cond_t *); +#endif #endif - // this uint32_t is really a LVRefNum - int EXPORT_FUNC setNewDataOccurRef(uint32_t refnum); +// this uint32_t is really a LVRefNum +int EXPORT_FUNC setNewDataOccurRef(uint32_t refnum); - int EXPORT_FUNC FRC_NetworkCommunication_getControlWord(struct ControlWord_t *controlWord); - int EXPORT_FUNC FRC_NetworkCommunication_getAllianceStation(enum AllianceStationID_t *allianceStation); - int EXPORT_FUNC FRC_NetworkCommunication_getMatchTime(float *matchTime); - int EXPORT_FUNC FRC_NetworkCommunication_getJoystickAxes(uint8_t joystickNum, struct JoystickAxes_t *axes, uint8_t maxAxes); - int EXPORT_FUNC FRC_NetworkCommunication_getJoystickButtons(uint8_t joystickNum, uint32_t *buttons, uint8_t *count); - int EXPORT_FUNC FRC_NetworkCommunication_getJoystickPOVs(uint8_t joystickNum, struct JoystickPOV_t *povs, uint8_t maxPOVs); - int EXPORT_FUNC FRC_NetworkCommunication_setJoystickOutputs(uint8_t joystickNum, uint32_t hidOutputs, uint16_t leftRumble, uint16_t rightRumble); - int EXPORT_FUNC FRC_NetworkCommunication_getJoystickDesc(uint8_t joystickNum, uint8_t *isXBox, uint8_t *type, char *name, - uint8_t *axisCount, uint8_t *axisTypes, uint8_t *buttonCount, uint8_t *povCount); +int EXPORT_FUNC +FRC_NetworkCommunication_getControlWord(struct ControlWord_t *controlWord); +int EXPORT_FUNC FRC_NetworkCommunication_getAllianceStation( + enum AllianceStationID_t *allianceStation); +int EXPORT_FUNC FRC_NetworkCommunication_getMatchTime(float *matchTime); +int EXPORT_FUNC +FRC_NetworkCommunication_getJoystickAxes(uint8_t joystickNum, + struct JoystickAxes_t *axes, + uint8_t maxAxes); +int EXPORT_FUNC FRC_NetworkCommunication_getJoystickButtons(uint8_t joystickNum, + uint32_t *buttons, + uint8_t *count); +int EXPORT_FUNC +FRC_NetworkCommunication_getJoystickPOVs(uint8_t joystickNum, + struct JoystickPOV_t *povs, + uint8_t maxPOVs); +int EXPORT_FUNC +FRC_NetworkCommunication_setJoystickOutputs(uint8_t joystickNum, + uint32_t hidOutputs, + uint16_t leftRumble, + uint16_t rightRumble); +int EXPORT_FUNC +FRC_NetworkCommunication_getJoystickDesc(uint8_t joystickNum, uint8_t *isXBox, + uint8_t *type, char *name, + uint8_t *axisCount, uint8_t *axisTypes, + uint8_t *buttonCount, + uint8_t *povCount); - void EXPORT_FUNC FRC_NetworkCommunication_getVersionString(char *version); - int EXPORT_FUNC FRC_NetworkCommunication_observeUserProgramStarting(void); - void EXPORT_FUNC FRC_NetworkCommunication_observeUserProgramDisabled(void); - void EXPORT_FUNC FRC_NetworkCommunication_observeUserProgramAutonomous(void); - void EXPORT_FUNC FRC_NetworkCommunication_observeUserProgramTeleop(void); - void EXPORT_FUNC FRC_NetworkCommunication_observeUserProgramTest(void); +void EXPORT_FUNC FRC_NetworkCommunication_getVersionString(char *version); +int EXPORT_FUNC FRC_NetworkCommunication_observeUserProgramStarting(void); +void EXPORT_FUNC FRC_NetworkCommunication_observeUserProgramDisabled(void); +void EXPORT_FUNC FRC_NetworkCommunication_observeUserProgramAutonomous(void); +void EXPORT_FUNC FRC_NetworkCommunication_observeUserProgramTeleop(void); +void EXPORT_FUNC FRC_NetworkCommunication_observeUserProgramTest(void); #ifdef __cplusplus } #endif diff --git a/wpilibc/wpilibC++Devices/include/NetworkCommunication/LoadOut.h b/wpilibc/wpilibC++Devices/include/NetworkCommunication/LoadOut.h index fce88a28e2..c9dad8bcc6 100644 --- a/wpilibc/wpilibC++Devices/include/NetworkCommunication/LoadOut.h +++ b/wpilibc/wpilibC++Devices/include/NetworkCommunication/LoadOut.h @@ -5,7 +5,7 @@ #ifdef SIMULATION #include #define EXPORT_FUNC __declspec(dllexport) __cdecl -#elif defined (__vxworks) +#elif defined(__vxworks) #include #define EXPORT_FUNC #else @@ -14,32 +14,32 @@ #endif #define kMaxModuleNumber 2 -namespace nLoadOut -{ +namespace nLoadOut { #if defined(__vxworks) || defined(SIMULATION) - typedef enum { - kModuleType_Unknown = 0x00, - kModuleType_Analog = 0x01, - kModuleType_Digital = 0x02, - kModuleType_Solenoid = 0x03, - } tModuleType; - bool EXPORT_FUNC getModulePresence(tModuleType moduleType, uint8_t moduleNumber); +typedef enum { + kModuleType_Unknown = 0x00, + kModuleType_Analog = 0x01, + kModuleType_Digital = 0x02, + kModuleType_Solenoid = 0x03, +} tModuleType; +bool EXPORT_FUNC +getModulePresence(tModuleType moduleType, uint8_t moduleNumber); #endif - typedef enum { - kTargetClass_Unknown = 0x00, - kTargetClass_FRC1 = 0x10, - kTargetClass_FRC2 = 0x20, - kTargetClass_FRC3 = 0x30, - kTargetClass_RoboRIO = 0x40, +typedef enum { + kTargetClass_Unknown = 0x00, + kTargetClass_FRC1 = 0x10, + kTargetClass_FRC2 = 0x20, + kTargetClass_FRC3 = 0x30, + kTargetClass_RoboRIO = 0x40, #if defined(__vxworks) || defined(SIMULATION) - kTargetClass_FRC2_Analog = kTargetClass_FRC2 | kModuleType_Analog, - kTargetClass_FRC2_Digital = kTargetClass_FRC2 | kModuleType_Digital, - kTargetClass_FRC2_Solenoid = kTargetClass_FRC2 | kModuleType_Solenoid, + kTargetClass_FRC2_Analog = kTargetClass_FRC2 | kModuleType_Analog, + kTargetClass_FRC2_Digital = kTargetClass_FRC2 | kModuleType_Digital, + kTargetClass_FRC2_Solenoid = kTargetClass_FRC2 | kModuleType_Solenoid, #endif - kTargetClass_FamilyMask = 0xF0, - kTargetClass_ModuleMask = 0x0F, - } tTargetClass; - tTargetClass EXPORT_FUNC getTargetClass(); + kTargetClass_FamilyMask = 0xF0, + kTargetClass_ModuleMask = 0x0F, +} tTargetClass; +tTargetClass EXPORT_FUNC getTargetClass(); } #ifdef __cplusplus @@ -47,12 +47,14 @@ extern "C" { #endif #if defined(__vxworks) || defined(SIMULATION) - uint32_t EXPORT_FUNC FRC_NetworkCommunication_nLoadOut_getModulePresence(uint32_t moduleType, uint8_t moduleNumber); +uint32_t EXPORT_FUNC +FRC_NetworkCommunication_nLoadOut_getModulePresence(uint32_t moduleType, + uint8_t moduleNumber); #endif - uint32_t EXPORT_FUNC FRC_NetworkCommunication_nLoadOut_getTargetClass(); +uint32_t EXPORT_FUNC FRC_NetworkCommunication_nLoadOut_getTargetClass(); #ifdef __cplusplus } #endif -#endif // __LoadOut_h__ +#endif // __LoadOut_h__ diff --git a/wpilibc/wpilibC++Devices/include/NetworkCommunication/UsageReporting.h b/wpilibc/wpilibC++Devices/include/NetworkCommunication/UsageReporting.h index 0ec2a3a4ea..ca73a2fbf2 100644 --- a/wpilibc/wpilibC++Devices/include/NetworkCommunication/UsageReporting.h +++ b/wpilibc/wpilibC++Devices/include/NetworkCommunication/UsageReporting.h @@ -5,7 +5,7 @@ #ifdef SIMULATION #include #define EXPORT_FUNC __declspec(dllexport) __cdecl -#elif defined (__vxworks) +#elif defined(__vxworks) #include #define EXPORT_FUNC #else @@ -16,128 +16,133 @@ #define kUsageReporting_version 1 -namespace nUsageReporting -{ - typedef enum - { - kResourceType_Controller, - kResourceType_Module, - kResourceType_Language, - kResourceType_CANPlugin, - kResourceType_Accelerometer, - kResourceType_ADXL345, - kResourceType_AnalogChannel, - kResourceType_AnalogTrigger, - kResourceType_AnalogTriggerOutput, - kResourceType_CANJaguar, - kResourceType_Compressor, - kResourceType_Counter, - kResourceType_Dashboard, - kResourceType_DigitalInput, - kResourceType_DigitalOutput, - kResourceType_DriverStationCIO, - kResourceType_DriverStationEIO, - kResourceType_DriverStationLCD, - kResourceType_Encoder, - kResourceType_GearTooth, - kResourceType_Gyro, - kResourceType_I2C, - kResourceType_Framework, - kResourceType_Jaguar, - kResourceType_Joystick, - kResourceType_Kinect, - kResourceType_KinectStick, - kResourceType_PIDController, - kResourceType_Preferences, - kResourceType_PWM, - kResourceType_Relay, - kResourceType_RobotDrive, - kResourceType_SerialPort, - kResourceType_Servo, - kResourceType_Solenoid, - kResourceType_SPI, - kResourceType_Task, - kResourceType_Ultrasonic, - kResourceType_Victor, - kResourceType_Button, - kResourceType_Command, - kResourceType_AxisCamera, - kResourceType_PCVideoServer, - kResourceType_SmartDashboard, - kResourceType_Talon, - kResourceType_HiTechnicColorSensor, - kResourceType_HiTechnicAccel, - kResourceType_HiTechnicCompass, - kResourceType_SRF08, - kResourceType_AnalogOutput, - kResourceType_VictorSP, - kResourceType_TalonSRX, - kResourceType_CANTalonSRX, - } tResourceType; +namespace nUsageReporting { +typedef enum { + kResourceType_Controller, + kResourceType_Module, + kResourceType_Language, + kResourceType_CANPlugin, + kResourceType_Accelerometer, + kResourceType_ADXL345, + kResourceType_AnalogChannel, + kResourceType_AnalogTrigger, + kResourceType_AnalogTriggerOutput, + kResourceType_CANJaguar, + kResourceType_Compressor, + kResourceType_Counter, + kResourceType_Dashboard, + kResourceType_DigitalInput, + kResourceType_DigitalOutput, + kResourceType_DriverStationCIO, + kResourceType_DriverStationEIO, + kResourceType_DriverStationLCD, + kResourceType_Encoder, + kResourceType_GearTooth, + kResourceType_Gyro, + kResourceType_I2C, + kResourceType_Framework, + kResourceType_Jaguar, + kResourceType_Joystick, + kResourceType_Kinect, + kResourceType_KinectStick, + kResourceType_PIDController, + kResourceType_Preferences, + kResourceType_PWM, + kResourceType_Relay, + kResourceType_RobotDrive, + kResourceType_SerialPort, + kResourceType_Servo, + kResourceType_Solenoid, + kResourceType_SPI, + kResourceType_Task, + kResourceType_Ultrasonic, + kResourceType_Victor, + kResourceType_Button, + kResourceType_Command, + kResourceType_AxisCamera, + kResourceType_PCVideoServer, + kResourceType_SmartDashboard, + kResourceType_Talon, + kResourceType_HiTechnicColorSensor, + kResourceType_HiTechnicAccel, + kResourceType_HiTechnicCompass, + kResourceType_SRF08, + kResourceType_AnalogOutput, + kResourceType_VictorSP, + kResourceType_TalonSRX, + kResourceType_CANTalonSRX, +} tResourceType; - typedef enum - { - kLanguage_LabVIEW = 1, - kLanguage_CPlusPlus = 2, - kLanguage_Java = 3, - kLanguage_Python = 4, +typedef enum { + kLanguage_LabVIEW = 1, + kLanguage_CPlusPlus = 2, + kLanguage_Java = 3, + kLanguage_Python = 4, - kCANPlugin_BlackJagBridge = 1, - kCANPlugin_2CAN = 2, + kCANPlugin_BlackJagBridge = 1, + kCANPlugin_2CAN = 2, - kFramework_Iterative = 1, - kFramework_Simple = 2, + kFramework_Iterative = 1, + kFramework_Simple = 2, - kRobotDrive_ArcadeStandard = 1, - kRobotDrive_ArcadeButtonSpin = 2, - kRobotDrive_ArcadeRatioCurve = 3, - kRobotDrive_Tank = 4, - kRobotDrive_MecanumPolar = 5, - kRobotDrive_MecanumCartesian = 6, + kRobotDrive_ArcadeStandard = 1, + kRobotDrive_ArcadeButtonSpin = 2, + kRobotDrive_ArcadeRatioCurve = 3, + kRobotDrive_Tank = 4, + kRobotDrive_MecanumPolar = 5, + kRobotDrive_MecanumCartesian = 6, - kDriverStationCIO_Analog = 1, - kDriverStationCIO_DigitalIn = 2, - kDriverStationCIO_DigitalOut = 3, + kDriverStationCIO_Analog = 1, + kDriverStationCIO_DigitalIn = 2, + kDriverStationCIO_DigitalOut = 3, - kDriverStationEIO_Acceleration = 1, - kDriverStationEIO_AnalogIn = 2, - kDriverStationEIO_AnalogOut = 3, - kDriverStationEIO_Button = 4, - kDriverStationEIO_LED = 5, - kDriverStationEIO_DigitalIn = 6, - kDriverStationEIO_DigitalOut = 7, - kDriverStationEIO_FixedDigitalOut = 8, - kDriverStationEIO_PWM = 9, - kDriverStationEIO_Encoder = 10, - kDriverStationEIO_TouchSlider = 11, + kDriverStationEIO_Acceleration = 1, + kDriverStationEIO_AnalogIn = 2, + kDriverStationEIO_AnalogOut = 3, + kDriverStationEIO_Button = 4, + kDriverStationEIO_LED = 5, + kDriverStationEIO_DigitalIn = 6, + kDriverStationEIO_DigitalOut = 7, + kDriverStationEIO_FixedDigitalOut = 8, + kDriverStationEIO_PWM = 9, + kDriverStationEIO_Encoder = 10, + kDriverStationEIO_TouchSlider = 11, - kADXL345_SPI = 1, - kADXL345_I2C = 2, + kADXL345_SPI = 1, + kADXL345_I2C = 2, - kCommand_Scheduler = 1, + kCommand_Scheduler = 1, - kSmartDashboard_Instance = 1, - } tInstances; + kSmartDashboard_Instance = 1, +} tInstances; - /** - * Report the usage of a resource of interest. - * - * @param resource one of the values in the tResourceType above (max value 51). - * @param instanceNumber an index that identifies the resource instance. - * @param context an optional additional context number for some cases (such as module number). Set to 0 to omit. - * @param feature a string to be included describing features in use on a specific resource. Setting the same resource more than once allows you to change the feature string. - */ - uint32_t EXPORT_FUNC report(tResourceType resource, uint8_t instanceNumber, uint8_t context = 0, const char *feature = NULL); +/** + * Report the usage of a resource of interest. + * + * @param resource one of the values in the tResourceType above (max value 51). + * @param instanceNumber an index that identifies the resource instance. + * @param context an optional additional context number for some cases (such as + * module number). Set to 0 to omit. + * @param feature a string to be included describing features in use on a + * specific resource. Setting the same resource more than once allows you to + * change the feature string. + */ +uint32_t EXPORT_FUNC report(tResourceType resource, uint8_t instanceNumber, + uint8_t context = 0, const char *feature = NULL); } #ifdef __cplusplus extern "C" { #endif - uint32_t EXPORT_FUNC FRC_NetworkCommunication_nUsageReporting_report(uint8_t resource, uint8_t instanceNumber, uint8_t context, const char *feature); +uint32_t EXPORT_FUNC +FRC_NetworkCommunication_nUsageReporting_report(uint8_t resource, + uint8_t instanceNumber, + uint8_t context, + const char *feature); #ifdef __cplusplus } #endif -#endif // __UsageReporting_h__ +#endif // __UsageReporting_h__ diff --git a/wpilibc/wpilibC++Devices/include/NetworkCommunication/symModuleLink.h b/wpilibc/wpilibC++Devices/include/NetworkCommunication/symModuleLink.h index 00867a52a4..621cbb6dc6 100644 --- a/wpilibc/wpilibC++Devices/include/NetworkCommunication/symModuleLink.h +++ b/wpilibc/wpilibC++Devices/include/NetworkCommunication/symModuleLink.h @@ -7,10 +7,9 @@ extern "C" { #endif -extern STATUS moduleNameFindBySymbolName - ( - const char * symbol, /* symbol name to look for */ - char * module /* where to return module name */ +extern STATUS moduleNameFindBySymbolName( + const char* symbol, /* symbol name to look for */ + char* module /* where to return module name */ ); #ifdef __cplusplus @@ -18,4 +17,3 @@ extern STATUS moduleNameFindBySymbolName #endif #endif - diff --git a/wpilibc/wpilibC++Devices/include/PWM.h b/wpilibc/wpilibC++Devices/include/PWM.h index 8c25d958fa..565f515e64 100644 --- a/wpilibc/wpilibC++Devices/include/PWM.h +++ b/wpilibc/wpilibC++Devices/include/PWM.h @@ -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,12 +13,14 @@ /** * Class implements the PWM generation in the FPGA. * - * The values supplied as arguments for PWM outputs range from -1.0 to 1.0. They are mapped + * The values supplied as arguments for PWM outputs range from -1.0 to 1.0. They + * are mapped * to the hardware dependent values, in this case 0-2000 for the FPGA. * Changes are immediately sent to the FPGA, and the update occurs at the next * FPGA cycle. There is no delay. * - * As of revision 0.1.10 of the FPGA, the FPGA interprets the 0-2000 values as follows: + * As of revision 0.1.10 of the FPGA, the FPGA interprets the 0-2000 values as + * follows: * - 2000 = maximum pulse width * - 1999 to 1001 = linear scaling from "full forward" to "center" * - 1000 = center value @@ -25,114 +28,105 @@ * - 1 = minimum pulse width (currently .5ms) * - 0 = disabled (i.e. PWM output is held low) */ -class PWM : public SensorBase, public ITableListener, public LiveWindowSendable -{ -public: - enum PeriodMultiplier - { - kPeriodMultiplier_1X = 1, - kPeriodMultiplier_2X = 2, - kPeriodMultiplier_4X = 4 - }; +class PWM : public SensorBase, + public ITableListener, + public LiveWindowSendable { + public: + enum PeriodMultiplier { + kPeriodMultiplier_1X = 1, + kPeriodMultiplier_2X = 2, + kPeriodMultiplier_4X = 4 + }; - explicit PWM(uint32_t channel); - virtual ~PWM(); - virtual void SetRaw(unsigned short value); - virtual unsigned short GetRaw() const; - void SetPeriodMultiplier(PeriodMultiplier mult); - void SetZeroLatch(); - void EnableDeadbandElimination(bool eliminateDeadband); - void SetBounds(int32_t max, int32_t deadbandMax, int32_t center, int32_t deadbandMin, - int32_t min); - void SetBounds(double max, double deadbandMax, double center, double deadbandMin, double min); - uint32_t GetChannel() const - { - return m_channel; - } + explicit PWM(uint32_t channel); + virtual ~PWM(); + virtual void SetRaw(unsigned short value); + virtual unsigned short GetRaw() const; + void SetPeriodMultiplier(PeriodMultiplier mult); + void SetZeroLatch(); + void EnableDeadbandElimination(bool eliminateDeadband); + void SetBounds(int32_t max, int32_t deadbandMax, int32_t center, + int32_t deadbandMin, int32_t min); + void SetBounds(double max, double deadbandMax, double center, + double deadbandMin, double min); + uint32_t GetChannel() const { return m_channel; } -protected: - /** - * kDefaultPwmPeriod is in ms - * - * - 20ms periods (50 Hz) are the "safest" setting in that this works for all devices - * - 20ms periods seem to be desirable for Vex Motors - * - 20ms periods are the specified period for HS-322HD servos, but work reliably down - * to 10.0 ms; starting at about 8.5ms, the servo sometimes hums and get hot; - * by 5.0ms the hum is nearly continuous - * - 10ms periods work well for Victor 884 - * - 5ms periods allows higher update rates for Luminary Micro Jaguar speed controllers. - * Due to the shipping firmware on the Jaguar, we can't run the update period less - * than 5.05 ms. - * - * kDefaultPwmPeriod is the 1x period (5.05 ms). In hardware, the period scaling is implemented as an - * output squelch to get longer periods for old devices. - */ - static constexpr float kDefaultPwmPeriod = 5.05; - /** - * kDefaultPwmCenter is the PWM range center in ms - */ - static constexpr float kDefaultPwmCenter = 1.5; - /** - * kDefaultPWMStepsDown is the number of PWM steps below the centerpoint - */ - static const int32_t kDefaultPwmStepsDown = 1000; - static const int32_t kPwmDisabled = 0; + protected: + /** + * kDefaultPwmPeriod is in ms + * + * - 20ms periods (50 Hz) are the "safest" setting in that this works for all + * devices + * - 20ms periods seem to be desirable for Vex Motors + * - 20ms periods are the specified period for HS-322HD servos, but work + * reliably down + * to 10.0 ms; starting at about 8.5ms, the servo sometimes hums and get + *hot; + * by 5.0ms the hum is nearly continuous + * - 10ms periods work well for Victor 884 + * - 5ms periods allows higher update rates for Luminary Micro Jaguar speed + * controllers. + * Due to the shipping firmware on the Jaguar, we can't run the update + * period less + * than 5.05 ms. + * + * kDefaultPwmPeriod is the 1x period (5.05 ms). In hardware, the period + * scaling is implemented as an + * output squelch to get longer periods for old devices. + */ + static constexpr float kDefaultPwmPeriod = 5.05; + /** + * kDefaultPwmCenter is the PWM range center in ms + */ + static constexpr float kDefaultPwmCenter = 1.5; + /** + * kDefaultPWMStepsDown is the number of PWM steps below the centerpoint + */ + static const int32_t kDefaultPwmStepsDown = 1000; + static const int32_t kPwmDisabled = 0; - virtual void SetPosition(float pos); - virtual float GetPosition() const; - virtual void SetSpeed(float speed); - virtual float GetSpeed() const; + virtual void SetPosition(float pos); + virtual float GetPosition() const; + virtual void SetSpeed(float speed); + virtual float GetSpeed() const; - bool m_eliminateDeadband; - int32_t m_maxPwm; - int32_t m_deadbandMaxPwm; - int32_t m_centerPwm; - int32_t m_deadbandMinPwm; - int32_t m_minPwm; + bool m_eliminateDeadband; + int32_t m_maxPwm; + int32_t m_deadbandMaxPwm; + int32_t m_centerPwm; + int32_t m_deadbandMinPwm; + int32_t m_minPwm; - 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; - ITable *m_table; + ITable* m_table; -private: - void InitPWM(uint32_t channel); - uint32_t m_channel; - int32_t GetMaxPositivePwm() const - { - return m_maxPwm; - } - int32_t GetMinPositivePwm() const - { - return m_eliminateDeadband ? m_deadbandMaxPwm : m_centerPwm + 1; - } - int32_t GetCenterPwm() const - { - return m_centerPwm; - } - int32_t GetMaxNegativePwm() const - { - return m_eliminateDeadband ? m_deadbandMinPwm : m_centerPwm - 1; - } - int32_t GetMinNegativePwm() const - { - return m_minPwm; - } - int32_t GetPositiveScaleFactor() const - { - return GetMaxPositivePwm() - GetMinPositivePwm(); - } ///< The scale for positive speeds. - int32_t GetNegativeScaleFactor() const - { - return GetMaxNegativePwm() - GetMinNegativePwm(); - } ///< The scale for negative speeds. - int32_t GetFullRangeScaleFactor() const - { - return GetMaxPositivePwm() - GetMinNegativePwm(); - } ///< The scale for positions. + private: + void InitPWM(uint32_t channel); + uint32_t m_channel; + int32_t GetMaxPositivePwm() const { return m_maxPwm; } + int32_t GetMinPositivePwm() const { + return m_eliminateDeadband ? m_deadbandMaxPwm : m_centerPwm + 1; + } + int32_t GetCenterPwm() const { return m_centerPwm; } + int32_t GetMaxNegativePwm() const { + return m_eliminateDeadband ? m_deadbandMinPwm : m_centerPwm - 1; + } + int32_t GetMinNegativePwm() const { return m_minPwm; } + int32_t GetPositiveScaleFactor() const { + return GetMaxPositivePwm() - GetMinPositivePwm(); + } ///< The scale for positive speeds. + int32_t GetNegativeScaleFactor() const { + return GetMaxNegativePwm() - GetMinNegativePwm(); + } ///< The scale for negative speeds. + int32_t GetFullRangeScaleFactor() const { + return GetMaxPositivePwm() - GetMinNegativePwm(); + } ///< The scale for positions. }; diff --git a/wpilibc/wpilibC++Devices/include/PowerDistributionPanel.h b/wpilibc/wpilibC++Devices/include/PowerDistributionPanel.h index 0737ca1edd..bfa9eae1f4 100644 --- a/wpilibc/wpilibC++Devices/include/PowerDistributionPanel.h +++ b/wpilibc/wpilibC++Devices/include/PowerDistributionPanel.h @@ -1,5 +1,6 @@ /*----------------------------------------------------------------------------*/ -/* Copyright (c) FIRST 2014. All Rights Reserved. */ +/* Copyright (c) FIRST 2014. 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,35 @@ #include "LiveWindow/LiveWindowSendable.h" /** - * Class for getting voltage, current, temperature, power and energy from the CAN PDP. + * Class for getting voltage, current, temperature, power and energy from the + * CAN PDP. * The PDP must be at CAN Address 0. * @author Thomas Clark */ class PowerDistributionPanel : public SensorBase, public LiveWindowSendable { - public: - PowerDistributionPanel(); - PowerDistributionPanel(uint8_t module); - - double GetVoltage() const; - double GetTemperature() const; - double GetCurrent(uint8_t channel) const; - double GetTotalCurrent() const; - double GetTotalPower() const; - double GetTotalEnergy() const; - void ResetTotalEnergy(); - void ClearStickyFaults(); + public: + PowerDistributionPanel(); + PowerDistributionPanel(uint8_t module); - void UpdateTable() override; - void StartLiveWindowMode() override; - void StopLiveWindowMode() override; - std::string GetSmartDashboardType() const override; - void InitTable(ITable *subTable) override; - ITable * GetTable() const override; + double GetVoltage() const; + double GetTemperature() const; + double GetCurrent(uint8_t channel) const; + double GetTotalCurrent() const; + double GetTotalPower() const; + double GetTotalEnergy() const; + void ResetTotalEnergy(); + void ClearStickyFaults(); - private: - ITable *m_table; - uint8_t m_module; + void UpdateTable() override; + void StartLiveWindowMode() override; + void StopLiveWindowMode() override; + std::string GetSmartDashboardType() const override; + void InitTable(ITable *subTable) override; + ITable *GetTable() const override; + + private: + ITable *m_table; + uint8_t m_module; }; #endif /* __WPILIB_POWER_DISTRIBUTION_PANEL_H__ */ - diff --git a/wpilibc/wpilibC++Devices/include/Preferences.h b/wpilibc/wpilibC++Devices/include/Preferences.h index d32e49c6e0..b3fd11d30d 100644 --- a/wpilibc/wpilibC++Devices/include/Preferences.h +++ b/wpilibc/wpilibC++Devices/include/Preferences.h @@ -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,84 +16,90 @@ #include "networktables/NetworkTable.h" /** - * The preferences class provides a relatively simple way to save important values to + * The preferences class provides a relatively simple way to save important + * values to * the RoboRIO to access the next time the RoboRIO is booted. * *

This class loads and saves from a file - * inside the RoboRIO. The user can not access the file directly, but may modify values at specific - * fields which will then be saved to the file when {@link Preferences#Save() Save()} is called.

+ * inside the RoboRIO. The user can not access the file directly, but may + * modify values at specific + * fields which will then be saved to the file when {@link Preferences#Save() + * Save()} is called.

* *

This class is thread safe.

* - *

This will also interact with {@link NetworkTable} by creating a table called "Preferences" with all the - * key-value pairs. To save using {@link NetworkTable}, simply set the boolean at position "~S A V E~" to true. - * Also, if the value of any variable is " in the {@link NetworkTable}, then that represents non-existence in the + *

This will also interact with {@link NetworkTable} by creating a table + * called "Preferences" with all the + * key-value pairs. To save using {@link NetworkTable}, simply set the boolean + * at position "~S A V E~" to true. + * Also, if the value of any variable is " in the {@link NetworkTable}, then + * that represents non-existence in the * {@link Preferences} table

*/ -class Preferences : public ErrorBase, public ITableListener -{ -public: - static Preferences *GetInstance(); +class Preferences : public ErrorBase, public ITableListener { + public: + static Preferences *GetInstance(); - std::vector GetKeys(); - std::string GetString(const char *key, const char *defaultValue = ""); - int GetString(const char *key, char *value, int valueSize, const char *defaultValue = ""); - int GetInt(const char *key, int defaultValue = 0); - double GetDouble(const char *key, double defaultValue = 0.0); - float GetFloat(const char *key, float defaultValue = 0.0); - bool GetBoolean(const char *key, bool defaultValue = false); - int64_t GetLong(const char *key, int64_t defaultValue = 0); - void PutString(const char *key, const char *value); - void PutInt(const char *key, int value); - void PutDouble(const char *key, double value); - void PutFloat(const char *key, float value); - void PutBoolean(const char *key, bool value); - void PutLong(const char *key, int64_t value); - void Save(); - bool ContainsKey(const char *key); - void Remove(const char *key); + std::vector GetKeys(); + std::string GetString(const char *key, const char *defaultValue = ""); + int GetString(const char *key, char *value, int valueSize, + const char *defaultValue = ""); + int GetInt(const char *key, int defaultValue = 0); + double GetDouble(const char *key, double defaultValue = 0.0); + float GetFloat(const char *key, float defaultValue = 0.0); + bool GetBoolean(const char *key, bool defaultValue = false); + int64_t GetLong(const char *key, int64_t defaultValue = 0); + void PutString(const char *key, const char *value); + void PutInt(const char *key, int value); + void PutDouble(const char *key, double value); + void PutFloat(const char *key, float value); + void PutBoolean(const char *key, bool value); + void PutLong(const char *key, int64_t value); + void Save(); + bool ContainsKey(const char *key); + void Remove(const char *key); - void ValueChanged(ITable* source, const std::string& key, EntryValue value, bool isNew) override; + void ValueChanged(ITable *source, const std::string &key, EntryValue value, + bool isNew) override; -protected: - Preferences(); - virtual ~Preferences(); + protected: + Preferences(); + virtual ~Preferences(); -private: - std::string Get(const char *key); - void Put(const char *key, std::string value); + private: + std::string Get(const char *key); + void Put(const char *key, std::string value); - void ReadTaskRun(); - void WriteTaskRun(); + void ReadTaskRun(); + void WriteTaskRun(); - static int InitReadTask(Preferences *obj) - { - obj->ReadTaskRun(); - return 0; - } - static int InitWriteTask(Preferences *obj) - { - obj->WriteTaskRun(); - return 0; - } + static int InitReadTask(Preferences *obj) { + obj->ReadTaskRun(); + return 0; + } + static int InitWriteTask(Preferences *obj) { + obj->WriteTaskRun(); + return 0; + } - static Preferences *_instance; + static Preferences *_instance; - /** The semaphore for accessing the file */ - MUTEX_ID m_fileLock; - /** The semaphore for beginning reads and writes to the file */ - SEMAPHORE_ID m_fileOpStarted; - /** The semaphore for reading from the table */ - MUTEX_ID m_tableLock; - typedef std::map StringMap; - /** The actual values (String->String) */ - StringMap m_values; - /** The keys in the order they were read from the file */ - std::vector m_keys; - /** The comments that were in the file sorted by which key they appeared over (String->Comment) */ - StringMap m_comments; - /** The comment at the end of the file */ - std::string m_endComment; - Task m_readTask; - Task m_writeTask; + /** The semaphore for accessing the file */ + MUTEX_ID m_fileLock; + /** The semaphore for beginning reads and writes to the file */ + SEMAPHORE_ID m_fileOpStarted; + /** The semaphore for reading from the table */ + MUTEX_ID m_tableLock; + typedef std::map StringMap; + /** The actual values (String->String) */ + StringMap m_values; + /** The keys in the order they were read from the file */ + std::vector m_keys; + /** The comments that were in the file sorted by which key they appeared over + * (String->Comment) */ + StringMap m_comments; + /** The comment at the end of the file */ + std::string m_endComment; + Task m_readTask; + Task m_writeTask; }; diff --git a/wpilibc/wpilibC++Devices/include/Relay.h b/wpilibc/wpilibC++Devices/include/Relay.h index 8d9c398353..0b2aa88f48 100644 --- a/wpilibc/wpilibC++Devices/include/Relay.h +++ b/wpilibc/wpilibC++Devices/include/Relay.h @@ -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,49 +13,45 @@ /** * Class for Spike style relay outputs. - * Relays are intended to be connected to spikes or similar relays. The relay channels controls - * a pair of pins that are either both off, one on, the other on, or both on. This translates into - * two spike outputs at 0v, one at 12v and one at 0v, one at 0v and the other at 12v, or two - * spike outputs at 12V. This allows off, full forward, or full reverse control of motors without - * variable speed. It also allows the two channels (forward and reverse) to be used independently + * Relays are intended to be connected to spikes or similar relays. The relay + * channels controls + * a pair of pins that are either both off, one on, the other on, or both on. + * This translates into + * two spike outputs at 0v, one at 12v and one at 0v, one at 0v and the other at + * 12v, or two + * spike outputs at 12V. This allows off, full forward, or full reverse control + * of motors without + * variable speed. It also allows the two channels (forward and reverse) to be + * used independently * for something that does not care about voltage polatiry (like a solenoid). */ -class Relay : public SensorBase, public ITableListener, public LiveWindowSendable -{ -public: - enum Value - { - kOff, - kOn, - kForward, - kReverse - }; - enum Direction - { - kBothDirections, - kForwardOnly, - kReverseOnly - }; +class Relay : public SensorBase, + public ITableListener, + public LiveWindowSendable { + public: + enum Value { kOff, kOn, kForward, kReverse }; + enum Direction { kBothDirections, kForwardOnly, kReverseOnly }; - Relay(uint32_t channel, Direction direction = kBothDirections); - virtual ~Relay(); + Relay(uint32_t channel, Direction direction = kBothDirections); + virtual ~Relay(); - void Set(Value value); - Value Get() const; + void Set(Value value); + Value Get() const; - 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; - ITable *m_table; + ITable* m_table; -private: - void InitRelay(); + private: + void InitRelay(); - uint32_t m_channel; - Direction m_direction; + uint32_t m_channel; + Direction m_direction; }; diff --git a/wpilibc/wpilibC++Devices/include/RobotBase.h b/wpilibc/wpilibC++Devices/include/RobotBase.h index 98b2ba6b61..79a5eecff0 100644 --- a/wpilibc/wpilibC++Devices/include/RobotBase.h +++ b/wpilibc/wpilibC++Devices/include/RobotBase.h @@ -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,54 +11,61 @@ class DriverStation; -#define START_ROBOT_CLASS(_ClassName_) \ - int main() \ - { \ - if (!HALInitialize()){std::cerr<<"FATAL ERROR: HAL could not be initialized"< m_imageData; - bool m_freshImage; + std::mutex m_imageDataMutex; + std::vector m_imageData; + bool m_freshImage; - int m_brightness; - WhiteBalance m_whiteBalance; - int m_colorLevel; - ExposureControl m_exposureControl; - int m_exposurePriority; - int m_maxFPS; - Resolution m_resolution; - int m_compression; - Rotation m_rotation; - bool m_parametersDirty; - bool m_streamDirty; - std::mutex m_parametersMutex; + int m_brightness; + WhiteBalance m_whiteBalance; + int m_colorLevel; + ExposureControl m_exposureControl; + int m_exposurePriority; + int m_maxFPS; + Resolution m_resolution; + int m_compression; + Rotation m_rotation; + bool m_parametersDirty; + bool m_streamDirty; + std::mutex m_parametersMutex; - bool m_done; + bool m_done; - void Capture(); - void ReadImagesFromCamera(); - bool WriteParameters(); + void Capture(); + void ReadImagesFromCamera(); + bool WriteParameters(); - int CreateCameraSocket(std::string const& requestString, bool setError); + int CreateCameraSocket(std::string const &requestString, bool setError); - DISALLOW_COPY_AND_ASSIGN(AxisCamera); + DISALLOW_COPY_AND_ASSIGN(AxisCamera); }; diff --git a/wpilibc/wpilibC++Devices/include/Vision/BaeUtilities.h b/wpilibc/wpilibC++Devices/include/Vision/BaeUtilities.h index a684b0785b..8983ef4d8b 100644 --- a/wpilibc/wpilibC++Devices/include/Vision/BaeUtilities.h +++ b/wpilibc/wpilibC++Devices/include/Vision/BaeUtilities.h @@ -7,30 +7,40 @@ #pragma once /* Constants */ -#define LOG_DEBUG __FILE__,__FUNCTION__,__LINE__,DEBUG_TYPE -#define LOG_INFO __FILE__,__FUNCTION__,__LINE__,INFO_TYPE -#define LOG_ERROR __FILE__,__FUNCTION__,__LINE__,ERROR_TYPE -#define LOG_CRITICAL __FILE__,__FUNCTION__,__LINE__,CRITICAL_TYPE -#define LOG_FATAL __FILE__,__FUNCTION__,__LINE__,FATAL_TYPE -#define LOG_DEBUG __FILE__,__FUNCTION__,__LINE__,DEBUG_TYPE +#define LOG_DEBUG __FILE__, __FUNCTION__, __LINE__, DEBUG_TYPE +#define LOG_INFO __FILE__, __FUNCTION__, __LINE__, INFO_TYPE +#define LOG_ERROR __FILE__, __FUNCTION__, __LINE__, ERROR_TYPE +#define LOG_CRITICAL __FILE__, __FUNCTION__, __LINE__, CRITICAL_TYPE +#define LOG_FATAL __FILE__, __FUNCTION__, __LINE__, FATAL_TYPE +#define LOG_DEBUG __FILE__, __FUNCTION__, __LINE__, DEBUG_TYPE /* Enumerated Types */ /** debug levels */ -enum dprint_type {DEBUG_TYPE, INFO_TYPE, ERROR_TYPE, CRITICAL_TYPE, FATAL_TYPE}; +enum dprint_type { + DEBUG_TYPE, + INFO_TYPE, + ERROR_TYPE, + CRITICAL_TYPE, + FATAL_TYPE +}; /** debug output setting */ -typedef enum DebugOutputType_enum { - DEBUG_OFF, DEBUG_MOSTLY_OFF, DEBUG_SCREEN_ONLY, DEBUG_FILE_ONLY, DEBUG_SCREEN_AND_FILE -}DebugOutputType; +typedef enum DebugOutputType_enum { + DEBUG_OFF, + DEBUG_MOSTLY_OFF, + DEBUG_SCREEN_ONLY, + DEBUG_FILE_ONLY, + DEBUG_SCREEN_AND_FILE +} DebugOutputType; /* Enumerated Types */ /* Utility functions */ /* debug */ -void SetDebugFlag ( DebugOutputType flag ); -void dprintf ( const char * tempString, ... ); /* Variable argument list */ +void SetDebugFlag(DebugOutputType flag); +void dprintf(const char *tempString, ...); /* Variable argument list */ /* set FRC ranges for drive */ double RangeToNormalized(double pixel, int range); @@ -39,12 +49,12 @@ float NormalizeToRange(float normalizedValue, float minRange, float maxRange); float NormalizeToRange(float normalizedValue); /* system utilities */ -void ShowActivity (char *fmt, ...); -double ElapsedTime (double startTime); +void ShowActivity(char *fmt, ...); +double ElapsedTime(double startTime); /* servo panning utilities */ class Servo; -double SinPosition (double *period, double sinStart); +double SinPosition(double *period, double sinStart); void panInit(); void panInit(double period); void panForTarget(Servo *panServo); @@ -54,4 +64,3 @@ void panForTarget(Servo *panServo, double sinStart); int processFile(char *inputFile, char *outputString, int lineNumber); int emptyString(char *string); void stripString(char *string); - diff --git a/wpilibc/wpilibC++Devices/include/Vision/BinaryImage.h b/wpilibc/wpilibC++Devices/include/Vision/BinaryImage.h index 7c33f54cb2..2eab08fb1f 100644 --- a/wpilibc/wpilibC++Devices/include/Vision/BinaryImage.h +++ b/wpilibc/wpilibC++Devices/include/Vision/BinaryImage.h @@ -9,31 +9,35 @@ #include "MonoImage.h" /** * Included for ParticleAnalysisReport definition - * TODO: Eliminate this dependency! + * TODO: Eliminate this dependency! */ #include "Vision/VisionAPI.h" #include #include -class BinaryImage : public MonoImage -{ -public: - BinaryImage(); - virtual ~BinaryImage(); - int GetNumberParticles(); - ParticleAnalysisReport GetParticleAnalysisReport(int particleNumber); - void GetParticleAnalysisReport(int particleNumber, ParticleAnalysisReport *par); - std::vector* GetOrderedParticleAnalysisReports(); - BinaryImage *RemoveSmallObjects(bool connectivity8, int erosions); - BinaryImage *RemoveLargeObjects(bool connectivity8, int erosions); - BinaryImage *ConvexHull(bool connectivity8); - BinaryImage *ParticleFilter(ParticleFilterCriteria2 *criteria, int criteriaCount); - virtual void Write(const char *fileName); -private: - bool ParticleMeasurement(int particleNumber, MeasurementType whatToMeasure, int *result); - bool ParticleMeasurement(int particleNumber, MeasurementType whatToMeasure, double *result); - static double NormalizeFromRange(double position, int range); - static bool CompareParticleSizes(ParticleAnalysisReport particle1, ParticleAnalysisReport particle2); -}; +class BinaryImage : public MonoImage { + public: + BinaryImage(); + virtual ~BinaryImage(); + int GetNumberParticles(); + ParticleAnalysisReport GetParticleAnalysisReport(int particleNumber); + void GetParticleAnalysisReport(int particleNumber, + ParticleAnalysisReport *par); + std::vector *GetOrderedParticleAnalysisReports(); + BinaryImage *RemoveSmallObjects(bool connectivity8, int erosions); + BinaryImage *RemoveLargeObjects(bool connectivity8, int erosions); + BinaryImage *ConvexHull(bool connectivity8); + BinaryImage *ParticleFilter(ParticleFilterCriteria2 *criteria, + int criteriaCount); + virtual void Write(const char *fileName); + private: + bool ParticleMeasurement(int particleNumber, MeasurementType whatToMeasure, + int *result); + bool ParticleMeasurement(int particleNumber, MeasurementType whatToMeasure, + double *result); + static double NormalizeFromRange(double position, int range); + static bool CompareParticleSizes(ParticleAnalysisReport particle1, + ParticleAnalysisReport particle2); +}; diff --git a/wpilibc/wpilibC++Devices/include/Vision/ColorImage.h b/wpilibc/wpilibC++Devices/include/Vision/ColorImage.h index 595ed83ca5..cabf08058e 100644 --- a/wpilibc/wpilibC++Devices/include/Vision/ColorImage.h +++ b/wpilibc/wpilibC++Devices/include/Vision/ColorImage.h @@ -10,56 +10,61 @@ #include "BinaryImage.h" #include "Threshold.h" -class ColorImage : public ImageBase -{ -public: - ColorImage(ImageType type); - virtual ~ColorImage(); - BinaryImage *ThresholdRGB(int redLow, int redHigh, int greenLow, int greenHigh, int blueLow, int blueHigh); - BinaryImage *ThresholdHSL(int hueLow, int hueHigh, int saturationLow, int saturationHigh, int luminenceLow, int luminenceHigh); - BinaryImage *ThresholdHSV(int hueLow, int hueHigh, int saturationLow, int saturationHigh, int valueHigh, int valueLow); - BinaryImage *ThresholdHSI(int hueLow, int hueHigh, int saturationLow, int saturationHigh, int intensityLow, int intensityHigh); - BinaryImage *ThresholdRGB(Threshold &threshold); - BinaryImage *ThresholdHSL(Threshold &threshold); - BinaryImage *ThresholdHSV(Threshold &threshold); - BinaryImage *ThresholdHSI(Threshold &threshold); - MonoImage *GetRedPlane(); - MonoImage *GetGreenPlane(); - MonoImage *GetBluePlane(); - MonoImage *GetHSLHuePlane(); - MonoImage *GetHSVHuePlane(); - MonoImage *GetHSIHuePlane(); - MonoImage *GetHSLSaturationPlane(); - MonoImage *GetHSVSaturationPlane(); - MonoImage *GetHSISaturationPlane(); - MonoImage *GetLuminancePlane(); - MonoImage *GetValuePlane(); - MonoImage *GetIntensityPlane(); - void ReplaceRedPlane(MonoImage *plane); - void ReplaceGreenPlane(MonoImage *plane); - void ReplaceBluePlane(MonoImage *plane); - void ReplaceHSLHuePlane(MonoImage *plane); - void ReplaceHSVHuePlane(MonoImage *plane); - void ReplaceHSIHuePlane(MonoImage *plane); - void ReplaceHSLSaturationPlane(MonoImage *plane); - void ReplaceHSVSaturationPlane(MonoImage *plane); - void ReplaceHSISaturationPlane(MonoImage *plane); - void ReplaceLuminancePlane(MonoImage *plane); - void ReplaceValuePlane(MonoImage *plane); - void ReplaceIntensityPlane(MonoImage *plane); - void ColorEqualize(); - void LuminanceEqualize(); - -private: - BinaryImage *ComputeThreshold(ColorMode colorMode, int low1, int high1, int low2, int high2, int low3, int high3); - void Equalize(bool allPlanes); - MonoImage * ExtractColorPlane(ColorMode mode, int planeNumber); - MonoImage * ExtractFirstColorPlane(ColorMode mode); - MonoImage * ExtractSecondColorPlane(ColorMode mode); - MonoImage * ExtractThirdColorPlane(ColorMode mode); - void ReplacePlane(ColorMode mode, MonoImage *plane, int planeNumber); - void ReplaceFirstColorPlane(ColorMode mode, MonoImage *plane); - void ReplaceSecondColorPlane(ColorMode mode, MonoImage *plane); - void ReplaceThirdColorPlane(ColorMode mode, MonoImage *plane); -}; +class ColorImage : public ImageBase { + public: + ColorImage(ImageType type); + virtual ~ColorImage(); + BinaryImage *ThresholdRGB(int redLow, int redHigh, int greenLow, + int greenHigh, int blueLow, int blueHigh); + BinaryImage *ThresholdHSL(int hueLow, int hueHigh, int saturationLow, + int saturationHigh, int luminenceLow, + int luminenceHigh); + BinaryImage *ThresholdHSV(int hueLow, int hueHigh, int saturationLow, + int saturationHigh, int valueHigh, int valueLow); + BinaryImage *ThresholdHSI(int hueLow, int hueHigh, int saturationLow, + int saturationHigh, int intensityLow, + int intensityHigh); + BinaryImage *ThresholdRGB(Threshold &threshold); + BinaryImage *ThresholdHSL(Threshold &threshold); + BinaryImage *ThresholdHSV(Threshold &threshold); + BinaryImage *ThresholdHSI(Threshold &threshold); + MonoImage *GetRedPlane(); + MonoImage *GetGreenPlane(); + MonoImage *GetBluePlane(); + MonoImage *GetHSLHuePlane(); + MonoImage *GetHSVHuePlane(); + MonoImage *GetHSIHuePlane(); + MonoImage *GetHSLSaturationPlane(); + MonoImage *GetHSVSaturationPlane(); + MonoImage *GetHSISaturationPlane(); + MonoImage *GetLuminancePlane(); + MonoImage *GetValuePlane(); + MonoImage *GetIntensityPlane(); + void ReplaceRedPlane(MonoImage *plane); + void ReplaceGreenPlane(MonoImage *plane); + void ReplaceBluePlane(MonoImage *plane); + void ReplaceHSLHuePlane(MonoImage *plane); + void ReplaceHSVHuePlane(MonoImage *plane); + void ReplaceHSIHuePlane(MonoImage *plane); + void ReplaceHSLSaturationPlane(MonoImage *plane); + void ReplaceHSVSaturationPlane(MonoImage *plane); + void ReplaceHSISaturationPlane(MonoImage *plane); + void ReplaceLuminancePlane(MonoImage *plane); + void ReplaceValuePlane(MonoImage *plane); + void ReplaceIntensityPlane(MonoImage *plane); + void ColorEqualize(); + void LuminanceEqualize(); + private: + BinaryImage *ComputeThreshold(ColorMode colorMode, int low1, int high1, + int low2, int high2, int low3, int high3); + void Equalize(bool allPlanes); + MonoImage *ExtractColorPlane(ColorMode mode, int planeNumber); + MonoImage *ExtractFirstColorPlane(ColorMode mode); + MonoImage *ExtractSecondColorPlane(ColorMode mode); + MonoImage *ExtractThirdColorPlane(ColorMode mode); + void ReplacePlane(ColorMode mode, MonoImage *plane, int planeNumber); + void ReplaceFirstColorPlane(ColorMode mode, MonoImage *plane); + void ReplaceSecondColorPlane(ColorMode mode, MonoImage *plane); + void ReplaceThirdColorPlane(ColorMode mode, MonoImage *plane); +}; diff --git a/wpilibc/wpilibC++Devices/include/Vision/FrcError.h b/wpilibc/wpilibC++Devices/include/Vision/FrcError.h index 9bd47f49f5..0897c8473d 100644 --- a/wpilibc/wpilibC++Devices/include/Vision/FrcError.h +++ b/wpilibc/wpilibC++Devices/include/Vision/FrcError.h @@ -7,24 +7,23 @@ #pragma once /* Error Codes */ -#define ERR_VISION_GENERAL_ERROR 166000 // -#define ERR_COLOR_NOT_FOUND 166100 // TrackAPI.cpp -#define ERR_PARTICLE_TOO_SMALL 166101 // TrackAPI.cpp +#define ERR_VISION_GENERAL_ERROR 166000 // +#define ERR_COLOR_NOT_FOUND 166100 // TrackAPI.cpp +#define ERR_PARTICLE_TOO_SMALL 166101 // TrackAPI.cpp -#define ERR_CAMERA_FAILURE 166200 // AxisCamera.cpp -#define ERR_CAMERA_SOCKET_CREATE_FAILED 166201 // AxisCamera.cpp -#define ERR_CAMERA_CONNECT_FAILED 166202 // AxisCamera.cpp -#define ERR_CAMERA_STALE_IMAGE 166203 // AxisCamera.cpp -#define ERR_CAMERA_NOT_INITIALIZED 166204 // AxisCamera.cpp -#define ERR_CAMERA_NO_BUFFER_AVAILABLE 166205 // AxisCamera.cpp -#define ERR_CAMERA_HEADER_ERROR 166206 // AxisCamera.cpp -#define ERR_CAMERA_BLOCKING_TIMEOUT 166207 // AxisCamera.cpp -#define ERR_CAMERA_AUTHORIZATION_FAILED 166208 // AxisCamera.cpp -#define ERR_CAMERA_TASK_SPAWN_FAILED 166209 // AxisCamera.cpp -#define ERR_CAMERA_TASK_INPUT_OUT_OF_RANGE 166210 // AxisCamera.cpp -#define ERR_CAMERA_COMMAND_FAILURE 166211 // AxisCamera.cpp +#define ERR_CAMERA_FAILURE 166200 // AxisCamera.cpp +#define ERR_CAMERA_SOCKET_CREATE_FAILED 166201 // AxisCamera.cpp +#define ERR_CAMERA_CONNECT_FAILED 166202 // AxisCamera.cpp +#define ERR_CAMERA_STALE_IMAGE 166203 // AxisCamera.cpp +#define ERR_CAMERA_NOT_INITIALIZED 166204 // AxisCamera.cpp +#define ERR_CAMERA_NO_BUFFER_AVAILABLE 166205 // AxisCamera.cpp +#define ERR_CAMERA_HEADER_ERROR 166206 // AxisCamera.cpp +#define ERR_CAMERA_BLOCKING_TIMEOUT 166207 // AxisCamera.cpp +#define ERR_CAMERA_AUTHORIZATION_FAILED 166208 // AxisCamera.cpp +#define ERR_CAMERA_TASK_SPAWN_FAILED 166209 // AxisCamera.cpp +#define ERR_CAMERA_TASK_INPUT_OUT_OF_RANGE 166210 // AxisCamera.cpp +#define ERR_CAMERA_COMMAND_FAILURE 166211 // AxisCamera.cpp /* error handling functions */ int GetLastVisionError(); const char* GetVisionErrorText(int errorCode); - diff --git a/wpilibc/wpilibC++Devices/include/Vision/HSLImage.h b/wpilibc/wpilibC++Devices/include/Vision/HSLImage.h index 71428aa7ee..54ee5f1b7b 100644 --- a/wpilibc/wpilibC++Devices/include/Vision/HSLImage.h +++ b/wpilibc/wpilibC++Devices/include/Vision/HSLImage.h @@ -11,12 +11,9 @@ /** * A color image represented in HSL color space at 3 bytes per pixel. */ -class HSLImage : public ColorImage -{ -public: - HSLImage(); - HSLImage(const char *fileName); - virtual ~HSLImage(); +class HSLImage : public ColorImage { + public: + HSLImage(); + HSLImage(const char *fileName); + virtual ~HSLImage(); }; - - diff --git a/wpilibc/wpilibC++Devices/include/Vision/ImageBase.h b/wpilibc/wpilibC++Devices/include/Vision/ImageBase.h index ee5e895f3d..c20ecfeb0a 100644 --- a/wpilibc/wpilibC++Devices/include/Vision/ImageBase.h +++ b/wpilibc/wpilibC++Devices/include/Vision/ImageBase.h @@ -12,16 +12,15 @@ #define DEFAULT_BORDER_SIZE 3 -class ImageBase : public ErrorBase -{ -public: - ImageBase(ImageType type); - virtual ~ImageBase(); - virtual void Write(const char *fileName); - int GetHeight(); - int GetWidth(); - Image *GetImaqImage(); -protected: - Image *m_imaqImage; -}; +class ImageBase : public ErrorBase { + public: + ImageBase(ImageType type); + virtual ~ImageBase(); + virtual void Write(const char *fileName); + int GetHeight(); + int GetWidth(); + Image *GetImaqImage(); + protected: + Image *m_imaqImage; +}; diff --git a/wpilibc/wpilibC++Devices/include/Vision/MonoImage.h b/wpilibc/wpilibC++Devices/include/Vision/MonoImage.h index e0e35eba2d..c45e53b0e2 100644 --- a/wpilibc/wpilibC++Devices/include/Vision/MonoImage.h +++ b/wpilibc/wpilibC++Devices/include/Vision/MonoImage.h @@ -10,16 +10,14 @@ #include -class MonoImage : public ImageBase -{ -public: - MonoImage(); - virtual ~MonoImage(); +class MonoImage : public ImageBase { + public: + MonoImage(); + virtual ~MonoImage(); - std::vector *DetectEllipses(EllipseDescriptor *ellipseDescriptor, - CurveOptions *curveOptions, - ShapeDetectionOptions *shapeDetectionOptions, - ROI *roi); - std::vector * DetectEllipses(EllipseDescriptor *ellipseDescriptor); + std::vector *DetectEllipses( + EllipseDescriptor *ellipseDescriptor, CurveOptions *curveOptions, + ShapeDetectionOptions *shapeDetectionOptions, ROI *roi); + std::vector *DetectEllipses( + EllipseDescriptor *ellipseDescriptor); }; - diff --git a/wpilibc/wpilibC++Devices/include/Vision/RGBImage.h b/wpilibc/wpilibC++Devices/include/Vision/RGBImage.h index 0ef2d722bb..efe3fda2ee 100644 --- a/wpilibc/wpilibC++Devices/include/Vision/RGBImage.h +++ b/wpilibc/wpilibC++Devices/include/Vision/RGBImage.h @@ -11,11 +11,9 @@ /** * A color image represented in RGB color space at 3 bytes per pixel. */ -class RGBImage : public ColorImage -{ -public: - RGBImage(); - RGBImage(const char *fileName); - virtual ~RGBImage(); +class RGBImage : public ColorImage { + public: + RGBImage(); + RGBImage(const char *fileName); + virtual ~RGBImage(); }; - diff --git a/wpilibc/wpilibC++Devices/include/Vision/Threshold.h b/wpilibc/wpilibC++Devices/include/Vision/Threshold.h index 9070cbfee3..2855ba25eb 100644 --- a/wpilibc/wpilibC++Devices/include/Vision/Threshold.h +++ b/wpilibc/wpilibC++Devices/include/Vision/Threshold.h @@ -12,17 +12,14 @@ * that is used in a threshhold operation. It simplifies passing values * around in a program for color detection. */ -class Threshold -{ -public: - int plane1Low; - int plane1High; - int plane2Low; - int plane2High; - int plane3Low; - int plane3High; - Threshold(int plane1Low, int plane1High, - int plane2Low, int plane2High, - int plane3Low, int plane3High); +class Threshold { + public: + int plane1Low; + int plane1High; + int plane2Low; + int plane2High; + int plane3Low; + int plane3High; + Threshold(int plane1Low, int plane1High, int plane2Low, int plane2High, + int plane3Low, int plane3High); }; - diff --git a/wpilibc/wpilibC++Devices/include/Vision/VisionAPI.h b/wpilibc/wpilibC++Devices/include/Vision/VisionAPI.h index ce291bf734..3153f1bc24 100644 --- a/wpilibc/wpilibC++Devices/include/Vision/VisionAPI.h +++ b/wpilibc/wpilibC++Devices/include/Vision/VisionAPI.h @@ -6,12 +6,12 @@ #pragma once -#include "nivision.h" +#include "nivision.h" /* Constants */ -#define DEFAULT_BORDER_SIZE 3 //VisionAPI.frcCreateImage -#define DEFAULT_SATURATION_THRESHOLD 40 //TrackAPI.FindColor +#define DEFAULT_BORDER_SIZE 3 // VisionAPI.frcCreateImage +#define DEFAULT_SATURATION_THRESHOLD 40 // TrackAPI.FindColor /* Forward Declare Data Structures */ typedef struct FindEdgeOptions_struct FindEdgeOptions; @@ -21,101 +21,116 @@ typedef struct CircularEdgeReport_struct CircularEdgeReport; /** frcParticleAnalysis returns this structure */ typedef struct ParticleAnalysisReport_struct { - int imageHeight; - int imageWidth; - double imageTimestamp; - int particleIndex; // the particle index analyzed - /* X-coordinate of the point representing the average position of the - * total particle mass, assuming every point in the particle has a constant density */ - int center_mass_x; // MeasurementType: IMAQ_MT_CENTER_OF_MASS_X - /* Y-coordinate of the point representing the average position of the - * total particle mass, assuming every point in the particle has a constant density */ - int center_mass_y; // MeasurementType: IMAQ_MT_CENTER_OF_MASS_Y - double center_mass_x_normalized; //Center of mass x value normalized to -1.0 to +1.0 range - double center_mass_y_normalized; //Center of mass y value normalized to -1.0 to +1.0 range - /* Area of the particle */ - double particleArea; // MeasurementType: IMAQ_MT_AREA - /* Bounding Rectangle */ - Rect boundingRect; // left/top/width/height - /* Percentage of the particle Area covering the Image Area. */ - double particleToImagePercent; // MeasurementType: IMAQ_MT_AREA_BY_IMAGE_AREA - /* Percentage of the particle Area in relation to its Particle and Holes Area */ - double particleQuality; // MeasurementType: IMAQ_MT_AREA_BY_PARTICLE_AND_HOLES_AREA + int imageHeight; + int imageWidth; + double imageTimestamp; + int particleIndex; // the particle index analyzed + /* X-coordinate of the point representing the average position of the + * total particle mass, assuming every point in the particle has a constant + * density */ + int center_mass_x; // MeasurementType: IMAQ_MT_CENTER_OF_MASS_X + /* Y-coordinate of the point representing the average position of the + * total particle mass, assuming every point in the particle has a constant + * density */ + int center_mass_y; // MeasurementType: IMAQ_MT_CENTER_OF_MASS_Y + double center_mass_x_normalized; // Center of mass x value normalized to -1.0 + // to +1.0 range + double center_mass_y_normalized; // Center of mass y value normalized to -1.0 + // to +1.0 range + /* Area of the particle */ + double particleArea; // MeasurementType: IMAQ_MT_AREA + /* Bounding Rectangle */ + Rect boundingRect; // left/top/width/height + /* Percentage of the particle Area covering the Image Area. */ + double particleToImagePercent; // MeasurementType: IMAQ_MT_AREA_BY_IMAGE_AREA + /* Percentage of the particle Area in relation to its Particle and Holes Area + */ + double particleQuality; // MeasurementType: + // IMAQ_MT_AREA_BY_PARTICLE_AND_HOLES_AREA } ParticleAnalysisReport; /** Tracking functions return this structure */ typedef struct ColorReport_struct { - int numberParticlesFound; // Number of particles found for this color - int largestParticleNumber; // The particle index of the largest particle - /* Color information */ - float particleHueMax; // HistogramReport: hue max - float particleHueMin; // HistogramReport: hue max - float particleHueMean; // HistogramReport: hue mean - float particleSatMax; // HistogramReport: saturation max - float particleSatMin; // HistogramReport: saturation max - float particleSatMean; // HistogramReport: saturation mean - float particleLumMax; // HistogramReport: luminance max - float particleLumMin; // HistogramReport: luminance max - float particleLumMean; // HistogramReport: luminance mean + int numberParticlesFound; // Number of particles found for this color + int largestParticleNumber; // The particle index of the largest particle + /* Color information */ + float particleHueMax; // HistogramReport: hue max + float particleHueMin; // HistogramReport: hue max + float particleHueMean; // HistogramReport: hue mean + float particleSatMax; // HistogramReport: saturation max + float particleSatMin; // HistogramReport: saturation max + float particleSatMean; // HistogramReport: saturation mean + float particleLumMax; // HistogramReport: luminance max + float particleLumMin; // HistogramReport: luminance max + float particleLumMean; // HistogramReport: luminance mean } ColorReport; - /* Image Management functions */ /* Create: calls imaqCreateImage. Border size is set to some default value */ -Image* frcCreateImage( ImageType type ); +Image* frcCreateImage(ImageType type); /* Dispose: calls imaqDispose */ -int frcDispose( void* object ); -int frcDispose( const char* filename, ... ) ; +int frcDispose(void* object); +int frcDispose(const char* filename, ...); /* Copy: calls imaqDuplicateImage */ -int frcCopyImage( Image* dest, const Image* source ); +int frcCopyImage(Image* dest, const Image* source); /* Image Extraction: Crop: calls imaqScale */ -int frcCrop( Image* dest, const Image* source, Rect rect ); +int frcCrop(Image* dest, const Image* source, Rect rect); /* Image Extraction: Scale: calls imaqScale. Scales entire image */ -int frcScale(Image* dest, const Image* source, int xScale, int yScale, ScalingMode scaleMode ); +int frcScale(Image* dest, const Image* source, int xScale, int yScale, + ScalingMode scaleMode); /* Read Image : calls imaqReadFile */ -int frcReadImage( Image* image, const char* fileName ); +int frcReadImage(Image* image, const char* fileName); /* Write Image : calls imaqWriteFile */ -int frcWriteImage( const Image* image, const char* fileName); +int frcWriteImage(const Image* image, const char* fileName); /* Measure Intensity functions */ /* Histogram: calls imaqHistogram */ -HistogramReport* frcHistogram( const Image* image, int numClasses, float min, float max, Rect rect ); +HistogramReport* frcHistogram(const Image* image, int numClasses, float min, + float max, Rect rect); /* Color Histogram: calls imaqColorHistogram2 */ -ColorHistogramReport* frcColorHistogram(const Image* image, int numClasses, ColorMode mode, Image* mask); +ColorHistogramReport* frcColorHistogram(const Image* image, int numClasses, + ColorMode mode, Image* mask); /* Get Pixel Value: calls imaqGetPixel */ -int frcGetPixelValue( const Image* image, Point pixel, PixelValue* value ); +int frcGetPixelValue(const Image* image, Point pixel, PixelValue* value); /* Particle Analysis functions */ /* Particle Filter: calls imaqParticleFilter3 */ -int frcParticleFilter(Image* dest, Image* source, const ParticleFilterCriteria2* criteria, - int criteriaCount, const ParticleFilterOptions* options, Rect rect, int* numParticles); -int frcParticleFilter(Image* dest, Image* source, const ParticleFilterCriteria2* criteria, - int criteriaCount, const ParticleFilterOptions* options, int* numParticles); +int frcParticleFilter(Image* dest, Image* source, + const ParticleFilterCriteria2* criteria, + int criteriaCount, const ParticleFilterOptions* options, + Rect rect, int* numParticles); +int frcParticleFilter(Image* dest, Image* source, + const ParticleFilterCriteria2* criteria, + int criteriaCount, const ParticleFilterOptions* options, + int* numParticles); /* Morphology: calls imaqMorphology */ int frcMorphology(Image* dest, Image* source, MorphologyMethod method); -int frcMorphology(Image* dest, Image* source, MorphologyMethod method, const StructuringElement* structuringElement); +int frcMorphology(Image* dest, Image* source, MorphologyMethod method, + const StructuringElement* structuringElement); /* Reject Border: calls imaqRejectBorder */ int frcRejectBorder(Image* dest, Image* source); int frcRejectBorder(Image* dest, Image* source, int connectivity8); /* Count Particles: calls imaqCountParticles */ int frcCountParticles(Image* image, int* numParticles); /* Particle Analysis Report: calls imaqMeasureParticle */ -int frcParticleAnalysis(Image* image, int particleNumber, ParticleAnalysisReport* par); +int frcParticleAnalysis(Image* image, int particleNumber, + ParticleAnalysisReport* par); /* Image Enhancement functions */ /* Equalize: calls imaqEqualize */ int frcEqualize(Image* dest, const Image* source, float min, float max); -int frcEqualize(Image* dest, const Image* source, float min, float max, const Image* mask); +int frcEqualize(Image* dest, const Image* source, float min, float max, + const Image* mask); /* Color Equalize: calls imaqColorEqualize */ int frcColorEqualize(Image* dest, const Image* source); @@ -124,25 +139,34 @@ int frcColorEqualize(Image* dest, const Image* source, int colorEqualization); /* Image Thresholding & Conversion functions */ /* Smart Threshold: calls imaqLocalThreshold */ -int frcSmartThreshold(Image* dest, const Image* source, unsigned int windowWidth, unsigned int windowHeight, - LocalThresholdMethod method, double deviationWeight, ObjectType type); -int frcSmartThreshold(Image* dest, const Image* source, unsigned int windowWidth, unsigned int windowHeight, - LocalThresholdMethod method, double deviationWeight, ObjectType type, float replaceValue); +int frcSmartThreshold(Image* dest, const Image* source, + unsigned int windowWidth, unsigned int windowHeight, + LocalThresholdMethod method, double deviationWeight, + ObjectType type); +int frcSmartThreshold(Image* dest, const Image* source, + unsigned int windowWidth, unsigned int windowHeight, + LocalThresholdMethod method, double deviationWeight, + ObjectType type, float replaceValue); /* Simple Threshold: calls imaqThreshold */ -int frcSimpleThreshold(Image* dest, const Image* source, float rangeMin, float rangeMax, float newValue); -int frcSimpleThreshold(Image* dest, const Image* source, float rangeMin, float rangeMax); +int frcSimpleThreshold(Image* dest, const Image* source, float rangeMin, + float rangeMax, float newValue); +int frcSimpleThreshold(Image* dest, const Image* source, float rangeMin, + float rangeMax); /* Color/Hue Threshold: calls imaqColorThreshold */ -int frcColorThreshold(Image* dest, const Image* source, ColorMode mode, - const Range* plane1Range, const Range* plane2Range, const Range* plane3Range); -int frcColorThreshold(Image* dest, const Image* source, int replaceValue, ColorMode mode, - const Range* plane1Range, const Range* plane2Range, const Range* plane3Range); +int frcColorThreshold(Image* dest, const Image* source, ColorMode mode, + const Range* plane1Range, const Range* plane2Range, + const Range* plane3Range); +int frcColorThreshold(Image* dest, const Image* source, int replaceValue, + ColorMode mode, const Range* plane1Range, + const Range* plane2Range, const Range* plane3Range); int frcHueThreshold(Image* dest, const Image* source, const Range* hueRange); -int frcHueThreshold(Image* dest, const Image* source, const Range* hueRange, int minSaturation); +int frcHueThreshold(Image* dest, const Image* source, const Range* hueRange, + int minSaturation); /* Extract ColorHue Plane: calls imaqExtractColorPlanes */ -int frcExtractColorPlanes(const Image* image, ColorMode mode, Image* plane1, Image* plane2, Image* plane3); +int frcExtractColorPlanes(const Image* image, ColorMode mode, Image* plane1, + Image* plane2, Image* plane3); int frcExtractHuePlane(const Image* image, Image* huePlane); int frcExtractHuePlane(const Image* image, Image* huePlane, int minSaturation); - diff --git a/wpilibc/wpilibC++Devices/include/WPILib.h b/wpilibc/wpilibC++Devices/include/WPILib.h index d0f6f929ee..7a1528c886 100644 --- a/wpilibc/wpilibC++Devices/include/WPILib.h +++ b/wpilibc/wpilibC++Devices/include/WPILib.h @@ -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. */ /*----------------------------------------------------------------------------*/ diff --git a/wpilibc/wpilibC++Devices/include/ctre/CanTalonSRX.h b/wpilibc/wpilibC++Devices/include/ctre/CanTalonSRX.h index 37bd5e4c67..3e8cb77234 100644 --- a/wpilibc/wpilibC++Devices/include/ctre/CanTalonSRX.h +++ b/wpilibc/wpilibC++Devices/include/ctre/CanTalonSRX.h @@ -1,40 +1,63 @@ /** * @brief CAN TALON SRX driver. * - * The TALON SRX is designed to instrument all runtime signals periodically. The default periods are chosen to support 16 TALONs - * with 10ms update rate for control (throttle or setpoint). However these can be overridden with SetStatusFrameRate. @see SetStatusFrameRate - * The getters for these unsolicited signals are auto generated at the bottom of this module. + * The TALON SRX is designed to instrument all runtime signals periodically. + * The default periods are chosen to support 16 TALONs + * with 10ms update rate for control (throttle or setpoint). However these can + * be overridden with SetStatusFrameRate. @see SetStatusFrameRate + * The getters for these unsolicited signals are auto generated at the bottom of + * this module. * - * Likewise most control signals are sent periodically using the fire-and-forget CAN API. - * The setters for these unsolicited signals are auto generated at the bottom of this module. + * Likewise most control signals are sent periodically using the fire-and-forget + * CAN API. + * The setters for these unsolicited signals are auto generated at the bottom of + * this module. * - * Signals that are not available in an unsolicited fashion are the Close Loop gains. - * For teams that have a single profile for their TALON close loop they can use either the webpage to configure their TALONs once - * or set the PIDF,Izone,CloseLoopRampRate,etc... once in the robot application. These parameters are saved to flash so once they are - * loaded in the TALON, they will persist through power cycles and mode changes. + * Signals that are not available in an unsolicited fashion are the Close Loop + * gains. + * For teams that have a single profile for their TALON close loop they can use + * either the webpage to configure their TALONs once + * or set the PIDF,Izone,CloseLoopRampRate,etc... once in the robot + * application. These parameters are saved to flash so once they are + * loaded in the TALON, they will persist through power cycles and mode + * changes. * - * For teams that have one or two profiles to switch between, they can use the same strategy since there are two slots to choose from + * For teams that have one or two profiles to switch between, they can use the + * same strategy since there are two slots to choose from * and the ProfileSlotSelect is periodically sent in the 10 ms control frame. * - * For teams that require changing gains frequently, they can use the soliciting API to get and set those parameters. Most likely - * they will only need to set them in a periodic fashion as a function of what motion the application is attempting. - * If this API is used, be mindful of the CAN utilization reported in the driver station. + * For teams that require changing gains frequently, they can use the soliciting + * API to get and set those parameters. Most likely + * they will only need to set them in a periodic fashion as a function of what + * motion the application is attempting. + * If this API is used, be mindful of the CAN utilization reported in the driver + * station. * - * Encoder position is measured in encoder edges. Every edge is counted (similar to roboRIO 4X mode). + * Encoder position is measured in encoder edges. Every edge is counted + * (similar to roboRIO 4X mode). * Analog position is 10 bits, meaning 1024 ticks per rotation (0V => 3.3V). - * Use SetFeedbackDeviceSelect to select which sensor type you need. Once you do that you can use GetSensorPosition() - * and GetSensorVelocity(). These signals are updated on CANBus every 20ms (by default). - * If a relative sensor is selected, you can zero (or change the current value) using SetSensorPosition. + * Use SetFeedbackDeviceSelect to select which sensor type you need. Once you + * do that you can use GetSensorPosition() + * and GetSensorVelocity(). These signals are updated on CANBus every 20ms (by + * default). + * If a relative sensor is selected, you can zero (or change the current value) + * using SetSensorPosition. * - * Analog Input and quadrature position (and velocity) are also explicitly reported in GetEncPosition, GetEncVel, GetAnalogInWithOv, GetAnalogInVel. - * These signals are available all the time, regardless of what sensor is selected at a rate of 100ms. This allows easy instrumentation - * for "in the pits" checking of all sensors regardless of modeselect. The 100ms rate is overridable for teams who want to acquire sensor - * data for processing, not just instrumentation. Or just select the sensor using SetFeedbackDeviceSelect to get it at 20ms. + * Analog Input and quadrature position (and velocity) are also explicitly + * reported in GetEncPosition, GetEncVel, GetAnalogInWithOv, GetAnalogInVel. + * These signals are available all the time, regardless of what sensor is + * selected at a rate of 100ms. This allows easy instrumentation + * for "in the pits" checking of all sensors regardless of modeselect. The + * 100ms rate is overridable for teams who want to acquire sensor + * data for processing, not just instrumentation. Or just select the sensor + * using SetFeedbackDeviceSelect to get it at 20ms. * * Velocity is in position ticks / 100ms. * - * All output units are in respect to duty cycle (throttle) which is -1023(full reverse) to +1023 (full forward). - * This includes demand (which specifies duty cycle when in duty cycle mode) and rampRamp, which is in throttle units per 10ms (if nonzero). + * All output units are in respect to duty cycle (throttle) which is -1023(full + * reverse) to +1023 (full forward). + * This includes demand (which specifies duty cycle when in duty cycle mode) + * and rampRamp, which is in throttle units per 10ms (if nonzero). * * Pos and velocity close loops are calc'd as * err = target - posOrVel. @@ -43,332 +66,376 @@ * ClearIaccum() * output = P X err + I X iErr + D X dErr + F X target * dErr = err - lastErr - * P, I,and D gains are always positive. F can be negative. - * Motor direction can be reversed using SetRevMotDuringCloseLoopEn if sensor and motor are out of phase. - * Similarly feedback sensor can also be reversed (multiplied by -1) if you prefer the sensor to be inverted. + * P, I,and D gains are always positive. F can be negative. + * Motor direction can be reversed using SetRevMotDuringCloseLoopEn if + * sensor and motor are out of phase. + * Similarly feedback sensor can also be reversed (multiplied by -1) if you + * prefer the sensor to be inverted. * - * P gain is specified in throttle per error tick. For example, a value of 102 is ~9.9% (which is 102/1023) throttle per 1 - * ADC unit(10bit) or 1 quadrature encoder edge depending on selected sensor. + * P gain is specified in throttle per error tick. For example, a value of 102 + * is ~9.9% (which is 102/1023) throttle per 1 + * ADC unit(10bit) or 1 quadrature encoder edge depending on + * selected sensor. * - * I gain is specified in throttle per integrated error. For example, a value of 10 equates to ~0.99% (which is 10/1023) - * for each accumulated ADC unit(10bit) or 1 quadrature encoder edge depending on selected sensor. + * I gain is specified in throttle per integrated error. For example, a value of + * 10 equates to ~0.99% (which is 10/1023) + * for each accumulated ADC unit(10bit) or 1 quadrature encoder edge + * depending on selected sensor. * Close loop and integral accumulator runs every 1ms. * - * D gain is specified in throttle per derivative error. For example a value of 102 equates to ~9.9% (which is 102/1023) + * D gain is specified in throttle per derivative error. For example a value of + * 102 equates to ~9.9% (which is 102/1023) * per change of 1 unit (ADC or encoder) per ms. * - * I Zone is specified in the same units as sensor position (ADC units or quadrature edges). If pos/vel error is outside of + * I Zone is specified in the same units as sensor position (ADC units or + * quadrature edges). If pos/vel error is outside of * this value, the integrated error will auto-clear... * if( (IZone!=0) and abs(err) > IZone) * ClearIaccum() - * ...this is very useful in preventing integral windup and is highly recommended if using full PID to keep stability low. + * ...this is very useful in preventing integral windup and is + * highly recommended if using full PID to keep stability low. * - * CloseLoopRampRate is in throttle units per 1ms. Set to zero to disable ramping. - * Works the same as RampThrottle but only is in effect when a close loop mode and profile slot is selected. + * CloseLoopRampRate is in throttle units per 1ms. Set to zero to disable + * ramping. + * Works the same as RampThrottle but only is in effect when a close + * loop mode and profile slot is selected. * * auto generated using spreadsheet and WpiClassGen.csproj - * @link https://docs.google.com/spreadsheets/d/1OU_ZV7fZLGYUQ-Uhc8sVAmUmWTlT8XBFYK8lfjg_tac/edit#gid=1766046967 + * @link + * https://docs.google.com/spreadsheets/d/1OU_ZV7fZLGYUQ-Uhc8sVAmUmWTlT8XBFYK8lfjg_tac/edit#gid=1766046967 */ #ifndef CanTalonSRX_H_ #define CanTalonSRX_H_ -#include "ctre.h" //BIT Defines + Typedefs +#include "ctre.h" //BIT Defines + Typedefs #include "CtreCanNode.h" -#include //CAN Comm +#include //CAN Comm #include -class CanTalonSRX : public CtreCanNode -{ -private: +class CanTalonSRX : public CtreCanNode { + private: + /** just in case user wants to modify periods of certain status frames. + * Default the vars to match the firmware default. */ + uint32_t _statusRateMs[4]; + //---------------------- Vars for opening a CAN stream if caller needs signals + //that require soliciting */ + uint32_t _can_h; //!< Session handle for catching response params. + int32_t _can_stat; //!< Session handle status. + struct tCANStreamMessage _msgBuff[20]; + static int const kMsgCapacity = 20; + typedef std::map sigs_t; + sigs_t _sigs; //!< Catches signal updates that are solicited. Expect this to + //be very few. + void OpenSessionIfNeedBe(); + void ProcessStreamMessages(); + /** + * Send a one shot frame to set an arbitrary signal. + * Most signals are in the control frame so avoid using this API unless you + * have to. + * Use this api for... + * -A motor controller profile signal eProfileParam_XXXs. These are backed up + * in flash. If you are gain-scheduling then call this periodically. + * -Default brake and limit switch signals... eOnBoot_XXXs. Avoid doing this, + * use the override signals in the control frame. + * Talon will automatically send a PARAM_RESPONSE after the set, so + * GetParamResponse will catch the latest value after a couple ms. + */ + CTR_Code SetParamRaw(uint32_t paramEnum, int32_t rawBits); + /** + * Checks cached CAN frames and updating solicited signals. + */ + CTR_Code GetParamResponseRaw(uint32_t paramEnum, int32_t &rawBits); - /** just in case user wants to modify periods of certain status frames. - * Default the vars to match the firmware default. */ - uint32_t _statusRateMs[4]; - //---------------------- Vars for opening a CAN stream if caller needs signals that require soliciting */ - uint32_t _can_h; //!< Session handle for catching response params. - int32_t _can_stat; //!< Session handle status. - struct tCANStreamMessage _msgBuff[20]; - static int const kMsgCapacity = 20; - typedef std::map sigs_t; - sigs_t _sigs; //!< Catches signal updates that are solicited. Expect this to be very few. - void OpenSessionIfNeedBe(); - void ProcessStreamMessages(); - /** - * Send a one shot frame to set an arbitrary signal. - * Most signals are in the control frame so avoid using this API unless you have to. - * Use this api for... - * -A motor controller profile signal eProfileParam_XXXs. These are backed up in flash. If you are gain-scheduling then call this periodically. - * -Default brake and limit switch signals... eOnBoot_XXXs. Avoid doing this, use the override signals in the control frame. - * Talon will automatically send a PARAM_RESPONSE after the set, so GetParamResponse will catch the latest value after a couple ms. - */ - CTR_Code SetParamRaw(uint32_t paramEnum, int32_t rawBits); - /** - * Checks cached CAN frames and updating solicited signals. - */ - CTR_Code GetParamResponseRaw(uint32_t paramEnum, int32_t & rawBits); -public: - static const int kDefaultControlPeriodMs = 10; //!< default control update rate is 10ms. - CanTalonSRX(int deviceNumber = 0,int controlPeriodMs = kDefaultControlPeriodMs); - ~CanTalonSRX(); - void Set(double value); - /* mode select enumerations */ - static const int kMode_DutyCycle = 0; //!< Demand is 11bit signed duty cycle [-1023,1023]. - static const int kMode_PositionCloseLoop = 1; //!< Position PIDF. - static const int kMode_VelocityCloseLoop = 2; //!< Velocity PIDF. - static const int kMode_CurrentCloseLoop = 3; //!< Current close loop - not done. - static const int kMode_VoltCompen = 4; //!< Voltage Compensation Mode - not done. Demand is fixed pt target 8.8 volts. - static const int kMode_SlaveFollower = 5; //!< Demand is the 6 bit Device ID of the 'master' TALON SRX. - static const int kMode_NoDrive = 15; //!< Zero the output (honors brake/coast) regardless of demand. Might be useful if we need to change modes but can't atomically change all the signals we want in between. - /* limit switch enumerations */ - static const int kLimitSwitchOverride_UseDefaultsFromFlash = 1; - static const int kLimitSwitchOverride_DisableFwd_DisableRev = 4; - static const int kLimitSwitchOverride_DisableFwd_EnableRev = 5; - static const int kLimitSwitchOverride_EnableFwd_DisableRev = 6; - static const int kLimitSwitchOverride_EnableFwd_EnableRev = 7; - /* brake override enumerations */ - static const int kBrakeOverride_UseDefaultsFromFlash = 0; - static const int kBrakeOverride_OverrideCoast = 1; - static const int kBrakeOverride_OverrideBrake = 2; - /* feedback device enumerations */ - static const int kFeedbackDev_DigitalQuadEnc=0; - static const int kFeedbackDev_AnalogPot=2; - static const int kFeedbackDev_AnalogEncoder=3; - static const int kFeedbackDev_CountEveryRisingEdge=4; - static const int kFeedbackDev_CountEveryFallingEdge=5; - static const int kFeedbackDev_PosIsPulseWidth=8; - /* ProfileSlotSelect enumerations*/ - static const int kProfileSlotSelect_Slot0 = 0; - static const int kProfileSlotSelect_Slot1 = 1; - /* status frame rate types */ - static const int kStatusFrame_General = 0; - static const int kStatusFrame_Feedback = 1; - static const int kStatusFrame_Encoder = 2; - static const int kStatusFrame_AnalogTempVbat = 3; - /** - * Signal enumeration for generic signal access. - * Although every signal is enumerated, only use this for traffic that must be solicited. - * Use the auto generated getters/setters at bottom of this header as much as possible. - */ - typedef enum _param_t{ - eProfileParamSlot0_P=1, - eProfileParamSlot0_I=2, - eProfileParamSlot0_D=3, - eProfileParamSlot0_F=4, - eProfileParamSlot0_IZone=5, - eProfileParamSlot0_CloseLoopRampRate=6, - eProfileParamSlot1_P=11, - eProfileParamSlot1_I=12, - eProfileParamSlot1_D=13, - eProfileParamSlot1_F=14, - eProfileParamSlot1_IZone=15, - eProfileParamSlot1_CloseLoopRampRate=16, - eProfileParamSoftLimitForThreshold=21, - eProfileParamSoftLimitRevThreshold=22, - eProfileParamSoftLimitForEnable=23, - eProfileParamSoftLimitRevEnable=24, - eOnBoot_BrakeMode=31, - eOnBoot_LimitSwitch_Forward_NormallyClosed=32, - eOnBoot_LimitSwitch_Reverse_NormallyClosed=33, - eOnBoot_LimitSwitch_Forward_Disable=34, - eOnBoot_LimitSwitch_Reverse_Disable=35, - eFault_OverTemp=41, - eFault_UnderVoltage=42, - eFault_ForLim=43, - eFault_RevLim=44, - eFault_HardwareFailure=45, - eFault_ForSoftLim=46, - eFault_RevSoftLim=47, - eStckyFault_OverTemp=48, - eStckyFault_UnderVoltage=49, - eStckyFault_ForLim=50, - eStckyFault_RevLim=51, - eStckyFault_ForSoftLim=52, - eStckyFault_RevSoftLim=53, - eAppliedThrottle=61, - eCloseLoopErr=62, - eFeedbackDeviceSelect=63, - eRevMotDuringCloseLoopEn=64, - eModeSelect=65, - eProfileSlotSelect=66, - eRampThrottle=67, - eRevFeedbackSensor=68, - eLimitSwitchEn=69, - eLimitSwitchClosedFor=70, - eLimitSwitchClosedRev=71, - eSensorPosition=73, - eSensorVelocity=74, - eCurrent=75, - eBrakeIsEnabled=76, - eEncPosition=77, - eEncVel=78, - eEncIndexRiseEvents=79, - eQuadApin=80, - eQuadBpin=81, - eQuadIdxpin=82, - eAnalogInWithOv=83, - eAnalogInVel=84, - eTemp=85, - eBatteryV=86, - eResetCount=87, - eResetFlags=88, - eFirmVers=89, - eSettingsChanged=90, - eQuadFilterEn=91, - ePidIaccum=93, - }param_t; - /*---------------------setters and getters that use the solicated param request/response-------------*//** - * Send a one shot frame to set an arbitrary signal. - * Most signals are in the control frame so avoid using this API unless you have to. - * Use this api for... - * -A motor controller profile signal eProfileParam_XXXs. These are backed up in flash. If you are gain-scheduling then call this periodically. - * -Default brake and limit switch signals... eOnBoot_XXXs. Avoid doing this, use the override signals in the control frame. - * Talon will automatically send a PARAM_RESPONSE after the set, so GetParamResponse will catch the latest value after a couple ms. - */ - CTR_Code SetParam(param_t paramEnum, double value); - /** - * Asks TALON to immedietely respond with signal value. This API is only used for signals that are not sent periodically. - * This can be useful for reading params that rarely change like Limit Switch settings and PIDF values. - * @param param to request. - */ - CTR_Code RequestParam(param_t paramEnum); - CTR_Code GetParamResponse(param_t paramEnum, double & value); - CTR_Code GetParamResponseInt32(param_t paramEnum, int & value); - /*----- getters and setters that use param request/response. These signals are backed up in flash and will survive a power cycle. ---------*/ - /*----- If your application requires changing these values consider using both slots and switch between slot0 <=> slot1. ------------------*/ - /*----- If your application requires changing these signals frequently then it makes sense to leverage this API. --------------------------*/ - /*----- Getters don't block, so it may require several calls to get the latest value. --------------------------*/ - CTR_Code SetPgain(unsigned slotIdx,double gain); - CTR_Code SetIgain(unsigned slotIdx,double gain); - CTR_Code SetDgain(unsigned slotIdx,double gain); - CTR_Code SetFgain(unsigned slotIdx,double gain); - CTR_Code SetIzone(unsigned slotIdx,int zone); - CTR_Code SetCloseLoopRampRate(unsigned slotIdx,int closeLoopRampRate); - CTR_Code SetSensorPosition(int pos); - CTR_Code SetForwardSoftLimit(int forwardLimit); - CTR_Code SetReverseSoftLimit(int reverseLimit); - CTR_Code SetForwardSoftEnable(int enable); - CTR_Code SetReverseSoftEnable(int enable); - CTR_Code GetPgain(unsigned slotIdx,double & gain); - CTR_Code GetIgain(unsigned slotIdx,double & gain); - CTR_Code GetDgain(unsigned slotIdx,double & gain); - CTR_Code GetFgain(unsigned slotIdx,double & gain); - CTR_Code GetIzone(unsigned slotIdx,int & zone); - CTR_Code GetCloseLoopRampRate(unsigned slotIdx,int & closeLoopRampRate); - CTR_Code GetForwardSoftLimit(int & forwardLimit); - CTR_Code GetReverseSoftLimit(int & reverseLimit); - CTR_Code GetForwardSoftEnable(int & enable); - CTR_Code GetReverseSoftEnable(int & enable); - /** - * Change the periodMs of a TALON's status frame. See kStatusFrame_* enums for what's available. - */ - CTR_Code SetStatusFrameRate(unsigned frameEnum, unsigned periodMs); - /** - * Clear all sticky faults in TALON. - */ - CTR_Code ClearStickyFaults(); - /*------------------------ auto generated. This API is optimal since it uses the fire-and-forget CAN interface ----------------------*/ - /*------------------------ These signals should cover the majority of all use cases. ----------------------------------*/ - CTR_Code GetFault_OverTemp(int ¶m); - CTR_Code GetFault_UnderVoltage(int ¶m); - CTR_Code GetFault_ForLim(int ¶m); - CTR_Code GetFault_RevLim(int ¶m); - CTR_Code GetFault_HardwareFailure(int ¶m); - CTR_Code GetFault_ForSoftLim(int ¶m); - CTR_Code GetFault_RevSoftLim(int ¶m); - CTR_Code GetStckyFault_OverTemp(int ¶m); - CTR_Code GetStckyFault_UnderVoltage(int ¶m); - CTR_Code GetStckyFault_ForLim(int ¶m); - CTR_Code GetStckyFault_RevLim(int ¶m); - CTR_Code GetStckyFault_ForSoftLim(int ¶m); - CTR_Code GetStckyFault_RevSoftLim(int ¶m); - CTR_Code GetAppliedThrottle(int ¶m); - CTR_Code GetCloseLoopErr(int ¶m); - CTR_Code GetFeedbackDeviceSelect(int ¶m); - CTR_Code GetModeSelect(int ¶m); - CTR_Code GetLimitSwitchEn(int ¶m); - CTR_Code GetLimitSwitchClosedFor(int ¶m); - CTR_Code GetLimitSwitchClosedRev(int ¶m); - CTR_Code GetSensorPosition(int ¶m); - CTR_Code GetSensorVelocity(int ¶m); - CTR_Code GetCurrent(double ¶m); - CTR_Code GetBrakeIsEnabled(int ¶m); - CTR_Code GetEncPosition(int ¶m); - CTR_Code GetEncVel(int ¶m); - CTR_Code GetEncIndexRiseEvents(int ¶m); - CTR_Code GetQuadApin(int ¶m); - CTR_Code GetQuadBpin(int ¶m); - CTR_Code GetQuadIdxpin(int ¶m); - CTR_Code GetAnalogInWithOv(int ¶m); - CTR_Code GetAnalogInVel(int ¶m); - CTR_Code GetTemp(double ¶m); - CTR_Code GetBatteryV(double ¶m); - CTR_Code GetResetCount(int ¶m); - CTR_Code GetResetFlags(int ¶m); - CTR_Code GetFirmVers(int ¶m); - CTR_Code SetDemand(int param); - CTR_Code SetOverrideLimitSwitchEn(int param); - CTR_Code SetFeedbackDeviceSelect(int param); - CTR_Code SetRevMotDuringCloseLoopEn(int param); - CTR_Code SetOverrideBrakeType(int param); - CTR_Code SetModeSelect(int param); - CTR_Code SetModeSelect(int modeSelect,int demand); - CTR_Code SetProfileSlotSelect(int param); - CTR_Code SetRampThrottle(int param); - CTR_Code SetRevFeedbackSensor(int param); + public: + static const int kDefaultControlPeriodMs = + 10; //!< default control update rate is 10ms. + CanTalonSRX(int deviceNumber = 0, + int controlPeriodMs = kDefaultControlPeriodMs); + ~CanTalonSRX(); + void Set(double value); + /* mode select enumerations */ + static const int kMode_DutyCycle = + 0; //!< Demand is 11bit signed duty cycle [-1023,1023]. + static const int kMode_PositionCloseLoop = 1; //!< Position PIDF. + static const int kMode_VelocityCloseLoop = 2; //!< Velocity PIDF. + static const int kMode_CurrentCloseLoop = + 3; //!< Current close loop - not done. + static const int kMode_VoltCompen = 4; //!< Voltage Compensation Mode - not + //done. Demand is fixed pt target 8.8 + //volts. + static const int kMode_SlaveFollower = + 5; //!< Demand is the 6 bit Device ID of the 'master' TALON SRX. + static const int kMode_NoDrive = + 15; //!< Zero the output (honors brake/coast) regardless of demand. + //Might be useful if we need to change modes but can't atomically + //change all the signals we want in between. + /* limit switch enumerations */ + static const int kLimitSwitchOverride_UseDefaultsFromFlash = 1; + static const int kLimitSwitchOverride_DisableFwd_DisableRev = 4; + static const int kLimitSwitchOverride_DisableFwd_EnableRev = 5; + static const int kLimitSwitchOverride_EnableFwd_DisableRev = 6; + static const int kLimitSwitchOverride_EnableFwd_EnableRev = 7; + /* brake override enumerations */ + static const int kBrakeOverride_UseDefaultsFromFlash = 0; + static const int kBrakeOverride_OverrideCoast = 1; + static const int kBrakeOverride_OverrideBrake = 2; + /* feedback device enumerations */ + static const int kFeedbackDev_DigitalQuadEnc = 0; + static const int kFeedbackDev_AnalogPot = 2; + static const int kFeedbackDev_AnalogEncoder = 3; + static const int kFeedbackDev_CountEveryRisingEdge = 4; + static const int kFeedbackDev_CountEveryFallingEdge = 5; + static const int kFeedbackDev_PosIsPulseWidth = 8; + /* ProfileSlotSelect enumerations*/ + static const int kProfileSlotSelect_Slot0 = 0; + static const int kProfileSlotSelect_Slot1 = 1; + /* status frame rate types */ + static const int kStatusFrame_General = 0; + static const int kStatusFrame_Feedback = 1; + static const int kStatusFrame_Encoder = 2; + static const int kStatusFrame_AnalogTempVbat = 3; + /** + * Signal enumeration for generic signal access. + * Although every signal is enumerated, only use this for traffic that must be + * solicited. + * Use the auto generated getters/setters at bottom of this header as much as + * possible. + */ + typedef enum _param_t { + eProfileParamSlot0_P = 1, + eProfileParamSlot0_I = 2, + eProfileParamSlot0_D = 3, + eProfileParamSlot0_F = 4, + eProfileParamSlot0_IZone = 5, + eProfileParamSlot0_CloseLoopRampRate = 6, + eProfileParamSlot1_P = 11, + eProfileParamSlot1_I = 12, + eProfileParamSlot1_D = 13, + eProfileParamSlot1_F = 14, + eProfileParamSlot1_IZone = 15, + eProfileParamSlot1_CloseLoopRampRate = 16, + eProfileParamSoftLimitForThreshold = 21, + eProfileParamSoftLimitRevThreshold = 22, + eProfileParamSoftLimitForEnable = 23, + eProfileParamSoftLimitRevEnable = 24, + eOnBoot_BrakeMode = 31, + eOnBoot_LimitSwitch_Forward_NormallyClosed = 32, + eOnBoot_LimitSwitch_Reverse_NormallyClosed = 33, + eOnBoot_LimitSwitch_Forward_Disable = 34, + eOnBoot_LimitSwitch_Reverse_Disable = 35, + eFault_OverTemp = 41, + eFault_UnderVoltage = 42, + eFault_ForLim = 43, + eFault_RevLim = 44, + eFault_HardwareFailure = 45, + eFault_ForSoftLim = 46, + eFault_RevSoftLim = 47, + eStckyFault_OverTemp = 48, + eStckyFault_UnderVoltage = 49, + eStckyFault_ForLim = 50, + eStckyFault_RevLim = 51, + eStckyFault_ForSoftLim = 52, + eStckyFault_RevSoftLim = 53, + eAppliedThrottle = 61, + eCloseLoopErr = 62, + eFeedbackDeviceSelect = 63, + eRevMotDuringCloseLoopEn = 64, + eModeSelect = 65, + eProfileSlotSelect = 66, + eRampThrottle = 67, + eRevFeedbackSensor = 68, + eLimitSwitchEn = 69, + eLimitSwitchClosedFor = 70, + eLimitSwitchClosedRev = 71, + eSensorPosition = 73, + eSensorVelocity = 74, + eCurrent = 75, + eBrakeIsEnabled = 76, + eEncPosition = 77, + eEncVel = 78, + eEncIndexRiseEvents = 79, + eQuadApin = 80, + eQuadBpin = 81, + eQuadIdxpin = 82, + eAnalogInWithOv = 83, + eAnalogInVel = 84, + eTemp = 85, + eBatteryV = 86, + eResetCount = 87, + eResetFlags = 88, + eFirmVers = 89, + eSettingsChanged = 90, + eQuadFilterEn = 91, + ePidIaccum = 93, + } param_t; + /*---------------------setters and getters that use the solicated param request/response-------------*/ /** + * Send a one shot frame to set an arbitrary signal. + * Most signals are in the control frame so avoid using this API unless you + * have to. + * Use this api for... + * -A motor controller profile signal eProfileParam_XXXs. These are backed + * up in flash. If you are gain-scheduling then call this periodically. + * -Default brake and limit switch signals... eOnBoot_XXXs. Avoid doing + * this, use the override signals in the control frame. + * Talon will automatically send a PARAM_RESPONSE after the set, so + * GetParamResponse will catch the latest value after a couple ms. + */ + CTR_Code SetParam(param_t paramEnum, double value); + /** + * Asks TALON to immedietely respond with signal value. This API is only used + * for signals that are not sent periodically. + * This can be useful for reading params that rarely change like Limit Switch + * settings and PIDF values. + * @param param to request. + */ + CTR_Code RequestParam(param_t paramEnum); + CTR_Code GetParamResponse(param_t paramEnum, double &value); + CTR_Code GetParamResponseInt32(param_t paramEnum, int &value); + /*----- getters and setters that use param request/response. These signals are + * backed up in flash and will survive a power cycle. ---------*/ + /*----- If your application requires changing these values consider using both + * slots and switch between slot0 <=> slot1. ------------------*/ + /*----- If your application requires changing these signals frequently then it + * makes sense to leverage this API. --------------------------*/ + /*----- Getters don't block, so it may require several calls to get the latest + * value. --------------------------*/ + CTR_Code SetPgain(unsigned slotIdx, double gain); + CTR_Code SetIgain(unsigned slotIdx, double gain); + CTR_Code SetDgain(unsigned slotIdx, double gain); + CTR_Code SetFgain(unsigned slotIdx, double gain); + CTR_Code SetIzone(unsigned slotIdx, int zone); + CTR_Code SetCloseLoopRampRate(unsigned slotIdx, int closeLoopRampRate); + CTR_Code SetSensorPosition(int pos); + CTR_Code SetForwardSoftLimit(int forwardLimit); + CTR_Code SetReverseSoftLimit(int reverseLimit); + CTR_Code SetForwardSoftEnable(int enable); + CTR_Code SetReverseSoftEnable(int enable); + CTR_Code GetPgain(unsigned slotIdx, double &gain); + CTR_Code GetIgain(unsigned slotIdx, double &gain); + CTR_Code GetDgain(unsigned slotIdx, double &gain); + CTR_Code GetFgain(unsigned slotIdx, double &gain); + CTR_Code GetIzone(unsigned slotIdx, int &zone); + CTR_Code GetCloseLoopRampRate(unsigned slotIdx, int &closeLoopRampRate); + CTR_Code GetForwardSoftLimit(int &forwardLimit); + CTR_Code GetReverseSoftLimit(int &reverseLimit); + CTR_Code GetForwardSoftEnable(int &enable); + CTR_Code GetReverseSoftEnable(int &enable); + /** + * Change the periodMs of a TALON's status frame. See kStatusFrame_* enums + * for what's available. + */ + CTR_Code SetStatusFrameRate(unsigned frameEnum, unsigned periodMs); + /** + * Clear all sticky faults in TALON. + */ + CTR_Code ClearStickyFaults(); + /*------------------------ auto generated. This API is optimal since it uses + * the fire-and-forget CAN interface ----------------------*/ + /*------------------------ These signals should cover the majority of all use + * cases. ----------------------------------*/ + CTR_Code GetFault_OverTemp(int ¶m); + CTR_Code GetFault_UnderVoltage(int ¶m); + CTR_Code GetFault_ForLim(int ¶m); + CTR_Code GetFault_RevLim(int ¶m); + CTR_Code GetFault_HardwareFailure(int ¶m); + CTR_Code GetFault_ForSoftLim(int ¶m); + CTR_Code GetFault_RevSoftLim(int ¶m); + CTR_Code GetStckyFault_OverTemp(int ¶m); + CTR_Code GetStckyFault_UnderVoltage(int ¶m); + CTR_Code GetStckyFault_ForLim(int ¶m); + CTR_Code GetStckyFault_RevLim(int ¶m); + CTR_Code GetStckyFault_ForSoftLim(int ¶m); + CTR_Code GetStckyFault_RevSoftLim(int ¶m); + CTR_Code GetAppliedThrottle(int ¶m); + CTR_Code GetCloseLoopErr(int ¶m); + CTR_Code GetFeedbackDeviceSelect(int ¶m); + CTR_Code GetModeSelect(int ¶m); + CTR_Code GetLimitSwitchEn(int ¶m); + CTR_Code GetLimitSwitchClosedFor(int ¶m); + CTR_Code GetLimitSwitchClosedRev(int ¶m); + CTR_Code GetSensorPosition(int ¶m); + CTR_Code GetSensorVelocity(int ¶m); + CTR_Code GetCurrent(double ¶m); + CTR_Code GetBrakeIsEnabled(int ¶m); + CTR_Code GetEncPosition(int ¶m); + CTR_Code GetEncVel(int ¶m); + CTR_Code GetEncIndexRiseEvents(int ¶m); + CTR_Code GetQuadApin(int ¶m); + CTR_Code GetQuadBpin(int ¶m); + CTR_Code GetQuadIdxpin(int ¶m); + CTR_Code GetAnalogInWithOv(int ¶m); + CTR_Code GetAnalogInVel(int ¶m); + CTR_Code GetTemp(double ¶m); + CTR_Code GetBatteryV(double ¶m); + CTR_Code GetResetCount(int ¶m); + CTR_Code GetResetFlags(int ¶m); + CTR_Code GetFirmVers(int ¶m); + CTR_Code SetDemand(int param); + CTR_Code SetOverrideLimitSwitchEn(int param); + CTR_Code SetFeedbackDeviceSelect(int param); + CTR_Code SetRevMotDuringCloseLoopEn(int param); + CTR_Code SetOverrideBrakeType(int param); + CTR_Code SetModeSelect(int param); + CTR_Code SetModeSelect(int modeSelect, int demand); + CTR_Code SetProfileSlotSelect(int param); + CTR_Code SetRampThrottle(int param); + CTR_Code SetRevFeedbackSensor(int param); }; extern "C" { - void *c_TalonSRX_Create(int deviceNumber, int controlPeriodMs); - void c_TalonSRX_Destroy(void *handle); - CTR_Code c_TalonSRX_SetParam(void *handle, int paramEnum, double value); - CTR_Code c_TalonSRX_RequestParam(void *handle, int paramEnum); - CTR_Code c_TalonSRX_GetParamResponse(void *handle, int paramEnum, double *value); - CTR_Code c_TalonSRX_GetParamResponseInt32(void *handle, int paramEnum, int *value); - CTR_Code c_TalonSRX_SetStatusFrameRate(void *handle, unsigned frameEnum, unsigned periodMs); - CTR_Code c_TalonSRX_ClearStickyFaults(void *handle); - CTR_Code c_TalonSRX_GetFault_OverTemp(void *handle, int *param); - CTR_Code c_TalonSRX_GetFault_UnderVoltage(void *handle, int *param); - CTR_Code c_TalonSRX_GetFault_ForLim(void *handle, int *param); - CTR_Code c_TalonSRX_GetFault_RevLim(void *handle, int *param); - CTR_Code c_TalonSRX_GetFault_HardwareFailure(void *handle, int *param); - CTR_Code c_TalonSRX_GetFault_ForSoftLim(void *handle, int *param); - CTR_Code c_TalonSRX_GetFault_RevSoftLim(void *handle, int *param); - CTR_Code c_TalonSRX_GetStckyFault_OverTemp(void *handle, int *param); - CTR_Code c_TalonSRX_GetStckyFault_UnderVoltage(void *handle, int *param); - CTR_Code c_TalonSRX_GetStckyFault_ForLim(void *handle, int *param); - CTR_Code c_TalonSRX_GetStckyFault_RevLim(void *handle, int *param); - CTR_Code c_TalonSRX_GetStckyFault_ForSoftLim(void *handle, int *param); - CTR_Code c_TalonSRX_GetStckyFault_RevSoftLim(void *handle, int *param); - CTR_Code c_TalonSRX_GetAppliedThrottle(void *handle, int *param); - CTR_Code c_TalonSRX_GetCloseLoopErr(void *handle, int *param); - CTR_Code c_TalonSRX_GetFeedbackDeviceSelect(void *handle, int *param); - CTR_Code c_TalonSRX_GetModeSelect(void *handle, int *param); - CTR_Code c_TalonSRX_GetLimitSwitchEn(void *handle, int *param); - CTR_Code c_TalonSRX_GetLimitSwitchClosedFor(void *handle, int *param); - CTR_Code c_TalonSRX_GetLimitSwitchClosedRev(void *handle, int *param); - CTR_Code c_TalonSRX_GetSensorPosition(void *handle, int *param); - CTR_Code c_TalonSRX_GetSensorVelocity(void *handle, int *param); - CTR_Code c_TalonSRX_GetCurrent(void *handle, double *param); - CTR_Code c_TalonSRX_GetBrakeIsEnabled(void *handle, int *param); - CTR_Code c_TalonSRX_GetEncPosition(void *handle, int *param); - CTR_Code c_TalonSRX_GetEncVel(void *handle, int *param); - CTR_Code c_TalonSRX_GetEncIndexRiseEvents(void *handle, int *param); - CTR_Code c_TalonSRX_GetQuadApin(void *handle, int *param); - CTR_Code c_TalonSRX_GetQuadBpin(void *handle, int *param); - CTR_Code c_TalonSRX_GetQuadIdxpin(void *handle, int *param); - CTR_Code c_TalonSRX_GetAnalogInWithOv(void *handle, int *param); - CTR_Code c_TalonSRX_GetAnalogInVel(void *handle, int *param); - CTR_Code c_TalonSRX_GetTemp(void *handle, double *param); - CTR_Code c_TalonSRX_GetBatteryV(void *handle, double *param); - CTR_Code c_TalonSRX_GetResetCount(void *handle, int *param); - CTR_Code c_TalonSRX_GetResetFlags(void *handle, int *param); - CTR_Code c_TalonSRX_GetFirmVers(void *handle, int *param); - CTR_Code c_TalonSRX_SetDemand(void *handle, int param); - CTR_Code c_TalonSRX_SetOverrideLimitSwitchEn(void *handle, int param); - CTR_Code c_TalonSRX_SetFeedbackDeviceSelect(void *handle, int param); - CTR_Code c_TalonSRX_SetRevMotDuringCloseLoopEn(void *handle, int param); - CTR_Code c_TalonSRX_SetOverrideBrakeType(void *handle, int param); - CTR_Code c_TalonSRX_SetModeSelect(void *handle, int param); - CTR_Code c_TalonSRX_SetProfileSlotSelect(void *handle, int param); - CTR_Code c_TalonSRX_SetRampThrottle(void *handle, int param); - CTR_Code c_TalonSRX_SetRevFeedbackSensor(void *handle, int param); +void *c_TalonSRX_Create(int deviceNumber, int controlPeriodMs); +void c_TalonSRX_Destroy(void *handle); +CTR_Code c_TalonSRX_SetParam(void *handle, int paramEnum, double value); +CTR_Code c_TalonSRX_RequestParam(void *handle, int paramEnum); +CTR_Code c_TalonSRX_GetParamResponse(void *handle, int paramEnum, + double *value); +CTR_Code c_TalonSRX_GetParamResponseInt32(void *handle, int paramEnum, + int *value); +CTR_Code c_TalonSRX_SetStatusFrameRate(void *handle, unsigned frameEnum, + unsigned periodMs); +CTR_Code c_TalonSRX_ClearStickyFaults(void *handle); +CTR_Code c_TalonSRX_GetFault_OverTemp(void *handle, int *param); +CTR_Code c_TalonSRX_GetFault_UnderVoltage(void *handle, int *param); +CTR_Code c_TalonSRX_GetFault_ForLim(void *handle, int *param); +CTR_Code c_TalonSRX_GetFault_RevLim(void *handle, int *param); +CTR_Code c_TalonSRX_GetFault_HardwareFailure(void *handle, int *param); +CTR_Code c_TalonSRX_GetFault_ForSoftLim(void *handle, int *param); +CTR_Code c_TalonSRX_GetFault_RevSoftLim(void *handle, int *param); +CTR_Code c_TalonSRX_GetStckyFault_OverTemp(void *handle, int *param); +CTR_Code c_TalonSRX_GetStckyFault_UnderVoltage(void *handle, int *param); +CTR_Code c_TalonSRX_GetStckyFault_ForLim(void *handle, int *param); +CTR_Code c_TalonSRX_GetStckyFault_RevLim(void *handle, int *param); +CTR_Code c_TalonSRX_GetStckyFault_ForSoftLim(void *handle, int *param); +CTR_Code c_TalonSRX_GetStckyFault_RevSoftLim(void *handle, int *param); +CTR_Code c_TalonSRX_GetAppliedThrottle(void *handle, int *param); +CTR_Code c_TalonSRX_GetCloseLoopErr(void *handle, int *param); +CTR_Code c_TalonSRX_GetFeedbackDeviceSelect(void *handle, int *param); +CTR_Code c_TalonSRX_GetModeSelect(void *handle, int *param); +CTR_Code c_TalonSRX_GetLimitSwitchEn(void *handle, int *param); +CTR_Code c_TalonSRX_GetLimitSwitchClosedFor(void *handle, int *param); +CTR_Code c_TalonSRX_GetLimitSwitchClosedRev(void *handle, int *param); +CTR_Code c_TalonSRX_GetSensorPosition(void *handle, int *param); +CTR_Code c_TalonSRX_GetSensorVelocity(void *handle, int *param); +CTR_Code c_TalonSRX_GetCurrent(void *handle, double *param); +CTR_Code c_TalonSRX_GetBrakeIsEnabled(void *handle, int *param); +CTR_Code c_TalonSRX_GetEncPosition(void *handle, int *param); +CTR_Code c_TalonSRX_GetEncVel(void *handle, int *param); +CTR_Code c_TalonSRX_GetEncIndexRiseEvents(void *handle, int *param); +CTR_Code c_TalonSRX_GetQuadApin(void *handle, int *param); +CTR_Code c_TalonSRX_GetQuadBpin(void *handle, int *param); +CTR_Code c_TalonSRX_GetQuadIdxpin(void *handle, int *param); +CTR_Code c_TalonSRX_GetAnalogInWithOv(void *handle, int *param); +CTR_Code c_TalonSRX_GetAnalogInVel(void *handle, int *param); +CTR_Code c_TalonSRX_GetTemp(void *handle, double *param); +CTR_Code c_TalonSRX_GetBatteryV(void *handle, double *param); +CTR_Code c_TalonSRX_GetResetCount(void *handle, int *param); +CTR_Code c_TalonSRX_GetResetFlags(void *handle, int *param); +CTR_Code c_TalonSRX_GetFirmVers(void *handle, int *param); +CTR_Code c_TalonSRX_SetDemand(void *handle, int param); +CTR_Code c_TalonSRX_SetOverrideLimitSwitchEn(void *handle, int param); +CTR_Code c_TalonSRX_SetFeedbackDeviceSelect(void *handle, int param); +CTR_Code c_TalonSRX_SetRevMotDuringCloseLoopEn(void *handle, int param); +CTR_Code c_TalonSRX_SetOverrideBrakeType(void *handle, int param); +CTR_Code c_TalonSRX_SetModeSelect(void *handle, int param); +CTR_Code c_TalonSRX_SetProfileSlotSelect(void *handle, int param); +CTR_Code c_TalonSRX_SetRampThrottle(void *handle, int param); +CTR_Code c_TalonSRX_SetRevFeedbackSensor(void *handle, int param); } #endif - diff --git a/wpilibc/wpilibC++Devices/include/ctre/CtreCanNode.h b/wpilibc/wpilibC++Devices/include/ctre/CtreCanNode.h index 59e09398f0..671f4d0688 100644 --- a/wpilibc/wpilibC++Devices/include/ctre/CtreCanNode.h +++ b/wpilibc/wpilibC++Devices/include/ctre/CtreCanNode.h @@ -1,116 +1,97 @@ #ifndef CtreCanNode_H_ #define CtreCanNode_H_ -#include "ctre.h" //BIT Defines + Typedefs -#include //CAN Comm +#include "ctre.h" //BIT Defines + Typedefs +#include //CAN Comm #include #include -#include // memcpy +#include // memcpy #include -class CtreCanNode -{ -public: - CtreCanNode(UINT8 deviceNumber); - ~CtreCanNode(); +class CtreCanNode { + public: + CtreCanNode(UINT8 deviceNumber); + ~CtreCanNode(); - UINT8 GetDeviceNumber() - { - return _deviceNumber; - } -protected: + UINT8 GetDeviceNumber() { return _deviceNumber; } + protected: + template + class txTask { + public: + uint32_t arbId; + T *toSend; + T *operator->() { return toSend; } + T &operator*() { return *toSend; } + bool IsEmpty() { + if (toSend == 0) return true; + return false; + } + }; + template + class recMsg { + public: + uint32_t arbId; + uint8_t bytes[8]; + CTR_Code err; + T *operator->() { return (T *)bytes; } + T &operator*() { return *(T *)bytes; } + }; + UINT8 _deviceNumber; + void RegisterRx(uint32_t arbId); + void RegisterTx(uint32_t arbId, uint32_t periodMs); - template class txTask{ - public: - uint32_t arbId; - T * toSend; - T * operator -> () - { - return toSend; - } - T & operator*() - { - return *toSend; - } - bool IsEmpty() - { - if(toSend == 0) - return true; - return false; - } - }; - template class recMsg{ - public: - uint32_t arbId; - uint8_t bytes[8]; - CTR_Code err; - T * operator -> () - { - return (T *)bytes; - } - T & operator*() - { - return *(T *)bytes; - } - }; - UINT8 _deviceNumber; - void RegisterRx(uint32_t arbId); - void RegisterTx(uint32_t arbId, uint32_t periodMs); + CTR_Code GetRx(uint32_t arbId, uint8_t *dataBytes, uint32_t timeoutMs); + void FlushTx(uint32_t arbId); - CTR_Code GetRx(uint32_t arbId,uint8_t * dataBytes,uint32_t timeoutMs); - void FlushTx(uint32_t arbId); + template + txTask GetTx(uint32_t arbId) { + txTask retval = {0}; + txJobs_t::iterator i = _txJobs.find(arbId); + if (i != _txJobs.end()) { + retval.arbId = i->second.arbId; + retval.toSend = (T *)i->second.toSend; + } + return retval; + } + template + void FlushTx(T &par) { + FlushTx(par.arbId); + } - template txTask GetTx(uint32_t arbId) - { - txTask retval = {0}; - txJobs_t::iterator i = _txJobs.find(arbId); - if(i != _txJobs.end()){ - retval.arbId = i->second.arbId; - retval.toSend = (T*)i->second.toSend; - } - return retval; - } - template void FlushTx(T & par) - { - FlushTx(par.arbId); - } + template + recMsg GetRx(uint32_t arbId, uint32_t timeoutMs) { + recMsg retval; + retval.err = GetRx(arbId, retval.bytes, timeoutMs); + return retval; + } - template recMsg GetRx(uint32_t arbId, uint32_t timeoutMs) - { - recMsg retval; - retval.err = GetRx(arbId,retval.bytes, timeoutMs); - return retval; - } + private: + class txJob_t { + public: + uint32_t arbId; + uint8_t toSend[8]; + uint32_t periodMs; + }; -private: + class rxEvent_t { + public: + uint8_t bytes[8]; + struct timespec time; + rxEvent_t() { + bytes[0] = 0; + bytes[1] = 0; + bytes[2] = 0; + bytes[3] = 0; + bytes[4] = 0; + bytes[5] = 0; + bytes[6] = 0; + bytes[7] = 0; + } + }; - class txJob_t { - public: - uint32_t arbId; - uint8_t toSend[8]; - uint32_t periodMs; - }; + typedef std::map txJobs_t; + txJobs_t _txJobs; - class rxEvent_t{ - public: - uint8_t bytes[8]; - struct timespec time; - rxEvent_t() - { - bytes[0] = 0; - bytes[1] = 0; - bytes[2] = 0; - bytes[3] = 0; - bytes[4] = 0; - bytes[5] = 0; - bytes[6] = 0; - bytes[7] = 0; - } - }; - - typedef std::map txJobs_t; - txJobs_t _txJobs; - - typedef std::map rxRxEvents_t; - rxRxEvents_t _rxRxEvents; + typedef std::map rxRxEvents_t; + rxRxEvents_t _rxRxEvents; }; #endif diff --git a/wpilibc/wpilibC++Devices/include/ctre/ctre.h b/wpilibc/wpilibC++Devices/include/ctre/ctre.h index c2d3f69614..01d4c55e5e 100644 --- a/wpilibc/wpilibC++Devices/include/ctre/ctre.h +++ b/wpilibc/wpilibC++Devices/include/ctre/ctre.h @@ -1,7 +1,7 @@ #ifndef GLOBAL_H #define GLOBAL_H -//Bit Defines +// Bit Defines #define BIT0 0x01 #define BIT1 0x02 #define BIT2 0x04 @@ -10,8 +10,8 @@ #define BIT5 0x20 #define BIT6 0x40 #define BIT7 0x80 -#define BIT8 0x0100 -#define BIT9 0x0200 +#define BIT8 0x0100 +#define BIT9 0x0200 #define BIT10 0x0400 #define BIT11 0x0800 #define BIT12 0x1000 @@ -19,32 +19,33 @@ #define BIT14 0x4000 #define BIT15 0x8000 -//Signed -typedef signed char INT8; -typedef signed short INT16; -typedef signed int INT32; -typedef signed long long INT64; +// Signed +typedef signed char INT8; +typedef signed short INT16; +typedef signed int INT32; +typedef signed long long INT64; -//Unsigned -typedef unsigned char UINT8; -typedef unsigned short UINT16; -typedef unsigned int UINT32; -typedef unsigned long long UINT64; +// Unsigned +typedef unsigned char UINT8; +typedef unsigned short UINT16; +typedef unsigned int UINT32; +typedef unsigned long long UINT64; -//Other -typedef unsigned char UCHAR; -typedef unsigned short USHORT; -typedef unsigned int UINT; -typedef unsigned long ULONG; +// Other +typedef unsigned char UCHAR; +typedef unsigned short USHORT; +typedef unsigned int UINT; +typedef unsigned long ULONG; typedef enum { - CTR_OKAY, //!< No Error - Function executed as expected - CTR_RxTimeout, //!< CAN frame has not been received within specified period of time. - CTR_TxTimeout, //!< Not used. - CTR_InvalidParamValue, //!< Caller passed an invalid param - CTR_UnexpectedArbId, //!< Specified CAN Id is invalid. - CTR_TxFailed, //!< Could not transmit the CAN frame. - CTR_SigNotUpdated, //!< Have not received an value response for signal. -}CTR_Code; + CTR_OKAY, //!< No Error - Function executed as expected + CTR_RxTimeout, //!< CAN frame has not been received within specified period + //of time. + CTR_TxTimeout, //!< Not used. + CTR_InvalidParamValue, //!< Caller passed an invalid param + CTR_UnexpectedArbId, //!< Specified CAN Id is invalid. + CTR_TxFailed, //!< Could not transmit the CAN frame. + CTR_SigNotUpdated, //!< Have not received an value response for signal. +} CTR_Code; #endif diff --git a/wpilibc/wpilibC++Devices/include/nivision.h b/wpilibc/wpilibC++Devices/include/nivision.h index 09bb9842e7..4289922e40 100644 --- a/wpilibc/wpilibC++Devices/include/nivision.h +++ b/wpilibc/wpilibC++Devices/include/nivision.h @@ -15,32 +15,31 @@ //============================================================================ #include - //============================================================================ // Control Defines //============================================================================ #if !defined(IMAQ_IMPORT) - #ifndef __GNUC__ - #define IMAQ_IMPORT __declspec(dllimport) - #else - #define IMAQ_IMPORT - #endif +#ifndef __GNUC__ +#define IMAQ_IMPORT __declspec(dllimport) +#else +#define IMAQ_IMPORT +#endif #endif #if !defined(IMAQ_FUNC) - #if !defined(__cplusplus) - #define IMAQ_FUNC IMAQ_IMPORT - #else - #define IMAQ_FUNC extern "C" IMAQ_IMPORT - #endif +#if !defined(__cplusplus) +#define IMAQ_FUNC IMAQ_IMPORT +#else +#define IMAQ_FUNC extern "C" IMAQ_IMPORT +#endif #endif #if !defined(IMAQ_STDCALL) - #ifndef __GNUC__ - #define IMAQ_STDCALL __stdcall - #else - #define IMAQ_STDCALL - #endif +#ifndef __GNUC__ +#define IMAQ_STDCALL __stdcall +#else +#define IMAQ_STDCALL +#endif #endif #ifdef _CVI_ @@ -54,19 +53,19 @@ // Manifest Constants //============================================================================ #ifndef NULL - #ifdef __cplusplus - #define NULL 0 - #else - #define NULL ((void *)0) - #endif +#ifdef __cplusplus +#define NULL 0 +#else +#define NULL ((void*)0) +#endif #endif #ifndef FALSE - #define FALSE 0 +#define FALSE 0 #endif #ifndef TRUE - #define TRUE 1 +#define TRUE 1 #endif #define IMAQ_DEFAULT_SHOW_COORDINATES TRUE @@ -77,2146 +76,3781 @@ #define IMAQ_DEFAULT_JPEG_QUALITY 750 #define IMAQ_ALL_CONTOURS -1 #define IMAQ_ALL_WINDOWS -1 -#define IMAQ_SHIFT 1 -#define IMAQ_ALT 2 -#define IMAQ_CTRL 4 -#define IMAQ_CAPS_LOCK 8 +#define IMAQ_SHIFT 1 +#define IMAQ_ALT 2 +#define IMAQ_CTRL 4 +#define IMAQ_CAPS_LOCK 8 #define IMAQ_MODAL_DIALOG -1 -#define IMAQ_INIT_RGB_TRANSPARENT { 0, 0, 0, 1 } -#define IMAQ_INIT_RGB_RED { 0, 0, 255, 0 } -#define IMAQ_INIT_RGB_BLUE { 255, 0, 0, 0 } -#define IMAQ_INIT_RGB_GREEN { 0, 255, 0, 0 } -#define IMAQ_INIT_RGB_YELLOW { 0, 255, 255, 0 } -#define IMAQ_INIT_RGB_WHITE { 255, 255, 255, 0 } -#define IMAQ_INIT_RGB_BLACK { 0, 0, 0, 0 } -#define IMAQ_USE_DEFAULT_QUALITY -1 -#define IMAQ_ALL_SAMPLES -1 -#define IMAQ_ALL_OBJECTS -1 -#define IMAQ_ALL_CHARACTERS -1 +#define IMAQ_INIT_RGB_TRANSPARENT \ + { 0, 0, 0, 1 } +#define IMAQ_INIT_RGB_RED \ + { 0, 0, 255, 0 } +#define IMAQ_INIT_RGB_BLUE \ + { 255, 0, 0, 0 } +#define IMAQ_INIT_RGB_GREEN \ + { 0, 255, 0, 0 } +#define IMAQ_INIT_RGB_YELLOW \ + { 0, 255, 255, 0 } +#define IMAQ_INIT_RGB_WHITE \ + { 255, 255, 255, 0 } +#define IMAQ_INIT_RGB_BLACK \ + { 0, 0, 0, 0 } +#define IMAQ_USE_DEFAULT_QUALITY -1 +#define IMAQ_ALL_SAMPLES -1 +#define IMAQ_ALL_OBJECTS -1 +#define IMAQ_ALL_CHARACTERS -1 //============================================================================ // Predefined Valid Characters //============================================================================ -#define IMAQ_ANY_CHARACTER "" //Any Character -#define IMAQ_ALPHABETIC "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" //Alphabetic -#define IMAQ_ALPHANUMERIC "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789" //Alphanumeric -#define IMAQ_UPPERCASE_LETTERS "ABCDEFGHIJKLMNOPQRSTUVWXYZ" //Uppercase Letters -#define IMAQ_LOWERCASE_LETTERS "abcdefghijklmnopqrstuvwxyz" //Lowercase Letters -#define IMAQ_DECIMAL_DIGITS "0123456789" //Decimal Digits -#define IMAQ_HEXADECIMAL_DIGITS "0123456789ABCDEFabcdef" //Hexadecimal Digits -#define IMAQ_PATTERN "\xFF" //Pattern (A single character string with the character value set to 255) -#define IMAQ_FORCE_SPACE " " //Force Space +#define IMAQ_ANY_CHARACTER "" // Any Character +#define IMAQ_ALPHABETIC \ + "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" // Alphabetic +#define IMAQ_ALPHANUMERIC \ + "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789" // Alphanumeric +#define IMAQ_UPPERCASE_LETTERS "ABCDEFGHIJKLMNOPQRSTUVWXYZ" // Uppercase + // Letters +#define IMAQ_LOWERCASE_LETTERS "abcdefghijklmnopqrstuvwxyz" // Lowercase + // Letters +#define IMAQ_DECIMAL_DIGITS "0123456789" // Decimal Digits +#define IMAQ_HEXADECIMAL_DIGITS "0123456789ABCDEFabcdef" // Hexadecimal Digits +#define IMAQ_PATTERN \ + "\xFF" // Pattern (A single character string with the character value set to + // 255) +#define IMAQ_FORCE_SPACE " " // Force Space //============================================================================ // Macros //============================================================================ -#define IMAQ_NO_RECT imaqMakeRect( 0, 0, 0x7FFFFFFF, 0x7FFFFFFF) -#define IMAQ_NO_ROTATED_RECT imaqMakeRotatedRect( 0, 0, 0x7FFFFFFF, 0x7FFFFFFF, 0) -#define IMAQ_NO_POINT imaqMakePoint( -1, -1) -#define IMAQ_NO_POINT_FLOAT imaqMakePointFloat( -1.0, -1.0 ) -#define IMAQ_NO_OFFSET imaqMakePointFloat( 0.0, 0.0 ) - - +#define IMAQ_NO_RECT imaqMakeRect(0, 0, 0x7FFFFFFF, 0x7FFFFFFF) +#define IMAQ_NO_ROTATED_RECT \ + imaqMakeRotatedRect(0, 0, 0x7FFFFFFF, 0x7FFFFFFF, 0) +#define IMAQ_NO_POINT imaqMakePoint(-1, -1) +#define IMAQ_NO_POINT_FLOAT imaqMakePointFloat(-1.0, -1.0) +#define IMAQ_NO_OFFSET imaqMakePointFloat(0.0, 0.0) //============================================================================ // When in Borland, some functions must be mapped to different names. // This accomplishes said task. //============================================================================ #if defined(__BORLANDC__) || (defined(_CVI_) && defined(_NI_BC_)) - #define imaqMakePoint imaqMakePoint_BC - #define imaqMakePointFloat imaqMakePointFloat_BC +#define imaqMakePoint imaqMakePoint_BC +#define imaqMakePointFloat imaqMakePointFloat_BC #endif - //============================================================================ // When in Watcom, some functions must be mapped to different names. // This accomplishes said task. //============================================================================ #if defined(__WATCOMC__) || (defined(_CVI_) && defined(_NI_WC_)) - #define imaqMakePoint imaqMakePoint_BC - #define imaqMakePointFloat imaqMakePointFloat_BC +#define imaqMakePoint imaqMakePoint_BC +#define imaqMakePointFloat imaqMakePointFloat_BC #endif //============================================================================ // If using Visual C++, force startup & shutdown code to run. //============================================================================ #if defined(_MSC_VER) && !defined(_CVI_) && !defined(__BORLANDC__) - #pragma comment(linker, "/INCLUDE:_nivision_startup_shutdown") - #pragma comment(linker, "/DEFAULTLIB:nivision.lib") +#pragma comment(linker, "/INCLUDE:_nivision_startup_shutdown") +#pragma comment(linker, "/DEFAULTLIB:nivision.lib") #endif //============================================================================ // Error Codes //============================================================================ -#define ERR_SUCCESS 0 // No error. -#define ERR_SYSTEM_ERROR -1074396160 // System error. -#define ERR_OUT_OF_MEMORY -1074396159 // Not enough memory for requested operation. -#define ERR_MEMORY_ERROR -1074396158 // Memory error. -#define ERR_UNREGISTERED -1074396157 // Unlicensed copy of NI Vision. -#define ERR_NEED_FULL_VERSION -1074396156 // The function requires an NI Vision 5.0 Advanced license. -#define ERR_UNINIT -1074396155 // NI Vision did not initialize properly. -#define ERR_IMAGE_TOO_SMALL -1074396154 // The image is not large enough for the operation. -#define ERR_BARCODE_CODABAR -1074396153 // The barcode is not a valid Codabar barcode. -#define ERR_BARCODE_CODE39 -1074396152 // The barcode is not a valid Code 3 of 9 barcode. -#define ERR_BARCODE_CODE93 -1074396151 // The barcode is not a valid Code93 barcode. -#define ERR_BARCODE_CODE128 -1074396150 // The barcode is not a valid Code128 barcode. -#define ERR_BARCODE_EAN8 -1074396149 // The barcode is not a valid EAN8 barcode. -#define ERR_BARCODE_EAN13 -1074396148 // The barcode is not a valid EAN13 barcode. -#define ERR_BARCODE_I25 -1074396147 // The barcode is not a valid Interleaved 2 of 5 barcode. -#define ERR_BARCODE_MSI -1074396146 // The barcode is not a valid MSI barcode. -#define ERR_BARCODE_UPCA -1074396145 // The barcode is not a valid UPCA barcode. -#define ERR_BARCODE_CODE93_SHIFT -1074396144 // The Code93 barcode contains invalid shift encoding. -#define ERR_BARCODE_TYPE -1074396143 // The barcode type is invalid. -#define ERR_BARCODE_INVALID -1074396142 // The image does not represent a valid linear barcode. -#define ERR_BARCODE_CODE128_FNC -1074396141 // The FNC value in the Code128 barcode is not located before the first data value. -#define ERR_BARCODE_CODE128_SET -1074396140 // The starting code set in the Code128 barcode is not valid. -#define ERR_ROLLBACK_RESOURCE_OUT_OF_MEMORY -1074396139 // Not enough reserved memory in the timed environment for the requested operation. -#define ERR_ROLLBACK_NOT_SUPPORTED -1074396138 // The function is not supported when a time limit is active. -#define ERR_DIRECTX_DLL_NOT_FOUND -1074396137 // Quartz.dll not found. Install DirectX 8.1 or later. -#define ERR_DIRECTX_INVALID_FILTER_QUALITY -1074396136 // The filter quality you provided is invalid. Valid quality values range from -1 to 1000. -#define ERR_INVALID_BUTTON_LABEL -1074396135 // Invalid button label. -#define ERR_THREAD_INITIALIZING -1074396134 // Could not execute the function in the separate thread because the thread has not completed initialization. -#define ERR_THREAD_COULD_NOT_INITIALIZE -1074396133 // Could not execute the function in the separate thread because the thread could not initialize. -#define ERR_MASK_NOT_TEMPLATE_SIZE -1074396132 // The mask must be the same size as the template. -#define ERR_NOT_RECT_OR_ROTATED_RECT -1074396130 // The ROI must only have either a single Rectangle contour or a single Rotated Rectangle contour. -#define ERR_ROLLBACK_UNBOUNDED_INTERFACE -1074396129 // During timed execution, you must use the preallocated version of this operation. -#define ERR_ROLLBACK_RESOURCE_CONFLICT_3 -1074396128 // An image being modified by one process cannot be requested by another process while a time limit is active. -#define ERR_ROLLBACK_RESOURCE_CONFLICT_2 -1074396127 // An image with pattern matching, calibration, or overlay information cannot be manipulated while a time limit is active. -#define ERR_ROLLBACK_RESOURCE_CONFLICT_1 -1074396126 // An image created before a time limit is started cannot be resized while a time limit is active. -#define ERR_INVALID_CONTRAST_THRESHOLD -1074396125 // Invalid contrast threshold. The threshold value must be greater than 0. -#define ERR_INVALID_CALIBRATION_ROI_MODE -1074396124 // NI Vision does not support the calibration ROI mode you supplied. -#define ERR_INVALID_CALIBRATION_MODE -1074396123 // NI Vision does not support the calibration mode you supplied. -#define ERR_DRAWTEXT_COLOR_MUST_BE_GRAYSCALE -1074396122 // Set the foreground and background text colors to grayscale to draw on a U8 image. -#define ERR_SATURATION_THRESHOLD_OUT_OF_RANGE -1074396121 // The value of the saturation threshold must be from 0 to 255. -#define ERR_NOT_IMAGE -1074396120 // Not an image. -#define ERR_CUSTOMDATA_INVALID_KEY -1074396119 // They custom data key you supplied is invalid. The only valid character values are decimal 32-126 and 161-255. There must also be no repeated, leading, or trailing spaces. -#define ERR_INVALID_STEP_SIZE -1074396118 // Step size must be greater than zero and less than Image size -#define ERR_MATRIX_SIZE -1074396117 // Invalid matrix size in the structuring element. -#define ERR_CALIBRATION_INSF_POINTS -1074396116 // Insufficient number of calibration feature points. -#define ERR_CALIBRATION_IMAGE_CORRECTED -1074396115 // The operation is invalid in a corrected image. -#define ERR_CALIBRATION_INVALID_ROI -1074396114 // The ROI contains an invalid contour type or is not contained in the ROI learned for calibration. -#define ERR_CALIBRATION_IMAGE_UNCALIBRATED -1074396113 // The source/input image has not been calibrated. -#define ERR_INCOMP_MATRIX_SIZE -1074396112 // The number of pixel and real-world coordinates must be equal. -#define ERR_CALIBRATION_FAILED_TO_FIND_GRID -1074396111 // Unable to automatically detect grid because the image is too distorted. -#define ERR_CALIBRATION_INFO_VERSION -1074396110 // Invalid calibration information version. -#define ERR_CALIBRATION_INVALID_SCALING_FACTOR -1074396109 // Invalid calibration scaling factor. -#define ERR_CALIBRATION_ERRORMAP -1074396108 // The calibration error map cannot be computed. -#define ERR_CALIBRATION_INFO_1 -1074396107 // Invalid calibration template image. -#define ERR_CALIBRATION_INFO_2 -1074396106 // Invalid calibration template image. -#define ERR_CALIBRATION_INFO_3 -1074396105 // Invalid calibration template image. -#define ERR_CALIBRATION_INFO_4 -1074396104 // Invalid calibration template image. -#define ERR_CALIBRATION_INFO_5 -1074396103 // Invalid calibration template image. -#define ERR_CALIBRATION_INFO_6 -1074396102 // Invalid calibration template image. -#define ERR_CALIBRATION_INFO_MICRO_PLANE -1074396101 // Invalid calibration template image. -#define ERR_CALIBRATION_INFO_PERSPECTIVE_PROJECTION -1074396100 // Invalid calibration template image. -#define ERR_CALIBRATION_INFO_SIMPLE_TRANSFORM -1074396099 // Invalid calibration template image. -#define ERR_RESERVED_MUST_BE_NULL -1074396098 // You must pass NULL for the reserved parameter. -#define ERR_INVALID_PARTICLE_PARAMETER_VALUE -1074396097 // You entered an invalid selection in the particle parameter. -#define ERR_NOT_AN_OBJECT -1074396096 // Not an object. -#define ERR_CALIBRATION_DUPLICATE_REFERENCE_POINT -1074396095 // The reference points passed are inconsistent. At least two similar pixel coordinates correspond to different real-world coordinates. -#define ERR_ROLLBACK_RESOURCE_CANNOT_UNLOCK -1074396094 // A resource conflict occurred in the timed environment. Two processes cannot manage the same resource and be time bounded. -#define ERR_ROLLBACK_RESOURCE_LOCKED -1074396093 // A resource conflict occurred in the timed environment. Two processes cannot access the same resource and be time bounded. -#define ERR_ROLLBACK_RESOURCE_NON_EMPTY_INITIALIZE -1074396092 // Multiple timed environments are not supported. -#define ERR_ROLLBACK_RESOURCE_UNINITIALIZED_ENABLE -1074396091 // A time limit cannot be started until the timed environment is initialized. -#define ERR_ROLLBACK_RESOURCE_ENABLED -1074396090 // Multiple timed environments are not supported. -#define ERR_ROLLBACK_RESOURCE_REINITIALIZE -1074396089 // The timed environment is already initialized. -#define ERR_ROLLBACK_RESIZE -1074396088 // The results of the operation exceeded the size limits on the output data arrays. -#define ERR_ROLLBACK_STOP_TIMER -1074396087 // No time limit is available to stop. -#define ERR_ROLLBACK_START_TIMER -1074396086 // A time limit could not be set. -#define ERR_ROLLBACK_INIT_TIMER -1074396085 // The timed environment could not be initialized. -#define ERR_ROLLBACK_DELETE_TIMER -1074396084 // No initialized timed environment is available to close. -#define ERR_ROLLBACK_TIMEOUT -1074396083 // The time limit has expired. -#define ERR_PALETTE_NOT_SUPPORTED -1074396082 // Only 8-bit images support the use of palettes. Either do not use a palette, or convert your image to an 8-bit image before using a palette. -#define ERR_BAD_PASSWORD -1074396081 // Incorrect password. -#define ERR_INVALID_IMAGE_TYPE -1074396080 // Invalid image type. -#define ERR_INVALID_METAFILE_HANDLE -1074396079 // Invalid metafile handle. -#define ERR_INCOMP_TYPE -1074396077 // Incompatible image type. -#define ERR_COORD_SYS_FIRST_AXIS -1074396076 // Unable to fit a line for the primary axis. -#define ERR_COORD_SYS_SECOND_AXIS -1074396075 // Unable to fit a line for the secondary axis. -#define ERR_INCOMP_SIZE -1074396074 // Incompatible image size. -#define ERR_MASK_OUTSIDE_IMAGE -1074396073 // When the mask's offset was applied, the mask was entirely outside of the image. -#define ERR_INVALID_BORDER -1074396072 // Invalid image border. -#define ERR_INVALID_SCAN_DIRECTION -1074396071 // Invalid scan direction. -#define ERR_INVALID_FUNCTION -1074396070 // Unsupported function. -#define ERR_INVALID_COLOR_MODE -1074396069 // NI Vision does not support the color mode you specified. -#define ERR_INVALID_ACTION -1074396068 // The function does not support the requested action. -#define ERR_IMAGES_NOT_DIFF -1074396067 // The source image and destination image must be different. -#define ERR_INVALID_POINTSYMBOL -1074396066 // Invalid point symbol. -#define ERR_CANT_RESIZE_EXTERNAL -1074396065 // Cannot resize an image in an acquisition buffer. -#define ERR_EXTERNAL_NOT_SUPPORTED -1074396064 // This operation is not supported for images in an acquisition buffer. -#define ERR_EXTERNAL_ALIGNMENT -1074396063 // The external buffer must be aligned on a 4-byte boundary. The line width and border pixels must be 4-byte aligned, as well. -#define ERR_INVALID_TOLERANCE -1074396062 // The tolerance parameter must be greater than or equal to 0. -#define ERR_INVALID_WINDOW_SIZE -1074396061 // The size of each dimension of the window must be greater than 2 and less than or equal to the size of the image in the corresponding dimension. -#define ERR_JPEG2000_LOSSLESS_WITH_FLOATING_POINT -1074396060 // Lossless compression cannot be used with the floating point wavelet transform mode. Either set the wavelet transform mode to integer, or use lossy compression. -#define ERR_INVALID_MAX_ITERATIONS -1074396059 // Invalid maximum number of iterations. Maximum number of iterations must be greater than zero. -#define ERR_INVALID_ROTATION_MODE -1074396058 // Invalid rotation mode. -#define ERR_INVALID_SEARCH_VECTOR_WIDTH -1074396057 // Invalid search vector width. The width must be an odd number greater than zero. -#define ERR_INVALID_MATRIX_MIRROR_MODE -1074396056 // Invalid matrix mirror mode. -#define ERR_INVALID_ASPECT_RATIO -1074396055 // Invalid aspect ratio. Valid aspect ratios must be greater than or equal to zero. -#define ERR_INVALID_CELL_FILL_TYPE -1074396054 // Invalid cell fill type. -#define ERR_INVALID_BORDER_INTEGRITY -1074396053 // Invalid border integrity. Valid values range from 0 to 100. -#define ERR_INVALID_DEMODULATION_MODE -1074396052 // Invalid demodulation mode. -#define ERR_INVALID_CELL_FILTER_MODE -1074396051 // Invalid cell filter mode. -#define ERR_INVALID_ECC_TYPE -1074396050 // Invalid ECC type. -#define ERR_INVALID_MATRIX_POLARITY -1074396049 // Invalid matrix polarity. -#define ERR_INVALID_CELL_SAMPLE_SIZE -1074396048 // Invalid cell sample size. -#define ERR_INVALID_LINEAR_AVERAGE_MODE -1074396047 // Invalid linear average mode. -#define ERR_INVALID_2D_BARCODE_CONTRAST_FOR_ROI -1074396046 // When using a region of interest that is not a rectangle, you must specify the contrast mode of the barcode as either black on white or white on black. -#define ERR_INVALID_2D_BARCODE_SUBTYPE -1074396045 // Invalid 2-D barcode Data Matrix subtype. -#define ERR_INVALID_2D_BARCODE_SHAPE -1074396044 // Invalid 2-D barcode shape. -#define ERR_INVALID_2D_BARCODE_CELL_SHAPE -1074396043 // Invalid 2-D barcode cell shape. -#define ERR_INVALID_2D_BARCODE_CONTRAST -1074396042 // Invalid 2-D barcode contrast. -#define ERR_INVALID_2D_BARCODE_TYPE -1074396041 // Invalid 2-D barcode type. -#define ERR_DRIVER -1074396040 // Cannot access NI-IMAQ driver. -#define ERR_IO_ERROR -1074396039 // I/O error. -#define ERR_FIND_COORDSYS_MORE_THAN_ONE_EDGE -1074396038 // When searching for a coordinate system, the number of lines to fit must be 1. -#define ERR_TIMEOUT -1074396037 // Trigger timeout. -#define ERR_INVALID_SKELETONMODE -1074396036 // The Skeleton mode you specified is invalid. -#define ERR_TEMPLATEIMAGE_NOCIRCLE -1074396035 // The template image does not contain enough information for learning the aggressive search strategy. -#define ERR_TEMPLATEIMAGE_EDGEINFO -1074396034 // The template image does not contain enough edge information for the sample size(s) requested. -#define ERR_TEMPLATEDESCRIPTOR_LEARNSETUPDATA -1074396033 // Invalid template descriptor. -#define ERR_TEMPLATEDESCRIPTOR_ROTATION_SEARCHSTRATEGY -1074396032 // The template descriptor does not contain data required for the requested search strategy in rotation-invariant matching. -#define ERR_INVALID_TETRAGON -1074396031 // The input tetragon must have four points. The points are specified clockwise starting with the top left point. -#define ERR_TOO_MANY_CLASSIFICATION_SESSIONS -1074396030 // There are too many classification sessions open. You must close a session before you can open another one. -#define ERR_TIME_BOUNDED_EXECUTION_NOT_SUPPORTED -1074396028 // NI Vision no longer supports time-bounded execution. -#define ERR_INVALID_COLOR_RESOLUTION -1074396027 // Invalid Color Resolution for the Color Classifier -#define ERR_INVALID_PROCESS_TYPE_FOR_EDGE_DETECTION -1074396026 // Invalid process type for edge detection. -#define ERR_INVALID_ANGLE_RANGE_FOR_STRAIGHT_EDGE -1074396025 // Angle range value should be equal to or greater than zero. -#define ERR_INVALID_MIN_COVERAGE_FOR_STRAIGHT_EDGE -1074396024 // Minimum coverage value should be greater than zero. -#define ERR_INVALID_ANGLE_TOL_FOR_STRAIGHT_EDGE -1074396023 // The angle tolerance should be equal to or greater than 0.001. -#define ERR_INVALID_SEARCH_MODE_FOR_STRAIGHT_EDGE -1074396022 // Invalid search mode for detecting straight edges -#define ERR_INVALID_KERNEL_SIZE_FOR_EDGE_DETECTION -1074396021 // Invalid kernel size for edge detection. The minimum kernel size is 3, the maximum kernel size is 1073741823 and the kernel size must be odd. -#define ERR_INVALID_GRADING_MODE -1074396020 // Invalid grading mode. -#define ERR_INVALID_THRESHOLD_PERCENTAGE -1074396019 // Invalid threshold percentage. Valid values range from 0 to 100. -#define ERR_INVALID_EDGE_POLARITY_SEARCH_MODE -1074396018 // Invalid edge polarity search mode. -#define ERR_OPENING_NEWER_AIM_GRADING_DATA -1074396017 // The AIM grading data attached to the image you tried to open was created with a newer version of NI Vision. Upgrade to the latest version of NI Vision to read this file. -#define ERR_NO_VIDEO_DRIVER -1074396016 // No video driver is installed. -#define ERR_RPC_EXECUTE_IVB -1074396015 // Unable to establish network connection with remote system. -#define ERR_INVALID_VIDEO_BLIT -1074396014 // RT Video Out does not support displaying the supplied image type at the selected color depth. -#define ERR_INVALID_VIDEO_MODE -1074396013 // Invalid video mode. -#define ERR_RPC_EXECUTE -1074396012 // Unable to display remote image on network connection. -#define ERR_RPC_BIND -1074396011 // Unable to establish network connection. -#define ERR_INVALID_FRAME_NUMBER -1074396010 // Invalid frame number. -#define ERR_DIRECTX -1074396009 // An internal DirectX error has occurred. Try upgrading to the latest version of DirectX. -#define ERR_DIRECTX_NO_FILTER -1074396008 // An appropriate DirectX filter to process this file could not be found. Install the filter that was used to create this AVI. Upgrading to the latest version of DirectX may correct this error. NI Vision requires DirectX 8.1 or higher. -#define ERR_DIRECTX_INCOMPATIBLE_COMPRESSION_FILTER -1074396007 // Incompatible compression filter. -#define ERR_DIRECTX_UNKNOWN_COMPRESSION_FILTER -1074396006 // Unknown compression filter. -#define ERR_INVALID_AVI_SESSION -1074396005 // Invalid AVI session. -#define ERR_DIRECTX_CERTIFICATION_FAILURE -1074396004 // A software key is restricting the use of this compression filter. -#define ERR_AVI_DATA_EXCEEDS_BUFFER_SIZE -1074396003 // The data for this frame exceeds the data buffer size specified when creating the AVI file. -#define ERR_INVALID_LINEGAUGEMETHOD -1074396002 // Invalid line gauge method. -#define ERR_TOO_MANY_AVI_SESSIONS -1074396001 // There are too many AVI sessions open. You must close a session before you can open another one. -#define ERR_FILE_FILE_HEADER -1074396000 // Invalid file header. -#define ERR_FILE_FILE_TYPE -1074395999 // Invalid file type. -#define ERR_FILE_COLOR_TABLE -1074395998 // Invalid color table. -#define ERR_FILE_ARGERR -1074395997 // Invalid parameter. -#define ERR_FILE_OPEN -1074395996 // File is already open for writing. -#define ERR_FILE_NOT_FOUND -1074395995 // File not found. -#define ERR_FILE_TOO_MANY_OPEN -1074395994 // Too many files open. -#define ERR_FILE_IO_ERR -1074395993 // File I/O error. -#define ERR_FILE_PERMISSION -1074395992 // File access denied. -#define ERR_FILE_INVALID_TYPE -1074395991 // NI Vision does not support the file type you specified. -#define ERR_FILE_GET_INFO -1074395990 // Could not read Vision info from file. -#define ERR_FILE_READ -1074395989 // Unable to read data. -#define ERR_FILE_WRITE -1074395988 // Unable to write data. -#define ERR_FILE_EOF -1074395987 // Premature end of file. -#define ERR_FILE_FORMAT -1074395986 // Invalid file format. -#define ERR_FILE_OPERATION -1074395985 // Invalid file operation. -#define ERR_FILE_INVALID_DATA_TYPE -1074395984 // NI Vision does not support the file data type you specified. -#define ERR_FILE_NO_SPACE -1074395983 // Disk full. -#define ERR_INVALID_FRAMES_PER_SECOND -1074395982 // The frames per second in an AVI must be greater than zero. -#define ERR_INSUFFICIENT_BUFFER_SIZE -1074395981 // The buffer that was passed in is not big enough to hold all of the data. -#define ERR_COM_INITIALIZE -1074395980 // Error initializing COM. -#define ERR_INVALID_PARTICLE_INFO -1074395979 // The image has invalid particle information. Call imaqCountParticles on the image to create particle information. -#define ERR_INVALID_PARTICLE_NUMBER -1074395978 // Invalid particle number. -#define ERR_AVI_VERSION -1074395977 // The AVI file was created in a newer version of NI Vision. Upgrade to the latest version of NI Vision to read this AVI file. -#define ERR_NUMBER_OF_PALETTE_COLORS -1074395976 // The color palette must have exactly 0 or 256 entries. -#define ERR_AVI_TIMEOUT -1074395975 // DirectX has timed out reading or writing the AVI file. When closing an AVI file, try adding an additional delay. When reading an AVI file, try reducing CPU and disk load. -#define ERR_UNSUPPORTED_JPEG2000_COLORSPACE_METHOD -1074395974 // NI Vision does not support reading JPEG2000 files with this colorspace method. -#define ERR_JPEG2000_UNSUPPORTED_MULTIPLE_LAYERS -1074395973 // NI Vision does not support reading JPEG2000 files with more than one layer. -#define ERR_DIRECTX_ENUMERATE_FILTERS -1074395972 // DirectX is unable to enumerate the compression filters. This is caused by a third-party compression filter that is either improperly installed or is preventing itself from being enumerated. Remove any recently installed compression filters and try again. -#define ERR_INVALID_OFFSET -1074395971 // The offset you specified must be size 2. -#define ERR_INIT -1074395960 // Initialization error. -#define ERR_CREATE_WINDOW -1074395959 // Unable to create window. -#define ERR_WINDOW_ID -1074395958 // Invalid window ID. -#define ERR_ARRAY_SIZE_MISMATCH -1074395957 // The array sizes are not compatible. -#define ERR_INVALID_QUALITY -1074395956 // The quality you provided is invalid. Valid quality values range from -1 to 1000. -#define ERR_INVALID_MAX_WAVELET_TRANSFORM_LEVEL -1074395955 // Invalid maximum wavelet transform level. Valid values range from 0 to 255. -#define ERR_INVALID_QUANTIZATION_STEP_SIZE -1074395954 // The quantization step size must be greater than or equal to 0. -#define ERR_INVALID_WAVELET_TRANSFORM_MODE -1074395953 // Invalid wavelet transform mode. -#define ERR_ROI_NOT_POINT -1074395952 // The ROI must only have a single Point contour. -#define ERR_ROI_NOT_POINTS -1074395951 // The ROI must only have Point contours. -#define ERR_ROI_NOT_LINE -1074395950 // The ROI must only have a single Line contour. -#define ERR_ROI_NOT_ANNULUS -1074395949 // The ROI must only have a single Annulus contour. -#define ERR_INVALID_MEASURE_PARTICLES_CALIBRATION_MODE -1074395948 // Invalid measure particles calibration mode. -#define ERR_INVALID_PARTICLE_CLASSIFIER_THRESHOLD_TYPE -1074395947 // Invalid particle classifier threshold type. -#define ERR_INVALID_DISTANCE -1074395946 // Invalid Color Segmentation Distance -#define ERR_INVALID_PARTICLE_AREA -1074395945 // Invalid Color Segmenation Particle Area -#define ERR_CLASS_NAME_NOT_FOUND -1074395944 // Required Class name is not found in trained labels/Class names -#define ERR_NUMBER_LABEL_LIMIT_EXCEEDED -1074395943 // Number of Labels exceeded limit of label Image type -#define ERR_INVALID_DISTANCE_LEVEL -1074395942 // Invalid Color Segmentation distance level -#define ERR_INVALID_SVM_TYPE -1074395941 // Invalid SVM model type -#define ERR_INVALID_SVM_KERNEL -1074395940 // Invalid SVM kernel type -#define ERR_NO_SUPPORT_VECTOR_FOUND -1074395939 // No Support Vector is found at SVM training -#define ERR_COST_LABEL_NOT_FOUND -1074395938 // Label name is not found in added samples -#define ERR_EXCEEDED_SVM_MAX_ITERATION -1074395937 // SVM training exceeded maximim Iteration limit -#define ERR_INVALID_SVM_PARAMETER -1074395936 // Invalid SVM Parameter -#define ERR_INVALID_IDENTIFICATION_SCORE -1074395935 // Invalid Identification score. Must be between 0-1000. -#define ERR_INVALID_TEXTURE_FEATURE -1074395934 // Requested for invalid texture feature -#define ERR_INVALID_COOCCURRENCE_LEVEL -1074395933 // The coOccurrence Level must lie between 1 and the maximum pixel value of an image (255 for U8 image) -#define ERR_INVALID_WAVELET_SUBBAND -1074395932 // Request for invalid wavelet subBand -#define ERR_INVALID_FINAL_STEP_SIZE -1074395931 // The final step size must be lesser than the initial step size -#define ERR_INVALID_ENERGY -1074395930 // Minimum Energy should lie between 0 and 100 -#define ERR_INVALID_TEXTURE_LABEL -1074395929 // The classification label must be texture or defect for texture defect classifier -#define ERR_INVALID_WAVELET_TYPE -1074395928 // The wavelet type is invalid -#define ERR_SAME_WAVELET_BANDS_SELECTED -1074395927 // Same Wavelet band is selected multiple times -#define ERR_IMAGE_SIZE_MISMATCH -1074395926 // The two input image sizes are different -#define ERR_NUMBER_CLASS -1074395920 // Invalid number of classes. -#define ERR_INVALID_LUCAS_KANADE_WINDOW_SIZE -1074395888 // Both dimensions of the window size should be odd, greater than 2 and less than 16. -#define ERR_INVALID_MATRIX_TYPE -1074395887 // The type of matrix supplied to the function is not supported. -#define ERR_INVALID_OPTICAL_FLOW_TERMINATION_CRITERIA_TYPE -1074395886 // An invalid termination criteria was specified for the optical flow computation. -#define ERR_LKP_NULL_PYRAMID -1074395885 // The pyramid levels where not properly allocated. -#define ERR_INVALID_PYRAMID_LEVEL -1074395884 // The pyramid level specified cannot be negative -#define ERR_INVALID_LKP_KERNEL -1074395883 // The kernel must be symmetric with non-zero coefficients and of odd size -#define ERR_INVALID_HORN_SCHUNCK_LAMBDA -1074395882 // Invalid smoothing parameter in Horn Schunck operation. -#define ERR_INVALID_HORN_SCHUNCK_TYPE -1074395881 // Invalid stopping criteria type for Horn Schunck optical flow. -#define ERR_PARTICLE -1074395880 // Invalid particle. -#define ERR_BAD_MEASURE -1074395879 // Invalid measure number. -#define ERR_PROP_NODE_WRITE_NOT_SUPPORTED -1074395878 // The Image Display control does not support writing this property node. -#define ERR_COLORMODE_REQUIRES_CHANGECOLORSPACE2 -1074395877 // The specified color mode requires the use of imaqChangeColorSpace2. -#define ERR_UNSUPPORTED_COLOR_MODE -1074395876 // This function does not currently support the color mode you specified. -#define ERR_BARCODE_PHARMACODE -1074395875 // The barcode is not a valid Pharmacode symbol -#define ERR_BAD_INDEX -1074395840 // Invalid handle table index. -#define ERR_INVALID_COMPRESSION_RATIO -1074395837 // The compression ratio must be greater than or equal to 1. -#define ERR_TOO_MANY_CONTOURS -1074395801 // The ROI contains too many contours. -#define ERR_PROTECTION -1074395800 // Protection error. -#define ERR_INTERNAL -1074395799 // Internal error. -#define ERR_INVALID_CUSTOM_SAMPLE -1074395798 // The size of the feature vector in the custom sample must match the size of those you have already added. -#define ERR_INVALID_CLASSIFIER_SESSION -1074395797 // Not a valid classifier session. -#define ERR_INVALID_KNN_METHOD -1074395796 // You requested an invalid Nearest Neighbor classifier method. -#define ERR_K_TOO_LOW -1074395795 // The k parameter must be greater than two. -#define ERR_K_TOO_HIGH -1074395794 // The k parameter must be <= the number of samples in each class. -#define ERR_INVALID_OPERATION_ON_COMPACT_SESSION_ATTEMPTED -1074395793 // This classifier session is compact. Only the Classify and Dispose functions may be called on a compact classifier session. -#define ERR_CLASSIFIER_SESSION_NOT_TRAINED -1074395792 // This classifier session is not trained. You may only call this function on a trained classifier session. -#define ERR_CLASSIFIER_INVALID_SESSION_TYPE -1074395791 // This classifier function cannot be called on this type of classifier session. -#define ERR_INVALID_DISTANCE_METRIC -1074395790 // You requested an invalid distance metric. -#define ERR_OPENING_NEWER_CLASSIFIER_SESSION -1074395789 // The classifier session you tried to open was created with a newer version of NI Vision. Upgrade to the latest version of NI Vision to read this file. -#define ERR_NO_SAMPLES -1074395788 // This operation cannot be performed because you have not added any samples. -#define ERR_INVALID_CLASSIFIER_TYPE -1074395787 // You requested an invalid classifier type. -#define ERR_INVALID_PARTICLE_OPTIONS -1074395786 // The sum of Scale Dependence and Symmetry Dependence must be less than 1000. -#define ERR_NO_PARTICLE -1074395785 // The image yielded no particles. -#define ERR_INVALID_LIMITS -1074395784 // The limits you supplied are not valid. -#define ERR_BAD_SAMPLE_INDEX -1074395783 // The Sample Index fell outside the range of Samples. -#define ERR_DESCRIPTION_TOO_LONG -1074395782 // The description must be <= 255 characters. -#define ERR_CLASSIFIER_INVALID_ENGINE_TYPE -1074395781 // The engine for this classifier session does not support this operation. -#define ERR_INVALID_PARTICLE_TYPE -1074395780 // You requested an invalid particle type. -#define ERR_CANNOT_COMPACT_UNTRAINED -1074395779 // You may only save a session in compact form if it is trained. -#define ERR_INVALID_KERNEL_SIZE -1074395778 // The Kernel size must be smaller than the image size. -#define ERR_INCOMPATIBLE_CLASSIFIER_TYPES -1074395777 // The session you read from file must be the same type as the session you passed in. -#define ERR_INVALID_USE_OF_COMPACT_SESSION_FILE -1074395776 // You can not use a compact classification file with read options other than Read All. -#define ERR_ROI_HAS_OPEN_CONTOURS -1074395775 // The ROI you passed in may only contain closed contours. -#define ERR_NO_LABEL -1074395774 // You must pass in a label. -#define ERR_NO_DEST_IMAGE -1074395773 // You must provide a destination image. -#define ERR_INVALID_REGISTRATION_METHOD -1074395772 // You provided an invalid registration method. -#define ERR_OPENING_NEWER_INSPECTION_TEMPLATE -1074395771 // The golden template you tried to open was created with a newer version of NI Vision. Upgrade to the latest version of NI Vision to read this file. -#define ERR_INVALID_INSPECTION_TEMPLATE -1074395770 // Invalid golden template. -#define ERR_INVALID_EDGE_THICKNESS -1074395769 // Edge Thickness to Ignore must be greater than zero. -#define ERR_INVALID_SCALE -1074395768 // Scale must be greater than zero. -#define ERR_INVALID_ALIGNMENT -1074395767 // The supplied scale is invalid for your template. -#define ERR_DEPRECATED_FUNCTION -1074395766 // This backwards-compatibility function can not be used with this session. Use newer, supported functions instead. -#define ERR_INVALID_NORMALIZATION_METHOD -1074395763 // You must provide a valid normalization method. -#define ERR_INVALID_NIBLACK_DEVIATION_FACTOR -1074395762 // The deviation factor for Niblack local threshold must be between 0 and 1. -#define ERR_BOARD_NOT_FOUND -1074395760 // Board not found. -#define ERR_BOARD_NOT_OPEN -1074395758 // Board not opened. -#define ERR_DLL_NOT_FOUND -1074395757 // DLL not found. -#define ERR_DLL_FUNCTION_NOT_FOUND -1074395756 // DLL function not found. -#define ERR_TRIG_TIMEOUT -1074395754 // Trigger timeout. -#define ERR_CONTOUR_INVALID_REFINEMENTS -1074395746 // Invalid number specified for maximum contour refinements. -#define ERR_TOO_MANY_CURVES -1074395745 // Too many curves extracted from image. Raise the edge threshold or reduce the ROI. -#define ERR_CONTOUR_INVALID_KERNEL_FOR_SMOOTHING -1074395744 // Invalid kernel for contour smoothing. Zero indicates no smoothing, otherwise value must be odd. -#define ERR_CONTOUR_LINE_INVALID -1074395743 // The contour line fit is invalid. Line segment start and stop must differ. -#define ERR_CONTOUR_TEMPLATE_IMAGE_INVALID -1074395742 // The template image must be trained with IMAQ Learn Contour Pattern or be the same size as the target image. -#define ERR_CONTOUR_GPM_FAIL -1074395741 // Matching failed to align the template and target contours. -#define ERR_CONTOUR_OPENING_NEWER_VERSION -1074395740 // The contour you tried to open was created with a newer version of NI Vision. Upgrade to the latest version of NI Vision to read this file. -#define ERR_CONTOUR_CONNECT_DUPLICATE -1074395739 // Only one range is allowed per curve connection constraint type. -#define ERR_CONTOUR_CONNECT_TYPE -1074395738 // Invalid contour connection constraint type. -#define ERR_CONTOUR_MATCH_STR_NOT_APPLICABLE -1074395737 // In order to use contour matching, you must provide a template image that has been trained with IMAQ Learn Contour Pattern -#define ERR_CONTOUR_CURVATURE_KERNEL -1074395736 // Invalid kernel width for curvature calculation. Must be an odd value greater than 1. -#define ERR_CONTOUR_EXTRACT_SELECTION -1074395735 // Invalid Contour Selection method for contour extraction. -#define ERR_CONTOUR_EXTRACT_DIRECTION -1074395734 // Invalid Search Direction for contour extraction. -#define ERR_CONTOUR_EXTRACT_ROI -1074395733 // Invalid ROI for contour extraction. The ROI must contain an annulus, rectangle or rotated rectangle. -#define ERR_CONTOUR_NO_CURVES -1074395732 // No curves were found in the image. -#define ERR_CONTOUR_COMPARE_KERNEL -1074395731 // Invalid Smoothing Kernel width for contour comparison. Must be zero or an odd positive integer. -#define ERR_CONTOUR_COMPARE_SINGLE_IMAGE -1074395730 // If no template image is provided, the target image must contain both a contour with extracted points and a fitted equation. -#define ERR_CONTOUR_INVALID -1074395729 // Invalid contour image. -#define ERR_INVALID_2D_BARCODE_SEARCH_MODE -1074395728 // NI Vision does not support the search mode you provided. -#define ERR_UNSUPPORTED_2D_BARCODE_SEARCH_MODE -1074395727 // NI Vision does not support the search mode you provided for the type of 2D barcode for which you are searching. -#define ERR_MATCHFACTOR_OBSOLETE -1074395726 // matchFactor has been obsoleted. Instead, set the initialMatchListLength and matchListReductionFactor in the MatchPatternAdvancedOptions structure. -#define ERR_DATA_VERSION -1074395725 // The data was stored with a newer version of NI Vision. Upgrade to the latest version of NI Vision to read this data. -#define ERR_CUSTOMDATA_INVALID_SIZE -1074395724 // The size you specified is out of the valid range. -#define ERR_CUSTOMDATA_KEY_NOT_FOUND -1074395723 // The key you specified cannot be found in the image. -#define ERR_CLASSIFIER_CLASSIFY_IMAGE_WITH_CUSTOM_SESSION -1074395722 // Custom classifier sessions only classify feature vectors. They do not support classifying images. -#define ERR_INVALID_BIT_DEPTH -1074395721 // NI Vision does not support the bit depth you supplied for the image you supplied. -#define ERR_BAD_ROI -1074395720 // Invalid ROI. -#define ERR_BAD_ROI_BOX -1074395719 // Invalid ROI global rectangle. -#define ERR_LAB_VERSION -1074395718 // The version of LabVIEW or BridgeVIEW you are running does not support this operation. -#define ERR_INVALID_RANGE -1074395717 // The range you supplied is invalid. -#define ERR_INVALID_SCALING_METHOD -1074395716 // NI Vision does not support the scaling method you provided. -#define ERR_INVALID_CALIBRATION_UNIT -1074395715 // NI Vision does not support the calibration unit you supplied. -#define ERR_INVALID_AXIS_ORIENTATION -1074395714 // NI Vision does not support the axis orientation you supplied. -#define ERR_VALUE_NOT_IN_ENUM -1074395713 // Value not in enumeration. -#define ERR_WRONG_REGION_TYPE -1074395712 // You selected a region that is not of the right type. -#define ERR_NOT_ENOUGH_REGIONS -1074395711 // You specified a viewer that does not contain enough regions. -#define ERR_TOO_MANY_PARTICLES -1074395710 // The image has too many particles for this process. -#define ERR_AVI_UNOPENED_SESSION -1074395709 // The AVI session has not been opened. -#define ERR_AVI_READ_SESSION_REQUIRED -1074395708 // The AVI session is a write session, but this operation requires a read session. -#define ERR_AVI_WRITE_SESSION_REQUIRED -1074395707 // The AVI session is a read session, but this operation requires a write session. -#define ERR_AVI_SESSION_ALREADY_OPEN -1074395706 // This AVI session is already open. You must close it before calling the Create or Open functions. -#define ERR_DATA_CORRUPTED -1074395705 // The data is corrupted and cannot be read. -#define ERR_INVALID_COMPRESSION_TYPE -1074395704 // Invalid compression type. -#define ERR_INVALID_TYPE_OF_FLATTEN -1074395703 // Invalid type of flatten. -#define ERR_INVALID_LENGTH -1074395702 // The length of the edge detection line must be greater than zero. -#define ERR_INVALID_MATRIX_SIZE_RANGE -1074395701 // The maximum Data Matrix barcode size must be equal to or greater than the minimum Data Matrix barcode size. -#define ERR_REQUIRES_WIN2000_OR_NEWER -1074395700 // The function requires the operating system to be Microsoft Windows 2000 or newer. -#define ERR_INVALID_CALIBRATION_METHOD -1074395662 // Invalid calibration method requested -#define ERR_INVALID_OPERATION_ON_COMPACT_CALIBRATION_ATTEMPTED -1074395661 // This calibration is compact. Re-Learning calibration and retrieving thumbnails are not possible with this calibration -#define ERR_INVALID_POLYNOMIAL_MODEL_K_COUNT -1074395660 // Invalid number of K values -#define ERR_INVALID_DISTORTION_MODEL -1074395659 // Invalid distortion model type -#define ERR_CAMERA_MODEL_NOT_AVAILABLE -1074395658 // Camera Model is not learned -#define ERR_INVALID_THUMBNAIL_INDEX -1074395657 // Supplied thumbnail index is invalid -#define ERR_SMOOTH_CONTOURS_MUST_BE_SAME -1074395656 // You must specify the same value for the smooth contours advanced match option for all templates you want to match. -#define ERR_ENABLE_CALIBRATION_SUPPORT_MUST_BE_SAME -1074395655 // You must specify the same value for the enable calibration support advanced match option for all templates you want to match. -#define ERR_GRADING_INFORMATION_NOT_FOUND -1074395654 // The source image does not contain grading information. You must prepare the source image for grading when reading the Data Matrix, and you cannot change the contents of the source image between reading and grading the Data Matrix. -#define ERR_OPENING_NEWER_MULTIPLE_GEOMETRIC_TEMPLATE -1074395653 // The multiple geometric matching template you tried to open was created with a newer version of NI Vision. Upgrade to the latest version of NI Vision to read this file. -#define ERR_OPENING_NEWER_GEOMETRIC_MATCHING_TEMPLATE -1074395652 // The geometric matching template you tried to open was created with a newer version of NI Vision. Upgrade to the latest version of NI Vision to read this file. -#define ERR_EDGE_FILTER_SIZE_MUST_BE_SAME -1074395651 // You must specify the same edge filter size for all the templates you want to match. -#define ERR_CURVE_EXTRACTION_MODE_MUST_BE_SAME -1074395650 // You must specify the same curve extraction mode for all the templates you want to match. -#define ERR_INVALID_GEOMETRIC_FEATURE_TYPE -1074395649 // The geometric feature type specified is invalid. -#define ERR_TEMPLATE_NOT_LEARNED -1074395648 // You supplied a template that was not learned. -#define ERR_INVALID_MULTIPLE_GEOMETRIC_TEMPLATE -1074395647 // Invalid multiple geometric template. -#define ERR_NO_TEMPLATE_TO_LEARN -1074395646 // Need at least one template to learn. -#define ERR_INVALID_NUMBER_OF_LABELS -1074395645 // You supplied an invalid number of labels. -#define ERR_LABEL_TOO_LONG -1074395644 // Labels must be <= 255 characters. -#define ERR_INVALID_NUMBER_OF_MATCH_OPTIONS -1074395643 // You supplied an invalid number of match options. -#define ERR_LABEL_NOT_FOUND -1074395642 // Cannot find a label that matches the one you specified. -#define ERR_DUPLICATE_LABEL -1074395641 // Duplicate labels are not allowed. -#define ERR_TOO_MANY_ZONES -1074395640 // The number of zones found exceeded the capacity of the algorithm. -#define ERR_INVALID_HATCH_STYLE -1074395639 // The hatch style for the window background is invalid. -#define ERR_INVALID_FILL_STYLE -1074395638 // The fill style for the window background is invalid. -#define ERR_HARDWARE_DOESNT_SUPPORT_NONTEARING -1074395637 // Your hardware is not supported by DirectX and cannot be put into NonTearing mode. -#define ERR_DIRECTX_NOT_FOUND -1074395636 // DirectX is required for this feature. Please install the latest version.. -#define ERR_INVALID_SHAPE_DESCRIPTOR -1074395635 // The passed shape descriptor is invalid. -#define ERR_INVALID_MAX_MATCH_OVERLAP -1074395634 // Invalid max match overlap. Values must be between -1 and 100. -#define ERR_INVALID_MIN_MATCH_SEPARATION_SCALE -1074395633 // Invalid minimum match separation scale. Values must be greater than or equal to -1. -#define ERR_INVALID_MIN_MATCH_SEPARATION_ANGLE -1074395632 // Invalid minimum match separation angle. Values must be between -1 and 360. -#define ERR_INVALID_MIN_MATCH_SEPARATION_DISTANCE -1074395631 // Invalid minimum match separation distance. Values must be greater than or equal to -1. -#define ERR_INVALID_MAXIMUM_FEATURES_LEARNED -1074395630 // Invalid maximum number of features learn. Values must be integers greater than zero. -#define ERR_INVALID_MAXIMUM_PIXEL_DISTANCE_FROM_LINE -1074395629 // Invalid maximum pixel distance from line. Values must be positive real numbers. -#define ERR_INVALID_GEOMETRIC_MATCHING_TEMPLATE -1074395628 // Invalid geometric matching template image. -#define ERR_NOT_ENOUGH_TEMPLATE_FEATURES_1 -1074395627 // The template does not contain enough features for geometric matching. -#define ERR_NOT_ENOUGH_TEMPLATE_FEATURES -1074395626 // The template does not contain enough features for geometric matching. -#define ERR_INVALID_MATCH_CONSTRAINT_TYPE -1074395625 // You specified an invalid value for the match constraint value of the range settings. -#define ERR_INVALID_OCCLUSION_RANGE -1074395624 // Invalid occlusion range. Valid values for the bounds range from 0 to 100 and the upper bound must be greater than or equal to the lower bound. -#define ERR_INVALID_SCALE_RANGE -1074395623 // Invalid scale range. Values for the lower bound must be a positive real numbers and the upper bound must be greater than or equal to the lower bound. -#define ERR_INVALID_MATCH_GEOMETRIC_PATTERN_SETUP_DATA -1074395622 // Invalid match geometric pattern setup data. -#define ERR_INVALID_LEARN_GEOMETRIC_PATTERN_SETUP_DATA -1074395621 // Invalid learn geometric pattern setup data. -#define ERR_INVALID_CURVE_EXTRACTION_MODE -1074395620 // Invalid curve extraction mode. -#define ERR_TOO_MANY_OCCLUSION_RANGES -1074395619 // You can specify only one occlusion range. -#define ERR_TOO_MANY_SCALE_RANGES -1074395618 // You can specify only one scale range. -#define ERR_INVALID_NUMBER_OF_FEATURES_RANGE -1074395617 // The minimum number of features must be less than or equal to the maximum number of features. -#define ERR_INVALID_EDGE_FILTER_SIZE -1074395616 // Invalid edge filter size. -#define ERR_INVALID_MINIMUM_FEATURE_STRENGTH -1074395615 // Invalid minimum strength for features. Values must be positive real numbers. -#define ERR_INVALID_MINIMUM_FEATURE_ASPECT_RATIO -1074395614 // Invalid aspect ratio for rectangular features. Values must be positive real numbers in the range 0.01 to 1.0. -#define ERR_INVALID_MINIMUM_FEATURE_LENGTH -1074395613 // Invalid minimum length for linear features. Values must be integers greater than 0. -#define ERR_INVALID_MINIMUM_FEATURE_RADIUS -1074395612 // Invalid minimum radius for circular features. Values must be integers greater than 0. -#define ERR_INVALID_MINIMUM_RECTANGLE_DIMENSION -1074395611 // Invalid minimum rectangle dimension. Values must be integers greater than 0. -#define ERR_INVALID_INITIAL_MATCH_LIST_LENGTH -1074395610 // Invalid initial match list length. Values must be integers greater than 5. -#define ERR_INVALID_SUBPIXEL_TOLERANCE -1074395609 // Invalid subpixel tolerance. Values must be positive real numbers. -#define ERR_INVALID_SUBPIXEL_ITERATIONS -1074395608 // Invalid number of subpixel iterations. Values must be integers greater 10. -#define ERR_INVALID_MAXIMUM_FEATURES_PER_MATCH -1074395607 // Invalid maximum number of features used per match. Values must be integers greater than or equal to zero. -#define ERR_INVALID_MINIMUM_FEATURES_TO_MATCH -1074395606 // Invalid minimum number of features used for matching. Values must be integers greater than zero. -#define ERR_INVALID_MAXIMUM_END_POINT_GAP -1074395605 // Invalid maximum end point gap. Valid values range from 0 to 32767. -#define ERR_INVALID_COLUMN_STEP -1074395604 // Invalid column step. Valid range is 1 to 255. -#define ERR_INVALID_ROW_STEP -1074395603 // Invalid row step. Valid range is 1 to 255. -#define ERR_INVALID_MINIMUM_CURVE_LENGTH -1074395602 // Invalid minimum length. Valid values must be greater than or equal to zero. -#define ERR_INVALID_EDGE_THRESHOLD -1074395601 // Invalid edge threshold. Valid values range from 1 to 360. -#define ERR_INFO_NOT_FOUND -1074395600 // You must provide information about the subimage within the browser. -#define ERR_NIOCR_INVALID_ACCEPTANCE_LEVEL -1074395598 // The acceptance level is outside the valid range of 0 to 1000. -#define ERR_NIOCR_NOT_A_VALID_SESSION -1074395597 // Not a valid OCR session. -#define ERR_NIOCR_INVALID_CHARACTER_SIZE -1074395596 // Invalid character size. Character size must be >= 1. -#define ERR_NIOCR_INVALID_THRESHOLD_MODE -1074395595 // Invalid threshold mode value. -#define ERR_NIOCR_INVALID_SUBSTITUTION_CHARACTER -1074395594 // Invalid substitution character. Valid substitution characters are ASCII values that range from 1 to 254. -#define ERR_NIOCR_INVALID_NUMBER_OF_BLOCKS -1074395593 // Invalid number of blocks. Number of blocks must be >= 4 and <= 50. -#define ERR_NIOCR_INVALID_READ_STRATEGY -1074395592 // Invalid read strategy. -#define ERR_NIOCR_INVALID_CHARACTER_INDEX -1074395591 // Invalid character index. -#define ERR_NIOCR_INVALID_NUMBER_OF_VALID_CHARACTER_POSITIONS -1074395590 // Invalid number of character positions. Valid values range from 0 to 255. -#define ERR_NIOCR_INVALID_LOW_THRESHOLD_VALUE -1074395589 // Invalid low threshold value. Valid threshold values range from 0 to 255. -#define ERR_NIOCR_INVALID_HIGH_THRESHOLD_VALUE -1074395588 // Invalid high threshold value. Valid threshold values range from 0 to 255. -#define ERR_NIOCR_INVALID_THRESHOLD_RANGE -1074395587 // The low threshold must be less than the high threshold. -#define ERR_NIOCR_INVALID_LOWER_THRESHOLD_LIMIT -1074395586 // Invalid lower threshold limit. Valid lower threshold limits range from 0 to 255. -#define ERR_NIOCR_INVALID_UPPER_THRESHOLD_LIMIT -1074395585 // Invalid upper threshold limit. Valid upper threshold limits range from 0 to 255. -#define ERR_NIOCR_INVALID_THRESHOLD_LIMITS -1074395584 // The lower threshold limit must be less than the upper threshold limit. -#define ERR_NIOCR_INVALID_MIN_CHAR_SPACING -1074395583 // Invalid minimum character spacing value. Character spacing must be >= 1 pixel. -#define ERR_NIOCR_INVALID_MAX_HORIZ_ELEMENT_SPACING -1074395582 // Invalid maximum horizontal element spacing value. Maximum horizontal element spacing must be >= 0. -#define ERR_NIOCR_INVALID_MAX_VERT_ELEMENT_SPACING -1074395581 // Invalid maximum vertical element spacing value. Maximum vertical element spacing must be >= 0. -#define ERR_NIOCR_INVALID_MIN_BOUNDING_RECT_WIDTH -1074395580 // Invalid minimum bounding rectangle width. Minimum bounding rectangle width must be >= 1. -#define ERR_NIOCR_INVALID_ASPECT_RATIO -1074395579 // Invalid aspect ratio value. The aspect ratio must be zero or >= 100. -#define ERR_NIOCR_INVALID_CHARACTER_SET_FILE -1074395578 // Invalid or corrupt character set file. -#define ERR_NIOCR_CHARACTER_VALUE_CANNOT_BE_EMPTYSTRING -1074395577 // The character value must not be an empty string. -#define ERR_NIOCR_CHARACTER_VALUE_TOO_LONG -1074395576 // Character values must be <=255 characters. -#define ERR_NIOCR_INVALID_NUMBER_OF_EROSIONS -1074395575 // Invalid number of erosions. The number of erosions must be >= 0. -#define ERR_NIOCR_CHARACTER_SET_DESCRIPTION_TOO_LONG -1074395574 // The character set description must be <=255 characters. -#define ERR_NIOCR_INVALID_CHARACTER_SET_FILE_VERSION -1074395573 // The character set file was created by a newer version of NI Vision. Upgrade to the latest version of NI Vision to read the character set file. -#define ERR_NIOCR_INTEGER_VALUE_FOR_STRING_ATTRIBUTE -1074395572 // You must specify characters for a string. A string cannot contain integers. -#define ERR_NIOCR_GET_ONLY_ATTRIBUTE -1074395571 // This attribute is read-only. -#define ERR_NIOCR_INTEGER_VALUE_FOR_BOOLEAN_ATTRIBUTE -1074395570 // This attribute requires a Boolean value. -#define ERR_NIOCR_INVALID_ATTRIBUTE -1074395569 // Invalid attribute. -#define ERR_NIOCR_STRING_VALUE_FOR_INTEGER_ATTRIBUTE -1074395568 // This attribute requires integer values. -#define ERR_NIOCR_STRING_VALUE_FOR_BOOLEAN_ATTRIBUTE -1074395567 // String values are invalid for this attribute. Enter a boolean value. -#define ERR_NIOCR_BOOLEAN_VALUE_FOR_INTEGER_ATTRIBUTE -1074395566 // Boolean values are not valid for this attribute. Enter an integer value. -#define ERR_NIOCR_MUST_BE_SINGLE_CHARACTER -1074395565 // Requires a single-character string. -#define ERR_NIOCR_INVALID_PREDEFINED_CHARACTER -1074395564 // Invalid predefined character value. -#define ERR_NIOCR_UNLICENSED -1074395563 // This copy of NI OCR is unlicensed. -#define ERR_NIOCR_BOOLEAN_VALUE_FOR_STRING_ATTRIBUTE -1074395562 // String values are not valid for this attribute. Enter a Boolean value. -#define ERR_NIOCR_INVALID_NUMBER_OF_CHARACTERS -1074395561 // The number of characters in the character value must match the number of objects in the image. -#define ERR_NIOCR_INVALID_OBJECT_INDEX -1074395560 // Invalid object index. -#define ERR_NIOCR_INVALID_READ_OPTION -1074395559 // Invalid read option. -#define ERR_NIOCR_INVALID_CHARACTER_SIZE_RANGE -1074395558 // The minimum character size must be less than the maximum character size. -#define ERR_NIOCR_INVALID_BOUNDING_RECT_WIDTH_RANGE -1074395557 // The minimum character bounding rectangle width must be less than the maximum character bounding rectangle width. -#define ERR_NIOCR_INVALID_BOUNDING_RECT_HEIGHT_RANGE -1074395556 // The minimum character bounding rectangle height must be less than the maximum character bounding rectangle height. -#define ERR_NIOCR_INVALID_SPACING_RANGE -1074395555 // The maximum horizontal element spacing value must not exceed the minimum character spacing value. -#define ERR_NIOCR_INVALID_READ_RESOLUTION -1074395554 // Invalid read resolution. -#define ERR_NIOCR_INVALID_MIN_BOUNDING_RECT_HEIGHT -1074395553 // Invalid minimum bounding rectangle height. The minimum bounding rectangle height must be >= 1. -#define ERR_NIOCR_NOT_A_VALID_CHARACTER_SET -1074395552 // Not a valid character set. -#define ERR_NIOCR_RENAME_REFCHAR -1074395551 // A trained OCR character cannot be renamed while it is a reference character. -#define ERR_NIOCR_INVALID_CHARACTER_VALUE -1074395550 // A character cannot have an ASCII value of 255. -#define ERR_NIOCR_INVALID_NUMBER_OF_OBJECTS_TO_VERIFY -1074395549 // The number of objects found does not match the number of expected characters or patterns to verify. -#define ERR_INVALID_STEREO_BLOCKMATCHING_PREFILTER_CAP -1074395421 // The specified value for the filter cap for block matching is invalid. -#define ERR_INVALID_STEREO_BLOCKMATCHING_PREFILTER_SIZE -1074395420 // The specified prefilter size for block matching is invalid. -#define ERR_INVALID_STEREO_BLOCKMATCHING_PREFILTER_TYPE -1074395419 // The specified prefilter type for block matching is invalid. -#define ERR_INVALID_STEREO_BLOCKMATCHING_NUMDISPARITIES -1074395418 // The specifed value for number of disparities is invalid. -#define ERR_INVALID_STEREO_BLOCKMATCHING_WINDOW_SIZE -1074395417 // The specified window size for block matching is invalid. -#define ERR_3DVISION_INVALID_SESSION_TYPE -1074395416 // This 3D vision function cannot be called on this type of 3d vision session. -#define ERR_TOO_MANY_3DVISION_SESSIONS -1074395415 // There are too many 3D vision sessions open. You must close a session before you can open another one. -#define ERR_OPENING_NEWER_3DVISION_SESSION -1074395414 // The 3D vision session you tried to open was created with a newer version of NI Vision. Upgrade to the latest version of NI Vision to read this file. -#define ERR_INVALID_STEREO_BLOCKMATCHING_FILTERTYPE -1074395413 // You have specified an invalid filter type for block matching. -#define ERR_INVALID_STEREO_CAMERA_POSITION -1074395412 // You have requested results at an invalid camera position in the stereo setup. -#define ERR_INVALID_3DVISION_SESSION -1074395411 // Not a valid 3D Vision session. -#define ERR_INVALID_ICONS_PER_LINE -1074395410 // NI Vision does not support less than one icon per line. -#define ERR_INVALID_SUBPIXEL_DIVISIONS -1074395409 // Invalid subpixel divisions. -#define ERR_INVALID_DETECTION_MODE -1074395408 // Invalid detection mode. -#define ERR_INVALID_CONTRAST -1074395407 // Invalid contrast value. Valid contrast values range from 0 to 255. -#define ERR_COORDSYS_NOT_FOUND -1074395406 // The coordinate system could not be found on this image. -#define ERR_INVALID_TEXTORIENTATION -1074395405 // NI Vision does not support the text orientation value you supplied. -#define ERR_INVALID_INTERPOLATIONMETHOD_FOR_UNWRAP -1074395404 // UnwrapImage does not support the interpolation method value you supplied. Valid interpolation methods are zero order and bilinear. -#define ERR_EXTRAINFO_VERSION -1074395403 // The image was created in a newer version of NI Vision. Upgrade to the latest version of NI Vision to use this image. -#define ERR_INVALID_MAXPOINTS -1074395402 // The function does not support the maximum number of points that you specified. -#define ERR_INVALID_MATCHFACTOR -1074395401 // The function does not support the matchFactor that you specified. -#define ERR_MULTICORE_OPERATION -1074395400 // The operation you have given Multicore Options is invalid. Please see the available enumeration values for Multicore Operation. -#define ERR_MULTICORE_INVALID_ARGUMENT -1074395399 // You have given Multicore Options an invalid argument. -#define ERR_COMPLEX_IMAGE_REQUIRED -1074395397 // A complex image is required. -#define ERR_COLOR_IMAGE_REQUIRED -1074395395 // The input image must be a color image. -#define ERR_COLOR_SPECTRUM_MASK -1074395394 // The color mask removes too much color information. -#define ERR_COLOR_TEMPLATE_IMAGE_TOO_SMALL -1074395393 // The color template image is too small. -#define ERR_COLOR_TEMPLATE_IMAGE_TOO_LARGE -1074395392 // The color template image is too large. -#define ERR_COLOR_TEMPLATE_IMAGE_HUE_CONTRAST_TOO_LOW -1074395391 // The contrast in the hue plane of the image is too low for learning shape features. -#define ERR_COLOR_TEMPLATE_IMAGE_LUMINANCE_CONTRAST_TOO_LOW -1074395390 // The contrast in the luminance plane of the image is too low to learn shape features. -#define ERR_COLOR_LEARN_SETUP_DATA -1074395389 // Invalid color learn setup data. -#define ERR_COLOR_LEARN_SETUP_DATA_SHAPE -1074395388 // Invalid color learn setup data. -#define ERR_COLOR_MATCH_SETUP_DATA -1074395387 // Invalid color match setup data. -#define ERR_COLOR_MATCH_SETUP_DATA_SHAPE -1074395386 // Invalid color match setup data. -#define ERR_COLOR_ROTATION_REQUIRES_SHAPE_FEATURE -1074395385 // Rotation-invariant color pattern matching requires a feature mode including shape. -#define ERR_COLOR_TEMPLATE_DESCRIPTOR -1074395384 // Invalid color template image. -#define ERR_COLOR_TEMPLATE_DESCRIPTOR_1 -1074395383 // Invalid color template image. -#define ERR_COLOR_TEMPLATE_DESCRIPTOR_2 -1074395382 // Invalid color template image. -#define ERR_COLOR_TEMPLATE_DESCRIPTOR_3 -1074395381 // Invalid color template image. -#define ERR_COLOR_TEMPLATE_DESCRIPTOR_4 -1074395380 // Invalid color template image. -#define ERR_COLOR_TEMPLATE_DESCRIPTOR_5 -1074395379 // Invalid color template image. -#define ERR_COLOR_TEMPLATE_DESCRIPTOR_6 -1074395378 // Invalid color template image. -#define ERR_COLOR_TEMPLATE_DESCRIPTOR_SHIFT -1074395377 // Invalid color template image. -#define ERR_COLOR_TEMPLATE_DESCRIPTOR_NOSHIFT -1074395376 // The color template image does not contain data required for shift-invariant color matching. -#define ERR_COLOR_TEMPLATE_DESCRIPTOR_SHIFT_1 -1074395375 // Invalid color template image. -#define ERR_COLOR_TEMPLATE_DESCRIPTOR_SHIFT_2 -1074395374 // Invalid color template image. -#define ERR_COLOR_TEMPLATE_DESCRIPTOR_ROTATION -1074395373 // Invalid color template image. -#define ERR_COLOR_TEMPLATE_DESCRIPTOR_NOROTATION -1074395372 // The color template image does not contain data required for rotation-invariant color matching. -#define ERR_COLOR_TEMPLATE_DESCRIPTOR_ROTATION_1 -1074395371 // Invalid color template image. -#define ERR_COLOR_TEMPLATE_DESCRIPTOR_ROTATION_2 -1074395370 // Invalid color template image. -#define ERR_COLOR_TEMPLATE_DESCRIPTOR_ROTATION_3 -1074395369 // Invalid color template image. -#define ERR_COLOR_TEMPLATE_DESCRIPTOR_ROTATION_4 -1074395368 // Invalid color template image. -#define ERR_COLOR_TEMPLATE_DESCRIPTOR_ROTATION_5 -1074395367 // Invalid color template image. -#define ERR_COLOR_TEMPLATE_DESCRIPTOR_NOSHAPE -1074395366 // The color template image does not contain data required for color matching in shape feature mode. -#define ERR_COLOR_TEMPLATE_DESCRIPTOR_NOSPECTRUM -1074395365 // The color template image does not contain data required for color matching in color feature mode. -#define ERR_IGNORE_COLOR_SPECTRUM_SET -1074395364 // The ignore color spectra array is invalid. -#define ERR_INVALID_SUBSAMPLING_RATIO -1074395363 // Invalid subsampling ratio. -#define ERR_INVALID_WIDTH -1074395362 // Invalid pixel width. -#define ERR_INVALID_STEEPNESS -1074395361 // Invalid steepness. -#define ERR_COMPLEX_PLANE -1074395360 // Invalid complex plane. -#define ERR_INVALID_COLOR_IGNORE_MODE -1074395357 // Invalid color ignore mode. -#define ERR_INVALID_MIN_MATCH_SCORE -1074395356 // Invalid minimum match score. Acceptable values range from 0 to 1000. -#define ERR_INVALID_NUM_MATCHES_REQUESTED -1074395355 // Invalid number of matches requested. You must request a minimum of one match. -#define ERR_INVALID_COLOR_WEIGHT -1074395354 // Invalid color weight. Acceptable values range from 0 to 1000. -#define ERR_INVALID_SEARCH_STRATEGY -1074395353 // Invalid search strategy. -#define ERR_INVALID_FEATURE_MODE -1074395352 // Invalid feature mode. -#define ERR_INVALID_RECT -1074395351 // NI Vision does not support rectangles with negative widths or negative heights. -#define ERR_INVALID_VISION_INFO -1074395350 // NI Vision does not support the vision information type you supplied. -#define ERR_INVALID_SKELETONMETHOD -1074395349 // NI Vision does not support the SkeletonMethod value you supplied. -#define ERR_INVALID_3DPLANE -1074395348 // NI Vision does not support the 3DPlane value you supplied. -#define ERR_INVALID_3DDIRECTION -1074395347 // NI Vision does not support the 3DDirection value you supplied. -#define ERR_INVALID_INTERPOLATIONMETHOD_FOR_ROTATE -1074395346 // imaqRotate does not support the InterpolationMethod value you supplied. -#define ERR_INVALID_FLIPAXIS -1074395345 // NI Vision does not support the axis of symmetry you supplied. -#define ERR_FILE_FILENAME_NULL -1074395343 // You must pass a valid file name. Do not pass in NULL. -#define ERR_INVALID_SIZETYPE -1074395340 // NI Vision does not support the SizeType value you supplied. -#define ERR_UNKNOWN_ALGORITHM -1074395336 // You specified the dispatch status of an unknown algorithm. -#define ERR_DISPATCH_STATUS_CONFLICT -1074395335 // You are attempting to set the same algorithm to dispatch and to not dispatch. Remove one of the conflicting settings. -#define ERR_INVALID_CONVERSIONSTYLE -1074395334 // NI Vision does not support the Conversion Method value you supplied. -#define ERR_INVALID_VERTICAL_TEXT_ALIGNMENT -1074395333 // NI Vision does not support the VerticalTextAlignment value you supplied. -#define ERR_INVALID_COMPAREFUNCTION -1074395332 // NI Vision does not support the CompareFunction value you supplied. -#define ERR_INVALID_BORDERMETHOD -1074395331 // NI Vision does not support the BorderMethod value you supplied. -#define ERR_INVALID_BORDER_SIZE -1074395330 // Invalid border size. Acceptable values range from 0 to 50. -#define ERR_INVALID_OUTLINEMETHOD -1074395329 // NI Vision does not support the OutlineMethod value you supplied. -#define ERR_INVALID_INTERPOLATIONMETHOD -1074395328 // NI Vision does not support the InterpolationMethod value you supplied. -#define ERR_INVALID_SCALINGMODE -1074395327 // NI Vision does not support the ScalingMode value you supplied. -#define ERR_INVALID_DRAWMODE_FOR_LINE -1074395326 // imaqDrawLineOnImage does not support the DrawMode value you supplied. -#define ERR_INVALID_DRAWMODE -1074395325 // NI Vision does not support the DrawMode value you supplied. -#define ERR_INVALID_SHAPEMODE -1074395324 // NI Vision does not support the ShapeMode value you supplied. -#define ERR_INVALID_FONTCOLOR -1074395323 // NI Vision does not support the FontColor value you supplied. -#define ERR_INVALID_TEXTALIGNMENT -1074395322 // NI Vision does not support the TextAlignment value you supplied. -#define ERR_INVALID_MORPHOLOGYMETHOD -1074395321 // NI Vision does not support the MorphologyMethod value you supplied. -#define ERR_TEMPLATE_EMPTY -1074395320 // The template image is empty. -#define ERR_INVALID_SUBPIX_TYPE -1074395319 // NI Vision does not support the interpolation type you supplied. -#define ERR_INSF_POINTS -1074395318 // You supplied an insufficient number of points to perform this operation. -#define ERR_UNDEF_POINT -1074395317 // You specified a point that lies outside the image. -#define ERR_INVALID_KERNEL_CODE -1074395316 // Invalid kernel code. -#define ERR_INEFFICIENT_POINTS -1074395315 // You supplied an inefficient set of points to match the minimum score. -#define ERR_WRITE_FILE_NOT_SUPPORTED -1074395313 // Writing files is not supported on this device. -#define ERR_LCD_CALIBRATE -1074395312 // The input image does not seem to be a valid LCD or LED calibration image. -#define ERR_INVALID_COLOR_SPECTRUM -1074395311 // The color spectrum array you provided has an invalid number of elements or contains an element set to not-a-number (NaN). -#define ERR_INVALID_PALETTE_TYPE -1074395310 // NI Vision does not support the PaletteType value you supplied. -#define ERR_INVALID_WINDOW_THREAD_POLICY -1074395309 // NI Vision does not support the WindowThreadPolicy value you supplied. -#define ERR_INVALID_COLORSENSITIVITY -1074395308 // NI Vision does not support the ColorSensitivity value you supplied. -#define ERR_PRECISION_NOT_GTR_THAN_0 -1074395307 // The precision parameter must be greater than 0. -#define ERR_INVALID_TOOL -1074395306 // NI Vision does not support the Tool value you supplied. -#define ERR_INVALID_REFERENCEMODE -1074395305 // NI Vision does not support the ReferenceMode value you supplied. -#define ERR_INVALID_MATHTRANSFORMMETHOD -1074395304 // NI Vision does not support the MathTransformMethod value you supplied. -#define ERR_INVALID_NUM_OF_CLASSES -1074395303 // Invalid number of classes for auto threshold. Acceptable values range from 2 to 256. -#define ERR_INVALID_THRESHOLDMETHOD -1074395302 // NI Vision does not support the threshold method value you supplied. -#define ERR_ROI_NOT_2_LINES -1074395301 // The ROI you passed into imaqGetMeterArc must consist of two lines. -#define ERR_INVALID_METERARCMODE -1074395300 // NI Vision does not support the MeterArcMode value you supplied. -#define ERR_INVALID_COMPLEXPLANE -1074395299 // NI Vision does not support the ComplexPlane value you supplied. -#define ERR_COMPLEXPLANE_NOT_REAL_OR_IMAGINARY -1074395298 // You can perform this operation on a real or an imaginary ComplexPlane only. -#define ERR_INVALID_PARTICLEINFOMODE -1074395297 // NI Vision does not support the ParticleInfoMode value you supplied. -#define ERR_INVALID_BARCODETYPE -1074395296 // NI Vision does not support the BarcodeType value you supplied. -#define ERR_INVALID_INTERPOLATIONMETHOD_INTERPOLATEPOINTS -1074395295 // imaqInterpolatePoints does not support the InterpolationMethod value you supplied. -#define ERR_CONTOUR_INDEX_OUT_OF_RANGE -1074395294 // The contour index you supplied is larger than the number of contours in the ROI. -#define ERR_CONTOURID_NOT_FOUND -1074395293 // The supplied ContourID did not correlate to a contour inside the ROI. -#define ERR_POINTS_ARE_COLLINEAR -1074395292 // Do not supply collinear points for this operation. -#define ERR_SHAPEMATCH_BADIMAGEDATA -1074395291 // Shape Match requires the image to contain only pixel values of 0 or 1. -#define ERR_SHAPEMATCH_BADTEMPLATE -1074395290 // The template you supplied for ShapeMatch contains no shape information. -#define ERR_CONTAINER_CAPACITY_EXCEEDED_UINT_MAX -1074395289 // The operation would have exceeded the capacity of an internal container, which is limited to 4294967296 unique elements. -#define ERR_CONTAINER_CAPACITY_EXCEEDED_INT_MAX -1074395288 // The operation would have exceeded the capacity of an internal container, which is limited to 2147483648 unique elements. -#define ERR_INVALID_LINE -1074395287 // The line you provided contains two identical points, or one of the coordinate locations for the line is not a number (NaN). -#define ERR_INVALID_CONCENTRIC_RAKE_DIRECTION -1074395286 // Invalid concentric rake direction. -#define ERR_INVALID_SPOKE_DIRECTION -1074395285 // Invalid spoke direction. -#define ERR_INVALID_EDGE_PROCESS -1074395284 // Invalid edge process. -#define ERR_INVALID_RAKE_DIRECTION -1074395283 // Invalid rake direction. -#define ERR_CANT_DRAW_INTO_VIEWER -1074395282 // Unable to draw to viewer. You must have the latest version of the control. -#define ERR_IMAGE_SMALLER_THAN_BORDER -1074395281 // Your image must be larger than its border size for this operation. -#define ERR_ROI_NOT_RECT -1074395280 // The ROI must only have a single Rectangle contour. -#define ERR_ROI_NOT_POLYGON -1074395279 // ROI is not a polygon. -#define ERR_LCD_NOT_NUMERIC -1074395278 // LCD image is not a number. -#define ERR_BARCODE_CHECKSUM -1074395277 // The decoded barcode information did not pass the checksum test. -#define ERR_LINES_PARALLEL -1074395276 // You specified parallel lines for the meter ROI. -#define ERR_INVALID_BROWSER_IMAGE -1074395275 // Invalid browser image. -#define ERR_DIV_BY_ZERO -1074395270 // Cannot divide by zero. -#define ERR_NULL_POINTER -1074395269 // Null pointer. -#define ERR_LINEAR_COEFF -1074395268 // The linear equations are not independent. -#define ERR_COMPLEX_ROOT -1074395267 // The roots of the equation are complex. -#define ERR_BARCODE -1074395265 // The barcode does not match the type you specified. -#define ERR_LCD_NO_SEGMENTS -1074395263 // No lit segment. -#define ERR_LCD_BAD_MATCH -1074395262 // The LCD does not form a known digit. -#define ERR_GIP_RANGE -1074395261 // An internal error occurred while attempting to access an invalid coordinate on an image. -#define ERR_HEAP_TRASHED -1074395260 // An internal memory error occurred. -#define ERR_BAD_FILTER_WIDTH -1074395258 // The filter width must be odd for the Canny operator. -#define ERR_INVALID_EDGE_DIR -1074395257 // You supplied an invalid edge direction in the Canny operator. -#define ERR_EVEN_WINDOW_SIZE -1074395256 // The window size must be odd for the Canny operator. -#define ERR_INVALID_LEARN_MODE -1074395253 // Invalid learn mode. -#define ERR_LEARN_SETUP_DATA -1074395252 // Invalid learn setup data. -#define ERR_INVALID_MATCH_MODE -1074395251 // Invalid match mode. -#define ERR_MATCH_SETUP_DATA -1074395250 // Invalid match setup data. -#define ERR_ROTATION_ANGLE_RANGE_TOO_LARGE -1074395249 // At least one range in the array of rotation angle ranges exceeds 360 degrees. -#define ERR_TOO_MANY_ROTATION_ANGLE_RANGES -1074395248 // The array of rotation angle ranges contains too many ranges. -#define ERR_TEMPLATE_DESCRIPTOR -1074395247 // Invalid template descriptor. -#define ERR_TEMPLATE_DESCRIPTOR_1 -1074395246 // Invalid template descriptor. -#define ERR_TEMPLATE_DESCRIPTOR_2 -1074395245 // Invalid template descriptor. -#define ERR_TEMPLATE_DESCRIPTOR_3 -1074395244 // Invalid template descriptor. -#define ERR_TEMPLATE_DESCRIPTOR_4 -1074395243 // The template descriptor was created with a newer version of NI Vision. Upgrade to the latest version of NI Vision to use this template. -#define ERR_TEMPLATE_DESCRIPTOR_ROTATION -1074395242 // Invalid template descriptor. -#define ERR_TEMPLATE_DESCRIPTOR_NOROTATION -1074395241 // The template descriptor does not contain data required for rotation-invariant matching. -#define ERR_TEMPLATE_DESCRIPTOR_ROTATION_1 -1074395240 // Invalid template descriptor. -#define ERR_TEMPLATE_DESCRIPTOR_SHIFT -1074395239 // Invalid template descriptor. -#define ERR_TEMPLATE_DESCRIPTOR_NOSHIFT -1074395238 // The template descriptor does not contain data required for shift-invariant matching. -#define ERR_TEMPLATE_DESCRIPTOR_SHIFT_1 -1074395237 // Invalid template descriptor. -#define ERR_TEMPLATE_DESCRIPTOR_NOSCALE -1074395236 // The template descriptor does not contain data required for scale-invariant matching. -#define ERR_TEMPLATE_IMAGE_CONTRAST_TOO_LOW -1074395235 // The template image does not contain enough contrast. -#define ERR_TEMPLATE_IMAGE_TOO_SMALL -1074395234 // The template image is too small. -#define ERR_TEMPLATE_IMAGE_TOO_LARGE -1074395233 // The template image is too large. -#define ERR_TOO_MANY_OCR_SESSIONS -1074395214 // There are too many OCR sessions open. You must close a session before you can open another one. -#define ERR_OCR_TEMPLATE_WRONG_SIZE -1074395212 // The size of the template string must match the size of the string you are trying to correct. -#define ERR_OCR_BAD_TEXT_TEMPLATE -1074395211 // The supplied text template contains nonstandard characters that cannot be generated by OCR. -#define ERR_OCR_CANNOT_MATCH_TEXT_TEMPLATE -1074395210 // At least one character in the text template was of a lexical class that did not match the supplied character reports. -#define ERR_OCR_LIB_INIT -1074395203 // The OCR library cannot be initialized correctly. -#define ERR_OCR_LOAD_LIBRARY -1074395201 // There was a failure when loading one of the internal OCR engine or LabView libraries. -#define ERR_OCR_INVALID_PARAMETER -1074395200 // One of the parameters supplied to the OCR function that generated this error is invalid. -#define ERR_MARKER_INFORMATION_NOT_SUPPLIED -1074395199 // Marker image and points are not supplied -#define ERR_INCOMPATIBLE_MARKER_IMAGE_SIZE -1074395198 // Source Image and Marker Image should be of same size. -#define ERR_BOTH_MARKER_INPUTS_SUPPLIED -1074395197 // Both Marker Image and Points are supplied. -#define ERR_INVALID_MORPHOLOGICAL_OPERATION -1074395196 // Invalid Morphological Operation. -#define ERR_IMAGE_CONTAINS_NAN_VALUES -1074395195 // Float image contains NaN values -#define ERR_OVERLAY_EXTRAINFO_OPENING_NEW_VERSION -1074395194 // The overlay information you tried to open was created with a newer version of NI Vision. Upgrade to the latest version of NI Vision to read this file. -#define ERR_NO_CLAMP_FOUND -1074395193 // No valid clamp was found with the current configuration -#define ERR_NO_CLAMP_WITHIN_ANGLE_RANGE -1074395192 // Supplied angle range for clamp is insufficient -#define ERR_GHT_INVALID_USE_ALL_CURVES_VALUE -1074395188 // The use all curves advanced option specified during learn is not supported -#define ERR_INVALID_GAUSS_SIGMA_VALUE -1074395187 // The sigma value specified for the Gaussian filter is too small. -#define ERR_INVALID_GAUSS_FILTER_TYPE -1074395186 // The specified Gaussian filter type is not supported. -#define ERR_INVALID_CONTRAST_REVERSAL_MODE -1074395185 // The contrast reversal mode specified during matching is invalid. -#define ERR_INVALID_ROTATION_RANGE -1074395184 // Invalid roation angle range. The upper bound must be greater than or equal to the lower bound. -#define ERR_GHT_INVALID_MINIMUM_LEARN_ANGLE_VALUE -1074395183 // The minimum rotation angle value specifed during learning of the template is not supported. -#define ERR_GHT_INVALID_MAXIMUM_LEARN_ANGLE_VALUE -1074395182 // The maximum rotation angle value specifed during learning of the template is not supported. -#define ERR_GHT_INVALID_MAXIMUM_LEARN_SCALE_FACTOR -1074395181 // The maximum scale factor specifed during learning of the template is not supported. -#define ERR_GHT_INVALID_MINIMUM_LEARN_SCALE_FACTOR -1074395180 // The minimum scale factor specifed during learning of the template is not supported. -#define ERR_OCR_PREPROCESSING_FAILED -1074395179 // The OCR engine failed during the preprocessing stage. -#define ERR_OCR_RECOGNITION_FAILED -1074395178 // The OCR engine failed during the recognition stage. -#define ERR_OCR_BAD_USER_DICTIONARY -1074395175 // The provided filename is not valid user dictionary filename. -#define ERR_OCR_INVALID_AUTOORIENTMODE -1074395174 // NI Vision does not support the AutoOrientMode value you supplied. -#define ERR_OCR_INVALID_LANGUAGE -1074395173 // NI Vision does not support the Language value you supplied. -#define ERR_OCR_INVALID_CHARACTERSET -1074395172 // NI Vision does not support the CharacterSet value you supplied. -#define ERR_OCR_INI_FILE_NOT_FOUND -1074395171 // The system could not locate the initialization file required for OCR initialization. -#define ERR_OCR_INVALID_CHARACTERTYPE -1074395170 // NI Vision does not support the CharacterType value you supplied. -#define ERR_OCR_INVALID_RECOGNITIONMODE -1074395169 // NI Vision does not support the RecognitionMode value you supplied. -#define ERR_OCR_INVALID_AUTOCORRECTIONMODE -1074395168 // NI Vision does not support the AutoCorrectionMode value you supplied. -#define ERR_OCR_INVALID_OUTPUTDELIMITER -1074395167 // NI Vision does not support the OutputDelimiter value you supplied. -#define ERR_OCR_BIN_DIR_NOT_FOUND -1074395166 // The system could not locate the OCR binary directory required for OCR initialization. -#define ERR_OCR_WTS_DIR_NOT_FOUND -1074395165 // The system could not locate the OCR weights directory required for OCR initialization. -#define ERR_OCR_ADD_WORD_FAILED -1074395164 // The supplied word could not be added to the user dictionary. -#define ERR_OCR_INVALID_CHARACTERPREFERENCE -1074395163 // NI Vision does not support the CharacterPreference value you supplied. -#define ERR_OCR_INVALID_CORRECTIONMODE -1074395162 // NI Vision does not support the CorrectionMethod value you supplied. -#define ERR_OCR_INVALID_CORRECTIONLEVEL -1074395161 // NI Vision does not support the CorrectionLevel value you supplied. -#define ERR_OCR_INVALID_MAXPOINTSIZE -1074395160 // NI Vision does not support the maximum point size you supplied. Valid values range from 4 to 72. -#define ERR_OCR_INVALID_TOLERANCE -1074395159 // NI Vision does not support the tolerance value you supplied. Valid values are non-negative. -#define ERR_OCR_INVALID_CONTRASTMODE -1074395158 // NI Vision does not support the ContrastMode value you supplied. -#define ERR_OCR_SKEW_DETECT_FAILED -1074395156 // The OCR attempted to detected the text skew and failed. -#define ERR_OCR_ORIENT_DETECT_FAILED -1074395155 // The OCR attempted to detected the text orientation and failed. -#define ERR_FONT_FILE_FORMAT -1074395153 // Invalid font file format. -#define ERR_FONT_FILE_NOT_FOUND -1074395152 // Font file not found. -#define ERR_OCR_CORRECTION_FAILED -1074395151 // The OCR engine failed during the correction stage. -#define ERR_INVALID_ROUNDING_MODE -1074395150 // NI Vision does not support the RoundingMode value you supplied. -#define ERR_DUPLICATE_TRANSFORM_TYPE -1074395149 // Found a duplicate transform type in the properties array. Each properties array may only contain one behavior for each transform type. -#define ERR_OVERLAY_GROUP_NOT_FOUND -1074395148 // Overlay Group Not Found. -#define ERR_BARCODE_RSSLIMITED -1074395147 // The barcode is not a valid RSS Limited symbol -#define ERR_QR_DETECTION_VERSION -1074395146 // Couldn't determine the correct version of the QR code. -#define ERR_QR_INVALID_READ -1074395145 // Invalid read of the QR code. -#define ERR_QR_INVALID_BARCODE -1074395144 // The barcode that was read contains invalid parameters. -#define ERR_QR_DETECTION_MODE -1074395143 // The data stream that was demodulated could not be read because the mode was not detected. -#define ERR_QR_DETECTION_MODELTYPE -1074395142 // Couldn't determine the correct model of the QR code. -#define ERR_OCR_NO_TEXT_FOUND -1074395141 // The OCR engine could not find any text in the supplied region. -#define ERR_OCR_CHAR_REPORT_CORRUPTED -1074395140 // One of the character reports is no longer usable by the system. -#define ERR_IMAQ_QR_DIMENSION_INVALID -1074395139 // Invalid Dimensions. -#define ERR_OCR_REGION_TOO_SMALL -1074395138 // The OCR region provided was too small to have contained any characters. -#define _FIRST_ERR ERR_SYSTEM_ERROR -#define _LAST_ERR ERR_OCR_REGION_TOO_SMALL +#define ERR_SUCCESS 0 // No error. +#define ERR_SYSTEM_ERROR -1074396160 // System error. +#define ERR_OUT_OF_MEMORY \ + -1074396159 // Not enough memory for requested operation. +#define ERR_MEMORY_ERROR -1074396158 // Memory error. +#define ERR_UNREGISTERED -1074396157 // Unlicensed copy of NI Vision. +#define ERR_NEED_FULL_VERSION \ + -1074396156 // The function requires an NI Vision 5.0 Advanced license. +#define ERR_UNINIT -1074396155 // NI Vision did not initialize properly. +#define ERR_IMAGE_TOO_SMALL \ + -1074396154 // The image is not large enough for the operation. +#define ERR_BARCODE_CODABAR \ + -1074396153 // The barcode is not a valid Codabar barcode. +#define ERR_BARCODE_CODE39 \ + -1074396152 // The barcode is not a valid Code 3 of 9 barcode. +#define ERR_BARCODE_CODE93 \ + -1074396151 // The barcode is not a valid Code93 barcode. +#define ERR_BARCODE_CODE128 \ + -1074396150 // The barcode is not a valid Code128 barcode. +#define ERR_BARCODE_EAN8 \ + -1074396149 // The barcode is not a valid EAN8 barcode. +#define ERR_BARCODE_EAN13 \ + -1074396148 // The barcode is not a valid EAN13 barcode. +#define ERR_BARCODE_I25 \ + -1074396147 // The barcode is not a valid Interleaved 2 of 5 barcode. +#define ERR_BARCODE_MSI -1074396146 // The barcode is not a valid MSI barcode. +#define ERR_BARCODE_UPCA \ + -1074396145 // The barcode is not a valid UPCA barcode. +#define ERR_BARCODE_CODE93_SHIFT \ + -1074396144 // The Code93 barcode contains invalid shift encoding. +#define ERR_BARCODE_TYPE -1074396143 // The barcode type is invalid. +#define ERR_BARCODE_INVALID \ + -1074396142 // The image does not represent a valid linear barcode. +#define ERR_BARCODE_CODE128_FNC \ + -1074396141 // The FNC value in the Code128 barcode is not located before the + // first data value. +#define ERR_BARCODE_CODE128_SET \ + -1074396140 // The starting code set in the Code128 barcode is not valid. +#define ERR_ROLLBACK_RESOURCE_OUT_OF_MEMORY \ + -1074396139 // Not enough reserved memory in the timed environment for the + // requested operation. +#define ERR_ROLLBACK_NOT_SUPPORTED \ + -1074396138 // The function is not supported when a time limit is active. +#define ERR_DIRECTX_DLL_NOT_FOUND \ + -1074396137 // Quartz.dll not found. Install DirectX 8.1 or later. +#define ERR_DIRECTX_INVALID_FILTER_QUALITY \ + -1074396136 // The filter quality you provided is invalid. Valid quality + // values range from -1 to 1000. +#define ERR_INVALID_BUTTON_LABEL -1074396135 // Invalid button label. +#define ERR_THREAD_INITIALIZING \ + -1074396134 // Could not execute the function in the separate thread because + // the thread has not completed initialization. +#define ERR_THREAD_COULD_NOT_INITIALIZE \ + -1074396133 // Could not execute the function in the separate thread because + // the thread could not initialize. +#define ERR_MASK_NOT_TEMPLATE_SIZE \ + -1074396132 // The mask must be the same size as the template. +#define ERR_NOT_RECT_OR_ROTATED_RECT \ + -1074396130 // The ROI must only have either a single Rectangle contour or a + // single Rotated Rectangle contour. +#define ERR_ROLLBACK_UNBOUNDED_INTERFACE \ + -1074396129 // During timed execution, you must use the preallocated version + // of this operation. +#define ERR_ROLLBACK_RESOURCE_CONFLICT_3 \ + -1074396128 // An image being modified by one process cannot be requested by + // another process while a time limit is active. +#define ERR_ROLLBACK_RESOURCE_CONFLICT_2 \ + -1074396127 // An image with pattern matching, calibration, or overlay + // information cannot be manipulated while a time limit is + // active. +#define ERR_ROLLBACK_RESOURCE_CONFLICT_1 \ + -1074396126 // An image created before a time limit is started cannot be + // resized while a time limit is active. +#define ERR_INVALID_CONTRAST_THRESHOLD \ + -1074396125 // Invalid contrast threshold. The threshold value must be + // greater than 0. +#define ERR_INVALID_CALIBRATION_ROI_MODE \ + -1074396124 // NI Vision does not support the calibration ROI mode you + // supplied. +#define ERR_INVALID_CALIBRATION_MODE \ + -1074396123 // NI Vision does not support the calibration mode you supplied. +#define ERR_DRAWTEXT_COLOR_MUST_BE_GRAYSCALE \ + -1074396122 // Set the foreground and background text colors to grayscale to + // draw on a U8 image. +#define ERR_SATURATION_THRESHOLD_OUT_OF_RANGE \ + -1074396121 // The value of the saturation threshold must be from 0 to 255. +#define ERR_NOT_IMAGE -1074396120 // Not an image. +#define ERR_CUSTOMDATA_INVALID_KEY \ + -1074396119 // They custom data key you supplied is invalid. The only valid + // character values are decimal 32-126 and 161-255. There must + // also be no repeated, leading, or trailing spaces. +#define ERR_INVALID_STEP_SIZE \ + -1074396118 // Step size must be greater than zero and less than Image size +#define ERR_MATRIX_SIZE \ + -1074396117 // Invalid matrix size in the structuring element. +#define ERR_CALIBRATION_INSF_POINTS \ + -1074396116 // Insufficient number of calibration feature points. +#define ERR_CALIBRATION_IMAGE_CORRECTED \ + -1074396115 // The operation is invalid in a corrected image. +#define ERR_CALIBRATION_INVALID_ROI \ + -1074396114 // The ROI contains an invalid contour type or is not contained + // in the ROI learned for calibration. +#define ERR_CALIBRATION_IMAGE_UNCALIBRATED \ + -1074396113 // The source/input image has not been calibrated. +#define ERR_INCOMP_MATRIX_SIZE \ + -1074396112 // The number of pixel and real-world coordinates must be equal. +#define ERR_CALIBRATION_FAILED_TO_FIND_GRID \ + -1074396111 // Unable to automatically detect grid because the image is too + // distorted. +#define ERR_CALIBRATION_INFO_VERSION \ + -1074396110 // Invalid calibration information version. +#define ERR_CALIBRATION_INVALID_SCALING_FACTOR \ + -1074396109 // Invalid calibration scaling factor. +#define ERR_CALIBRATION_ERRORMAP \ + -1074396108 // The calibration error map cannot be computed. +#define ERR_CALIBRATION_INFO_1 \ + -1074396107 // Invalid calibration template image. +#define ERR_CALIBRATION_INFO_2 \ + -1074396106 // Invalid calibration template image. +#define ERR_CALIBRATION_INFO_3 \ + -1074396105 // Invalid calibration template image. +#define ERR_CALIBRATION_INFO_4 \ + -1074396104 // Invalid calibration template image. +#define ERR_CALIBRATION_INFO_5 \ + -1074396103 // Invalid calibration template image. +#define ERR_CALIBRATION_INFO_6 \ + -1074396102 // Invalid calibration template image. +#define ERR_CALIBRATION_INFO_MICRO_PLANE \ + -1074396101 // Invalid calibration template image. +#define ERR_CALIBRATION_INFO_PERSPECTIVE_PROJECTION \ + -1074396100 // Invalid calibration template image. +#define ERR_CALIBRATION_INFO_SIMPLE_TRANSFORM \ + -1074396099 // Invalid calibration template image. +#define ERR_RESERVED_MUST_BE_NULL \ + -1074396098 // You must pass NULL for the reserved parameter. +#define ERR_INVALID_PARTICLE_PARAMETER_VALUE \ + -1074396097 // You entered an invalid selection in the particle parameter. +#define ERR_NOT_AN_OBJECT -1074396096 // Not an object. +#define ERR_CALIBRATION_DUPLICATE_REFERENCE_POINT \ + -1074396095 // The reference points passed are inconsistent. At least two + // similar pixel coordinates correspond to different real-world + // coordinates. +#define ERR_ROLLBACK_RESOURCE_CANNOT_UNLOCK \ + -1074396094 // A resource conflict occurred in the timed environment. Two + // processes cannot manage the same resource and be time bounded. +#define ERR_ROLLBACK_RESOURCE_LOCKED \ + -1074396093 // A resource conflict occurred in the timed environment. Two + // processes cannot access the same resource and be time bounded. +#define ERR_ROLLBACK_RESOURCE_NON_EMPTY_INITIALIZE \ + -1074396092 // Multiple timed environments are not supported. +#define ERR_ROLLBACK_RESOURCE_UNINITIALIZED_ENABLE \ + -1074396091 // A time limit cannot be started until the timed environment is + // initialized. +#define ERR_ROLLBACK_RESOURCE_ENABLED \ + -1074396090 // Multiple timed environments are not supported. +#define ERR_ROLLBACK_RESOURCE_REINITIALIZE \ + -1074396089 // The timed environment is already initialized. +#define ERR_ROLLBACK_RESIZE \ + -1074396088 // The results of the operation exceeded the size limits on the + // output data arrays. +#define ERR_ROLLBACK_STOP_TIMER \ + -1074396087 // No time limit is available to stop. +#define ERR_ROLLBACK_START_TIMER -1074396086 // A time limit could not be set. +#define ERR_ROLLBACK_INIT_TIMER \ + -1074396085 // The timed environment could not be initialized. +#define ERR_ROLLBACK_DELETE_TIMER \ + -1074396084 // No initialized timed environment is available to close. +#define ERR_ROLLBACK_TIMEOUT -1074396083 // The time limit has expired. +#define ERR_PALETTE_NOT_SUPPORTED \ + -1074396082 // Only 8-bit images support the use of palettes. Either do not + // use a palette, or convert your image to an 8-bit image before + // using a palette. +#define ERR_BAD_PASSWORD -1074396081 // Incorrect password. +#define ERR_INVALID_IMAGE_TYPE -1074396080 // Invalid image type. +#define ERR_INVALID_METAFILE_HANDLE -1074396079 // Invalid metafile handle. +#define ERR_INCOMP_TYPE -1074396077 // Incompatible image type. +#define ERR_COORD_SYS_FIRST_AXIS \ + -1074396076 // Unable to fit a line for the primary axis. +#define ERR_COORD_SYS_SECOND_AXIS \ + -1074396075 // Unable to fit a line for the secondary axis. +#define ERR_INCOMP_SIZE -1074396074 // Incompatible image size. +#define ERR_MASK_OUTSIDE_IMAGE \ + -1074396073 // When the mask's offset was applied, the mask was entirely + // outside of the image. +#define ERR_INVALID_BORDER -1074396072 // Invalid image border. +#define ERR_INVALID_SCAN_DIRECTION -1074396071 // Invalid scan direction. +#define ERR_INVALID_FUNCTION -1074396070 // Unsupported function. +#define ERR_INVALID_COLOR_MODE \ + -1074396069 // NI Vision does not support the color mode you specified. +#define ERR_INVALID_ACTION \ + -1074396068 // The function does not support the requested action. +#define ERR_IMAGES_NOT_DIFF \ + -1074396067 // The source image and destination image must be different. +#define ERR_INVALID_POINTSYMBOL -1074396066 // Invalid point symbol. +#define ERR_CANT_RESIZE_EXTERNAL \ + -1074396065 // Cannot resize an image in an acquisition buffer. +#define ERR_EXTERNAL_NOT_SUPPORTED \ + -1074396064 // This operation is not supported for images in an acquisition + // buffer. +#define ERR_EXTERNAL_ALIGNMENT \ + -1074396063 // The external buffer must be aligned on a 4-byte boundary. The + // line width and border pixels must be 4-byte aligned, as well. +#define ERR_INVALID_TOLERANCE \ + -1074396062 // The tolerance parameter must be greater than or equal to 0. +#define ERR_INVALID_WINDOW_SIZE \ + -1074396061 // The size of each dimension of the window must be greater than + // 2 and less than or equal to the size of the image in the + // corresponding dimension. +#define ERR_JPEG2000_LOSSLESS_WITH_FLOATING_POINT \ + -1074396060 // Lossless compression cannot be used with the floating point + // wavelet transform mode. Either set the wavelet transform mode + // to integer, or use lossy compression. +#define ERR_INVALID_MAX_ITERATIONS \ + -1074396059 // Invalid maximum number of iterations. Maximum number of + // iterations must be greater than zero. +#define ERR_INVALID_ROTATION_MODE -1074396058 // Invalid rotation mode. +#define ERR_INVALID_SEARCH_VECTOR_WIDTH \ + -1074396057 // Invalid search vector width. The width must be an odd number + // greater than zero. +#define ERR_INVALID_MATRIX_MIRROR_MODE \ + -1074396056 // Invalid matrix mirror mode. +#define ERR_INVALID_ASPECT_RATIO \ + -1074396055 // Invalid aspect ratio. Valid aspect ratios must be greater than + // or equal to zero. +#define ERR_INVALID_CELL_FILL_TYPE -1074396054 // Invalid cell fill type. +#define ERR_INVALID_BORDER_INTEGRITY \ + -1074396053 // Invalid border integrity. Valid values range from 0 to 100. +#define ERR_INVALID_DEMODULATION_MODE -1074396052 // Invalid demodulation mode. +#define ERR_INVALID_CELL_FILTER_MODE -1074396051 // Invalid cell filter mode. +#define ERR_INVALID_ECC_TYPE -1074396050 // Invalid ECC type. +#define ERR_INVALID_MATRIX_POLARITY -1074396049 // Invalid matrix polarity. +#define ERR_INVALID_CELL_SAMPLE_SIZE -1074396048 // Invalid cell sample size. +#define ERR_INVALID_LINEAR_AVERAGE_MODE \ + -1074396047 // Invalid linear average mode. +#define ERR_INVALID_2D_BARCODE_CONTRAST_FOR_ROI \ + -1074396046 // When using a region of interest that is not a rectangle, you + // must specify the contrast mode of the barcode as either black + // on white or white on black. +#define ERR_INVALID_2D_BARCODE_SUBTYPE \ + -1074396045 // Invalid 2-D barcode Data Matrix subtype. +#define ERR_INVALID_2D_BARCODE_SHAPE -1074396044 // Invalid 2-D barcode shape. +#define ERR_INVALID_2D_BARCODE_CELL_SHAPE \ + -1074396043 // Invalid 2-D barcode cell shape. +#define ERR_INVALID_2D_BARCODE_CONTRAST \ + -1074396042 // Invalid 2-D barcode contrast. +#define ERR_INVALID_2D_BARCODE_TYPE -1074396041 // Invalid 2-D barcode type. +#define ERR_DRIVER -1074396040 // Cannot access NI-IMAQ driver. +#define ERR_IO_ERROR -1074396039 // I/O error. +#define ERR_FIND_COORDSYS_MORE_THAN_ONE_EDGE \ + -1074396038 // When searching for a coordinate system, the number of lines to + // fit must be 1. +#define ERR_TIMEOUT -1074396037 // Trigger timeout. +#define ERR_INVALID_SKELETONMODE \ + -1074396036 // The Skeleton mode you specified is invalid. +#define ERR_TEMPLATEIMAGE_NOCIRCLE \ + -1074396035 // The template image does not contain enough information for + // learning the aggressive search strategy. +#define ERR_TEMPLATEIMAGE_EDGEINFO \ + -1074396034 // The template image does not contain enough edge information + // for the sample size(s) requested. +#define ERR_TEMPLATEDESCRIPTOR_LEARNSETUPDATA \ + -1074396033 // Invalid template descriptor. +#define ERR_TEMPLATEDESCRIPTOR_ROTATION_SEARCHSTRATEGY \ + -1074396032 // The template descriptor does not contain data required for the + // requested search strategy in rotation-invariant matching. +#define ERR_INVALID_TETRAGON \ + -1074396031 // The input tetragon must have four points. The points are + // specified clockwise starting with the top left point. +#define ERR_TOO_MANY_CLASSIFICATION_SESSIONS \ + -1074396030 // There are too many classification sessions open. You must + // close a session before you can open another one. +#define ERR_TIME_BOUNDED_EXECUTION_NOT_SUPPORTED \ + -1074396028 // NI Vision no longer supports time-bounded execution. +#define ERR_INVALID_COLOR_RESOLUTION \ + -1074396027 // Invalid Color Resolution for the Color Classifier +#define ERR_INVALID_PROCESS_TYPE_FOR_EDGE_DETECTION \ + -1074396026 // Invalid process type for edge detection. +#define ERR_INVALID_ANGLE_RANGE_FOR_STRAIGHT_EDGE \ + -1074396025 // Angle range value should be equal to or greater than zero. +#define ERR_INVALID_MIN_COVERAGE_FOR_STRAIGHT_EDGE \ + -1074396024 // Minimum coverage value should be greater than zero. +#define ERR_INVALID_ANGLE_TOL_FOR_STRAIGHT_EDGE \ + -1074396023 // The angle tolerance should be equal to or greater than 0.001. +#define ERR_INVALID_SEARCH_MODE_FOR_STRAIGHT_EDGE \ + -1074396022 // Invalid search mode for detecting straight edges +#define ERR_INVALID_KERNEL_SIZE_FOR_EDGE_DETECTION \ + -1074396021 // Invalid kernel size for edge detection. The minimum kernel + // size is 3, the maximum kernel size is 1073741823 and the + // kernel size must be odd. +#define ERR_INVALID_GRADING_MODE -1074396020 // Invalid grading mode. +#define ERR_INVALID_THRESHOLD_PERCENTAGE \ + -1074396019 // Invalid threshold percentage. Valid values range from 0 to + // 100. +#define ERR_INVALID_EDGE_POLARITY_SEARCH_MODE \ + -1074396018 // Invalid edge polarity search mode. +#define ERR_OPENING_NEWER_AIM_GRADING_DATA \ + -1074396017 // The AIM grading data attached to the image you tried to open + // was created with a newer version of NI Vision. Upgrade to the + // latest version of NI Vision to read this file. +#define ERR_NO_VIDEO_DRIVER -1074396016 // No video driver is installed. +#define ERR_RPC_EXECUTE_IVB \ + -1074396015 // Unable to establish network connection with remote system. +#define ERR_INVALID_VIDEO_BLIT \ + -1074396014 // RT Video Out does not support displaying the supplied image + // type at the selected color depth. +#define ERR_INVALID_VIDEO_MODE -1074396013 // Invalid video mode. +#define ERR_RPC_EXECUTE \ + -1074396012 // Unable to display remote image on network connection. +#define ERR_RPC_BIND -1074396011 // Unable to establish network connection. +#define ERR_INVALID_FRAME_NUMBER -1074396010 // Invalid frame number. +#define ERR_DIRECTX \ + -1074396009 // An internal DirectX error has occurred. Try upgrading to the + // latest version of DirectX. +#define ERR_DIRECTX_NO_FILTER \ + -1074396008 // An appropriate DirectX filter to process this file could not + // be found. Install the filter that was used to create this + // AVI. Upgrading to the latest version of DirectX may correct + // this error. NI Vision requires DirectX 8.1 or higher. +#define ERR_DIRECTX_INCOMPATIBLE_COMPRESSION_FILTER \ + -1074396007 // Incompatible compression filter. +#define ERR_DIRECTX_UNKNOWN_COMPRESSION_FILTER \ + -1074396006 // Unknown compression filter. +#define ERR_INVALID_AVI_SESSION -1074396005 // Invalid AVI session. +#define ERR_DIRECTX_CERTIFICATION_FAILURE \ + -1074396004 // A software key is restricting the use of this compression + // filter. +#define ERR_AVI_DATA_EXCEEDS_BUFFER_SIZE \ + -1074396003 // The data for this frame exceeds the data buffer size specified + // when creating the AVI file. +#define ERR_INVALID_LINEGAUGEMETHOD -1074396002 // Invalid line gauge method. +#define ERR_TOO_MANY_AVI_SESSIONS \ + -1074396001 // There are too many AVI sessions open. You must close a + // session before you can open another one. +#define ERR_FILE_FILE_HEADER -1074396000 // Invalid file header. +#define ERR_FILE_FILE_TYPE -1074395999 // Invalid file type. +#define ERR_FILE_COLOR_TABLE -1074395998 // Invalid color table. +#define ERR_FILE_ARGERR -1074395997 // Invalid parameter. +#define ERR_FILE_OPEN -1074395996 // File is already open for writing. +#define ERR_FILE_NOT_FOUND -1074395995 // File not found. +#define ERR_FILE_TOO_MANY_OPEN -1074395994 // Too many files open. +#define ERR_FILE_IO_ERR -1074395993 // File I/O error. +#define ERR_FILE_PERMISSION -1074395992 // File access denied. +#define ERR_FILE_INVALID_TYPE \ + -1074395991 // NI Vision does not support the file type you specified. +#define ERR_FILE_GET_INFO -1074395990 // Could not read Vision info from file. +#define ERR_FILE_READ -1074395989 // Unable to read data. +#define ERR_FILE_WRITE -1074395988 // Unable to write data. +#define ERR_FILE_EOF -1074395987 // Premature end of file. +#define ERR_FILE_FORMAT -1074395986 // Invalid file format. +#define ERR_FILE_OPERATION -1074395985 // Invalid file operation. +#define ERR_FILE_INVALID_DATA_TYPE \ + -1074395984 // NI Vision does not support the file data type you specified. +#define ERR_FILE_NO_SPACE -1074395983 // Disk full. +#define ERR_INVALID_FRAMES_PER_SECOND \ + -1074395982 // The frames per second in an AVI must be greater than zero. +#define ERR_INSUFFICIENT_BUFFER_SIZE \ + -1074395981 // The buffer that was passed in is not big enough to hold all of + // the data. +#define ERR_COM_INITIALIZE -1074395980 // Error initializing COM. +#define ERR_INVALID_PARTICLE_INFO \ + -1074395979 // The image has invalid particle information. Call + // imaqCountParticles on the image to create particle + // information. +#define ERR_INVALID_PARTICLE_NUMBER -1074395978 // Invalid particle number. +#define ERR_AVI_VERSION \ + -1074395977 // The AVI file was created in a newer version of NI Vision. + // Upgrade to the latest version of NI Vision to read this AVI + // file. +#define ERR_NUMBER_OF_PALETTE_COLORS \ + -1074395976 // The color palette must have exactly 0 or 256 entries. +#define ERR_AVI_TIMEOUT \ + -1074395975 // DirectX has timed out reading or writing the AVI file. When + // closing an AVI file, try adding an additional delay. When + // reading an AVI file, try reducing CPU and disk load. +#define ERR_UNSUPPORTED_JPEG2000_COLORSPACE_METHOD \ + -1074395974 // NI Vision does not support reading JPEG2000 files with this + // colorspace method. +#define ERR_JPEG2000_UNSUPPORTED_MULTIPLE_LAYERS \ + -1074395973 // NI Vision does not support reading JPEG2000 files with more + // than one layer. +#define ERR_DIRECTX_ENUMERATE_FILTERS \ + -1074395972 // DirectX is unable to enumerate the compression filters. This + // is caused by a third-party compression filter that is either + // improperly installed or is preventing itself from being + // enumerated. Remove any recently installed compression filters + // and try again. +#define ERR_INVALID_OFFSET \ + -1074395971 // The offset you specified must be size 2. +#define ERR_INIT -1074395960 // Initialization error. +#define ERR_CREATE_WINDOW -1074395959 // Unable to create window. +#define ERR_WINDOW_ID -1074395958 // Invalid window ID. +#define ERR_ARRAY_SIZE_MISMATCH \ + -1074395957 // The array sizes are not compatible. +#define ERR_INVALID_QUALITY \ + -1074395956 // The quality you provided is invalid. Valid quality values + // range from -1 to 1000. +#define ERR_INVALID_MAX_WAVELET_TRANSFORM_LEVEL \ + -1074395955 // Invalid maximum wavelet transform level. Valid values range + // from 0 to 255. +#define ERR_INVALID_QUANTIZATION_STEP_SIZE \ + -1074395954 // The quantization step size must be greater than or equal to 0. +#define ERR_INVALID_WAVELET_TRANSFORM_MODE \ + -1074395953 // Invalid wavelet transform mode. +#define ERR_ROI_NOT_POINT \ + -1074395952 // The ROI must only have a single Point contour. +#define ERR_ROI_NOT_POINTS \ + -1074395951 // The ROI must only have Point contours. +#define ERR_ROI_NOT_LINE \ + -1074395950 // The ROI must only have a single Line contour. +#define ERR_ROI_NOT_ANNULUS \ + -1074395949 // The ROI must only have a single Annulus contour. +#define ERR_INVALID_MEASURE_PARTICLES_CALIBRATION_MODE \ + -1074395948 // Invalid measure particles calibration mode. +#define ERR_INVALID_PARTICLE_CLASSIFIER_THRESHOLD_TYPE \ + -1074395947 // Invalid particle classifier threshold type. +#define ERR_INVALID_DISTANCE -1074395946 // Invalid Color Segmentation Distance +#define ERR_INVALID_PARTICLE_AREA \ + -1074395945 // Invalid Color Segmenation Particle Area +#define ERR_CLASS_NAME_NOT_FOUND \ + -1074395944 // Required Class name is not found in trained labels/Class names +#define ERR_NUMBER_LABEL_LIMIT_EXCEEDED \ + -1074395943 // Number of Labels exceeded limit of label Image type +#define ERR_INVALID_DISTANCE_LEVEL \ + -1074395942 // Invalid Color Segmentation distance level +#define ERR_INVALID_SVM_TYPE -1074395941 // Invalid SVM model type +#define ERR_INVALID_SVM_KERNEL -1074395940 // Invalid SVM kernel type +#define ERR_NO_SUPPORT_VECTOR_FOUND \ + -1074395939 // No Support Vector is found at SVM training +#define ERR_COST_LABEL_NOT_FOUND \ + -1074395938 // Label name is not found in added samples +#define ERR_EXCEEDED_SVM_MAX_ITERATION \ + -1074395937 // SVM training exceeded maximim Iteration limit +#define ERR_INVALID_SVM_PARAMETER -1074395936 // Invalid SVM Parameter +#define ERR_INVALID_IDENTIFICATION_SCORE \ + -1074395935 // Invalid Identification score. Must be between 0-1000. +#define ERR_INVALID_TEXTURE_FEATURE \ + -1074395934 // Requested for invalid texture feature +#define ERR_INVALID_COOCCURRENCE_LEVEL \ + -1074395933 // The coOccurrence Level must lie between 1 and the maximum + // pixel value of an image (255 for U8 image) +#define ERR_INVALID_WAVELET_SUBBAND \ + -1074395932 // Request for invalid wavelet subBand +#define ERR_INVALID_FINAL_STEP_SIZE \ + -1074395931 // The final step size must be lesser than the initial step size +#define ERR_INVALID_ENERGY \ + -1074395930 // Minimum Energy should lie between 0 and 100 +#define ERR_INVALID_TEXTURE_LABEL \ + -1074395929 // The classification label must be texture or defect for texture + // defect classifier +#define ERR_INVALID_WAVELET_TYPE -1074395928 // The wavelet type is invalid +#define ERR_SAME_WAVELET_BANDS_SELECTED \ + -1074395927 // Same Wavelet band is selected multiple times +#define ERR_IMAGE_SIZE_MISMATCH \ + -1074395926 // The two input image sizes are different +#define ERR_NUMBER_CLASS -1074395920 // Invalid number of classes. +#define ERR_INVALID_LUCAS_KANADE_WINDOW_SIZE \ + -1074395888 // Both dimensions of the window size should be odd, greater than + // 2 and less than 16. +#define ERR_INVALID_MATRIX_TYPE \ + -1074395887 // The type of matrix supplied to the function is not supported. +#define ERR_INVALID_OPTICAL_FLOW_TERMINATION_CRITERIA_TYPE \ + -1074395886 // An invalid termination criteria was specified for the optical + // flow computation. +#define ERR_LKP_NULL_PYRAMID \ + -1074395885 // The pyramid levels where not properly allocated. +#define ERR_INVALID_PYRAMID_LEVEL \ + -1074395884 // The pyramid level specified cannot be negative +#define ERR_INVALID_LKP_KERNEL \ + -1074395883 // The kernel must be symmetric with non-zero coefficients and + // of odd size +#define ERR_INVALID_HORN_SCHUNCK_LAMBDA \ + -1074395882 // Invalid smoothing parameter in Horn Schunck operation. +#define ERR_INVALID_HORN_SCHUNCK_TYPE \ + -1074395881 // Invalid stopping criteria type for Horn Schunck optical flow. +#define ERR_PARTICLE -1074395880 // Invalid particle. +#define ERR_BAD_MEASURE -1074395879 // Invalid measure number. +#define ERR_PROP_NODE_WRITE_NOT_SUPPORTED \ + -1074395878 // The Image Display control does not support writing this + // property node. +#define ERR_COLORMODE_REQUIRES_CHANGECOLORSPACE2 \ + -1074395877 // The specified color mode requires the use of + // imaqChangeColorSpace2. +#define ERR_UNSUPPORTED_COLOR_MODE \ + -1074395876 // This function does not currently support the color mode you + // specified. +#define ERR_BARCODE_PHARMACODE \ + -1074395875 // The barcode is not a valid Pharmacode symbol +#define ERR_BAD_INDEX -1074395840 // Invalid handle table index. +#define ERR_INVALID_COMPRESSION_RATIO \ + -1074395837 // The compression ratio must be greater than or equal to 1. +#define ERR_TOO_MANY_CONTOURS \ + -1074395801 // The ROI contains too many contours. +#define ERR_PROTECTION -1074395800 // Protection error. +#define ERR_INTERNAL -1074395799 // Internal error. +#define ERR_INVALID_CUSTOM_SAMPLE \ + -1074395798 // The size of the feature vector in the custom sample must match + // the size of those you have already added. +#define ERR_INVALID_CLASSIFIER_SESSION \ + -1074395797 // Not a valid classifier session. +#define ERR_INVALID_KNN_METHOD \ + -1074395796 // You requested an invalid Nearest Neighbor classifier method. +#define ERR_K_TOO_LOW -1074395795 // The k parameter must be greater than two. +#define ERR_K_TOO_HIGH \ + -1074395794 // The k parameter must be <= the number of samples in each + // class. +#define ERR_INVALID_OPERATION_ON_COMPACT_SESSION_ATTEMPTED \ + -1074395793 // This classifier session is compact. Only the Classify and + // Dispose functions may be called on a compact classifier + // session. +#define ERR_CLASSIFIER_SESSION_NOT_TRAINED \ + -1074395792 // This classifier session is not trained. You may only call this + // function on a trained classifier session. +#define ERR_CLASSIFIER_INVALID_SESSION_TYPE \ + -1074395791 // This classifier function cannot be called on this type of + // classifier session. +#define ERR_INVALID_DISTANCE_METRIC \ + -1074395790 // You requested an invalid distance metric. +#define ERR_OPENING_NEWER_CLASSIFIER_SESSION \ + -1074395789 // The classifier session you tried to open was created with a + // newer version of NI Vision. Upgrade to the latest version of + // NI Vision to read this file. +#define ERR_NO_SAMPLES \ + -1074395788 // This operation cannot be performed because you have not added + // any samples. +#define ERR_INVALID_CLASSIFIER_TYPE \ + -1074395787 // You requested an invalid classifier type. +#define ERR_INVALID_PARTICLE_OPTIONS \ + -1074395786 // The sum of Scale Dependence and Symmetry Dependence must be + // less than 1000. +#define ERR_NO_PARTICLE -1074395785 // The image yielded no particles. +#define ERR_INVALID_LIMITS \ + -1074395784 // The limits you supplied are not valid. +#define ERR_BAD_SAMPLE_INDEX \ + -1074395783 // The Sample Index fell outside the range of Samples. +#define ERR_DESCRIPTION_TOO_LONG \ + -1074395782 // The description must be <= 255 characters. +#define ERR_CLASSIFIER_INVALID_ENGINE_TYPE \ + -1074395781 // The engine for this classifier session does not support this + // operation. +#define ERR_INVALID_PARTICLE_TYPE \ + -1074395780 // You requested an invalid particle type. +#define ERR_CANNOT_COMPACT_UNTRAINED \ + -1074395779 // You may only save a session in compact form if it is trained. +#define ERR_INVALID_KERNEL_SIZE \ + -1074395778 // The Kernel size must be smaller than the image size. +#define ERR_INCOMPATIBLE_CLASSIFIER_TYPES \ + -1074395777 // The session you read from file must be the same type as the + // session you passed in. +#define ERR_INVALID_USE_OF_COMPACT_SESSION_FILE \ + -1074395776 // You can not use a compact classification file with read + // options other than Read All. +#define ERR_ROI_HAS_OPEN_CONTOURS \ + -1074395775 // The ROI you passed in may only contain closed contours. +#define ERR_NO_LABEL -1074395774 // You must pass in a label. +#define ERR_NO_DEST_IMAGE -1074395773 // You must provide a destination image. +#define ERR_INVALID_REGISTRATION_METHOD \ + -1074395772 // You provided an invalid registration method. +#define ERR_OPENING_NEWER_INSPECTION_TEMPLATE \ + -1074395771 // The golden template you tried to open was created with a newer + // version of NI Vision. Upgrade to the latest version of NI + // Vision to read this file. +#define ERR_INVALID_INSPECTION_TEMPLATE -1074395770 // Invalid golden template. +#define ERR_INVALID_EDGE_THICKNESS \ + -1074395769 // Edge Thickness to Ignore must be greater than zero. +#define ERR_INVALID_SCALE -1074395768 // Scale must be greater than zero. +#define ERR_INVALID_ALIGNMENT \ + -1074395767 // The supplied scale is invalid for your template. +#define ERR_DEPRECATED_FUNCTION \ + -1074395766 // This backwards-compatibility function can not be used with + // this session. Use newer, supported functions instead. +#define ERR_INVALID_NORMALIZATION_METHOD \ + -1074395763 // You must provide a valid normalization method. +#define ERR_INVALID_NIBLACK_DEVIATION_FACTOR \ + -1074395762 // The deviation factor for Niblack local threshold must be + // between 0 and 1. +#define ERR_BOARD_NOT_FOUND -1074395760 // Board not found. +#define ERR_BOARD_NOT_OPEN -1074395758 // Board not opened. +#define ERR_DLL_NOT_FOUND -1074395757 // DLL not found. +#define ERR_DLL_FUNCTION_NOT_FOUND -1074395756 // DLL function not found. +#define ERR_TRIG_TIMEOUT -1074395754 // Trigger timeout. +#define ERR_CONTOUR_INVALID_REFINEMENTS \ + -1074395746 // Invalid number specified for maximum contour refinements. +#define ERR_TOO_MANY_CURVES \ + -1074395745 // Too many curves extracted from image. Raise the edge threshold + // or reduce the ROI. +#define ERR_CONTOUR_INVALID_KERNEL_FOR_SMOOTHING \ + -1074395744 // Invalid kernel for contour smoothing. Zero indicates no + // smoothing, otherwise value must be odd. +#define ERR_CONTOUR_LINE_INVALID \ + -1074395743 // The contour line fit is invalid. Line segment start and stop + // must differ. +#define ERR_CONTOUR_TEMPLATE_IMAGE_INVALID \ + -1074395742 // The template image must be trained with IMAQ Learn Contour + // Pattern or be the same size as the target image. +#define ERR_CONTOUR_GPM_FAIL \ + -1074395741 // Matching failed to align the template and target contours. +#define ERR_CONTOUR_OPENING_NEWER_VERSION \ + -1074395740 // The contour you tried to open was created with a newer version + // of NI Vision. Upgrade to the latest version of NI Vision to + // read this file. +#define ERR_CONTOUR_CONNECT_DUPLICATE \ + -1074395739 // Only one range is allowed per curve connection constraint + // type. +#define ERR_CONTOUR_CONNECT_TYPE \ + -1074395738 // Invalid contour connection constraint type. +#define ERR_CONTOUR_MATCH_STR_NOT_APPLICABLE \ + -1074395737 // In order to use contour matching, you must provide a template + // image that has been trained with IMAQ Learn Contour Pattern +#define ERR_CONTOUR_CURVATURE_KERNEL \ + -1074395736 // Invalid kernel width for curvature calculation. Must be an odd + // value greater than 1. +#define ERR_CONTOUR_EXTRACT_SELECTION \ + -1074395735 // Invalid Contour Selection method for contour extraction. +#define ERR_CONTOUR_EXTRACT_DIRECTION \ + -1074395734 // Invalid Search Direction for contour extraction. +#define ERR_CONTOUR_EXTRACT_ROI \ + -1074395733 // Invalid ROI for contour extraction. The ROI must contain an + // annulus, rectangle or rotated rectangle. +#define ERR_CONTOUR_NO_CURVES -1074395732 // No curves were found in the image. +#define ERR_CONTOUR_COMPARE_KERNEL \ + -1074395731 // Invalid Smoothing Kernel width for contour comparison. Must be + // zero or an odd positive integer. +#define ERR_CONTOUR_COMPARE_SINGLE_IMAGE \ + -1074395730 // If no template image is provided, the target image must + // contain both a contour with extracted points and a fitted + // equation. +#define ERR_CONTOUR_INVALID -1074395729 // Invalid contour image. +#define ERR_INVALID_2D_BARCODE_SEARCH_MODE \ + -1074395728 // NI Vision does not support the search mode you provided. +#define ERR_UNSUPPORTED_2D_BARCODE_SEARCH_MODE \ + -1074395727 // NI Vision does not support the search mode you provided for + // the type of 2D barcode for which you are searching. +#define ERR_MATCHFACTOR_OBSOLETE \ + -1074395726 // matchFactor has been obsoleted. Instead, set the + // initialMatchListLength and matchListReductionFactor in the + // MatchPatternAdvancedOptions structure. +#define ERR_DATA_VERSION \ + -1074395725 // The data was stored with a newer version of NI Vision. Upgrade + // to the latest version of NI Vision to read this data. +#define ERR_CUSTOMDATA_INVALID_SIZE \ + -1074395724 // The size you specified is out of the valid range. +#define ERR_CUSTOMDATA_KEY_NOT_FOUND \ + -1074395723 // The key you specified cannot be found in the image. +#define ERR_CLASSIFIER_CLASSIFY_IMAGE_WITH_CUSTOM_SESSION \ + -1074395722 // Custom classifier sessions only classify feature vectors. They + // do not support classifying images. +#define ERR_INVALID_BIT_DEPTH \ + -1074395721 // NI Vision does not support the bit depth you supplied for the + // image you supplied. +#define ERR_BAD_ROI -1074395720 // Invalid ROI. +#define ERR_BAD_ROI_BOX -1074395719 // Invalid ROI global rectangle. +#define ERR_LAB_VERSION \ + -1074395718 // The version of LabVIEW or BridgeVIEW you are running does not + // support this operation. +#define ERR_INVALID_RANGE -1074395717 // The range you supplied is invalid. +#define ERR_INVALID_SCALING_METHOD \ + -1074395716 // NI Vision does not support the scaling method you provided. +#define ERR_INVALID_CALIBRATION_UNIT \ + -1074395715 // NI Vision does not support the calibration unit you supplied. +#define ERR_INVALID_AXIS_ORIENTATION \ + -1074395714 // NI Vision does not support the axis orientation you supplied. +#define ERR_VALUE_NOT_IN_ENUM -1074395713 // Value not in enumeration. +#define ERR_WRONG_REGION_TYPE \ + -1074395712 // You selected a region that is not of the right type. +#define ERR_NOT_ENOUGH_REGIONS \ + -1074395711 // You specified a viewer that does not contain enough regions. +#define ERR_TOO_MANY_PARTICLES \ + -1074395710 // The image has too many particles for this process. +#define ERR_AVI_UNOPENED_SESSION \ + -1074395709 // The AVI session has not been opened. +#define ERR_AVI_READ_SESSION_REQUIRED \ + -1074395708 // The AVI session is a write session, but this operation + // requires a read session. +#define ERR_AVI_WRITE_SESSION_REQUIRED \ + -1074395707 // The AVI session is a read session, but this operation requires + // a write session. +#define ERR_AVI_SESSION_ALREADY_OPEN \ + -1074395706 // This AVI session is already open. You must close it before + // calling the Create or Open functions. +#define ERR_DATA_CORRUPTED \ + -1074395705 // The data is corrupted and cannot be read. +#define ERR_INVALID_COMPRESSION_TYPE -1074395704 // Invalid compression type. +#define ERR_INVALID_TYPE_OF_FLATTEN -1074395703 // Invalid type of flatten. +#define ERR_INVALID_LENGTH \ + -1074395702 // The length of the edge detection line must be greater than + // zero. +#define ERR_INVALID_MATRIX_SIZE_RANGE \ + -1074395701 // The maximum Data Matrix barcode size must be equal to or + // greater than the minimum Data Matrix barcode size. +#define ERR_REQUIRES_WIN2000_OR_NEWER \ + -1074395700 // The function requires the operating system to be Microsoft + // Windows 2000 or newer. +#define ERR_INVALID_CALIBRATION_METHOD \ + -1074395662 // Invalid calibration method requested +#define ERR_INVALID_OPERATION_ON_COMPACT_CALIBRATION_ATTEMPTED \ + -1074395661 // This calibration is compact. Re-Learning calibration and + // retrieving thumbnails are not possible with this calibration +#define ERR_INVALID_POLYNOMIAL_MODEL_K_COUNT \ + -1074395660 // Invalid number of K values +#define ERR_INVALID_DISTORTION_MODEL \ + -1074395659 // Invalid distortion model type +#define ERR_CAMERA_MODEL_NOT_AVAILABLE \ + -1074395658 // Camera Model is not learned +#define ERR_INVALID_THUMBNAIL_INDEX \ + -1074395657 // Supplied thumbnail index is invalid +#define ERR_SMOOTH_CONTOURS_MUST_BE_SAME \ + -1074395656 // You must specify the same value for the smooth contours + // advanced match option for all templates you want to match. +#define ERR_ENABLE_CALIBRATION_SUPPORT_MUST_BE_SAME \ + -1074395655 // You must specify the same value for the enable calibration + // support advanced match option for all templates you want to + // match. +#define ERR_GRADING_INFORMATION_NOT_FOUND \ + -1074395654 // The source image does not contain grading information. You + // must prepare the source image for grading when reading the + // Data Matrix, and you cannot change the contents of the source + // image between reading and grading the Data Matrix. +#define ERR_OPENING_NEWER_MULTIPLE_GEOMETRIC_TEMPLATE \ + -1074395653 // The multiple geometric matching template you tried to open was + // created with a newer version of NI Vision. Upgrade to the + // latest version of NI Vision to read this file. +#define ERR_OPENING_NEWER_GEOMETRIC_MATCHING_TEMPLATE \ + -1074395652 // The geometric matching template you tried to open was created + // with a newer version of NI Vision. Upgrade to the latest + // version of NI Vision to read this file. +#define ERR_EDGE_FILTER_SIZE_MUST_BE_SAME \ + -1074395651 // You must specify the same edge filter size for all the + // templates you want to match. +#define ERR_CURVE_EXTRACTION_MODE_MUST_BE_SAME \ + -1074395650 // You must specify the same curve extraction mode for all the + // templates you want to match. +#define ERR_INVALID_GEOMETRIC_FEATURE_TYPE \ + -1074395649 // The geometric feature type specified is invalid. +#define ERR_TEMPLATE_NOT_LEARNED \ + -1074395648 // You supplied a template that was not learned. +#define ERR_INVALID_MULTIPLE_GEOMETRIC_TEMPLATE \ + -1074395647 // Invalid multiple geometric template. +#define ERR_NO_TEMPLATE_TO_LEARN \ + -1074395646 // Need at least one template to learn. +#define ERR_INVALID_NUMBER_OF_LABELS \ + -1074395645 // You supplied an invalid number of labels. +#define ERR_LABEL_TOO_LONG -1074395644 // Labels must be <= 255 characters. +#define ERR_INVALID_NUMBER_OF_MATCH_OPTIONS \ + -1074395643 // You supplied an invalid number of match options. +#define ERR_LABEL_NOT_FOUND \ + -1074395642 // Cannot find a label that matches the one you specified. +#define ERR_DUPLICATE_LABEL -1074395641 // Duplicate labels are not allowed. +#define ERR_TOO_MANY_ZONES \ + -1074395640 // The number of zones found exceeded the capacity of the + // algorithm. +#define ERR_INVALID_HATCH_STYLE \ + -1074395639 // The hatch style for the window background is invalid. +#define ERR_INVALID_FILL_STYLE \ + -1074395638 // The fill style for the window background is invalid. +#define ERR_HARDWARE_DOESNT_SUPPORT_NONTEARING \ + -1074395637 // Your hardware is not supported by DirectX and cannot be put + // into NonTearing mode. +#define ERR_DIRECTX_NOT_FOUND \ + -1074395636 // DirectX is required for this feature. Please install the + // latest version.. +#define ERR_INVALID_SHAPE_DESCRIPTOR \ + -1074395635 // The passed shape descriptor is invalid. +#define ERR_INVALID_MAX_MATCH_OVERLAP \ + -1074395634 // Invalid max match overlap. Values must be between -1 and 100. +#define ERR_INVALID_MIN_MATCH_SEPARATION_SCALE \ + -1074395633 // Invalid minimum match separation scale. Values must be + // greater than or equal to -1. +#define ERR_INVALID_MIN_MATCH_SEPARATION_ANGLE \ + -1074395632 // Invalid minimum match separation angle. Values must be + // between -1 and 360. +#define ERR_INVALID_MIN_MATCH_SEPARATION_DISTANCE \ + -1074395631 // Invalid minimum match separation distance. Values must be + // greater than or equal to -1. +#define ERR_INVALID_MAXIMUM_FEATURES_LEARNED \ + -1074395630 // Invalid maximum number of features learn. Values must be + // integers greater than zero. +#define ERR_INVALID_MAXIMUM_PIXEL_DISTANCE_FROM_LINE \ + -1074395629 // Invalid maximum pixel distance from line. Values must be + // positive real numbers. +#define ERR_INVALID_GEOMETRIC_MATCHING_TEMPLATE \ + -1074395628 // Invalid geometric matching template image. +#define ERR_NOT_ENOUGH_TEMPLATE_FEATURES_1 \ + -1074395627 // The template does not contain enough features for geometric + // matching. +#define ERR_NOT_ENOUGH_TEMPLATE_FEATURES \ + -1074395626 // The template does not contain enough features for geometric + // matching. +#define ERR_INVALID_MATCH_CONSTRAINT_TYPE \ + -1074395625 // You specified an invalid value for the match constraint value + // of the range settings. +#define ERR_INVALID_OCCLUSION_RANGE \ + -1074395624 // Invalid occlusion range. Valid values for the bounds range + // from 0 to 100 and the upper bound must be greater than or + // equal to the lower bound. +#define ERR_INVALID_SCALE_RANGE \ + -1074395623 // Invalid scale range. Values for the lower bound must be a + // positive real numbers and the upper bound must be greater than + // or equal to the lower bound. +#define ERR_INVALID_MATCH_GEOMETRIC_PATTERN_SETUP_DATA \ + -1074395622 // Invalid match geometric pattern setup data. +#define ERR_INVALID_LEARN_GEOMETRIC_PATTERN_SETUP_DATA \ + -1074395621 // Invalid learn geometric pattern setup data. +#define ERR_INVALID_CURVE_EXTRACTION_MODE \ + -1074395620 // Invalid curve extraction mode. +#define ERR_TOO_MANY_OCCLUSION_RANGES \ + -1074395619 // You can specify only one occlusion range. +#define ERR_TOO_MANY_SCALE_RANGES \ + -1074395618 // You can specify only one scale range. +#define ERR_INVALID_NUMBER_OF_FEATURES_RANGE \ + -1074395617 // The minimum number of features must be less than or equal to + // the maximum number of features. +#define ERR_INVALID_EDGE_FILTER_SIZE -1074395616 // Invalid edge filter size. +#define ERR_INVALID_MINIMUM_FEATURE_STRENGTH \ + -1074395615 // Invalid minimum strength for features. Values must be positive + // real numbers. +#define ERR_INVALID_MINIMUM_FEATURE_ASPECT_RATIO \ + -1074395614 // Invalid aspect ratio for rectangular features. Values must be + // positive real numbers in the range 0.01 to 1.0. +#define ERR_INVALID_MINIMUM_FEATURE_LENGTH \ + -1074395613 // Invalid minimum length for linear features. Values must be + // integers greater than 0. +#define ERR_INVALID_MINIMUM_FEATURE_RADIUS \ + -1074395612 // Invalid minimum radius for circular features. Values must be + // integers greater than 0. +#define ERR_INVALID_MINIMUM_RECTANGLE_DIMENSION \ + -1074395611 // Invalid minimum rectangle dimension. Values must be integers + // greater than 0. +#define ERR_INVALID_INITIAL_MATCH_LIST_LENGTH \ + -1074395610 // Invalid initial match list length. Values must be integers + // greater than 5. +#define ERR_INVALID_SUBPIXEL_TOLERANCE \ + -1074395609 // Invalid subpixel tolerance. Values must be positive real + // numbers. +#define ERR_INVALID_SUBPIXEL_ITERATIONS \ + -1074395608 // Invalid number of subpixel iterations. Values must be integers + // greater 10. +#define ERR_INVALID_MAXIMUM_FEATURES_PER_MATCH \ + -1074395607 // Invalid maximum number of features used per match. Values must + // be integers greater than or equal to zero. +#define ERR_INVALID_MINIMUM_FEATURES_TO_MATCH \ + -1074395606 // Invalid minimum number of features used for matching. Values + // must be integers greater than zero. +#define ERR_INVALID_MAXIMUM_END_POINT_GAP \ + -1074395605 // Invalid maximum end point gap. Valid values range from 0 to + // 32767. +#define ERR_INVALID_COLUMN_STEP \ + -1074395604 // Invalid column step. Valid range is 1 to 255. +#define ERR_INVALID_ROW_STEP \ + -1074395603 // Invalid row step. Valid range is 1 to 255. +#define ERR_INVALID_MINIMUM_CURVE_LENGTH \ + -1074395602 // Invalid minimum length. Valid values must be greater than or + // equal to zero. +#define ERR_INVALID_EDGE_THRESHOLD \ + -1074395601 // Invalid edge threshold. Valid values range from 1 to 360. +#define ERR_INFO_NOT_FOUND \ + -1074395600 // You must provide information about the subimage within the + // browser. +#define ERR_NIOCR_INVALID_ACCEPTANCE_LEVEL \ + -1074395598 // The acceptance level is outside the valid range of 0 to 1000. +#define ERR_NIOCR_NOT_A_VALID_SESSION -1074395597 // Not a valid OCR session. +#define ERR_NIOCR_INVALID_CHARACTER_SIZE \ + -1074395596 // Invalid character size. Character size must be >= 1. +#define ERR_NIOCR_INVALID_THRESHOLD_MODE \ + -1074395595 // Invalid threshold mode value. +#define ERR_NIOCR_INVALID_SUBSTITUTION_CHARACTER \ + -1074395594 // Invalid substitution character. Valid substitution characters + // are ASCII values that range from 1 to 254. +#define ERR_NIOCR_INVALID_NUMBER_OF_BLOCKS \ + -1074395593 // Invalid number of blocks. Number of blocks must be >= 4 and <= + // 50. +#define ERR_NIOCR_INVALID_READ_STRATEGY -1074395592 // Invalid read strategy. +#define ERR_NIOCR_INVALID_CHARACTER_INDEX \ + -1074395591 // Invalid character index. +#define ERR_NIOCR_INVALID_NUMBER_OF_VALID_CHARACTER_POSITIONS \ + -1074395590 // Invalid number of character positions. Valid values range from + // 0 to 255. +#define ERR_NIOCR_INVALID_LOW_THRESHOLD_VALUE \ + -1074395589 // Invalid low threshold value. Valid threshold values range from + // 0 to 255. +#define ERR_NIOCR_INVALID_HIGH_THRESHOLD_VALUE \ + -1074395588 // Invalid high threshold value. Valid threshold values range + // from 0 to 255. +#define ERR_NIOCR_INVALID_THRESHOLD_RANGE \ + -1074395587 // The low threshold must be less than the high threshold. +#define ERR_NIOCR_INVALID_LOWER_THRESHOLD_LIMIT \ + -1074395586 // Invalid lower threshold limit. Valid lower threshold limits + // range from 0 to 255. +#define ERR_NIOCR_INVALID_UPPER_THRESHOLD_LIMIT \ + -1074395585 // Invalid upper threshold limit. Valid upper threshold limits + // range from 0 to 255. +#define ERR_NIOCR_INVALID_THRESHOLD_LIMITS \ + -1074395584 // The lower threshold limit must be less than the upper + // threshold limit. +#define ERR_NIOCR_INVALID_MIN_CHAR_SPACING \ + -1074395583 // Invalid minimum character spacing value. Character spacing + // must be >= 1 pixel. +#define ERR_NIOCR_INVALID_MAX_HORIZ_ELEMENT_SPACING \ + -1074395582 // Invalid maximum horizontal element spacing value. Maximum + // horizontal element spacing must be >= 0. +#define ERR_NIOCR_INVALID_MAX_VERT_ELEMENT_SPACING \ + -1074395581 // Invalid maximum vertical element spacing value. Maximum + // vertical element spacing must be >= 0. +#define ERR_NIOCR_INVALID_MIN_BOUNDING_RECT_WIDTH \ + -1074395580 // Invalid minimum bounding rectangle width. Minimum bounding + // rectangle width must be >= 1. +#define ERR_NIOCR_INVALID_ASPECT_RATIO \ + -1074395579 // Invalid aspect ratio value. The aspect ratio must be zero or + // >= 100. +#define ERR_NIOCR_INVALID_CHARACTER_SET_FILE \ + -1074395578 // Invalid or corrupt character set file. +#define ERR_NIOCR_CHARACTER_VALUE_CANNOT_BE_EMPTYSTRING \ + -1074395577 // The character value must not be an empty string. +#define ERR_NIOCR_CHARACTER_VALUE_TOO_LONG \ + -1074395576 // Character values must be <=255 characters. +#define ERR_NIOCR_INVALID_NUMBER_OF_EROSIONS \ + -1074395575 // Invalid number of erosions. The number of erosions must be >= + // 0. +#define ERR_NIOCR_CHARACTER_SET_DESCRIPTION_TOO_LONG \ + -1074395574 // The character set description must be <=255 characters. +#define ERR_NIOCR_INVALID_CHARACTER_SET_FILE_VERSION \ + -1074395573 // The character set file was created by a newer version of NI + // Vision. Upgrade to the latest version of NI Vision to read the + // character set file. +#define ERR_NIOCR_INTEGER_VALUE_FOR_STRING_ATTRIBUTE \ + -1074395572 // You must specify characters for a string. A string cannot + // contain integers. +#define ERR_NIOCR_GET_ONLY_ATTRIBUTE \ + -1074395571 // This attribute is read-only. +#define ERR_NIOCR_INTEGER_VALUE_FOR_BOOLEAN_ATTRIBUTE \ + -1074395570 // This attribute requires a Boolean value. +#define ERR_NIOCR_INVALID_ATTRIBUTE -1074395569 // Invalid attribute. +#define ERR_NIOCR_STRING_VALUE_FOR_INTEGER_ATTRIBUTE \ + -1074395568 // This attribute requires integer values. +#define ERR_NIOCR_STRING_VALUE_FOR_BOOLEAN_ATTRIBUTE \ + -1074395567 // String values are invalid for this attribute. Enter a boolean + // value. +#define ERR_NIOCR_BOOLEAN_VALUE_FOR_INTEGER_ATTRIBUTE \ + -1074395566 // Boolean values are not valid for this attribute. Enter an + // integer value. +#define ERR_NIOCR_MUST_BE_SINGLE_CHARACTER \ + -1074395565 // Requires a single-character string. +#define ERR_NIOCR_INVALID_PREDEFINED_CHARACTER \ + -1074395564 // Invalid predefined character value. +#define ERR_NIOCR_UNLICENSED -1074395563 // This copy of NI OCR is unlicensed. +#define ERR_NIOCR_BOOLEAN_VALUE_FOR_STRING_ATTRIBUTE \ + -1074395562 // String values are not valid for this attribute. Enter a + // Boolean value. +#define ERR_NIOCR_INVALID_NUMBER_OF_CHARACTERS \ + -1074395561 // The number of characters in the character value must match the + // number of objects in the image. +#define ERR_NIOCR_INVALID_OBJECT_INDEX -1074395560 // Invalid object index. +#define ERR_NIOCR_INVALID_READ_OPTION -1074395559 // Invalid read option. +#define ERR_NIOCR_INVALID_CHARACTER_SIZE_RANGE \ + -1074395558 // The minimum character size must be less than the maximum + // character size. +#define ERR_NIOCR_INVALID_BOUNDING_RECT_WIDTH_RANGE \ + -1074395557 // The minimum character bounding rectangle width must be less + // than the maximum character bounding rectangle width. +#define ERR_NIOCR_INVALID_BOUNDING_RECT_HEIGHT_RANGE \ + -1074395556 // The minimum character bounding rectangle height must be less + // than the maximum character bounding rectangle height. +#define ERR_NIOCR_INVALID_SPACING_RANGE \ + -1074395555 // The maximum horizontal element spacing value must not exceed + // the minimum character spacing value. +#define ERR_NIOCR_INVALID_READ_RESOLUTION \ + -1074395554 // Invalid read resolution. +#define ERR_NIOCR_INVALID_MIN_BOUNDING_RECT_HEIGHT \ + -1074395553 // Invalid minimum bounding rectangle height. The minimum + // bounding rectangle height must be >= 1. +#define ERR_NIOCR_NOT_A_VALID_CHARACTER_SET \ + -1074395552 // Not a valid character set. +#define ERR_NIOCR_RENAME_REFCHAR \ + -1074395551 // A trained OCR character cannot be renamed while it is a + // reference character. +#define ERR_NIOCR_INVALID_CHARACTER_VALUE \ + -1074395550 // A character cannot have an ASCII value of 255. +#define ERR_NIOCR_INVALID_NUMBER_OF_OBJECTS_TO_VERIFY \ + -1074395549 // The number of objects found does not match the number of + // expected characters or patterns to verify. +#define ERR_INVALID_STEREO_BLOCKMATCHING_PREFILTER_CAP \ + -1074395421 // The specified value for the filter cap for block matching is + // invalid. +#define ERR_INVALID_STEREO_BLOCKMATCHING_PREFILTER_SIZE \ + -1074395420 // The specified prefilter size for block matching is invalid. +#define ERR_INVALID_STEREO_BLOCKMATCHING_PREFILTER_TYPE \ + -1074395419 // The specified prefilter type for block matching is invalid. +#define ERR_INVALID_STEREO_BLOCKMATCHING_NUMDISPARITIES \ + -1074395418 // The specifed value for number of disparities is invalid. +#define ERR_INVALID_STEREO_BLOCKMATCHING_WINDOW_SIZE \ + -1074395417 // The specified window size for block matching is invalid. +#define ERR_3DVISION_INVALID_SESSION_TYPE \ + -1074395416 // This 3D vision function cannot be called on this type of 3d + // vision session. +#define ERR_TOO_MANY_3DVISION_SESSIONS \ + -1074395415 // There are too many 3D vision sessions open. You must close a + // session before you can open another one. +#define ERR_OPENING_NEWER_3DVISION_SESSION \ + -1074395414 // The 3D vision session you tried to open was created with a + // newer version of NI Vision. Upgrade to the latest version of + // NI Vision to read this file. +#define ERR_INVALID_STEREO_BLOCKMATCHING_FILTERTYPE \ + -1074395413 // You have specified an invalid filter type for block matching. +#define ERR_INVALID_STEREO_CAMERA_POSITION \ + -1074395412 // You have requested results at an invalid camera position in + // the stereo setup. +#define ERR_INVALID_3DVISION_SESSION \ + -1074395411 // Not a valid 3D Vision session. +#define ERR_INVALID_ICONS_PER_LINE \ + -1074395410 // NI Vision does not support less than one icon per line. +#define ERR_INVALID_SUBPIXEL_DIVISIONS \ + -1074395409 // Invalid subpixel divisions. +#define ERR_INVALID_DETECTION_MODE -1074395408 // Invalid detection mode. +#define ERR_INVALID_CONTRAST \ + -1074395407 // Invalid contrast value. Valid contrast values range from 0 to + // 255. +#define ERR_COORDSYS_NOT_FOUND \ + -1074395406 // The coordinate system could not be found on this image. +#define ERR_INVALID_TEXTORIENTATION \ + -1074395405 // NI Vision does not support the text orientation value you + // supplied. +#define ERR_INVALID_INTERPOLATIONMETHOD_FOR_UNWRAP \ + -1074395404 // UnwrapImage does not support the interpolation method value + // you supplied. Valid interpolation methods are zero order and + // bilinear. +#define ERR_EXTRAINFO_VERSION \ + -1074395403 // The image was created in a newer version of NI Vision. Upgrade + // to the latest version of NI Vision to use this image. +#define ERR_INVALID_MAXPOINTS \ + -1074395402 // The function does not support the maximum number of points + // that you specified. +#define ERR_INVALID_MATCHFACTOR \ + -1074395401 // The function does not support the matchFactor that you + // specified. +#define ERR_MULTICORE_OPERATION \ + -1074395400 // The operation you have given Multicore Options is invalid. + // Please see the available enumeration values for Multicore + // Operation. +#define ERR_MULTICORE_INVALID_ARGUMENT \ + -1074395399 // You have given Multicore Options an invalid argument. +#define ERR_COMPLEX_IMAGE_REQUIRED -1074395397 // A complex image is required. +#define ERR_COLOR_IMAGE_REQUIRED \ + -1074395395 // The input image must be a color image. +#define ERR_COLOR_SPECTRUM_MASK \ + -1074395394 // The color mask removes too much color information. +#define ERR_COLOR_TEMPLATE_IMAGE_TOO_SMALL \ + -1074395393 // The color template image is too small. +#define ERR_COLOR_TEMPLATE_IMAGE_TOO_LARGE \ + -1074395392 // The color template image is too large. +#define ERR_COLOR_TEMPLATE_IMAGE_HUE_CONTRAST_TOO_LOW \ + -1074395391 // The contrast in the hue plane of the image is too low for + // learning shape features. +#define ERR_COLOR_TEMPLATE_IMAGE_LUMINANCE_CONTRAST_TOO_LOW \ + -1074395390 // The contrast in the luminance plane of the image is too low to + // learn shape features. +#define ERR_COLOR_LEARN_SETUP_DATA \ + -1074395389 // Invalid color learn setup data. +#define ERR_COLOR_LEARN_SETUP_DATA_SHAPE \ + -1074395388 // Invalid color learn setup data. +#define ERR_COLOR_MATCH_SETUP_DATA \ + -1074395387 // Invalid color match setup data. +#define ERR_COLOR_MATCH_SETUP_DATA_SHAPE \ + -1074395386 // Invalid color match setup data. +#define ERR_COLOR_ROTATION_REQUIRES_SHAPE_FEATURE \ + -1074395385 // Rotation-invariant color pattern matching requires a feature + // mode including shape. +#define ERR_COLOR_TEMPLATE_DESCRIPTOR \ + -1074395384 // Invalid color template image. +#define ERR_COLOR_TEMPLATE_DESCRIPTOR_1 \ + -1074395383 // Invalid color template image. +#define ERR_COLOR_TEMPLATE_DESCRIPTOR_2 \ + -1074395382 // Invalid color template image. +#define ERR_COLOR_TEMPLATE_DESCRIPTOR_3 \ + -1074395381 // Invalid color template image. +#define ERR_COLOR_TEMPLATE_DESCRIPTOR_4 \ + -1074395380 // Invalid color template image. +#define ERR_COLOR_TEMPLATE_DESCRIPTOR_5 \ + -1074395379 // Invalid color template image. +#define ERR_COLOR_TEMPLATE_DESCRIPTOR_6 \ + -1074395378 // Invalid color template image. +#define ERR_COLOR_TEMPLATE_DESCRIPTOR_SHIFT \ + -1074395377 // Invalid color template image. +#define ERR_COLOR_TEMPLATE_DESCRIPTOR_NOSHIFT \ + -1074395376 // The color template image does not contain data required for + // shift-invariant color matching. +#define ERR_COLOR_TEMPLATE_DESCRIPTOR_SHIFT_1 \ + -1074395375 // Invalid color template image. +#define ERR_COLOR_TEMPLATE_DESCRIPTOR_SHIFT_2 \ + -1074395374 // Invalid color template image. +#define ERR_COLOR_TEMPLATE_DESCRIPTOR_ROTATION \ + -1074395373 // Invalid color template image. +#define ERR_COLOR_TEMPLATE_DESCRIPTOR_NOROTATION \ + -1074395372 // The color template image does not contain data required for + // rotation-invariant color matching. +#define ERR_COLOR_TEMPLATE_DESCRIPTOR_ROTATION_1 \ + -1074395371 // Invalid color template image. +#define ERR_COLOR_TEMPLATE_DESCRIPTOR_ROTATION_2 \ + -1074395370 // Invalid color template image. +#define ERR_COLOR_TEMPLATE_DESCRIPTOR_ROTATION_3 \ + -1074395369 // Invalid color template image. +#define ERR_COLOR_TEMPLATE_DESCRIPTOR_ROTATION_4 \ + -1074395368 // Invalid color template image. +#define ERR_COLOR_TEMPLATE_DESCRIPTOR_ROTATION_5 \ + -1074395367 // Invalid color template image. +#define ERR_COLOR_TEMPLATE_DESCRIPTOR_NOSHAPE \ + -1074395366 // The color template image does not contain data required for + // color matching in shape feature mode. +#define ERR_COLOR_TEMPLATE_DESCRIPTOR_NOSPECTRUM \ + -1074395365 // The color template image does not contain data required for + // color matching in color feature mode. +#define ERR_IGNORE_COLOR_SPECTRUM_SET \ + -1074395364 // The ignore color spectra array is invalid. +#define ERR_INVALID_SUBSAMPLING_RATIO -1074395363 // Invalid subsampling ratio. +#define ERR_INVALID_WIDTH -1074395362 // Invalid pixel width. +#define ERR_INVALID_STEEPNESS -1074395361 // Invalid steepness. +#define ERR_COMPLEX_PLANE -1074395360 // Invalid complex plane. +#define ERR_INVALID_COLOR_IGNORE_MODE -1074395357 // Invalid color ignore mode. +#define ERR_INVALID_MIN_MATCH_SCORE \ + -1074395356 // Invalid minimum match score. Acceptable values range from 0 to + // 1000. +#define ERR_INVALID_NUM_MATCHES_REQUESTED \ + -1074395355 // Invalid number of matches requested. You must request a + // minimum of one match. +#define ERR_INVALID_COLOR_WEIGHT \ + -1074395354 // Invalid color weight. Acceptable values range from 0 to 1000. +#define ERR_INVALID_SEARCH_STRATEGY -1074395353 // Invalid search strategy. +#define ERR_INVALID_FEATURE_MODE -1074395352 // Invalid feature mode. +#define ERR_INVALID_RECT \ + -1074395351 // NI Vision does not support rectangles with negative widths or + // negative heights. +#define ERR_INVALID_VISION_INFO \ + -1074395350 // NI Vision does not support the vision information type you + // supplied. +#define ERR_INVALID_SKELETONMETHOD \ + -1074395349 // NI Vision does not support the SkeletonMethod value you + // supplied. +#define ERR_INVALID_3DPLANE \ + -1074395348 // NI Vision does not support the 3DPlane value you supplied. +#define ERR_INVALID_3DDIRECTION \ + -1074395347 // NI Vision does not support the 3DDirection value you supplied. +#define ERR_INVALID_INTERPOLATIONMETHOD_FOR_ROTATE \ + -1074395346 // imaqRotate does not support the InterpolationMethod value you + // supplied. +#define ERR_INVALID_FLIPAXIS \ + -1074395345 // NI Vision does not support the axis of symmetry you supplied. +#define ERR_FILE_FILENAME_NULL \ + -1074395343 // You must pass a valid file name. Do not pass in NULL. +#define ERR_INVALID_SIZETYPE \ + -1074395340 // NI Vision does not support the SizeType value you supplied. +#define ERR_UNKNOWN_ALGORITHM \ + -1074395336 // You specified the dispatch status of an unknown algorithm. +#define ERR_DISPATCH_STATUS_CONFLICT \ + -1074395335 // You are attempting to set the same algorithm to dispatch and + // to not dispatch. Remove one of the conflicting settings. +#define ERR_INVALID_CONVERSIONSTYLE \ + -1074395334 // NI Vision does not support the Conversion Method value you + // supplied. +#define ERR_INVALID_VERTICAL_TEXT_ALIGNMENT \ + -1074395333 // NI Vision does not support the VerticalTextAlignment value you + // supplied. +#define ERR_INVALID_COMPAREFUNCTION \ + -1074395332 // NI Vision does not support the CompareFunction value you + // supplied. +#define ERR_INVALID_BORDERMETHOD \ + -1074395331 // NI Vision does not support the BorderMethod value you + // supplied. +#define ERR_INVALID_BORDER_SIZE \ + -1074395330 // Invalid border size. Acceptable values range from 0 to 50. +#define ERR_INVALID_OUTLINEMETHOD \ + -1074395329 // NI Vision does not support the OutlineMethod value you + // supplied. +#define ERR_INVALID_INTERPOLATIONMETHOD \ + -1074395328 // NI Vision does not support the InterpolationMethod value you + // supplied. +#define ERR_INVALID_SCALINGMODE \ + -1074395327 // NI Vision does not support the ScalingMode value you supplied. +#define ERR_INVALID_DRAWMODE_FOR_LINE \ + -1074395326 // imaqDrawLineOnImage does not support the DrawMode value you + // supplied. +#define ERR_INVALID_DRAWMODE \ + -1074395325 // NI Vision does not support the DrawMode value you supplied. +#define ERR_INVALID_SHAPEMODE \ + -1074395324 // NI Vision does not support the ShapeMode value you supplied. +#define ERR_INVALID_FONTCOLOR \ + -1074395323 // NI Vision does not support the FontColor value you supplied. +#define ERR_INVALID_TEXTALIGNMENT \ + -1074395322 // NI Vision does not support the TextAlignment value you + // supplied. +#define ERR_INVALID_MORPHOLOGYMETHOD \ + -1074395321 // NI Vision does not support the MorphologyMethod value you + // supplied. +#define ERR_TEMPLATE_EMPTY -1074395320 // The template image is empty. +#define ERR_INVALID_SUBPIX_TYPE \ + -1074395319 // NI Vision does not support the interpolation type you + // supplied. +#define ERR_INSF_POINTS \ + -1074395318 // You supplied an insufficient number of points to perform this + // operation. +#define ERR_UNDEF_POINT \ + -1074395317 // You specified a point that lies outside the image. +#define ERR_INVALID_KERNEL_CODE -1074395316 // Invalid kernel code. +#define ERR_INEFFICIENT_POINTS \ + -1074395315 // You supplied an inefficient set of points to match the minimum + // score. +#define ERR_WRITE_FILE_NOT_SUPPORTED \ + -1074395313 // Writing files is not supported on this device. +#define ERR_LCD_CALIBRATE \ + -1074395312 // The input image does not seem to be a valid LCD or LED + // calibration image. +#define ERR_INVALID_COLOR_SPECTRUM \ + -1074395311 // The color spectrum array you provided has an invalid number of + // elements or contains an element set to not-a-number (NaN). +#define ERR_INVALID_PALETTE_TYPE \ + -1074395310 // NI Vision does not support the PaletteType value you supplied. +#define ERR_INVALID_WINDOW_THREAD_POLICY \ + -1074395309 // NI Vision does not support the WindowThreadPolicy value you + // supplied. +#define ERR_INVALID_COLORSENSITIVITY \ + -1074395308 // NI Vision does not support the ColorSensitivity value you + // supplied. +#define ERR_PRECISION_NOT_GTR_THAN_0 \ + -1074395307 // The precision parameter must be greater than 0. +#define ERR_INVALID_TOOL \ + -1074395306 // NI Vision does not support the Tool value you supplied. +#define ERR_INVALID_REFERENCEMODE \ + -1074395305 // NI Vision does not support the ReferenceMode value you + // supplied. +#define ERR_INVALID_MATHTRANSFORMMETHOD \ + -1074395304 // NI Vision does not support the MathTransformMethod value you + // supplied. +#define ERR_INVALID_NUM_OF_CLASSES \ + -1074395303 // Invalid number of classes for auto threshold. Acceptable + // values range from 2 to 256. +#define ERR_INVALID_THRESHOLDMETHOD \ + -1074395302 // NI Vision does not support the threshold method value you + // supplied. +#define ERR_ROI_NOT_2_LINES \ + -1074395301 // The ROI you passed into imaqGetMeterArc must consist of two + // lines. +#define ERR_INVALID_METERARCMODE \ + -1074395300 // NI Vision does not support the MeterArcMode value you + // supplied. +#define ERR_INVALID_COMPLEXPLANE \ + -1074395299 // NI Vision does not support the ComplexPlane value you + // supplied. +#define ERR_COMPLEXPLANE_NOT_REAL_OR_IMAGINARY \ + -1074395298 // You can perform this operation on a real or an imaginary + // ComplexPlane only. +#define ERR_INVALID_PARTICLEINFOMODE \ + -1074395297 // NI Vision does not support the ParticleInfoMode value you + // supplied. +#define ERR_INVALID_BARCODETYPE \ + -1074395296 // NI Vision does not support the BarcodeType value you supplied. +#define ERR_INVALID_INTERPOLATIONMETHOD_INTERPOLATEPOINTS \ + -1074395295 // imaqInterpolatePoints does not support the InterpolationMethod + // value you supplied. +#define ERR_CONTOUR_INDEX_OUT_OF_RANGE \ + -1074395294 // The contour index you supplied is larger than the number of + // contours in the ROI. +#define ERR_CONTOURID_NOT_FOUND \ + -1074395293 // The supplied ContourID did not correlate to a contour inside + // the ROI. +#define ERR_POINTS_ARE_COLLINEAR \ + -1074395292 // Do not supply collinear points for this operation. +#define ERR_SHAPEMATCH_BADIMAGEDATA \ + -1074395291 // Shape Match requires the image to contain only pixel values of + // 0 or 1. +#define ERR_SHAPEMATCH_BADTEMPLATE \ + -1074395290 // The template you supplied for ShapeMatch contains no shape + // information. +#define ERR_CONTAINER_CAPACITY_EXCEEDED_UINT_MAX \ + -1074395289 // The operation would have exceeded the capacity of an internal + // container, which is limited to 4294967296 unique elements. +#define ERR_CONTAINER_CAPACITY_EXCEEDED_INT_MAX \ + -1074395288 // The operation would have exceeded the capacity of an internal + // container, which is limited to 2147483648 unique elements. +#define ERR_INVALID_LINE \ + -1074395287 // The line you provided contains two identical points, or one of + // the coordinate locations for the line is not a number (NaN). +#define ERR_INVALID_CONCENTRIC_RAKE_DIRECTION \ + -1074395286 // Invalid concentric rake direction. +#define ERR_INVALID_SPOKE_DIRECTION -1074395285 // Invalid spoke direction. +#define ERR_INVALID_EDGE_PROCESS -1074395284 // Invalid edge process. +#define ERR_INVALID_RAKE_DIRECTION -1074395283 // Invalid rake direction. +#define ERR_CANT_DRAW_INTO_VIEWER \ + -1074395282 // Unable to draw to viewer. You must have the latest version of + // the control. +#define ERR_IMAGE_SMALLER_THAN_BORDER \ + -1074395281 // Your image must be larger than its border size for this + // operation. +#define ERR_ROI_NOT_RECT \ + -1074395280 // The ROI must only have a single Rectangle contour. +#define ERR_ROI_NOT_POLYGON -1074395279 // ROI is not a polygon. +#define ERR_LCD_NOT_NUMERIC -1074395278 // LCD image is not a number. +#define ERR_BARCODE_CHECKSUM \ + -1074395277 // The decoded barcode information did not pass the checksum + // test. +#define ERR_LINES_PARALLEL \ + -1074395276 // You specified parallel lines for the meter ROI. +#define ERR_INVALID_BROWSER_IMAGE -1074395275 // Invalid browser image. +#define ERR_DIV_BY_ZERO -1074395270 // Cannot divide by zero. +#define ERR_NULL_POINTER -1074395269 // Null pointer. +#define ERR_LINEAR_COEFF \ + -1074395268 // The linear equations are not independent. +#define ERR_COMPLEX_ROOT -1074395267 // The roots of the equation are complex. +#define ERR_BARCODE \ + -1074395265 // The barcode does not match the type you specified. +#define ERR_LCD_NO_SEGMENTS -1074395263 // No lit segment. +#define ERR_LCD_BAD_MATCH -1074395262 // The LCD does not form a known digit. +#define ERR_GIP_RANGE \ + -1074395261 // An internal error occurred while attempting to access an + // invalid coordinate on an image. +#define ERR_HEAP_TRASHED -1074395260 // An internal memory error occurred. +#define ERR_BAD_FILTER_WIDTH \ + -1074395258 // The filter width must be odd for the Canny operator. +#define ERR_INVALID_EDGE_DIR \ + -1074395257 // You supplied an invalid edge direction in the Canny operator. +#define ERR_EVEN_WINDOW_SIZE \ + -1074395256 // The window size must be odd for the Canny operator. +#define ERR_INVALID_LEARN_MODE -1074395253 // Invalid learn mode. +#define ERR_LEARN_SETUP_DATA -1074395252 // Invalid learn setup data. +#define ERR_INVALID_MATCH_MODE -1074395251 // Invalid match mode. +#define ERR_MATCH_SETUP_DATA -1074395250 // Invalid match setup data. +#define ERR_ROTATION_ANGLE_RANGE_TOO_LARGE \ + -1074395249 // At least one range in the array of rotation angle ranges + // exceeds 360 degrees. +#define ERR_TOO_MANY_ROTATION_ANGLE_RANGES \ + -1074395248 // The array of rotation angle ranges contains too many ranges. +#define ERR_TEMPLATE_DESCRIPTOR -1074395247 // Invalid template descriptor. +#define ERR_TEMPLATE_DESCRIPTOR_1 -1074395246 // Invalid template descriptor. +#define ERR_TEMPLATE_DESCRIPTOR_2 -1074395245 // Invalid template descriptor. +#define ERR_TEMPLATE_DESCRIPTOR_3 -1074395244 // Invalid template descriptor. +#define ERR_TEMPLATE_DESCRIPTOR_4 \ + -1074395243 // The template descriptor was created with a newer version of NI + // Vision. Upgrade to the latest version of NI Vision to use this + // template. +#define ERR_TEMPLATE_DESCRIPTOR_ROTATION \ + -1074395242 // Invalid template descriptor. +#define ERR_TEMPLATE_DESCRIPTOR_NOROTATION \ + -1074395241 // The template descriptor does not contain data required for + // rotation-invariant matching. +#define ERR_TEMPLATE_DESCRIPTOR_ROTATION_1 \ + -1074395240 // Invalid template descriptor. +#define ERR_TEMPLATE_DESCRIPTOR_SHIFT \ + -1074395239 // Invalid template descriptor. +#define ERR_TEMPLATE_DESCRIPTOR_NOSHIFT \ + -1074395238 // The template descriptor does not contain data required for + // shift-invariant matching. +#define ERR_TEMPLATE_DESCRIPTOR_SHIFT_1 \ + -1074395237 // Invalid template descriptor. +#define ERR_TEMPLATE_DESCRIPTOR_NOSCALE \ + -1074395236 // The template descriptor does not contain data required for + // scale-invariant matching. +#define ERR_TEMPLATE_IMAGE_CONTRAST_TOO_LOW \ + -1074395235 // The template image does not contain enough contrast. +#define ERR_TEMPLATE_IMAGE_TOO_SMALL \ + -1074395234 // The template image is too small. +#define ERR_TEMPLATE_IMAGE_TOO_LARGE \ + -1074395233 // The template image is too large. +#define ERR_TOO_MANY_OCR_SESSIONS \ + -1074395214 // There are too many OCR sessions open. You must close a + // session before you can open another one. +#define ERR_OCR_TEMPLATE_WRONG_SIZE \ + -1074395212 // The size of the template string must match the size of the + // string you are trying to correct. +#define ERR_OCR_BAD_TEXT_TEMPLATE \ + -1074395211 // The supplied text template contains nonstandard characters + // that cannot be generated by OCR. +#define ERR_OCR_CANNOT_MATCH_TEXT_TEMPLATE \ + -1074395210 // At least one character in the text template was of a lexical + // class that did not match the supplied character reports. +#define ERR_OCR_LIB_INIT \ + -1074395203 // The OCR library cannot be initialized correctly. +#define ERR_OCR_LOAD_LIBRARY \ + -1074395201 // There was a failure when loading one of the internal OCR + // engine or LabView libraries. +#define ERR_OCR_INVALID_PARAMETER \ + -1074395200 // One of the parameters supplied to the OCR function that + // generated this error is invalid. +#define ERR_MARKER_INFORMATION_NOT_SUPPLIED \ + -1074395199 // Marker image and points are not supplied +#define ERR_INCOMPATIBLE_MARKER_IMAGE_SIZE \ + -1074395198 // Source Image and Marker Image should be of same size. +#define ERR_BOTH_MARKER_INPUTS_SUPPLIED \ + -1074395197 // Both Marker Image and Points are supplied. +#define ERR_INVALID_MORPHOLOGICAL_OPERATION \ + -1074395196 // Invalid Morphological Operation. +#define ERR_IMAGE_CONTAINS_NAN_VALUES \ + -1074395195 // Float image contains NaN values +#define ERR_OVERLAY_EXTRAINFO_OPENING_NEW_VERSION \ + -1074395194 // The overlay information you tried to open was created with a + // newer version of NI Vision. Upgrade to the latest version of + // NI Vision to read this file. +#define ERR_NO_CLAMP_FOUND \ + -1074395193 // No valid clamp was found with the current configuration +#define ERR_NO_CLAMP_WITHIN_ANGLE_RANGE \ + -1074395192 // Supplied angle range for clamp is insufficient +#define ERR_GHT_INVALID_USE_ALL_CURVES_VALUE \ + -1074395188 // The use all curves advanced option specified during learn is + // not supported +#define ERR_INVALID_GAUSS_SIGMA_VALUE \ + -1074395187 // The sigma value specified for the Gaussian filter is too + // small. +#define ERR_INVALID_GAUSS_FILTER_TYPE \ + -1074395186 // The specified Gaussian filter type is not supported. +#define ERR_INVALID_CONTRAST_REVERSAL_MODE \ + -1074395185 // The contrast reversal mode specified during matching is + // invalid. +#define ERR_INVALID_ROTATION_RANGE \ + -1074395184 // Invalid roation angle range. The upper bound must be greater + // than or equal to the lower bound. +#define ERR_GHT_INVALID_MINIMUM_LEARN_ANGLE_VALUE \ + -1074395183 // The minimum rotation angle value specifed during learning of + // the template is not supported. +#define ERR_GHT_INVALID_MAXIMUM_LEARN_ANGLE_VALUE \ + -1074395182 // The maximum rotation angle value specifed during learning of + // the template is not supported. +#define ERR_GHT_INVALID_MAXIMUM_LEARN_SCALE_FACTOR \ + -1074395181 // The maximum scale factor specifed during learning of the + // template is not supported. +#define ERR_GHT_INVALID_MINIMUM_LEARN_SCALE_FACTOR \ + -1074395180 // The minimum scale factor specifed during learning of the + // template is not supported. +#define ERR_OCR_PREPROCESSING_FAILED \ + -1074395179 // The OCR engine failed during the preprocessing stage. +#define ERR_OCR_RECOGNITION_FAILED \ + -1074395178 // The OCR engine failed during the recognition stage. +#define ERR_OCR_BAD_USER_DICTIONARY \ + -1074395175 // The provided filename is not valid user dictionary filename. +#define ERR_OCR_INVALID_AUTOORIENTMODE \ + -1074395174 // NI Vision does not support the AutoOrientMode value you + // supplied. +#define ERR_OCR_INVALID_LANGUAGE \ + -1074395173 // NI Vision does not support the Language value you supplied. +#define ERR_OCR_INVALID_CHARACTERSET \ + -1074395172 // NI Vision does not support the CharacterSet value you + // supplied. +#define ERR_OCR_INI_FILE_NOT_FOUND \ + -1074395171 // The system could not locate the initialization file required + // for OCR initialization. +#define ERR_OCR_INVALID_CHARACTERTYPE \ + -1074395170 // NI Vision does not support the CharacterType value you + // supplied. +#define ERR_OCR_INVALID_RECOGNITIONMODE \ + -1074395169 // NI Vision does not support the RecognitionMode value you + // supplied. +#define ERR_OCR_INVALID_AUTOCORRECTIONMODE \ + -1074395168 // NI Vision does not support the AutoCorrectionMode value you + // supplied. +#define ERR_OCR_INVALID_OUTPUTDELIMITER \ + -1074395167 // NI Vision does not support the OutputDelimiter value you + // supplied. +#define ERR_OCR_BIN_DIR_NOT_FOUND \ + -1074395166 // The system could not locate the OCR binary directory required + // for OCR initialization. +#define ERR_OCR_WTS_DIR_NOT_FOUND \ + -1074395165 // The system could not locate the OCR weights directory required + // for OCR initialization. +#define ERR_OCR_ADD_WORD_FAILED \ + -1074395164 // The supplied word could not be added to the user dictionary. +#define ERR_OCR_INVALID_CHARACTERPREFERENCE \ + -1074395163 // NI Vision does not support the CharacterPreference value you + // supplied. +#define ERR_OCR_INVALID_CORRECTIONMODE \ + -1074395162 // NI Vision does not support the CorrectionMethod value you + // supplied. +#define ERR_OCR_INVALID_CORRECTIONLEVEL \ + -1074395161 // NI Vision does not support the CorrectionLevel value you + // supplied. +#define ERR_OCR_INVALID_MAXPOINTSIZE \ + -1074395160 // NI Vision does not support the maximum point size you + // supplied. Valid values range from 4 to 72. +#define ERR_OCR_INVALID_TOLERANCE \ + -1074395159 // NI Vision does not support the tolerance value you supplied. + // Valid values are non-negative. +#define ERR_OCR_INVALID_CONTRASTMODE \ + -1074395158 // NI Vision does not support the ContrastMode value you + // supplied. +#define ERR_OCR_SKEW_DETECT_FAILED \ + -1074395156 // The OCR attempted to detected the text skew and failed. +#define ERR_OCR_ORIENT_DETECT_FAILED \ + -1074395155 // The OCR attempted to detected the text orientation and failed. +#define ERR_FONT_FILE_FORMAT -1074395153 // Invalid font file format. +#define ERR_FONT_FILE_NOT_FOUND -1074395152 // Font file not found. +#define ERR_OCR_CORRECTION_FAILED \ + -1074395151 // The OCR engine failed during the correction stage. +#define ERR_INVALID_ROUNDING_MODE \ + -1074395150 // NI Vision does not support the RoundingMode value you + // supplied. +#define ERR_DUPLICATE_TRANSFORM_TYPE \ + -1074395149 // Found a duplicate transform type in the properties array. Each + // properties array may only contain one behavior for each + // transform type. +#define ERR_OVERLAY_GROUP_NOT_FOUND -1074395148 // Overlay Group Not Found. +#define ERR_BARCODE_RSSLIMITED \ + -1074395147 // The barcode is not a valid RSS Limited symbol +#define ERR_QR_DETECTION_VERSION \ + -1074395146 // Couldn't determine the correct version of the QR code. +#define ERR_QR_INVALID_READ -1074395145 // Invalid read of the QR code. +#define ERR_QR_INVALID_BARCODE \ + -1074395144 // The barcode that was read contains invalid parameters. +#define ERR_QR_DETECTION_MODE \ + -1074395143 // The data stream that was demodulated could not be read because + // the mode was not detected. +#define ERR_QR_DETECTION_MODELTYPE \ + -1074395142 // Couldn't determine the correct model of the QR code. +#define ERR_OCR_NO_TEXT_FOUND \ + -1074395141 // The OCR engine could not find any text in the supplied region. +#define ERR_OCR_CHAR_REPORT_CORRUPTED \ + -1074395140 // One of the character reports is no longer usable by the + // system. +#define ERR_IMAQ_QR_DIMENSION_INVALID -1074395139 // Invalid Dimensions. +#define ERR_OCR_REGION_TOO_SMALL \ + -1074395138 // The OCR region provided was too small to have contained any + // characters. +#define _FIRST_ERR ERR_SYSTEM_ERROR +#define _LAST_ERR ERR_OCR_REGION_TOO_SMALL //============================================================================ // Enumerated Types //============================================================================ typedef enum PointSymbol_enum { - IMAQ_POINT_AS_PIXEL = 0, //A single pixel represents a point in the overlay. - IMAQ_POINT_AS_CROSS = 1, //A cross represents a point in the overlay. - IMAQ_POINT_USER_DEFINED = 2, //The pattern supplied by the user represents a point in the overlay. - IMAQ_POINT_SYMBOL_SIZE_GUARD = 0xFFFFFFFF + IMAQ_POINT_AS_PIXEL = 0, // A single pixel represents a point in the overlay. + IMAQ_POINT_AS_CROSS = 1, // A cross represents a point in the overlay. + IMAQ_POINT_USER_DEFINED = + 2, // The pattern supplied by the user represents a point in the overlay. + IMAQ_POINT_SYMBOL_SIZE_GUARD = 0xFFFFFFFF } PointSymbol; typedef enum MeasurementValue_enum { - IMAQ_AREA = 0, //Surface area of the particle in pixels. - IMAQ_AREA_CALIBRATED = 1, //Surface area of the particle in calibrated units. - IMAQ_NUM_HOLES = 2, //Number of holes in the particle. - IMAQ_AREA_OF_HOLES = 3, //Surface area of the holes in calibrated units. - IMAQ_TOTAL_AREA = 4, //Total surface area (holes and particle) in calibrated units. - IMAQ_IMAGE_AREA = 5, //Surface area of the entire image in calibrated units. - IMAQ_PARTICLE_TO_IMAGE = 6, //Ratio, expressed as a percentage, of the surface area of a particle in relation to the total area of the particle. - IMAQ_PARTICLE_TO_TOTAL = 7, //Ratio, expressed as a percentage, of the surface area of a particle in relation to the total area of the particle. - IMAQ_CENTER_MASS_X = 8, //X-coordinate of the center of mass. - IMAQ_CENTER_MASS_Y = 9, //Y-coordinate of the center of mass. - IMAQ_LEFT_COLUMN = 10, //Left edge of the bounding rectangle. - IMAQ_TOP_ROW = 11, //Top edge of the bounding rectangle. - IMAQ_RIGHT_COLUMN = 12, //Right edge of the bounding rectangle. - IMAQ_BOTTOM_ROW = 13, //Bottom edge of bounding rectangle. - IMAQ_WIDTH = 14, //Width of bounding rectangle in calibrated units. - IMAQ_HEIGHT = 15, //Height of bounding rectangle in calibrated units. - IMAQ_MAX_SEGMENT_LENGTH = 16, //Length of longest horizontal line segment. - IMAQ_MAX_SEGMENT_LEFT_COLUMN = 17, //Leftmost x-coordinate of longest horizontal line segment. - IMAQ_MAX_SEGMENT_TOP_ROW = 18, //Y-coordinate of longest horizontal line segment. - IMAQ_PERIMETER = 19, //Outer perimeter of the particle. - IMAQ_PERIMETER_OF_HOLES = 20, //Perimeter of all holes within the particle. - IMAQ_SIGMA_X = 21, //Sum of the particle pixels on the x-axis. - IMAQ_SIGMA_Y = 22, //Sum of the particle pixels on the y-axis. - IMAQ_SIGMA_XX = 23, //Sum of the particle pixels on the x-axis squared. - IMAQ_SIGMA_YY = 24, //Sum of the particle pixels on the y-axis squared. - IMAQ_SIGMA_XY = 25, //Sum of the particle pixels on the x-axis and y-axis. - IMAQ_PROJ_X = 26, //Projection corrected in X. - IMAQ_PROJ_Y = 27, //Projection corrected in Y. - IMAQ_INERTIA_XX = 28, //Inertia matrix coefficient in XX. - IMAQ_INERTIA_YY = 29, //Inertia matrix coefficient in YY. - IMAQ_INERTIA_XY = 30, //Inertia matrix coefficient in XY. - IMAQ_MEAN_H = 31, //Mean length of horizontal segments. - IMAQ_MEAN_V = 32, //Mean length of vertical segments. - IMAQ_MAX_INTERCEPT = 33, //Length of longest segment of the convex hull. - IMAQ_MEAN_INTERCEPT = 34, //Mean length of the chords in an object perpendicular to its max intercept. - IMAQ_ORIENTATION = 35, //The orientation based on the inertia of the pixels in the particle. - IMAQ_EQUIV_ELLIPSE_MINOR = 36, //Total length of the axis of the ellipse having the same area as the particle and a major axis equal to half the max intercept. - IMAQ_ELLIPSE_MAJOR = 37, //Total length of major axis having the same area and perimeter as the particle in calibrated units. - IMAQ_ELLIPSE_MINOR = 38, //Total length of minor axis having the same area and perimeter as the particle in calibrated units. - IMAQ_ELLIPSE_RATIO = 39, //Fraction of major axis to minor axis. - IMAQ_RECT_LONG_SIDE = 40, //Length of the long side of a rectangle having the same area and perimeter as the particle in calibrated units. - IMAQ_RECT_SHORT_SIDE = 41, //Length of the short side of a rectangle having the same area and perimeter as the particle in calibrated units. - IMAQ_RECT_RATIO = 42, //Ratio of rectangle long side to rectangle short side. - IMAQ_ELONGATION = 43, //Max intercept/mean perpendicular intercept. - IMAQ_COMPACTNESS = 44, //Particle area/(height x width). - IMAQ_HEYWOOD = 45, //Particle perimeter/perimeter of the circle having the same area as the particle. - IMAQ_TYPE_FACTOR = 46, //A complex factor relating the surface area to the moment of inertia. - IMAQ_HYDRAULIC = 47, //Particle area/particle perimeter. - IMAQ_WADDLE_DISK = 48, //Diameter of the disk having the same area as the particle in user units. - IMAQ_DIAGONAL = 49, //Diagonal of an equivalent rectangle in user units. - IMAQ_MEASUREMENT_VALUE_SIZE_GUARD = 0xFFFFFFFF + IMAQ_AREA = 0, // Surface area of the particle in pixels. + IMAQ_AREA_CALIBRATED = + 1, // Surface area of the particle in calibrated units. + IMAQ_NUM_HOLES = 2, // Number of holes in the particle. + IMAQ_AREA_OF_HOLES = 3, // Surface area of the holes in calibrated units. + IMAQ_TOTAL_AREA = + 4, // Total surface area (holes and particle) in calibrated units. + IMAQ_IMAGE_AREA = 5, // Surface area of the entire image in calibrated units. + IMAQ_PARTICLE_TO_IMAGE = 6, // Ratio, expressed as a percentage, of the + // surface area of a particle in relation to the + // total area of the particle. + IMAQ_PARTICLE_TO_TOTAL = 7, // Ratio, expressed as a percentage, of the + // surface area of a particle in relation to the + // total area of the particle. + IMAQ_CENTER_MASS_X = 8, // X-coordinate of the center of mass. + IMAQ_CENTER_MASS_Y = 9, // Y-coordinate of the center of mass. + IMAQ_LEFT_COLUMN = 10, // Left edge of the bounding rectangle. + IMAQ_TOP_ROW = 11, // Top edge of the bounding rectangle. + IMAQ_RIGHT_COLUMN = 12, // Right edge of the bounding rectangle. + IMAQ_BOTTOM_ROW = 13, // Bottom edge of bounding rectangle. + IMAQ_WIDTH = 14, // Width of bounding rectangle in calibrated units. + IMAQ_HEIGHT = 15, // Height of bounding rectangle in calibrated units. + IMAQ_MAX_SEGMENT_LENGTH = 16, // Length of longest horizontal line segment. + IMAQ_MAX_SEGMENT_LEFT_COLUMN = + 17, // Leftmost x-coordinate of longest horizontal line segment. + IMAQ_MAX_SEGMENT_TOP_ROW = + 18, // Y-coordinate of longest horizontal line segment. + IMAQ_PERIMETER = 19, // Outer perimeter of the particle. + IMAQ_PERIMETER_OF_HOLES = 20, // Perimeter of all holes within the particle. + IMAQ_SIGMA_X = 21, // Sum of the particle pixels on the x-axis. + IMAQ_SIGMA_Y = 22, // Sum of the particle pixels on the y-axis. + IMAQ_SIGMA_XX = 23, // Sum of the particle pixels on the x-axis squared. + IMAQ_SIGMA_YY = 24, // Sum of the particle pixels on the y-axis squared. + IMAQ_SIGMA_XY = 25, // Sum of the particle pixels on the x-axis and y-axis. + IMAQ_PROJ_X = 26, // Projection corrected in X. + IMAQ_PROJ_Y = 27, // Projection corrected in Y. + IMAQ_INERTIA_XX = 28, // Inertia matrix coefficient in XX. + IMAQ_INERTIA_YY = 29, // Inertia matrix coefficient in YY. + IMAQ_INERTIA_XY = 30, // Inertia matrix coefficient in XY. + IMAQ_MEAN_H = 31, // Mean length of horizontal segments. + IMAQ_MEAN_V = 32, // Mean length of vertical segments. + IMAQ_MAX_INTERCEPT = 33, // Length of longest segment of the convex hull. + IMAQ_MEAN_INTERCEPT = 34, // Mean length of the chords in an object + // perpendicular to its max intercept. + IMAQ_ORIENTATION = 35, // The orientation based on the inertia of the pixels + // in the particle. + IMAQ_EQUIV_ELLIPSE_MINOR = 36, // Total length of the axis of the ellipse + // having the same area as the particle and a + // major axis equal to half the max intercept. + IMAQ_ELLIPSE_MAJOR = 37, // Total length of major axis having the same area + // and perimeter as the particle in calibrated + // units. + IMAQ_ELLIPSE_MINOR = 38, // Total length of minor axis having the same area + // and perimeter as the particle in calibrated + // units. + IMAQ_ELLIPSE_RATIO = 39, // Fraction of major axis to minor axis. + IMAQ_RECT_LONG_SIDE = 40, // Length of the long side of a rectangle having + // the same area and perimeter as the particle in + // calibrated units. + IMAQ_RECT_SHORT_SIDE = 41, // Length of the short side of a rectangle having + // the same area and perimeter as the particle in + // calibrated units. + IMAQ_RECT_RATIO = + 42, // Ratio of rectangle long side to rectangle short side. + IMAQ_ELONGATION = 43, // Max intercept/mean perpendicular intercept. + IMAQ_COMPACTNESS = 44, // Particle area/(height x width). + IMAQ_HEYWOOD = 45, // Particle perimeter/perimeter of the circle having the + // same area as the particle. + IMAQ_TYPE_FACTOR = 46, // A complex factor relating the surface area to the + // moment of inertia. + IMAQ_HYDRAULIC = 47, // Particle area/particle perimeter. + IMAQ_WADDLE_DISK = 48, // Diameter of the disk having the same area as the + // particle in user units. + IMAQ_DIAGONAL = 49, // Diagonal of an equivalent rectangle in user units. + IMAQ_MEASUREMENT_VALUE_SIZE_GUARD = 0xFFFFFFFF } MeasurementValue; typedef enum ScalingMode_enum { - IMAQ_SCALE_LARGER = 0, //The function duplicates pixels to make the image larger. - IMAQ_SCALE_SMALLER = 1, //The function subsamples pixels to make the image smaller. - IMAQ_SCALING_MODE_SIZE_GUARD = 0xFFFFFFFF + IMAQ_SCALE_LARGER = + 0, // The function duplicates pixels to make the image larger. + IMAQ_SCALE_SMALLER = + 1, // The function subsamples pixels to make the image smaller. + IMAQ_SCALING_MODE_SIZE_GUARD = 0xFFFFFFFF } ScalingMode; typedef enum ScalingMethod_enum { - IMAQ_SCALE_TO_PRESERVE_AREA = 0, //Correction functions scale the image such that the features in the corrected image have the same area as the features in the input image. - IMAQ_SCALE_TO_FIT = 1, //Correction functions scale the image such that the corrected image is the same size as the input image. - IMAQ_SCALING_METHOD_SIZE_GUARD = 0xFFFFFFFF + IMAQ_SCALE_TO_PRESERVE_AREA = 0, // Correction functions scale the image such + // that the features in the corrected image + // have the same area as the features in the + // input image. + IMAQ_SCALE_TO_FIT = 1, // Correction functions scale the image such that the + // corrected image is the same size as the input + // image. + IMAQ_SCALING_METHOD_SIZE_GUARD = 0xFFFFFFFF } ScalingMethod; typedef enum ReferenceMode_enum { - IMAQ_COORD_X_Y = 0, //This method requires three elements in the points array. - IMAQ_COORD_ORIGIN_X = 1, //This method requires two elements in the points array. - IMAQ_REFERENCE_MODE_SIZE_GUARD = 0xFFFFFFFF + IMAQ_COORD_X_Y = + 0, // This method requires three elements in the points array. + IMAQ_COORD_ORIGIN_X = + 1, // This method requires two elements in the points array. + IMAQ_REFERENCE_MODE_SIZE_GUARD = 0xFFFFFFFF } ReferenceMode; typedef enum RectOrientation_enum { - IMAQ_BASE_INSIDE = 0, //Specifies that the base of the rectangular image lies along the inside edge of the annulus. - IMAQ_BASE_OUTSIDE = 1, //Specifies that the base of the rectangular image lies along the outside edge of the annulus. - IMAQ_TEXT_ORIENTATION_SIZE_GUARD = 0xFFFFFFFF + IMAQ_BASE_INSIDE = 0, // Specifies that the base of the rectangular image + // lies along the inside edge of the annulus. + IMAQ_BASE_OUTSIDE = 1, // Specifies that the base of the rectangular image + // lies along the outside edge of the annulus. + IMAQ_TEXT_ORIENTATION_SIZE_GUARD = 0xFFFFFFFF } RectOrientation; typedef enum ShapeMode_enum { - IMAQ_SHAPE_RECT = 1, //The function draws a rectangle. - IMAQ_SHAPE_OVAL = 2, //The function draws an oval. - IMAQ_SHAPE_MODE_SIZE_GUARD = 0xFFFFFFFF + IMAQ_SHAPE_RECT = 1, // The function draws a rectangle. + IMAQ_SHAPE_OVAL = 2, // The function draws an oval. + IMAQ_SHAPE_MODE_SIZE_GUARD = 0xFFFFFFFF } ShapeMode; typedef enum PolarityType_enum { - IMAQ_EDGE_RISING = 1, //The edge is a rising edge. - IMAQ_EDGE_FALLING = -1, //The edge is a falling edge. - IMAQ_POLARITY_TYPE_SIZE_GUARD = 0xFFFFFFFF + IMAQ_EDGE_RISING = 1, // The edge is a rising edge. + IMAQ_EDGE_FALLING = -1, // The edge is a falling edge. + IMAQ_POLARITY_TYPE_SIZE_GUARD = 0xFFFFFFFF } PolarityType; typedef enum SizeType_enum { - IMAQ_KEEP_LARGE = 0, //The function keeps large particles remaining after the erosion. - IMAQ_KEEP_SMALL = 1, //The function keeps small particles eliminated by the erosion. - IMAQ_SIZE_TYPE_SIZE_GUARD = 0xFFFFFFFF + IMAQ_KEEP_LARGE = + 0, // The function keeps large particles remaining after the erosion. + IMAQ_KEEP_SMALL = + 1, // The function keeps small particles eliminated by the erosion. + IMAQ_SIZE_TYPE_SIZE_GUARD = 0xFFFFFFFF } SizeType; typedef enum Plane3D_enum { - IMAQ_3D_REAL = 0, //The function shows the real part of complex images. - IMAQ_3D_IMAGINARY = 1, //The function shows the imaginary part of complex images. - IMAQ_3D_MAGNITUDE = 2, //The function shows the magnitude part of complex images. - IMAQ_3D_PHASE = 3, //The function shows the phase part of complex images. - IMAQ_PLANE_3D_SIZE_GUARD = 0xFFFFFFFF + IMAQ_3D_REAL = 0, // The function shows the real part of complex images. + IMAQ_3D_IMAGINARY = + 1, // The function shows the imaginary part of complex images. + IMAQ_3D_MAGNITUDE = + 2, // The function shows the magnitude part of complex images. + IMAQ_3D_PHASE = 3, // The function shows the phase part of complex images. + IMAQ_PLANE_3D_SIZE_GUARD = 0xFFFFFFFF } Plane3D; typedef enum PhotometricMode_enum { - IMAQ_WHITE_IS_ZERO = 0, //The function interprets zero-value pixels as white. - IMAQ_BLACK_IS_ZERO = 1, //The function interprets zero-value pixels as black. - IMAQ_PHOTOMETRIC_MODE_SIZE_GUARD = 0xFFFFFFFF + IMAQ_WHITE_IS_ZERO = + 0, // The function interprets zero-value pixels as white. + IMAQ_BLACK_IS_ZERO = + 1, // The function interprets zero-value pixels as black. + IMAQ_PHOTOMETRIC_MODE_SIZE_GUARD = 0xFFFFFFFF } PhotometricMode; typedef enum ParticleInfoMode_enum { - IMAQ_BASIC_INFO = 0, //The function returns only the following elements of each report: area, calibratedArea, boundingRect. - IMAQ_ALL_INFO = 1, //The function returns all the information about each particle. - IMAQ_PARTICLE_INFO_MODE_SIZE_GUARD = 0xFFFFFFFF + IMAQ_BASIC_INFO = 0, // The function returns only the following elements of + // each report: area, calibratedArea, boundingRect. + IMAQ_ALL_INFO = + 1, // The function returns all the information about each particle. + IMAQ_PARTICLE_INFO_MODE_SIZE_GUARD = 0xFFFFFFFF } ParticleInfoMode; typedef enum OutlineMethod_enum { - IMAQ_EDGE_DIFFERENCE = 0, //The function uses a method that produces continuous contours by highlighting each pixel where an intensity variation occurs between itself and its three upper-left neighbors. - IMAQ_EDGE_GRADIENT = 1, //The function uses a method that outlines contours where an intensity variation occurs along the vertical axis. - IMAQ_EDGE_PREWITT = 2, //The function uses a method that extracts the outer contours of objects. - IMAQ_EDGE_ROBERTS = 3, //The function uses a method that outlines the contours that highlight pixels where an intensity variation occurs along the diagonal axes. - IMAQ_EDGE_SIGMA = 4, //The function uses a method that outlines contours and details by setting pixels to the mean value found in their neighborhood, if their deviation from this value is not significant. - IMAQ_EDGE_SOBEL = 5, //The function uses a method that extracts the outer contours of objects. - IMAQ_OUTLINE_METHOD_SIZE_GUARD = 0xFFFFFFFF + IMAQ_EDGE_DIFFERENCE = 0, // The function uses a method that produces + // continuous contours by highlighting each pixel + // where an intensity variation occurs between + // itself and its three upper-left neighbors. + IMAQ_EDGE_GRADIENT = 1, // The function uses a method that outlines contours + // where an intensity variation occurs along the + // vertical axis. + IMAQ_EDGE_PREWITT = 2, // The function uses a method that extracts the outer + // contours of objects. + IMAQ_EDGE_ROBERTS = 3, // The function uses a method that outlines the + // contours that highlight pixels where an intensity + // variation occurs along the diagonal axes. + IMAQ_EDGE_SIGMA = 4, // The function uses a method that outlines contours and + // details by setting pixels to the mean value found in + // their neighborhood, if their deviation from this + // value is not significant. + IMAQ_EDGE_SOBEL = 5, // The function uses a method that extracts the outer + // contours of objects. + IMAQ_OUTLINE_METHOD_SIZE_GUARD = 0xFFFFFFFF } OutlineMethod; typedef enum MorphologyMethod_enum { - IMAQ_AUTOM = 0, //The function uses a transformation that generates simpler particles that contain fewer details. - IMAQ_CLOSE = 1, //The function uses a transformation that fills tiny holes and smooths boundaries. - IMAQ_DILATE = 2, //The function uses a transformation that eliminates tiny holes isolated in particles and expands the contour of the particles according to the template defined by the structuring element. - IMAQ_ERODE = 3, //The function uses a transformation that eliminates pixels isolated in the background and erodes the contour of particles according to the template defined by the structuring element. - IMAQ_GRADIENT = 4, //The function uses a transformation that leaves only the pixels that would be added by the dilation process or eliminated by the erosion process. - IMAQ_GRADIENTOUT = 5, //The function uses a transformation that leaves only the pixels that would be added by the dilation process. - IMAQ_GRADIENTIN = 6, //The function uses a transformation that leaves only the pixels that would be eliminated by the erosion process. - IMAQ_HITMISS = 7, //The function uses a transformation that extracts each pixel located in a neighborhood exactly matching the template defined by the structuring element. - IMAQ_OPEN = 8, //The function uses a transformation that removes small particles and smooths boundaries. - IMAQ_PCLOSE = 9, //The function uses a transformation that fills tiny holes and smooths the inner contour of particles according to the template defined by the structuring element. - IMAQ_POPEN = 10, //The function uses a transformation that removes small particles and smooths the contour of particles according to the template defined by the structuring element. - IMAQ_THICK = 11, //The function uses a transformation that adds to an image those pixels located in a neighborhood that matches a template specified by the structuring element. - IMAQ_THIN = 12, //The function uses a transformation that eliminates pixels that are located in a neighborhood matching a template specified by the structuring element. - IMAQ_MORPHOLOGY_METHOD_SIZE_GUARD = 0xFFFFFFFF + IMAQ_AUTOM = 0, // The function uses a transformation that generates simpler + // particles that contain fewer details. + IMAQ_CLOSE = 1, // The function uses a transformation that fills tiny holes + // and smooths boundaries. + IMAQ_DILATE = 2, // The function uses a transformation that eliminates tiny + // holes isolated in particles and expands the contour of + // the particles according to the template defined by the + // structuring element. + IMAQ_ERODE = 3, // The function uses a transformation that eliminates pixels + // isolated in the background and erodes the contour of + // particles according to the template defined by the + // structuring element. + IMAQ_GRADIENT = 4, // The function uses a transformation that leaves only the + // pixels that would be added by the dilation process or + // eliminated by the erosion process. + IMAQ_GRADIENTOUT = 5, // The function uses a transformation that leaves only + // the pixels that would be added by the dilation + // process. + IMAQ_GRADIENTIN = 6, // The function uses a transformation that leaves only + // the pixels that would be eliminated by the erosion + // process. + IMAQ_HITMISS = 7, // The function uses a transformation that extracts each + // pixel located in a neighborhood exactly matching the + // template defined by the structuring element. + IMAQ_OPEN = 8, // The function uses a transformation that removes small + // particles and smooths boundaries. + IMAQ_PCLOSE = 9, // The function uses a transformation that fills tiny holes + // and smooths the inner contour of particles according to + // the template defined by the structuring element. + IMAQ_POPEN = 10, // The function uses a transformation that removes small + // particles and smooths the contour of particles according + // to the template defined by the structuring element. + IMAQ_THICK = 11, // The function uses a transformation that adds to an image + // those pixels located in a neighborhood that matches a + // template specified by the structuring element. + IMAQ_THIN = 12, // The function uses a transformation that eliminates pixels + // that are located in a neighborhood matching a template + // specified by the structuring element. + IMAQ_MORPHOLOGY_METHOD_SIZE_GUARD = 0xFFFFFFFF } MorphologyMethod; typedef enum MeterArcMode_enum { - IMAQ_METER_ARC_ROI = 0, //The function uses the roi parameter and ignores the base, start, and end parameters. - IMAQ_METER_ARC_POINTS = 1, //The function uses the base,start, and end parameters and ignores the roi parameter. - IMAQ_METER_ARC_MODE_SIZE_GUARD = 0xFFFFFFFF + IMAQ_METER_ARC_ROI = 0, // The function uses the roi parameter and ignores + // the base, start, and end parameters. + IMAQ_METER_ARC_POINTS = 1, // The function uses the base,start, and end + // parameters and ignores the roi parameter. + IMAQ_METER_ARC_MODE_SIZE_GUARD = 0xFFFFFFFF } MeterArcMode; typedef enum RakeDirection_enum { - IMAQ_LEFT_TO_RIGHT = 0, //The function searches from the left side of the search area to the right side of the search area. - IMAQ_RIGHT_TO_LEFT = 1, //The function searches from the right side of the search area to the left side of the search area. - IMAQ_TOP_TO_BOTTOM = 2, //The function searches from the top side of the search area to the bottom side of the search area. - IMAQ_BOTTOM_TO_TOP = 3, //The function searches from the bottom side of the search area to the top side of the search area. - IMAQ_RAKE_DIRECTION_SIZE_GUARD = 0xFFFFFFFF + IMAQ_LEFT_TO_RIGHT = 0, // The function searches from the left side of the + // search area to the right side of the search area. + IMAQ_RIGHT_TO_LEFT = 1, // The function searches from the right side of the + // search area to the left side of the search area. + IMAQ_TOP_TO_BOTTOM = 2, // The function searches from the top side of the + // search area to the bottom side of the search area. + IMAQ_BOTTOM_TO_TOP = 3, // The function searches from the bottom side of the + // search area to the top side of the search area. + IMAQ_RAKE_DIRECTION_SIZE_GUARD = 0xFFFFFFFF } RakeDirection; typedef enum TruncateMode_enum { - IMAQ_TRUNCATE_LOW = 0, //The function truncates low frequencies. - IMAQ_TRUNCATE_HIGH = 1, //The function truncates high frequencies. - IMAQ_TRUNCATE_MODE_SIZE_GUARD = 0xFFFFFFFF + IMAQ_TRUNCATE_LOW = 0, // The function truncates low frequencies. + IMAQ_TRUNCATE_HIGH = 1, // The function truncates high frequencies. + IMAQ_TRUNCATE_MODE_SIZE_GUARD = 0xFFFFFFFF } TruncateMode; typedef enum AttenuateMode_enum { - IMAQ_ATTENUATE_LOW = 0, //The function attenuates low frequencies. - IMAQ_ATTENUATE_HIGH = 1, //The function attenuates high frequencies. - IMAQ_ATTENUATE_MODE_SIZE_GUARD = 0xFFFFFFFF + IMAQ_ATTENUATE_LOW = 0, // The function attenuates low frequencies. + IMAQ_ATTENUATE_HIGH = 1, // The function attenuates high frequencies. + IMAQ_ATTENUATE_MODE_SIZE_GUARD = 0xFFFFFFFF } AttenuateMode; typedef enum WindowThreadPolicy_enum { - IMAQ_CALLING_THREAD = 0, //Using this policy, NI Vision creates windows in the thread that makes the first display function call for a given window number. - IMAQ_SEPARATE_THREAD = 1, //Using this policy, NI Vision creates windows in a separate thread and processes messages for the windows automatically. - IMAQ_WINDOW_THREAD_POLICY_SIZE_GUARD = 0xFFFFFFFF + IMAQ_CALLING_THREAD = 0, // Using this policy, NI Vision creates windows in + // the thread that makes the first display function + // call for a given window number. + IMAQ_SEPARATE_THREAD = 1, // Using this policy, NI Vision creates windows in + // a separate thread and processes messages for the + // windows automatically. + IMAQ_WINDOW_THREAD_POLICY_SIZE_GUARD = 0xFFFFFFFF } WindowThreadPolicy; typedef enum WindowOptions_enum { - IMAQ_WIND_RESIZABLE = 1, //When present, the user may resize the window interactively. - IMAQ_WIND_TITLEBAR = 2, //When present, the title bar on the window is visible. - IMAQ_WIND_CLOSEABLE = 4, //When present, the close box is available. - IMAQ_WIND_TOPMOST = 8, //When present, the window is always on top. - IMAQ_WINDOW_OPTIONS_SIZE_GUARD = 0xFFFFFFFF + IMAQ_WIND_RESIZABLE = + 1, // When present, the user may resize the window interactively. + IMAQ_WIND_TITLEBAR = + 2, // When present, the title bar on the window is visible. + IMAQ_WIND_CLOSEABLE = 4, // When present, the close box is available. + IMAQ_WIND_TOPMOST = 8, // When present, the window is always on top. + IMAQ_WINDOW_OPTIONS_SIZE_GUARD = 0xFFFFFFFF } WindowOptions; typedef enum WindowEventType_enum { - IMAQ_NO_EVENT = 0, //No event occurred since the last call to imaqGetLastEvent(). - IMAQ_CLICK_EVENT = 1, //The user clicked on a window. - IMAQ_DRAW_EVENT = 2, //The user drew an ROI in a window. - IMAQ_MOVE_EVENT = 3, //The user moved a window. - IMAQ_SIZE_EVENT = 4, //The user sized a window. - IMAQ_SCROLL_EVENT = 5, //The user scrolled a window. - IMAQ_ACTIVATE_EVENT = 6, //The user activated a window. - IMAQ_CLOSE_EVENT = 7, //The user closed a window. - IMAQ_DOUBLE_CLICK_EVENT = 8, //The user double-clicked in a window. - IMAQ_WINDOW_EVENT_TYPE_SIZE_GUARD = 0xFFFFFFFF + IMAQ_NO_EVENT = + 0, // No event occurred since the last call to imaqGetLastEvent(). + IMAQ_CLICK_EVENT = 1, // The user clicked on a window. + IMAQ_DRAW_EVENT = 2, // The user drew an ROI in a window. + IMAQ_MOVE_EVENT = 3, // The user moved a window. + IMAQ_SIZE_EVENT = 4, // The user sized a window. + IMAQ_SCROLL_EVENT = 5, // The user scrolled a window. + IMAQ_ACTIVATE_EVENT = 6, // The user activated a window. + IMAQ_CLOSE_EVENT = 7, // The user closed a window. + IMAQ_DOUBLE_CLICK_EVENT = 8, // The user double-clicked in a window. + IMAQ_WINDOW_EVENT_TYPE_SIZE_GUARD = 0xFFFFFFFF } WindowEventType; typedef enum VisionInfoType_enum { - IMAQ_ANY_VISION_INFO = 0, //The function checks if any extra vision information is associated with the image. - IMAQ_PATTERN_MATCHING_INFO = 1, //The function checks if any pattern matching template information is associated with the image. - IMAQ_CALIBRATION_INFO = 2, //The function checks if any calibration information is associated with the image. - IMAQ_OVERLAY_INFO = 3, //The function checks if any overlay information is associated with the image. - IMAQ_VISION_INFO_TYPE_SIZE_GUARD = 0xFFFFFFFF + IMAQ_ANY_VISION_INFO = 0, // The function checks if any extra vision + // information is associated with the image. + IMAQ_PATTERN_MATCHING_INFO = 1, // The function checks if any pattern + // matching template information is + // associated with the image. + IMAQ_CALIBRATION_INFO = 2, // The function checks if any calibration + // information is associated with the image. + IMAQ_OVERLAY_INFO = 3, // The function checks if any overlay information is + // associated with the image. + IMAQ_VISION_INFO_TYPE_SIZE_GUARD = 0xFFFFFFFF } VisionInfoType; typedef enum SearchStrategy_enum { - IMAQ_CONSERVATIVE = 1, //Instructs the pattern matching algorithm to use the largest possible amount of information from the image at the expense of slowing down the speed of the algorithm. - IMAQ_BALANCED = 2, //Instructs the pattern matching algorithm to balance the amount of information from the image it uses with the speed of the algorithm. - IMAQ_AGGRESSIVE = 3, //Instructs the pattern matching algorithm to use a lower amount of information from the image, which allows the algorithm to run quickly but at the expense of accuracy. - IMAQ_VERY_AGGRESSIVE = 4, //Instructs the pattern matching algorithm to use the smallest possible amount of information from the image, which allows the algorithm to run at the highest speed possible but at the expense of accuracy. - IMAQ_SEARCH_STRATEGY_SIZE_GUARD = 0xFFFFFFFF + IMAQ_CONSERVATIVE = 1, // Instructs the pattern matching algorithm to use the + // largest possible amount of information from the + // image at the expense of slowing down the speed of + // the algorithm. + IMAQ_BALANCED = 2, // Instructs the pattern matching algorithm to balance the + // amount of information from the image it uses with the + // speed of the algorithm. + IMAQ_AGGRESSIVE = 3, // Instructs the pattern matching algorithm to use a + // lower amount of information from the image, which + // allows the algorithm to run quickly but at the + // expense of accuracy. + IMAQ_VERY_AGGRESSIVE = 4, // Instructs the pattern matching algorithm to use + // the smallest possible amount of information from + // the image, which allows the algorithm to run at + // the highest speed possible but at the expense of + // accuracy. + IMAQ_SEARCH_STRATEGY_SIZE_GUARD = 0xFFFFFFFF } SearchStrategy; typedef enum TwoEdgePolarityType_enum { - IMAQ_NONE = 0, //The function ignores the polarity of the edges. - IMAQ_RISING_FALLING = 1, //The polarity of the first edge is rising (dark to light) and the polarity of the second edge is falling (light to dark). - IMAQ_FALLING_RISING = 2, //The polarity of the first edge is falling (light to dark) and the polarity of the second edge is rising (dark to light). - IMAQ_RISING_RISING = 3, //The polarity of the first edge is rising (dark to light) and the polarity of the second edge is rising (dark to light). - IMAQ_FALLING_FALLING = 4, //The polarity of the first edge is falling (light to dark) and the polarity of the second edge is falling (light to dark). - IMAQ_TWO_EDGE_POLARITY_TYPE_SIZE_GUARD = 0xFFFFFFFF + IMAQ_NONE = 0, // The function ignores the polarity of the edges. + IMAQ_RISING_FALLING = 1, // The polarity of the first edge is rising (dark to + // light) and the polarity of the second edge is + // falling (light to dark). + IMAQ_FALLING_RISING = 2, // The polarity of the first edge is falling (light + // to dark) and the polarity of the second edge is + // rising (dark to light). + IMAQ_RISING_RISING = 3, // The polarity of the first edge is rising (dark to + // light) and the polarity of the second edge is + // rising (dark to light). + IMAQ_FALLING_FALLING = 4, // The polarity of the first edge is falling (light + // to dark) and the polarity of the second edge is + // falling (light to dark). + IMAQ_TWO_EDGE_POLARITY_TYPE_SIZE_GUARD = 0xFFFFFFFF } TwoEdgePolarityType; typedef enum ObjectType_enum { - IMAQ_BRIGHT_OBJECTS = 0, //The function detects bright objects. - IMAQ_DARK_OBJECTS = 1, //The function detects dark objects. - IMAQ_OBJECT_TYPE_SIZE_GUARD = 0xFFFFFFFF + IMAQ_BRIGHT_OBJECTS = 0, // The function detects bright objects. + IMAQ_DARK_OBJECTS = 1, // The function detects dark objects. + IMAQ_OBJECT_TYPE_SIZE_GUARD = 0xFFFFFFFF } ObjectType; typedef enum Tool_enum { - IMAQ_NO_TOOL = -1, //No tool is in the selected state. - IMAQ_SELECTION_TOOL = 0, //The selection tool selects an existing ROI in an image. - IMAQ_POINT_TOOL = 1, //The point tool draws a point on the image. - IMAQ_LINE_TOOL = 2, //The line tool draws a line on the image. - IMAQ_RECTANGLE_TOOL = 3, //The rectangle tool draws a rectangle on the image. - IMAQ_OVAL_TOOL = 4, //The oval tool draws an oval on the image. - IMAQ_POLYGON_TOOL = 5, //The polygon tool draws a polygon on the image. - IMAQ_CLOSED_FREEHAND_TOOL = 6, //The closed freehand tool draws closed freehand shapes on the image. - IMAQ_ANNULUS_TOOL = 7, //The annulus tool draws annuluses on the image. - IMAQ_ZOOM_TOOL = 8, //The zoom tool controls the zoom of an image. - IMAQ_PAN_TOOL = 9, //The pan tool shifts the view of the image. - IMAQ_POLYLINE_TOOL = 10, //The polyline tool draws a series of connected straight lines on the image. - IMAQ_FREEHAND_TOOL = 11, //The freehand tool draws freehand lines on the image. - IMAQ_ROTATED_RECT_TOOL = 12, //The rotated rectangle tool draws rotated rectangles on the image. - IMAQ_ZOOM_OUT_TOOL = 13, //The zoom out tool controls the zoom of an image. - IMAQ_TOOL_SIZE_GUARD = 0xFFFFFFFF + IMAQ_NO_TOOL = -1, // No tool is in the selected state. + IMAQ_SELECTION_TOOL = + 0, // The selection tool selects an existing ROI in an image. + IMAQ_POINT_TOOL = 1, // The point tool draws a point on the image. + IMAQ_LINE_TOOL = 2, // The line tool draws a line on the image. + IMAQ_RECTANGLE_TOOL = + 3, // The rectangle tool draws a rectangle on the image. + IMAQ_OVAL_TOOL = 4, // The oval tool draws an oval on the image. + IMAQ_POLYGON_TOOL = 5, // The polygon tool draws a polygon on the image. + IMAQ_CLOSED_FREEHAND_TOOL = + 6, // The closed freehand tool draws closed freehand shapes on the image. + IMAQ_ANNULUS_TOOL = 7, // The annulus tool draws annuluses on the image. + IMAQ_ZOOM_TOOL = 8, // The zoom tool controls the zoom of an image. + IMAQ_PAN_TOOL = 9, // The pan tool shifts the view of the image. + IMAQ_POLYLINE_TOOL = 10, // The polyline tool draws a series of connected + // straight lines on the image. + IMAQ_FREEHAND_TOOL = + 11, // The freehand tool draws freehand lines on the image. + IMAQ_ROTATED_RECT_TOOL = + 12, // The rotated rectangle tool draws rotated rectangles on the image. + IMAQ_ZOOM_OUT_TOOL = 13, // The zoom out tool controls the zoom of an image. + IMAQ_TOOL_SIZE_GUARD = 0xFFFFFFFF } Tool; typedef enum TIFFCompressionType_enum { - IMAQ_NO_COMPRESSION = 0, //The function does not compress the TIFF file. - IMAQ_JPEG = 1, //The function uses the JPEG compression algorithm to compress the TIFF file. - IMAQ_RUN_LENGTH = 2, //The function uses a run length compression algorithm to compress the TIFF file. - IMAQ_ZIP = 3, //The function uses the ZIP compression algorithm to compress the TIFF file. - IMAQ_TIFF_COMPRESSION_TYPE_SIZE_GUARD = 0xFFFFFFFF + IMAQ_NO_COMPRESSION = 0, // The function does not compress the TIFF file. + IMAQ_JPEG = 1, // The function uses the JPEG compression algorithm to + // compress the TIFF file. + IMAQ_RUN_LENGTH = 2, // The function uses a run length compression algorithm + // to compress the TIFF file. + IMAQ_ZIP = 3, // The function uses the ZIP compression algorithm to compress + // the TIFF file. + IMAQ_TIFF_COMPRESSION_TYPE_SIZE_GUARD = 0xFFFFFFFF } TIFFCompressionType; typedef enum ThresholdMethod_enum { - IMAQ_THRESH_CLUSTERING = 0, //The function uses a method that sorts the histogram of the image within a discrete number of classes corresponding to the number of phases perceived in an image. - IMAQ_THRESH_ENTROPY = 1, //The function uses a method that is best for detecting particles that are present in minuscule proportions on the image. - IMAQ_THRESH_METRIC = 2, //The function uses a method that is well-suited for images in which classes are not too disproportionate. - IMAQ_THRESH_MOMENTS = 3, //The function uses a method that is suited for images that have poor contrast. - IMAQ_THRESH_INTERCLASS = 4, //The function uses a method that is well-suited for images in which classes have well separated pixel value distributions. - IMAQ_THRESHOLD_METHOD_SIZE_GUARD = 0xFFFFFFFF + IMAQ_THRESH_CLUSTERING = 0, // The function uses a method that sorts the + // histogram of the image within a discrete + // number of classes corresponding to the number + // of phases perceived in an image. + IMAQ_THRESH_ENTROPY = 1, // The function uses a method that is best for + // detecting particles that are present in minuscule + // proportions on the image. + IMAQ_THRESH_METRIC = 2, // The function uses a method that is well-suited for + // images in which classes are not too + // disproportionate. + IMAQ_THRESH_MOMENTS = 3, // The function uses a method that is suited for + // images that have poor contrast. + IMAQ_THRESH_INTERCLASS = 4, // The function uses a method that is well-suited + // for images in which classes have well + // separated pixel value distributions. + IMAQ_THRESHOLD_METHOD_SIZE_GUARD = 0xFFFFFFFF } ThresholdMethod; typedef enum TextAlignment_enum { - IMAQ_LEFT = 0, //Left aligns the text at the reference point. - IMAQ_CENTER = 1, //Centers the text around the reference point. - IMAQ_RIGHT = 2, //Right aligns the text at the reference point. - IMAQ_TEXT_ALIGNMENT_SIZE_GUARD = 0xFFFFFFFF + IMAQ_LEFT = 0, // Left aligns the text at the reference point. + IMAQ_CENTER = 1, // Centers the text around the reference point. + IMAQ_RIGHT = 2, // Right aligns the text at the reference point. + IMAQ_TEXT_ALIGNMENT_SIZE_GUARD = 0xFFFFFFFF } TextAlignment; typedef enum SpokeDirection_enum { - IMAQ_OUTSIDE_TO_INSIDE = 0, //The function searches from the outside of the search area to the inside of the search area. - IMAQ_INSIDE_TO_OUTSIDE = 1, //The function searches from the inside of the search area to the outside of the search area. - IMAQ_SPOKE_DIRECTION_SIZE_GUARD = 0xFFFFFFFF + IMAQ_OUTSIDE_TO_INSIDE = 0, // The function searches from the outside of the + // search area to the inside of the search area. + IMAQ_INSIDE_TO_OUTSIDE = 1, // The function searches from the inside of the + // search area to the outside of the search area. + IMAQ_SPOKE_DIRECTION_SIZE_GUARD = 0xFFFFFFFF } SpokeDirection; typedef enum SkeletonMethod_enum { - IMAQ_SKELETON_L = 0, //Uses an L-shaped structuring element in the skeleton function. - IMAQ_SKELETON_M = 1, //Uses an M-shaped structuring element in the skeleton function. - IMAQ_SKELETON_INVERSE = 2, //Uses an L-shaped structuring element on an inverse of the image in the skeleton function. - IMAQ_SKELETON_METHOD_SIZE_GUARD = 0xFFFFFFFF + IMAQ_SKELETON_L = + 0, // Uses an L-shaped structuring element in the skeleton function. + IMAQ_SKELETON_M = + 1, // Uses an M-shaped structuring element in the skeleton function. + IMAQ_SKELETON_INVERSE = 2, // Uses an L-shaped structuring element on an + // inverse of the image in the skeleton function. + IMAQ_SKELETON_METHOD_SIZE_GUARD = 0xFFFFFFFF } SkeletonMethod; typedef enum VerticalTextAlignment_enum { - IMAQ_BOTTOM = 0, //Aligns the bottom of the text at the reference point. - IMAQ_TOP = 1, //Aligns the top of the text at the reference point. - IMAQ_BASELINE = 2, //Aligns the baseline of the text at the reference point. - IMAQ_VERTICAL_TEXT_ALIGNMENT_SIZE_GUARD = 0xFFFFFFFF + IMAQ_BOTTOM = 0, // Aligns the bottom of the text at the reference point. + IMAQ_TOP = 1, // Aligns the top of the text at the reference point. + IMAQ_BASELINE = 2, // Aligns the baseline of the text at the reference point. + IMAQ_VERTICAL_TEXT_ALIGNMENT_SIZE_GUARD = 0xFFFFFFFF } VerticalTextAlignment; typedef enum CalibrationROI_enum { - IMAQ_FULL_IMAGE = 0, //The correction function corrects the whole image, regardless of the user-defined or calibration-defined ROIs. - IMAQ_CALIBRATION_ROI = 1, //The correction function corrects the area defined by the calibration ROI. - IMAQ_USER_ROI = 2, //The correction function corrects the area defined by the user-defined ROI. - IMAQ_CALIBRATION_AND_USER_ROI = 3, //The correction function corrects the area defined by the intersection of the user-defined ROI and the calibration ROI. - IMAQ_CALIBRATION_OR_USER_ROI = 4, //The correction function corrects the area defined by the union of the user-defined ROI and the calibration ROI. - IMAQ_CALIBRATION_ROI_SIZE_GUARD = 0xFFFFFFFF + IMAQ_FULL_IMAGE = 0, // The correction function corrects the whole image, + // regardless of the user-defined or calibration-defined + // ROIs. + IMAQ_CALIBRATION_ROI = 1, // The correction function corrects the area + // defined by the calibration ROI. + IMAQ_USER_ROI = 2, // The correction function corrects the area defined by + // the user-defined ROI. + IMAQ_CALIBRATION_AND_USER_ROI = + 3, // The correction function corrects the area defined by the + // intersection of the user-defined ROI and the calibration ROI. + IMAQ_CALIBRATION_OR_USER_ROI = + 4, // The correction function corrects the area defined by the union of + // the user-defined ROI and the calibration ROI. + IMAQ_CALIBRATION_ROI_SIZE_GUARD = 0xFFFFFFFF } CalibrationROI; typedef enum ContourType_enum { - IMAQ_EMPTY_CONTOUR = 0, //The contour is empty. - IMAQ_POINT = 1, //The contour represents a point. - IMAQ_LINE = 2, //The contour represents a line. - IMAQ_RECT = 3, //The contour represents a rectangle. - IMAQ_OVAL = 4, //The contour represents an oval. - IMAQ_CLOSED_CONTOUR = 5, //The contour represents a series of connected points where the last point connects to the first. - IMAQ_OPEN_CONTOUR = 6, //The contour represents a series of connected points where the last point does not connect to the first. - IMAQ_ANNULUS = 7, //The contour represents an annulus. - IMAQ_ROTATED_RECT = 8, //The contour represents a rotated rectangle. - IMAQ_CONTOUR_TYPE_SIZE_GUARD = 0xFFFFFFFF + IMAQ_EMPTY_CONTOUR = 0, // The contour is empty. + IMAQ_POINT = 1, // The contour represents a point. + IMAQ_LINE = 2, // The contour represents a line. + IMAQ_RECT = 3, // The contour represents a rectangle. + IMAQ_OVAL = 4, // The contour represents an oval. + IMAQ_CLOSED_CONTOUR = 5, // The contour represents a series of connected + // points where the last point connects to the + // first. + IMAQ_OPEN_CONTOUR = 6, // The contour represents a series of connected points + // where the last point does not connect to the first. + IMAQ_ANNULUS = 7, // The contour represents an annulus. + IMAQ_ROTATED_RECT = 8, // The contour represents a rotated rectangle. + IMAQ_CONTOUR_TYPE_SIZE_GUARD = 0xFFFFFFFF } ContourType; typedef enum MathTransformMethod_enum { - IMAQ_TRANSFORM_LINEAR = 0, //The function uses linear remapping. - IMAQ_TRANSFORM_LOG = 1, //The function uses logarithmic remapping. - IMAQ_TRANSFORM_EXP = 2, //The function uses exponential remapping. - IMAQ_TRANSFORM_SQR = 3, //The function uses square remapping. - IMAQ_TRANSFORM_SQRT = 4, //The function uses square root remapping. - IMAQ_TRANSFORM_POWX = 5, //The function uses power X remapping. - IMAQ_TRANSFORM_POW1X = 6, //The function uses power 1/X remapping. - IMAQ_MATH_TRANSFORM_METHOD_SIZE_GUARD = 0xFFFFFFFF + IMAQ_TRANSFORM_LINEAR = 0, // The function uses linear remapping. + IMAQ_TRANSFORM_LOG = 1, // The function uses logarithmic remapping. + IMAQ_TRANSFORM_EXP = 2, // The function uses exponential remapping. + IMAQ_TRANSFORM_SQR = 3, // The function uses square remapping. + IMAQ_TRANSFORM_SQRT = 4, // The function uses square root remapping. + IMAQ_TRANSFORM_POWX = 5, // The function uses power X remapping. + IMAQ_TRANSFORM_POW1X = 6, // The function uses power 1/X remapping. + IMAQ_MATH_TRANSFORM_METHOD_SIZE_GUARD = 0xFFFFFFFF } MathTransformMethod; typedef enum ComplexPlane_enum { - IMAQ_REAL = 0, //The function operates on the real plane of the complex image. - IMAQ_IMAGINARY = 1, //The function operates on the imaginary plane of the complex image. - IMAQ_MAGNITUDE = 2, //The function operates on the magnitude plane of the complex image. - IMAQ_PHASE = 3, //The function operates on the phase plane of the complex image. - IMAQ_COMPLEX_PLANE_SIZE_GUARD = 0xFFFFFFFF + IMAQ_REAL = + 0, // The function operates on the real plane of the complex image. + IMAQ_IMAGINARY = + 1, // The function operates on the imaginary plane of the complex image. + IMAQ_MAGNITUDE = + 2, // The function operates on the magnitude plane of the complex image. + IMAQ_PHASE = + 3, // The function operates on the phase plane of the complex image. + IMAQ_COMPLEX_PLANE_SIZE_GUARD = 0xFFFFFFFF } ComplexPlane; typedef enum PaletteType_enum { - IMAQ_PALETTE_GRAY = 0, //The function uses a palette that has a gradual gray-level variation from black to white. - IMAQ_PALETTE_BINARY = 1, //The function uses a palette of 16 cycles of 16 different colors that is useful with binary images. - IMAQ_PALETTE_GRADIENT = 2, //The function uses a palette that has a gradation from red to white with a prominent range of light blue in the upper value range. - IMAQ_PALETTE_RAINBOW = 3, //The function uses a palette that has a gradation from blue to red with a prominent range of greens in the middle value range. - IMAQ_PALETTE_TEMPERATURE = 4, //The function uses a palette that has a gradation from light brown to dark brown. - IMAQ_PALETTE_USER = 5, //The function uses a palette defined by the user. - IMAQ_PALETTE_TYPE_SIZE_GUARD = 0xFFFFFFFF + IMAQ_PALETTE_GRAY = 0, // The function uses a palette that has a gradual + // gray-level variation from black to white. + IMAQ_PALETTE_BINARY = 1, // The function uses a palette of 16 cycles of 16 + // different colors that is useful with binary + // images. + IMAQ_PALETTE_GRADIENT = 2, // The function uses a palette that has a + // gradation from red to white with a prominent + // range of light blue in the upper value range. + IMAQ_PALETTE_RAINBOW = 3, // The function uses a palette that has a gradation + // from blue to red with a prominent range of + // greens in the middle value range. + IMAQ_PALETTE_TEMPERATURE = 4, // The function uses a palette that has a + // gradation from light brown to dark brown. + IMAQ_PALETTE_USER = 5, // The function uses a palette defined by the user. + IMAQ_PALETTE_TYPE_SIZE_GUARD = 0xFFFFFFFF } PaletteType; typedef enum ColorSensitivity_enum { - IMAQ_SENSITIVITY_LOW = 0, //Instructs the algorithm to divide the hue plane into a low number of sectors, allowing for simple color analysis. - IMAQ_SENSITIVITY_MED = 1, //Instructs the algorithm to divide the hue plane into a medium number of sectors, allowing for color analysis that balances sensitivity and complexity. - IMAQ_SENSITIVITY_HIGH = 2, //Instructs the algorithm to divide the hue plane into a high number of sectors, allowing for complex, sensitive color analysis. - IMAQ_COLOR_SENSITIVITY_SIZE_GUARD = 0xFFFFFFFF + IMAQ_SENSITIVITY_LOW = 0, // Instructs the algorithm to divide the hue plane + // into a low number of sectors, allowing for + // simple color analysis. + IMAQ_SENSITIVITY_MED = 1, // Instructs the algorithm to divide the hue plane + // into a medium number of sectors, allowing for + // color analysis that balances sensitivity and + // complexity. + IMAQ_SENSITIVITY_HIGH = 2, // Instructs the algorithm to divide the hue plane + // into a high number of sectors, allowing for + // complex, sensitive color analysis. + IMAQ_COLOR_SENSITIVITY_SIZE_GUARD = 0xFFFFFFFF } ColorSensitivity; typedef enum ColorMode_enum { - IMAQ_RGB = 0, //The function operates in the RGB (Red, Blue, Green) color space. - IMAQ_HSL = 1, //The function operates in the HSL (Hue, Saturation, Luminance) color space. - IMAQ_HSV = 2, //The function operates in the HSV (Hue, Saturation, Value) color space. - IMAQ_HSI = 3, //The function operates in the HSI (Hue, Saturation, Intensity) color space. - IMAQ_CIE = 4, //The function operates in the CIE L*a*b* color space. - IMAQ_CIEXYZ = 5, //The function operates in the CIE XYZ color space. - IMAQ_COLOR_MODE_SIZE_GUARD = 0xFFFFFFFF + IMAQ_RGB = + 0, // The function operates in the RGB (Red, Blue, Green) color space. + IMAQ_HSL = 1, // The function operates in the HSL (Hue, Saturation, + // Luminance) color space. + IMAQ_HSV = 2, // The function operates in the HSV (Hue, Saturation, Value) + // color space. + IMAQ_HSI = 3, // The function operates in the HSI (Hue, Saturation, + // Intensity) color space. + IMAQ_CIE = 4, // The function operates in the CIE L*a*b* color space. + IMAQ_CIEXYZ = 5, // The function operates in the CIE XYZ color space. + IMAQ_COLOR_MODE_SIZE_GUARD = 0xFFFFFFFF } ColorMode; typedef enum DetectionMode_enum { - IMAQ_DETECT_PEAKS = 0, //The function detects peaks. - IMAQ_DETECT_VALLEYS = 1, //The function detects valleys. - IMAQ_DETECTION_MODE_SIZE_GUARD = 0xFFFFFFFF + IMAQ_DETECT_PEAKS = 0, // The function detects peaks. + IMAQ_DETECT_VALLEYS = 1, // The function detects valleys. + IMAQ_DETECTION_MODE_SIZE_GUARD = 0xFFFFFFFF } DetectionMode; typedef enum CalibrationUnit_enum { - IMAQ_UNDEFINED = 0, //The image does not have a defined unit of measurement. - IMAQ_ANGSTROM = 1, //The unit of measure for the image is angstroms. - IMAQ_MICROMETER = 2, //The unit of measure for the image is micrometers. - IMAQ_MILLIMETER = 3, //The unit of measure for the image is millimeters. - IMAQ_CENTIMETER = 4, //The unit of measure for the image is centimeters. - IMAQ_METER = 5, //The unit of measure for the image is meters. - IMAQ_KILOMETER = 6, //The unit of measure for the image is kilometers. - IMAQ_MICROINCH = 7, //The unit of measure for the image is microinches. - IMAQ_INCH = 8, //The unit of measure for the image is inches. - IMAQ_FOOT = 9, //The unit of measure for the image is feet. - IMAQ_NAUTICMILE = 10, //The unit of measure for the image is nautical miles. - IMAQ_GROUNDMILE = 11, //The unit of measure for the image is ground miles. - IMAQ_STEP = 12, //The unit of measure for the image is steps. - IMAQ_CALIBRATION_UNIT_SIZE_GUARD = 0xFFFFFFFF + IMAQ_UNDEFINED = 0, // The image does not have a defined unit of measurement. + IMAQ_ANGSTROM = 1, // The unit of measure for the image is angstroms. + IMAQ_MICROMETER = 2, // The unit of measure for the image is micrometers. + IMAQ_MILLIMETER = 3, // The unit of measure for the image is millimeters. + IMAQ_CENTIMETER = 4, // The unit of measure for the image is centimeters. + IMAQ_METER = 5, // The unit of measure for the image is meters. + IMAQ_KILOMETER = 6, // The unit of measure for the image is kilometers. + IMAQ_MICROINCH = 7, // The unit of measure for the image is microinches. + IMAQ_INCH = 8, // The unit of measure for the image is inches. + IMAQ_FOOT = 9, // The unit of measure for the image is feet. + IMAQ_NAUTICMILE = 10, // The unit of measure for the image is nautical miles. + IMAQ_GROUNDMILE = 11, // The unit of measure for the image is ground miles. + IMAQ_STEP = 12, // The unit of measure for the image is steps. + IMAQ_CALIBRATION_UNIT_SIZE_GUARD = 0xFFFFFFFF } CalibrationUnit; typedef enum ConcentricRakeDirection_enum { - IMAQ_COUNTER_CLOCKWISE = 0, //The function searches the search area in a counter-clockwise direction. - IMAQ_CLOCKWISE = 1, //The function searches the search area in a clockwise direction. - IMAQ_CONCENTRIC_RAKE_DIRECTION_SIZE_GUARD = 0xFFFFFFFF + IMAQ_COUNTER_CLOCKWISE = 0, // The function searches the search area in a + // counter-clockwise direction. + IMAQ_CLOCKWISE = + 1, // The function searches the search area in a clockwise direction. + IMAQ_CONCENTRIC_RAKE_DIRECTION_SIZE_GUARD = 0xFFFFFFFF } ConcentricRakeDirection; typedef enum CalibrationMode_enum { - IMAQ_PERSPECTIVE = 0, //Functions correct for distortion caused by the camera's perspective. - IMAQ_NONLINEAR = 1, //Functions correct for distortion caused by the camera's lens. - IMAQ_SIMPLE_CALIBRATION = 2, //Functions do not correct for distortion. - IMAQ_CORRECTED_IMAGE = 3, //The image is already corrected. - IMAQ_CALIBRATION_MODE_SIZE_GUARD = 0xFFFFFFFF + IMAQ_PERSPECTIVE = 0, // Functions correct for distortion caused by the + // camera's perspective. + IMAQ_NONLINEAR = + 1, // Functions correct for distortion caused by the camera's lens. + IMAQ_SIMPLE_CALIBRATION = 2, // Functions do not correct for distortion. + IMAQ_CORRECTED_IMAGE = 3, // The image is already corrected. + IMAQ_CALIBRATION_MODE_SIZE_GUARD = 0xFFFFFFFF } CalibrationMode; typedef enum BrowserLocation_enum { - IMAQ_INSERT_FIRST_FREE = 0, //Inserts the thumbnail in the first available cell. - IMAQ_INSERT_END = 1, //Inserts the thumbnail after the last occupied cell. - IMAQ_BROWSER_LOCATION_SIZE_GUARD = 0xFFFFFFFF + IMAQ_INSERT_FIRST_FREE = + 0, // Inserts the thumbnail in the first available cell. + IMAQ_INSERT_END = 1, // Inserts the thumbnail after the last occupied cell. + IMAQ_BROWSER_LOCATION_SIZE_GUARD = 0xFFFFFFFF } BrowserLocation; typedef enum BrowserFrameStyle_enum { - IMAQ_RAISED_FRAME = 0, //Each thumbnail has a raised frame. - IMAQ_BEVELLED_FRAME = 1, //Each thumbnail has a beveled frame. - IMAQ_OUTLINE_FRAME = 2, //Each thumbnail has an outlined frame. - IMAQ_HIDDEN_FRAME = 3, //Each thumbnail has a hidden frame. - IMAQ_STEP_FRAME = 4, //Each thumbnail has a stepped frame. - IMAQ_RAISED_OUTLINE_FRAME = 5, //Each thumbnail has a raised, outlined frame. - IMAQ_BROWSER_FRAME_STYLE_SIZE_GUARD = 0xFFFFFFFF + IMAQ_RAISED_FRAME = 0, // Each thumbnail has a raised frame. + IMAQ_BEVELLED_FRAME = 1, // Each thumbnail has a beveled frame. + IMAQ_OUTLINE_FRAME = 2, // Each thumbnail has an outlined frame. + IMAQ_HIDDEN_FRAME = 3, // Each thumbnail has a hidden frame. + IMAQ_STEP_FRAME = 4, // Each thumbnail has a stepped frame. + IMAQ_RAISED_OUTLINE_FRAME = + 5, // Each thumbnail has a raised, outlined frame. + IMAQ_BROWSER_FRAME_STYLE_SIZE_GUARD = 0xFFFFFFFF } BrowserFrameStyle; typedef enum BorderMethod_enum { - IMAQ_BORDER_MIRROR = 0, //Symmetrically copies pixel values from the image into the border. - IMAQ_BORDER_COPY = 1, //Copies the value of the pixel closest to the edge of the image into the border. - IMAQ_BORDER_CLEAR = 2, //Sets all pixels in the border to 0. - IMAQ_BORDER_METHOD_SIZE_GUARD = 0xFFFFFFFF + IMAQ_BORDER_MIRROR = + 0, // Symmetrically copies pixel values from the image into the border. + IMAQ_BORDER_COPY = 1, // Copies the value of the pixel closest to the edge of + // the image into the border. + IMAQ_BORDER_CLEAR = 2, // Sets all pixels in the border to 0. + IMAQ_BORDER_METHOD_SIZE_GUARD = 0xFFFFFFFF } BorderMethod; typedef enum BarcodeType_enum { - IMAQ_INVALID = -1, //The barcode is not of a type known by NI Vision. - IMAQ_CODABAR = 1, //The barcode is of type Codabar. - IMAQ_CODE39 = 2, //The barcode is of type Code 39. - IMAQ_CODE93 = 4, //The barcode is of type Code 93. - IMAQ_CODE128 = 8, //The barcode is of type Code 128. - IMAQ_EAN8 = 16, //The barcode is of type EAN 8. - IMAQ_EAN13 = 32, //The barcode is of type EAN 13. - IMAQ_I2_OF_5 = 64, //The barcode is of type Code 25. - IMAQ_MSI = 128, //The barcode is of type MSI code. - IMAQ_UPCA = 256, //The barcode is of type UPC A. - IMAQ_PHARMACODE = 512, //The barcode is of type Pharmacode. - IMAQ_RSS_LIMITED = 1024, //The barcode is of type RSS Limited. - IMAQ_BARCODE_TYPE_SIZE_GUARD = 0xFFFFFFFF + IMAQ_INVALID = -1, // The barcode is not of a type known by NI Vision. + IMAQ_CODABAR = 1, // The barcode is of type Codabar. + IMAQ_CODE39 = 2, // The barcode is of type Code 39. + IMAQ_CODE93 = 4, // The barcode is of type Code 93. + IMAQ_CODE128 = 8, // The barcode is of type Code 128. + IMAQ_EAN8 = 16, // The barcode is of type EAN 8. + IMAQ_EAN13 = 32, // The barcode is of type EAN 13. + IMAQ_I2_OF_5 = 64, // The barcode is of type Code 25. + IMAQ_MSI = 128, // The barcode is of type MSI code. + IMAQ_UPCA = 256, // The barcode is of type UPC A. + IMAQ_PHARMACODE = 512, // The barcode is of type Pharmacode. + IMAQ_RSS_LIMITED = 1024, // The barcode is of type RSS Limited. + IMAQ_BARCODE_TYPE_SIZE_GUARD = 0xFFFFFFFF } BarcodeType; typedef enum AxisOrientation_enum { - IMAQ_DIRECT = 0, //The y-axis direction corresponds to the y-axis direction of the Cartesian coordinate system. - IMAQ_INDIRECT = 1, //The y-axis direction corresponds to the y-axis direction of an image. - IMAQ_AXIS_ORIENTATION_SIZE_GUARD = 0xFFFFFFFF + IMAQ_DIRECT = 0, // The y-axis direction corresponds to the y-axis direction + // of the Cartesian coordinate system. + IMAQ_INDIRECT = 1, // The y-axis direction corresponds to the y-axis + // direction of an image. + IMAQ_AXIS_ORIENTATION_SIZE_GUARD = 0xFFFFFFFF } AxisOrientation; typedef enum ColorIgnoreMode_enum { - IMAQ_IGNORE_NONE = 0, //Specifies that the function does not ignore any pixels. - IMAQ_IGNORE_BLACK = 1, //Specifies that the function ignores black pixels. - IMAQ_IGNORE_WHITE = 2, //Specifies that the function ignores white pixels. - IMAQ_IGNORE_BLACK_AND_WHITE = 3, //Specifies that the function ignores black pixels and white pixels. - IMAQ_BLACK_WHITE_IGNORE_MODE_SIZE_GUARD = 0xFFFFFFFF + IMAQ_IGNORE_NONE = + 0, // Specifies that the function does not ignore any pixels. + IMAQ_IGNORE_BLACK = 1, // Specifies that the function ignores black pixels. + IMAQ_IGNORE_WHITE = 2, // Specifies that the function ignores white pixels. + IMAQ_IGNORE_BLACK_AND_WHITE = + 3, // Specifies that the function ignores black pixels and white pixels. + IMAQ_BLACK_WHITE_IGNORE_MODE_SIZE_GUARD = 0xFFFFFFFF } ColorIgnoreMode; typedef enum LevelType_enum { - IMAQ_ABSOLUTE = 0, //The function evaluates the threshold and hysteresis values as absolute values. - IMAQ_RELATIVE = 1, //The function evaluates the threshold and hysteresis values relative to the dynamic range of the given path. - IMAQ_LEVEL_TYPE_SIZE_GUARD = 0xFFFFFFFF + IMAQ_ABSOLUTE = 0, // The function evaluates the threshold and hysteresis + // values as absolute values. + IMAQ_RELATIVE = 1, // The function evaluates the threshold and hysteresis + // values relative to the dynamic range of the given path. + IMAQ_LEVEL_TYPE_SIZE_GUARD = 0xFFFFFFFF } LevelType; typedef enum MatchingMode_enum { - IMAQ_MATCH_SHIFT_INVARIANT = 1, //Searches for occurrences of the template image anywhere in the searchRect, assuming that the pattern is not rotated more than plus or minus 4 degrees. - IMAQ_MATCH_ROTATION_INVARIANT = 2, //Searches for occurrences of the pattern in the image with no restriction on the rotation of the pattern. - IMAQ_MATCHING_MODE_SIZE_GUARD = 0xFFFFFFFF + IMAQ_MATCH_SHIFT_INVARIANT = 1, // Searches for occurrences of the template + // image anywhere in the searchRect, assuming + // that the pattern is not rotated more than + // plus or minus 4 degrees. + IMAQ_MATCH_ROTATION_INVARIANT = 2, // Searches for occurrences of the pattern + // in the image with no restriction on the + // rotation of the pattern. + IMAQ_MATCHING_MODE_SIZE_GUARD = 0xFFFFFFFF } MatchingMode; typedef enum MappingMethod_enum { - IMAQ_FULL_DYNAMIC = 0, //(Obsolete) When the image bit depth is 0, the function maps the full dynamic range of the 16-bit image to an 8-bit scale. - IMAQ_DOWNSHIFT = 1, //(Obsolete) When the image bit depth is 0, the function shifts the 16-bit image pixels to the right the number of times specified by the shiftCount element of the DisplayMapping structure. - IMAQ_RANGE = 2, //(Obsolete) When the image bit depth is 0, the function maps the pixel values in the range specified by the minimumValue and maximumValue elements of the DisplayMapping structure to an 8-bit scale. - IMAQ_90_PCT_DYNAMIC = 3, //(Obsolete) When the image bit depth to 0, the function maps the dynamic range containing the middle 90 percent of the cumulated histogram of the image to an 8-bit (256 grayscale values) scale. - IMAQ_PERCENT_RANGE = 4, //(Obsolete) When the image bit depth is 0, the function maps the pixel values in the relative percentage range (0 to 100) of the cumulated histogram specified by minimumValue and maximumValue to an 8-bit scale. - IMAQ_DEFAULT_MAPPING = 10, //If the bit depth is 0, the function maps the 16-bit image to 8 bits by following the IMAQ_FULL_DYNAMIC_ALWAYS behavior; otherwise, the function shifts the image data to the right according to the IMAQ_MOST_SIGNIFICANT behavior. - IMAQ_MOST_SIGNIFICANT = 11, //The function shifts the 16-bit image pixels to the right until the 8 most significant bits of the image data are remaining. - IMAQ_FULL_DYNAMIC_ALWAYS = 12, //The function maps the full dynamic range of the 16-bit image to an 8-bit scale. - IMAQ_DOWNSHIFT_ALWAYS = 13, //The function shifts the 16-bit image pixels to the right the number of times specified by the shiftCount element of the DisplayMapping structure. - IMAQ_RANGE_ALWAYS = 14, //The function maps the pixel values in the range specified by the minimumValue and maximumValue elements of the DisplayMapping structure to an 8-bit scale. - IMAQ_90_PCT_DYNAMIC_ALWAYS = 15, //The function maps the dynamic range containing the middle 90 percent of the cumulated histogram of the image to an 8-bit (256 grayscale values) scale. - IMAQ_PERCENT_RANGE_ALWAYS = 16, //The function maps the pixel values in the relative percentage range (0 to 100) of the cumulated histogram specified by minimumValue and maximumValue to an 8-bit scale. - IMAQ_MAPPING_METHOD_SIZE_GUARD = 0xFFFFFFFF + IMAQ_FULL_DYNAMIC = 0, //(Obsolete) When the image bit depth is 0, the + //function maps the full dynamic range of the 16-bit + //image to an 8-bit scale. + IMAQ_DOWNSHIFT = 1, //(Obsolete) When the image bit depth is 0, the function + //shifts the 16-bit image pixels to the right the number + //of times specified by the shiftCount element of the + //DisplayMapping structure. + IMAQ_RANGE = 2, //(Obsolete) When the image bit depth is 0, the function maps + //the pixel values in the range specified by the minimumValue + //and maximumValue elements of the DisplayMapping structure + //to an 8-bit scale. + IMAQ_90_PCT_DYNAMIC = + 3, //(Obsolete) When the image bit depth to 0, the function maps the + //dynamic range containing the middle 90 percent of the cumulated + //histogram of the image to an 8-bit (256 grayscale values) scale. + IMAQ_PERCENT_RANGE = 4, //(Obsolete) When the image bit depth is 0, the + //function maps the pixel values in the relative + //percentage range (0 to 100) of the cumulated + //histogram specified by minimumValue and + //maximumValue to an 8-bit scale. + IMAQ_DEFAULT_MAPPING = + 10, // If the bit depth is 0, the function maps the 16-bit image to 8 + // bits by following the IMAQ_FULL_DYNAMIC_ALWAYS behavior; + // otherwise, the function shifts the image data to the right + // according to the IMAQ_MOST_SIGNIFICANT behavior. + IMAQ_MOST_SIGNIFICANT = 11, // The function shifts the 16-bit image pixels to + // the right until the 8 most significant bits of + // the image data are remaining. + IMAQ_FULL_DYNAMIC_ALWAYS = 12, // The function maps the full dynamic range of + // the 16-bit image to an 8-bit scale. + IMAQ_DOWNSHIFT_ALWAYS = 13, // The function shifts the 16-bit image pixels to + // the right the number of times specified by the + // shiftCount element of the DisplayMapping + // structure. + IMAQ_RANGE_ALWAYS = 14, // The function maps the pixel values in the range + // specified by the minimumValue and maximumValue + // elements of the DisplayMapping structure to an + // 8-bit scale. + IMAQ_90_PCT_DYNAMIC_ALWAYS = 15, // The function maps the dynamic range + // containing the middle 90 percent of the + // cumulated histogram of the image to an + // 8-bit (256 grayscale values) scale. + IMAQ_PERCENT_RANGE_ALWAYS = + 16, // The function maps the pixel values in the relative percentage + // range (0 to 100) of the cumulated histogram specified by + // minimumValue and maximumValue to an 8-bit scale. + IMAQ_MAPPING_METHOD_SIZE_GUARD = 0xFFFFFFFF } MappingMethod; typedef enum ComparisonFunction_enum { - IMAQ_CLEAR_LESS = 0, //The comparison is true if the source pixel value is less than the comparison image pixel value. - IMAQ_CLEAR_LESS_OR_EQUAL = 1, //The comparison is true if the source pixel value is less than or equal to the comparison image pixel value. - IMAQ_CLEAR_EQUAL = 2, //The comparison is true if the source pixel value is equal to the comparison image pixel value. - IMAQ_CLEAR_GREATER_OR_EQUAL = 3, //The comparison is true if the source pixel value is greater than or equal to the comparison image pixel value. - IMAQ_CLEAR_GREATER = 4, //The comparison is true if the source pixel value is greater than the comparison image pixel value. - IMAQ_COMPARE_FUNCTION_SIZE_GUARD = 0xFFFFFFFF + IMAQ_CLEAR_LESS = 0, // The comparison is true if the source pixel value is + // less than the comparison image pixel value. + IMAQ_CLEAR_LESS_OR_EQUAL = 1, // The comparison is true if the source pixel + // value is less than or equal to the + // comparison image pixel value. + IMAQ_CLEAR_EQUAL = 2, // The comparison is true if the source pixel value is + // equal to the comparison image pixel value. + IMAQ_CLEAR_GREATER_OR_EQUAL = 3, // The comparison is true if the source + // pixel value is greater than or equal to + // the comparison image pixel value. + IMAQ_CLEAR_GREATER = 4, // The comparison is true if the source pixel value + // is greater than the comparison image pixel value. + IMAQ_COMPARE_FUNCTION_SIZE_GUARD = 0xFFFFFFFF } ComparisonFunction; typedef enum LineGaugeMethod_enum { - IMAQ_EDGE_TO_EDGE = 0, //Measures from the first edge on the line to the last edge on the line. - IMAQ_EDGE_TO_POINT = 1, //Measures from the first edge on the line to the end point of the line. - IMAQ_POINT_TO_EDGE = 2, //Measures from the start point of the line to the first edge on the line. - IMAQ_POINT_TO_POINT = 3, //Measures from the start point of the line to the end point of the line. - IMAQ_LINE_GAUGE_METHOD_SIZE_GUARD = 0xFFFFFFFF + IMAQ_EDGE_TO_EDGE = 0, // Measures from the first edge on the line to the + // last edge on the line. + IMAQ_EDGE_TO_POINT = 1, // Measures from the first edge on the line to the + // end point of the line. + IMAQ_POINT_TO_EDGE = 2, // Measures from the start point of the line to the + // first edge on the line. + IMAQ_POINT_TO_POINT = 3, // Measures from the start point of the line to the + // end point of the line. + IMAQ_LINE_GAUGE_METHOD_SIZE_GUARD = 0xFFFFFFFF } LineGaugeMethod; typedef enum Direction3D_enum { - IMAQ_3D_NW = 0, //The viewing angle for the 3D image is from the northwest. - IMAQ_3D_SW = 1, //The viewing angle for the 3D image is from the southwest. - IMAQ_3D_SE = 2, //The viewing angle for the 3D image is from the southeast. - IMAQ_3D_NE = 3, //The viewing angle for the 3D image is from the northeast. - IMAQ_DIRECTION_3D_SIZE_GUARD = 0xFFFFFFFF + IMAQ_3D_NW = 0, // The viewing angle for the 3D image is from the northwest. + IMAQ_3D_SW = 1, // The viewing angle for the 3D image is from the southwest. + IMAQ_3D_SE = 2, // The viewing angle for the 3D image is from the southeast. + IMAQ_3D_NE = 3, // The viewing angle for the 3D image is from the northeast. + IMAQ_DIRECTION_3D_SIZE_GUARD = 0xFFFFFFFF } Direction3D; typedef enum LearningMode_enum { - IMAQ_LEARN_ALL = 0, //The function extracts information for shift- and rotation-invariant matching. - IMAQ_LEARN_SHIFT_INFORMATION = 1, //The function extracts information for shift-invariant matching. - IMAQ_LEARN_ROTATION_INFORMATION = 2, //The function extracts information for rotation-invariant matching. - IMAQ_LEARNING_MODE_SIZE_GUARD = 0xFFFFFFFF + IMAQ_LEARN_ALL = 0, // The function extracts information for shift- and + // rotation-invariant matching. + IMAQ_LEARN_SHIFT_INFORMATION = + 1, // The function extracts information for shift-invariant matching. + IMAQ_LEARN_ROTATION_INFORMATION = + 2, // The function extracts information for rotation-invariant matching. + IMAQ_LEARNING_MODE_SIZE_GUARD = 0xFFFFFFFF } LearningMode; typedef enum KernelFamily_enum { - IMAQ_GRADIENT_FAMILY = 0, //The kernel is in the gradient family. - IMAQ_LAPLACIAN_FAMILY = 1, //The kernel is in the Laplacian family. - IMAQ_SMOOTHING_FAMILY = 2, //The kernel is in the smoothing family. - IMAQ_GAUSSIAN_FAMILY = 3, //The kernel is in the Gaussian family. - IMAQ_KERNEL_FAMILY_SIZE_GUARD = 0xFFFFFFFF + IMAQ_GRADIENT_FAMILY = 0, // The kernel is in the gradient family. + IMAQ_LAPLACIAN_FAMILY = 1, // The kernel is in the Laplacian family. + IMAQ_SMOOTHING_FAMILY = 2, // The kernel is in the smoothing family. + IMAQ_GAUSSIAN_FAMILY = 3, // The kernel is in the Gaussian family. + IMAQ_KERNEL_FAMILY_SIZE_GUARD = 0xFFFFFFFF } KernelFamily; typedef enum InterpolationMethod_enum { - IMAQ_ZERO_ORDER = 0, //The function uses an interpolation method that interpolates new pixel values using the nearest valid neighboring pixel. - IMAQ_BILINEAR = 1, //The function uses an interpolation method that interpolates new pixel values using a bidirectional average of the neighboring pixels. - IMAQ_QUADRATIC = 2, //The function uses an interpolation method that interpolates new pixel values using a quadratic approximating polynomial. - IMAQ_CUBIC_SPLINE = 3, //The function uses an interpolation method that interpolates new pixel values by fitting them to a cubic spline curve, where the curve is based on known pixel values from the image. - IMAQ_BILINEAR_FIXED = 4, //The function uses an interpolation method that interpolates new pixel values using a bidirectional average of the neighboring pixels. - IMAQ_INTERPOLATION_METHOD_SIZE_GUARD = 0xFFFFFFFF + IMAQ_ZERO_ORDER = 0, // The function uses an interpolation method that + // interpolates new pixel values using the nearest valid + // neighboring pixel. + IMAQ_BILINEAR = 1, // The function uses an interpolation method that + // interpolates new pixel values using a bidirectional + // average of the neighboring pixels. + IMAQ_QUADRATIC = 2, // The function uses an interpolation method that + // interpolates new pixel values using a quadratic + // approximating polynomial. + IMAQ_CUBIC_SPLINE = 3, // The function uses an interpolation method that + // interpolates new pixel values by fitting them to a + // cubic spline curve, where the curve is based on + // known pixel values from the image. + IMAQ_BILINEAR_FIXED = 4, // The function uses an interpolation method that + // interpolates new pixel values using a + // bidirectional average of the neighboring pixels. + IMAQ_INTERPOLATION_METHOD_SIZE_GUARD = 0xFFFFFFFF } InterpolationMethod; typedef enum ImageType_enum { - IMAQ_IMAGE_U8 = 0, //The image type is 8-bit unsigned integer grayscale. - IMAQ_IMAGE_U16 = 7, //The image type is 16-bit unsigned integer grayscale. - IMAQ_IMAGE_I16 = 1, //The image type is 16-bit signed integer grayscale. - IMAQ_IMAGE_SGL = 2, //The image type is 32-bit floating-point grayscale. - IMAQ_IMAGE_COMPLEX = 3, //The image type is complex. - IMAQ_IMAGE_RGB = 4, //The image type is RGB color. - IMAQ_IMAGE_HSL = 5, //The image type is HSL color. - IMAQ_IMAGE_RGB_U64 = 6, //The image type is 64-bit unsigned RGB color. - IMAQ_IMAGE_TYPE_SIZE_GUARD = 0xFFFFFFFF + IMAQ_IMAGE_U8 = 0, // The image type is 8-bit unsigned integer grayscale. + IMAQ_IMAGE_U16 = 7, // The image type is 16-bit unsigned integer grayscale. + IMAQ_IMAGE_I16 = 1, // The image type is 16-bit signed integer grayscale. + IMAQ_IMAGE_SGL = 2, // The image type is 32-bit floating-point grayscale. + IMAQ_IMAGE_COMPLEX = 3, // The image type is complex. + IMAQ_IMAGE_RGB = 4, // The image type is RGB color. + IMAQ_IMAGE_HSL = 5, // The image type is HSL color. + IMAQ_IMAGE_RGB_U64 = 6, // The image type is 64-bit unsigned RGB color. + IMAQ_IMAGE_TYPE_SIZE_GUARD = 0xFFFFFFFF } ImageType; typedef enum ImageFeatureMode_enum { - IMAQ_COLOR_AND_SHAPE_FEATURES = 0, //Instructs the function to use the color and the shape features of the color pattern. - IMAQ_COLOR_FEATURES = 1, //Instructs the function to use the color features of the color pattern. - IMAQ_SHAPE_FEATURES = 2, //Instructs the function to use the shape features of the color pattern. - IMAQ_FEATURE_MODE_SIZE_GUARD = 0xFFFFFFFF + IMAQ_COLOR_AND_SHAPE_FEATURES = 0, // Instructs the function to use the color + // and the shape features of the color + // pattern. + IMAQ_COLOR_FEATURES = 1, // Instructs the function to use the color features + // of the color pattern. + IMAQ_SHAPE_FEATURES = 2, // Instructs the function to use the shape features + // of the color pattern. + IMAQ_FEATURE_MODE_SIZE_GUARD = 0xFFFFFFFF } ImageFeatureMode; typedef enum FontColor_enum { - IMAQ_WHITE = 0, //Draws text in white. - IMAQ_BLACK = 1, //Draws text in black. - IMAQ_INVERT = 2, //Inverts the text pixels. - IMAQ_BLACK_ON_WHITE = 3, //Draws text in black with a white background. - IMAQ_WHITE_ON_BLACK = 4, //Draws text in white with a black background. - IMAQ_FONT_COLOR_SIZE_GUARD = 0xFFFFFFFF + IMAQ_WHITE = 0, // Draws text in white. + IMAQ_BLACK = 1, // Draws text in black. + IMAQ_INVERT = 2, // Inverts the text pixels. + IMAQ_BLACK_ON_WHITE = 3, // Draws text in black with a white background. + IMAQ_WHITE_ON_BLACK = 4, // Draws text in white with a black background. + IMAQ_FONT_COLOR_SIZE_GUARD = 0xFFFFFFFF } FontColor; typedef enum FlipAxis_enum { - IMAQ_HORIZONTAL_AXIS = 0, //Flips the image over the central horizontal axis. - IMAQ_VERTICAL_AXIS = 1, //Flips the image over the central vertical axis. - IMAQ_CENTER_AXIS = 2, //Flips the image over both the central vertical and horizontal axes. - IMAQ_DIAG_L_TO_R_AXIS = 3, //Flips the image over an axis from the upper left corner to lower right corner. - IMAQ_DIAG_R_TO_L_AXIS = 4, //Flips the image over an axis from the upper right corner to lower left corner. - IMAQ_FLIP_AXIS_SIZE_GUARD = 0xFFFFFFFF + IMAQ_HORIZONTAL_AXIS = + 0, // Flips the image over the central horizontal axis. + IMAQ_VERTICAL_AXIS = 1, // Flips the image over the central vertical axis. + IMAQ_CENTER_AXIS = + 2, // Flips the image over both the central vertical and horizontal axes. + IMAQ_DIAG_L_TO_R_AXIS = 3, // Flips the image over an axis from the upper + // left corner to lower right corner. + IMAQ_DIAG_R_TO_L_AXIS = 4, // Flips the image over an axis from the upper + // right corner to lower left corner. + IMAQ_FLIP_AXIS_SIZE_GUARD = 0xFFFFFFFF } FlipAxis; typedef enum EdgeProcess_enum { - IMAQ_FIRST = 0, //The function looks for the first edge. - IMAQ_FIRST_AND_LAST = 1, //The function looks for the first and last edge. - IMAQ_ALL = 2, //The function looks for all edges. - IMAQ_BEST = 3, //The function looks for the best edge. - IMAQ_EDGE_PROCESS_SIZE_GUARD = 0xFFFFFFFF + IMAQ_FIRST = 0, // The function looks for the first edge. + IMAQ_FIRST_AND_LAST = 1, // The function looks for the first and last edge. + IMAQ_ALL = 2, // The function looks for all edges. + IMAQ_BEST = 3, // The function looks for the best edge. + IMAQ_EDGE_PROCESS_SIZE_GUARD = 0xFFFFFFFF } EdgeProcess; typedef enum DrawMode_enum { - IMAQ_DRAW_VALUE = 0, //Draws the boundary of the object with the specified pixel value. - IMAQ_DRAW_INVERT = 2, //Inverts the pixel values of the boundary of the object. - IMAQ_PAINT_VALUE = 1, //Fills the object with the given pixel value. - IMAQ_PAINT_INVERT = 3, //Inverts the pixel values of the object. - IMAQ_HIGHLIGHT_VALUE = 4, //The function fills the object by highlighting the enclosed pixels with the color of the object. - IMAQ_DRAW_MODE_SIZE_GUARD = 0xFFFFFFFF + IMAQ_DRAW_VALUE = + 0, // Draws the boundary of the object with the specified pixel value. + IMAQ_DRAW_INVERT = + 2, // Inverts the pixel values of the boundary of the object. + IMAQ_PAINT_VALUE = 1, // Fills the object with the given pixel value. + IMAQ_PAINT_INVERT = 3, // Inverts the pixel values of the object. + IMAQ_HIGHLIGHT_VALUE = 4, // The function fills the object by highlighting + // the enclosed pixels with the color of the + // object. + IMAQ_DRAW_MODE_SIZE_GUARD = 0xFFFFFFFF } DrawMode; typedef enum NearestNeighborMetric_enum { - IMAQ_METRIC_MAXIMUM = 0, //The maximum metric. - IMAQ_METRIC_SUM = 1, //The sum metric. - IMAQ_METRIC_EUCLIDEAN = 2, //The Euclidean metric. - IMAQ_NEAREST_NEIGHBOR_METRIC_SIZE_GUARD = 0xFFFFFFFF + IMAQ_METRIC_MAXIMUM = 0, // The maximum metric. + IMAQ_METRIC_SUM = 1, // The sum metric. + IMAQ_METRIC_EUCLIDEAN = 2, // The Euclidean metric. + IMAQ_NEAREST_NEIGHBOR_METRIC_SIZE_GUARD = 0xFFFFFFFF } NearestNeighborMetric; typedef enum ReadResolution_enum { - IMAQ_LOW_RESOLUTION = 0, //Configures NI Vision to use low resolution during the read process. - IMAQ_MEDIUM_RESOLUTION = 1, //Configures NI Vision to use medium resolution during the read process. - IMAQ_HIGH_RESOLUTION = 2, //Configures NI Vision to use high resolution during the read process. - IMAQ_READ_RESOLUTION_SIZE_GUARD = 0xFFFFFFFF + IMAQ_LOW_RESOLUTION = + 0, // Configures NI Vision to use low resolution during the read process. + IMAQ_MEDIUM_RESOLUTION = 1, // Configures NI Vision to use medium resolution + // during the read process. + IMAQ_HIGH_RESOLUTION = 2, // Configures NI Vision to use high resolution + // during the read process. + IMAQ_READ_RESOLUTION_SIZE_GUARD = 0xFFFFFFFF } ReadResolution; typedef enum ThresholdMode_enum { - IMAQ_FIXED_RANGE = 0, //Performs thresholding using the values you provide in the lowThreshold and highThreshold elements of OCRProcessingOptions. - IMAQ_COMPUTED_UNIFORM = 1, //Calculates a single threshold value for the entire ROI. - IMAQ_COMPUTED_LINEAR = 2, //Calculates a value on the left side of the ROI, calculates a value on the right side of the ROI, and linearly fills the middle values from left to right. - IMAQ_COMPUTED_NONLINEAR = 3, //Divides the ROI into the number of blocks specified by the blockCount element of OCRProcessingOptions and calculates a threshold value for each block. - IMAQ_THRESHOLD_MODE_SIZE_GUARD = 0xFFFFFFFF + IMAQ_FIXED_RANGE = 0, // Performs thresholding using the values you provide + // in the lowThreshold and highThreshold elements of + // OCRProcessingOptions. + IMAQ_COMPUTED_UNIFORM = + 1, // Calculates a single threshold value for the entire ROI. + IMAQ_COMPUTED_LINEAR = 2, // Calculates a value on the left side of the ROI, + // calculates a value on the right side of the ROI, + // and linearly fills the middle values from left + // to right. + IMAQ_COMPUTED_NONLINEAR = 3, // Divides the ROI into the number of blocks + // specified by the blockCount element of + // OCRProcessingOptions and calculates a + // threshold value for each block. + IMAQ_THRESHOLD_MODE_SIZE_GUARD = 0xFFFFFFFF } ThresholdMode; typedef enum ReadStrategy_enum { - IMAQ_READ_AGGRESSIVE = 0, //Configures NI Vision to perform fewer checks when analyzing objects to determine if they match trained characters. - IMAQ_READ_CONSERVATIVE = 1, //Configures NI Vision to perform more checks to determine if an object matches a trained character. - IMAQ_READ_STRATEGY_SIZE_GUARD = 0xFFFFFFFF + IMAQ_READ_AGGRESSIVE = 0, // Configures NI Vision to perform fewer checks + // when analyzing objects to determine if they + // match trained characters. + IMAQ_READ_CONSERVATIVE = 1, // Configures NI Vision to perform more checks to + // determine if an object matches a trained + // character. + IMAQ_READ_STRATEGY_SIZE_GUARD = 0xFFFFFFFF } ReadStrategy; typedef enum MeasurementType_enum { - IMAQ_MT_CENTER_OF_MASS_X = 0, //X-coordinate of the point representing the average position of the total particle mass, assuming every point in the particle has a constant density. - IMAQ_MT_CENTER_OF_MASS_Y = 1, //Y-coordinate of the point representing the average position of the total particle mass, assuming every point in the particle has a constant density. - IMAQ_MT_FIRST_PIXEL_X = 2, //X-coordinate of the highest, leftmost particle pixel. - IMAQ_MT_FIRST_PIXEL_Y = 3, //Y-coordinate of the highest, leftmost particle pixel. - IMAQ_MT_BOUNDING_RECT_LEFT = 4, //X-coordinate of the leftmost particle point. - IMAQ_MT_BOUNDING_RECT_TOP = 5, //Y-coordinate of highest particle point. - IMAQ_MT_BOUNDING_RECT_RIGHT = 6, //X-coordinate of the rightmost particle point. - IMAQ_MT_BOUNDING_RECT_BOTTOM = 7, //Y-coordinate of the lowest particle point. - IMAQ_MT_MAX_FERET_DIAMETER_START_X = 8, //X-coordinate of the start of the line segment connecting the two perimeter points that are the furthest apart. - IMAQ_MT_MAX_FERET_DIAMETER_START_Y = 9, //Y-coordinate of the start of the line segment connecting the two perimeter points that are the furthest apart. - IMAQ_MT_MAX_FERET_DIAMETER_END_X = 10, //X-coordinate of the end of the line segment connecting the two perimeter points that are the furthest apart. - IMAQ_MT_MAX_FERET_DIAMETER_END_Y = 11, //Y-coordinate of the end of the line segment connecting the two perimeter points that are the furthest apart. - IMAQ_MT_MAX_HORIZ_SEGMENT_LENGTH_LEFT = 12, //X-coordinate of the leftmost pixel in the longest row of contiguous pixels in the particle. - IMAQ_MT_MAX_HORIZ_SEGMENT_LENGTH_RIGHT = 13, //X-coordinate of the rightmost pixel in the longest row of contiguous pixels in the particle. - IMAQ_MT_MAX_HORIZ_SEGMENT_LENGTH_ROW = 14, //Y-coordinate of all of the pixels in the longest row of contiguous pixels in the particle. - IMAQ_MT_BOUNDING_RECT_WIDTH = 16, //Distance between the x-coordinate of the leftmost particle point and the x-coordinate of the rightmost particle point. - IMAQ_MT_BOUNDING_RECT_HEIGHT = 17, //Distance between the y-coordinate of highest particle point and the y-coordinate of the lowest particle point. - IMAQ_MT_BOUNDING_RECT_DIAGONAL = 18, //Distance between opposite corners of the bounding rectangle. - IMAQ_MT_PERIMETER = 19, //Length of the outer boundary of the particle. - IMAQ_MT_CONVEX_HULL_PERIMETER = 20, //Perimeter of the smallest convex polygon containing all points in the particle. - IMAQ_MT_HOLES_PERIMETER = 21, //Sum of the perimeters of each hole in the particle. - IMAQ_MT_MAX_FERET_DIAMETER = 22, //Distance between the start and end of the line segment connecting the two perimeter points that are the furthest apart. - IMAQ_MT_EQUIVALENT_ELLIPSE_MAJOR_AXIS = 23, //Length of the major axis of the ellipse with the same perimeter and area as the particle. - IMAQ_MT_EQUIVALENT_ELLIPSE_MINOR_AXIS = 24, //Length of the minor axis of the ellipse with the same perimeter and area as the particle. - IMAQ_MT_EQUIVALENT_ELLIPSE_MINOR_AXIS_FERET = 25, //Length of the minor axis of the ellipse with the same area as the particle, and Major Axis equal in length to the Max Feret Diameter. - IMAQ_MT_EQUIVALENT_RECT_LONG_SIDE = 26, //Longest side of the rectangle with the same perimeter and area as the particle. - IMAQ_MT_EQUIVALENT_RECT_SHORT_SIDE = 27, //Shortest side of the rectangle with the same perimeter and area as the particle. - IMAQ_MT_EQUIVALENT_RECT_DIAGONAL = 28, //Distance between opposite corners of the rectangle with the same perimeter and area as the particle. - IMAQ_MT_EQUIVALENT_RECT_SHORT_SIDE_FERET = 29, //Shortest side of the rectangle with the same area as the particle, and longest side equal in length to the Max Feret Diameter. - IMAQ_MT_AVERAGE_HORIZ_SEGMENT_LENGTH = 30, //Average length of a horizontal segment in the particle. - IMAQ_MT_AVERAGE_VERT_SEGMENT_LENGTH = 31, //Average length of a vertical segment in the particle. - IMAQ_MT_HYDRAULIC_RADIUS = 32, //The particle area divided by the particle perimeter. - IMAQ_MT_WADDEL_DISK_DIAMETER = 33, //Diameter of a disk with the same area as the particle. - IMAQ_MT_AREA = 35, //Area of the particle. - IMAQ_MT_HOLES_AREA = 36, //Sum of the areas of each hole in the particle. - IMAQ_MT_PARTICLE_AND_HOLES_AREA = 37, //Area of a particle that completely covers the image. - IMAQ_MT_CONVEX_HULL_AREA = 38, //Area of the smallest convex polygon containing all points in the particle. - IMAQ_MT_IMAGE_AREA = 39, //Area of the image. - IMAQ_MT_NUMBER_OF_HOLES = 41, //Number of holes in the particle. - IMAQ_MT_NUMBER_OF_HORIZ_SEGMENTS = 42, //Number of horizontal segments in the particle. - IMAQ_MT_NUMBER_OF_VERT_SEGMENTS = 43, //Number of vertical segments in the particle. - IMAQ_MT_ORIENTATION = 45, //The angle of the line that passes through the particle Center of Mass about which the particle has the lowest moment of inertia. - IMAQ_MT_MAX_FERET_DIAMETER_ORIENTATION = 46, //The angle of the line segment connecting the two perimeter points that are the furthest apart. - IMAQ_MT_AREA_BY_IMAGE_AREA = 48, //Percentage of the particle Area covering the Image Area. - IMAQ_MT_AREA_BY_PARTICLE_AND_HOLES_AREA = 49, //Percentage of the particle Area in relation to its Particle and Holes Area. - IMAQ_MT_RATIO_OF_EQUIVALENT_ELLIPSE_AXES = 50, //Equivalent Ellipse Major Axis divided by Equivalent Ellipse Minor Axis. - IMAQ_MT_RATIO_OF_EQUIVALENT_RECT_SIDES = 51, //Equivalent Rect Long Side divided by Equivalent Rect Short Side. - IMAQ_MT_ELONGATION_FACTOR = 53, //Max Feret Diameter divided by Equivalent Rect Short Side (Feret). - IMAQ_MT_COMPACTNESS_FACTOR = 54, //Area divided by the product of Bounding Rect Width and Bounding Rect Height. - IMAQ_MT_HEYWOOD_CIRCULARITY_FACTOR = 55, //Perimeter divided by the circumference of a circle with the same area. - IMAQ_MT_TYPE_FACTOR = 56, //Factor relating area to moment of inertia. - IMAQ_MT_SUM_X = 58, //The sum of all x-coordinates in the particle. - IMAQ_MT_SUM_Y = 59, //The sum of all y-coordinates in the particle. - IMAQ_MT_SUM_XX = 60, //The sum of all x-coordinates squared in the particle. - IMAQ_MT_SUM_XY = 61, //The sum of all x-coordinates times y-coordinates in the particle. - IMAQ_MT_SUM_YY = 62, //The sum of all y-coordinates squared in the particle. - IMAQ_MT_SUM_XXX = 63, //The sum of all x-coordinates cubed in the particle. - IMAQ_MT_SUM_XXY = 64, //The sum of all x-coordinates squared times y-coordinates in the particle. - IMAQ_MT_SUM_XYY = 65, //The sum of all x-coordinates times y-coordinates squared in the particle. - IMAQ_MT_SUM_YYY = 66, //The sum of all y-coordinates cubed in the particle. - IMAQ_MT_MOMENT_OF_INERTIA_XX = 68, //The moment of inertia in the x-direction twice. - IMAQ_MT_MOMENT_OF_INERTIA_XY = 69, //The moment of inertia in the x and y directions. - IMAQ_MT_MOMENT_OF_INERTIA_YY = 70, //The moment of inertia in the y-direction twice. - IMAQ_MT_MOMENT_OF_INERTIA_XXX = 71, //The moment of inertia in the x-direction three times. - IMAQ_MT_MOMENT_OF_INERTIA_XXY = 72, //The moment of inertia in the x-direction twice and the y-direction once. - IMAQ_MT_MOMENT_OF_INERTIA_XYY = 73, //The moment of inertia in the x-direction once and the y-direction twice. - IMAQ_MT_MOMENT_OF_INERTIA_YYY = 74, //The moment of inertia in the y-direction three times. - IMAQ_MT_NORM_MOMENT_OF_INERTIA_XX = 75, //The normalized moment of inertia in the x-direction twice. - IMAQ_MT_NORM_MOMENT_OF_INERTIA_XY = 76, //The normalized moment of inertia in the x- and y-directions. - IMAQ_MT_NORM_MOMENT_OF_INERTIA_YY = 77, //The normalized moment of inertia in the y-direction twice. - IMAQ_MT_NORM_MOMENT_OF_INERTIA_XXX = 78, //The normalized moment of inertia in the x-direction three times. - IMAQ_MT_NORM_MOMENT_OF_INERTIA_XXY = 79, //The normalized moment of inertia in the x-direction twice and the y-direction once. - IMAQ_MT_NORM_MOMENT_OF_INERTIA_XYY = 80, //The normalized moment of inertia in the x-direction once and the y-direction twice. - IMAQ_MT_NORM_MOMENT_OF_INERTIA_YYY = 81, //The normalized moment of inertia in the y-direction three times. - IMAQ_MT_HU_MOMENT_1 = 82, //The first Hu moment. - IMAQ_MT_HU_MOMENT_2 = 83, //The second Hu moment. - IMAQ_MT_HU_MOMENT_3 = 84, //The third Hu moment. - IMAQ_MT_HU_MOMENT_4 = 85, //The fourth Hu moment. - IMAQ_MT_HU_MOMENT_5 = 86, //The fifth Hu moment. - IMAQ_MT_HU_MOMENT_6 = 87, //The sixth Hu moment. - IMAQ_MT_HU_MOMENT_7 = 88, //The seventh Hu moment. - IMAQ_MEASUREMENT_TYPE_SIZE_GUARD = 0xFFFFFFFF + IMAQ_MT_CENTER_OF_MASS_X = 0, // X-coordinate of the point representing the + // average position of the total particle mass, + // assuming every point in the particle has a + // constant density. + IMAQ_MT_CENTER_OF_MASS_Y = 1, // Y-coordinate of the point representing the + // average position of the total particle mass, + // assuming every point in the particle has a + // constant density. + IMAQ_MT_FIRST_PIXEL_X = + 2, // X-coordinate of the highest, leftmost particle pixel. + IMAQ_MT_FIRST_PIXEL_Y = + 3, // Y-coordinate of the highest, leftmost particle pixel. + IMAQ_MT_BOUNDING_RECT_LEFT = + 4, // X-coordinate of the leftmost particle point. + IMAQ_MT_BOUNDING_RECT_TOP = 5, // Y-coordinate of highest particle point. + IMAQ_MT_BOUNDING_RECT_RIGHT = + 6, // X-coordinate of the rightmost particle point. + IMAQ_MT_BOUNDING_RECT_BOTTOM = + 7, // Y-coordinate of the lowest particle point. + IMAQ_MT_MAX_FERET_DIAMETER_START_X = + 8, // X-coordinate of the start of the line segment connecting the two + // perimeter points that are the furthest apart. + IMAQ_MT_MAX_FERET_DIAMETER_START_Y = + 9, // Y-coordinate of the start of the line segment connecting the two + // perimeter points that are the furthest apart. + IMAQ_MT_MAX_FERET_DIAMETER_END_X = + 10, // X-coordinate of the end of the line segment connecting the two + // perimeter points that are the furthest apart. + IMAQ_MT_MAX_FERET_DIAMETER_END_Y = + 11, // Y-coordinate of the end of the line segment connecting the two + // perimeter points that are the furthest apart. + IMAQ_MT_MAX_HORIZ_SEGMENT_LENGTH_LEFT = + 12, // X-coordinate of the leftmost pixel in the longest row of + // contiguous pixels in the particle. + IMAQ_MT_MAX_HORIZ_SEGMENT_LENGTH_RIGHT = + 13, // X-coordinate of the rightmost pixel in the longest row of + // contiguous pixels in the particle. + IMAQ_MT_MAX_HORIZ_SEGMENT_LENGTH_ROW = + 14, // Y-coordinate of all of the pixels in the longest row of contiguous + // pixels in the particle. + IMAQ_MT_BOUNDING_RECT_WIDTH = + 16, // Distance between the x-coordinate of the leftmost particle point + // and the x-coordinate of the rightmost particle point. + IMAQ_MT_BOUNDING_RECT_HEIGHT = + 17, // Distance between the y-coordinate of highest particle point and + // the y-coordinate of the lowest particle point. + IMAQ_MT_BOUNDING_RECT_DIAGONAL = + 18, // Distance between opposite corners of the bounding rectangle. + IMAQ_MT_PERIMETER = 19, // Length of the outer boundary of the particle. + IMAQ_MT_CONVEX_HULL_PERIMETER = 20, // Perimeter of the smallest convex + // polygon containing all points in the + // particle. + IMAQ_MT_HOLES_PERIMETER = + 21, // Sum of the perimeters of each hole in the particle. + IMAQ_MT_MAX_FERET_DIAMETER = 22, // Distance between the start and end of the + // line segment connecting the two perimeter + // points that are the furthest apart. + IMAQ_MT_EQUIVALENT_ELLIPSE_MAJOR_AXIS = + 23, // Length of the major axis of the ellipse with the same perimeter + // and area as the particle. + IMAQ_MT_EQUIVALENT_ELLIPSE_MINOR_AXIS = + 24, // Length of the minor axis of the ellipse with the same perimeter + // and area as the particle. + IMAQ_MT_EQUIVALENT_ELLIPSE_MINOR_AXIS_FERET = + 25, // Length of the minor axis of the ellipse with the same area as the + // particle, and Major Axis equal in length to the Max Feret + // Diameter. + IMAQ_MT_EQUIVALENT_RECT_LONG_SIDE = 26, // Longest side of the rectangle with + // the same perimeter and area as the + // particle. + IMAQ_MT_EQUIVALENT_RECT_SHORT_SIDE = 27, // Shortest side of the rectangle + // with the same perimeter and area + // as the particle. + IMAQ_MT_EQUIVALENT_RECT_DIAGONAL = 28, // Distance between opposite corners + // of the rectangle with the same + // perimeter and area as the particle. + IMAQ_MT_EQUIVALENT_RECT_SHORT_SIDE_FERET = + 29, // Shortest side of the rectangle with the same area as the particle, + // and longest side equal in length to the Max Feret Diameter. + IMAQ_MT_AVERAGE_HORIZ_SEGMENT_LENGTH = + 30, // Average length of a horizontal segment in the particle. + IMAQ_MT_AVERAGE_VERT_SEGMENT_LENGTH = + 31, // Average length of a vertical segment in the particle. + IMAQ_MT_HYDRAULIC_RADIUS = + 32, // The particle area divided by the particle perimeter. + IMAQ_MT_WADDEL_DISK_DIAMETER = + 33, // Diameter of a disk with the same area as the particle. + IMAQ_MT_AREA = 35, // Area of the particle. + IMAQ_MT_HOLES_AREA = 36, // Sum of the areas of each hole in the particle. + IMAQ_MT_PARTICLE_AND_HOLES_AREA = + 37, // Area of a particle that completely covers the image. + IMAQ_MT_CONVEX_HULL_AREA = 38, // Area of the smallest convex polygon + // containing all points in the particle. + IMAQ_MT_IMAGE_AREA = 39, // Area of the image. + IMAQ_MT_NUMBER_OF_HOLES = 41, // Number of holes in the particle. + IMAQ_MT_NUMBER_OF_HORIZ_SEGMENTS = + 42, // Number of horizontal segments in the particle. + IMAQ_MT_NUMBER_OF_VERT_SEGMENTS = + 43, // Number of vertical segments in the particle. + IMAQ_MT_ORIENTATION = 45, // The angle of the line that passes through the + // particle Center of Mass about which the particle + // has the lowest moment of inertia. + IMAQ_MT_MAX_FERET_DIAMETER_ORIENTATION = + 46, // The angle of the line segment connecting the two perimeter points + // that are the furthest apart. + IMAQ_MT_AREA_BY_IMAGE_AREA = + 48, // Percentage of the particle Area covering the Image Area. + IMAQ_MT_AREA_BY_PARTICLE_AND_HOLES_AREA = 49, // Percentage of the particle + // Area in relation to its + // Particle and Holes Area. + IMAQ_MT_RATIO_OF_EQUIVALENT_ELLIPSE_AXES = 50, // Equivalent Ellipse Major + // Axis divided by Equivalent + // Ellipse Minor Axis. + IMAQ_MT_RATIO_OF_EQUIVALENT_RECT_SIDES = + 51, // Equivalent Rect Long Side divided by Equivalent Rect Short Side. + IMAQ_MT_ELONGATION_FACTOR = + 53, // Max Feret Diameter divided by Equivalent Rect Short Side (Feret). + IMAQ_MT_COMPACTNESS_FACTOR = 54, // Area divided by the product of Bounding + // Rect Width and Bounding Rect Height. + IMAQ_MT_HEYWOOD_CIRCULARITY_FACTOR = 55, // Perimeter divided by the + // circumference of a circle with + // the same area. + IMAQ_MT_TYPE_FACTOR = 56, // Factor relating area to moment of inertia. + IMAQ_MT_SUM_X = 58, // The sum of all x-coordinates in the particle. + IMAQ_MT_SUM_Y = 59, // The sum of all y-coordinates in the particle. + IMAQ_MT_SUM_XX = 60, // The sum of all x-coordinates squared in the particle. + IMAQ_MT_SUM_XY = + 61, // The sum of all x-coordinates times y-coordinates in the particle. + IMAQ_MT_SUM_YY = 62, // The sum of all y-coordinates squared in the particle. + IMAQ_MT_SUM_XXX = 63, // The sum of all x-coordinates cubed in the particle. + IMAQ_MT_SUM_XXY = 64, // The sum of all x-coordinates squared times + // y-coordinates in the particle. + IMAQ_MT_SUM_XYY = 65, // The sum of all x-coordinates times y-coordinates + // squared in the particle. + IMAQ_MT_SUM_YYY = 66, // The sum of all y-coordinates cubed in the particle. + IMAQ_MT_MOMENT_OF_INERTIA_XX = + 68, // The moment of inertia in the x-direction twice. + IMAQ_MT_MOMENT_OF_INERTIA_XY = + 69, // The moment of inertia in the x and y directions. + IMAQ_MT_MOMENT_OF_INERTIA_YY = + 70, // The moment of inertia in the y-direction twice. + IMAQ_MT_MOMENT_OF_INERTIA_XXX = + 71, // The moment of inertia in the x-direction three times. + IMAQ_MT_MOMENT_OF_INERTIA_XXY = 72, // The moment of inertia in the + // x-direction twice and the y-direction + // once. + IMAQ_MT_MOMENT_OF_INERTIA_XYY = 73, // The moment of inertia in the + // x-direction once and the y-direction + // twice. + IMAQ_MT_MOMENT_OF_INERTIA_YYY = + 74, // The moment of inertia in the y-direction three times. + IMAQ_MT_NORM_MOMENT_OF_INERTIA_XX = + 75, // The normalized moment of inertia in the x-direction twice. + IMAQ_MT_NORM_MOMENT_OF_INERTIA_XY = + 76, // The normalized moment of inertia in the x- and y-directions. + IMAQ_MT_NORM_MOMENT_OF_INERTIA_YY = + 77, // The normalized moment of inertia in the y-direction twice. + IMAQ_MT_NORM_MOMENT_OF_INERTIA_XXX = + 78, // The normalized moment of inertia in the x-direction three times. + IMAQ_MT_NORM_MOMENT_OF_INERTIA_XXY = 79, // The normalized moment of inertia + // in the x-direction twice and the + // y-direction once. + IMAQ_MT_NORM_MOMENT_OF_INERTIA_XYY = 80, // The normalized moment of inertia + // in the x-direction once and the + // y-direction twice. + IMAQ_MT_NORM_MOMENT_OF_INERTIA_YYY = + 81, // The normalized moment of inertia in the y-direction three times. + IMAQ_MT_HU_MOMENT_1 = 82, // The first Hu moment. + IMAQ_MT_HU_MOMENT_2 = 83, // The second Hu moment. + IMAQ_MT_HU_MOMENT_3 = 84, // The third Hu moment. + IMAQ_MT_HU_MOMENT_4 = 85, // The fourth Hu moment. + IMAQ_MT_HU_MOMENT_5 = 86, // The fifth Hu moment. + IMAQ_MT_HU_MOMENT_6 = 87, // The sixth Hu moment. + IMAQ_MT_HU_MOMENT_7 = 88, // The seventh Hu moment. + IMAQ_MEASUREMENT_TYPE_SIZE_GUARD = 0xFFFFFFFF } MeasurementType; typedef enum GeometricMatchingMode_enum { - IMAQ_GEOMETRIC_MATCH_SHIFT_INVARIANT = 0, //Searches for occurrences of the pattern in the image, assuming that the pattern is not rotated more than plus or minus 5 degrees. - IMAQ_GEOMETRIC_MATCH_ROTATION_INVARIANT = 1, //Searches for occurrences of the pattern in the image with reduced restriction on the rotation of the pattern. - IMAQ_GEOMETRIC_MATCH_SCALE_INVARIANT = 2, //Searches for occurrences of the pattern in the image with reduced restriction on the size of the pattern. - IMAQ_GEOMETRIC_MATCH_OCCLUSION_INVARIANT = 4, //Searches for occurrences of the pattern in the image, allowing for a specified percentage of the pattern to be occluded. - IMAQ_GEOMETRIC_MATCHING_MODE_SIZE_GUARD = 0xFFFFFFFF + IMAQ_GEOMETRIC_MATCH_SHIFT_INVARIANT = + 0, // Searches for occurrences of the pattern in the image, assuming that + // the pattern is not rotated more than plus or minus 5 degrees. + IMAQ_GEOMETRIC_MATCH_ROTATION_INVARIANT = + 1, // Searches for occurrences of the pattern in the image with reduced + // restriction on the rotation of the pattern. + IMAQ_GEOMETRIC_MATCH_SCALE_INVARIANT = + 2, // Searches for occurrences of the pattern in the image with reduced + // restriction on the size of the pattern. + IMAQ_GEOMETRIC_MATCH_OCCLUSION_INVARIANT = + 4, // Searches for occurrences of the pattern in the image, allowing for + // a specified percentage of the pattern to be occluded. + IMAQ_GEOMETRIC_MATCHING_MODE_SIZE_GUARD = 0xFFFFFFFF } GeometricMatchingMode; typedef enum ButtonLabel_enum { - IMAQ_BUTTON_OK = 0, //The label "OK". - IMAQ_BUTTON_SAVE = 1, //The label "Save". - IMAQ_BUTTON_SELECT = 2, //The label "Select". - IMAQ_BUTTON_LOAD = 3, //The label "Load". - IMAQ_BUTTON_LABEL_SIZE_GUARD = 0xFFFFFFFF + IMAQ_BUTTON_OK = 0, // The label "OK". + IMAQ_BUTTON_SAVE = 1, // The label "Save". + IMAQ_BUTTON_SELECT = 2, // The label "Select". + IMAQ_BUTTON_LOAD = 3, // The label "Load". + IMAQ_BUTTON_LABEL_SIZE_GUARD = 0xFFFFFFFF } ButtonLabel; typedef enum NearestNeighborMethod_enum { - IMAQ_MINIMUM_MEAN_DISTANCE = 0, //The minimum mean distance method. - IMAQ_K_NEAREST_NEIGHBOR = 1, //The k-nearest neighbor method. - IMAQ_NEAREST_PROTOTYPE = 2, //The nearest prototype method. - IMAQ_NEAREST_NEIGHBOR_METHOD_SIZE_GUARD = 0xFFFFFFFF + IMAQ_MINIMUM_MEAN_DISTANCE = 0, // The minimum mean distance method. + IMAQ_K_NEAREST_NEIGHBOR = 1, // The k-nearest neighbor method. + IMAQ_NEAREST_PROTOTYPE = 2, // The nearest prototype method. + IMAQ_NEAREST_NEIGHBOR_METHOD_SIZE_GUARD = 0xFFFFFFFF } NearestNeighborMethod; typedef enum QRMirrorMode_enum { - IMAQ_QR_MIRROR_MODE_AUTO_DETECT = -2, //The function should determine if the QR code is mirrored. - IMAQ_QR_MIRROR_MODE_MIRRORED = 1, //The function should expect the QR code to appear mirrored. - IMAQ_QR_MIRROR_MODE_NORMAL = 0, //The function should expect the QR code to appear normal. - IMAQ_QR_MIRROR_MODE_SIZE_GUARD = 0xFFFFFFFF + IMAQ_QR_MIRROR_MODE_AUTO_DETECT = + -2, // The function should determine if the QR code is mirrored. + IMAQ_QR_MIRROR_MODE_MIRRORED = + 1, // The function should expect the QR code to appear mirrored. + IMAQ_QR_MIRROR_MODE_NORMAL = + 0, // The function should expect the QR code to appear normal. + IMAQ_QR_MIRROR_MODE_SIZE_GUARD = 0xFFFFFFFF } QRMirrorMode; typedef enum ColumnProcessingMode_enum { - IMAQ_AVERAGE_COLUMNS = 0, //Averages the data extracted for edge detection. - IMAQ_MEDIAN_COLUMNS = 1, //Takes the median of the data extracted for edge detection. - IMAQ_COLUMN_PROCESSING_MODE_SIZE_GUARD = 0xFFFFFFFF + IMAQ_AVERAGE_COLUMNS = 0, // Averages the data extracted for edge detection. + IMAQ_MEDIAN_COLUMNS = + 1, // Takes the median of the data extracted for edge detection. + IMAQ_COLUMN_PROCESSING_MODE_SIZE_GUARD = 0xFFFFFFFF } ColumnProcessingMode; typedef enum FindReferenceDirection_enum { - IMAQ_LEFT_TO_RIGHT_DIRECT = 0, //Searches from the left side of the search area to the right side of the search area for a direct axis. - IMAQ_LEFT_TO_RIGHT_INDIRECT = 1, //Searches from the left side of the search area to the right side of the search area for an indirect axis. - IMAQ_TOP_TO_BOTTOM_DIRECT = 2, //Searches from the top of the search area to the bottom of the search area for a direct axis. - IMAQ_TOP_TO_BOTTOM_INDIRECT = 3, //Searches from the top of the search area to the bottom of the search area for an indirect axis. - IMAQ_RIGHT_TO_LEFT_DIRECT = 4, //Searches from the right side of the search area to the left side of the search area for a direct axis. - IMAQ_RIGHT_TO_LEFT_INDIRECT = 5, //Searches from the right side of the search area to the left side of the search area for an indirect axis. - IMAQ_BOTTOM_TO_TOP_DIRECT = 6, //Searches from the bottom of the search area to the top of the search area for a direct axis. - IMAQ_BOTTOM_TO_TOP_INDIRECT = 7, //Searches from the bottom of the search area to the top of the search area for an indirect axis. - IMAQ_FIND_COORD_SYS_DIR_SIZE_GUARD = 0xFFFFFFFF + IMAQ_LEFT_TO_RIGHT_DIRECT = 0, // Searches from the left side of the search + // area to the right side of the search area + // for a direct axis. + IMAQ_LEFT_TO_RIGHT_INDIRECT = 1, // Searches from the left side of the search + // area to the right side of the search area + // for an indirect axis. + IMAQ_TOP_TO_BOTTOM_DIRECT = 2, // Searches from the top of the search area to + // the bottom of the search area for a direct + // axis. + IMAQ_TOP_TO_BOTTOM_INDIRECT = 3, // Searches from the top of the search area + // to the bottom of the search area for an + // indirect axis. + IMAQ_RIGHT_TO_LEFT_DIRECT = 4, // Searches from the right side of the search + // area to the left side of the search area + // for a direct axis. + IMAQ_RIGHT_TO_LEFT_INDIRECT = 5, // Searches from the right side of the + // search area to the left side of the + // search area for an indirect axis. + IMAQ_BOTTOM_TO_TOP_DIRECT = 6, // Searches from the bottom of the search area + // to the top of the search area for a direct + // axis. + IMAQ_BOTTOM_TO_TOP_INDIRECT = 7, // Searches from the bottom of the search + // area to the top of the search area for an + // indirect axis. + IMAQ_FIND_COORD_SYS_DIR_SIZE_GUARD = 0xFFFFFFFF } FindReferenceDirection; typedef enum MulticoreOperation_enum { - IMAQ_GET_CORES = 0, //The number of processor cores NI Vision is currently using. - IMAQ_SET_CORES = 1, //The number of processor cores for NI Vision to use. - IMAQ_USE_MAX_AVAILABLE = 2, //Use the maximum number of available processor cores. - IMAQ_MULTICORE_OPERATION_SIZE_GUARD = 0xFFFFFFFF + IMAQ_GET_CORES = + 0, // The number of processor cores NI Vision is currently using. + IMAQ_SET_CORES = 1, // The number of processor cores for NI Vision to use. + IMAQ_USE_MAX_AVAILABLE = + 2, // Use the maximum number of available processor cores. + IMAQ_MULTICORE_OPERATION_SIZE_GUARD = 0xFFFFFFFF } MulticoreOperation; typedef enum GroupBehavior_enum { - IMAQ_GROUP_CLEAR = 0, //Sets the behavior of the overlay group to clear the current settings when an image is transformed. - IMAQ_GROUP_KEEP = 1, //Sets the behavior of the overlay group to keep the current settings when an image is transformed. - IMAQ_GROUP_TRANSFORM = 2, //Sets the behavior of the overlay group to transform with the image. - IMAQ_GROUP_BEHAVIOR_SIZE_GUARD = 0xFFFFFFFF + IMAQ_GROUP_CLEAR = 0, // Sets the behavior of the overlay group to clear the + // current settings when an image is transformed. + IMAQ_GROUP_KEEP = 1, // Sets the behavior of the overlay group to keep the + // current settings when an image is transformed. + IMAQ_GROUP_TRANSFORM = + 2, // Sets the behavior of the overlay group to transform with the image. + IMAQ_GROUP_BEHAVIOR_SIZE_GUARD = 0xFFFFFFFF } GroupBehavior; typedef enum QRDimensions_enum { - IMAQ_QR_DIMENSIONS_AUTO_DETECT = 0, //The function will automatically determine the dimensions of the QR code. - IMAQ_QR_DIMENSIONS_11x11 = 11, //Specifies the dimensions of the QR code as 11 x 11. - IMAQ_QR_DIMENSIONS_13x13 = 13, //Specifies the dimensions of the QR code as 13 x 13. - IMAQ_QR_DIMENSIONS_15x15 = 15, //Specifies the dimensions of the QR code as 15 x 15. - IMAQ_QR_DIMENSIONS_17x17 = 17, //Specifies the dimensions of the QR code as 17 x 17. - IMAQ_QR_DIMENSIONS_21x21 = 21, //Specifies the dimensions of the QR code as 21 x 21. - IMAQ_QR_DIMENSIONS_25x25 = 25, //Specifies the dimensions of the QR code as 25 x 25. - IMAQ_QR_DIMENSIONS_29x29 = 29, //Specifies the dimensions of the QR code as 29 x 29. - IMAQ_QR_DIMENSIONS_33x33 = 33, //Specifies the dimensions of the QR code as 33 x 33. - IMAQ_QR_DIMENSIONS_37x37 = 37, //Specifies the dimensions of the QR code as 37 x 37. - IMAQ_QR_DIMENSIONS_41x41 = 41, //Specifies the dimensions of the QR code as 41 x 41. - IMAQ_QR_DIMENSIONS_45x45 = 45, //Specifies the dimensions of the QR code as 45 x 45. - IMAQ_QR_DIMENSIONS_49x49 = 49, //Specifies the dimensions of the QR code as 49 x 49. - IMAQ_QR_DIMENSIONS_53x53 = 53, //Specifies the dimensions of the QR code as 53 x 53. - IMAQ_QR_DIMENSIONS_57x57 = 57, //Specifies the dimensions of the QR code as 57 x 57. - IMAQ_QR_DIMENSIONS_61x61 = 61, //Specifies the dimensions of the QR code as 61 x 61. - IMAQ_QR_DIMENSIONS_65x65 = 65, //Specifies the dimensions of the QR code as 65 x 65. - IMAQ_QR_DIMENSIONS_69x69 = 69, //Specifies the dimensions of the QR code as 69 x 69. - IMAQ_QR_DIMENSIONS_73x73 = 73, //Specifies the dimensions of the QR code as 73 x 73. - IMAQ_QR_DIMENSIONS_77x77 = 77, //Specifies the dimensions of the QR code as 77 x 77. - IMAQ_QR_DIMENSIONS_81x81 = 81, //Specifies the dimensions of the QR code as 81 x 81. - IMAQ_QR_DIMENSIONS_85x85 = 85, //Specifies the dimensions of the QR code as 85 x 85. - IMAQ_QR_DIMENSIONS_89x89 = 89, //Specifies the dimensions of the QR code as 89 x 89. - IMAQ_QR_DIMENSIONS_93x93 = 93, //Specifies the dimensions of the QR code as 93 x 93. - IMAQ_QR_DIMENSIONS_97x97 = 97, //Specifies the dimensions of the QR code as 97 x 97. - IMAQ_QR_DIMENSIONS_101x101 = 101, //Specifies the dimensions of the QR code as 101 x 101. - IMAQ_QR_DIMENSIONS_105x105 = 105, //Specifies the dimensions of the QR code as 105 x 105. - IMAQ_QR_DIMENSIONS_109x109 = 109, //Specifies the dimensions of the QR code as 109 x 109. - IMAQ_QR_DIMENSIONS_113x113 = 113, //Specifies the dimensions of the QR code as 113 x 113. - IMAQ_QR_DIMENSIONS_117x117 = 117, //Specifies the dimensions of the QR code as 117 x 117. - IMAQ_QR_DIMENSIONS_121x121 = 121, //Specifies the dimensions of the QR code as 121 x 121. - IMAQ_QR_DIMENSIONS_125x125 = 125, //Specifies the dimensions of the QR code as 125 x 125. - IMAQ_QR_DIMENSIONS_129x129 = 129, //Specifies the dimensions of the QR code as 129 x 129. - IMAQ_QR_DIMENSIONS_133x133 = 133, //Specifies the dimensions of the QR code as 133 x 133. - IMAQ_QR_DIMENSIONS_137x137 = 137, //Specifies the dimensions of the QR code as 137 x 137. - IMAQ_QR_DIMENSIONS_141x141 = 141, //Specifies the dimensions of the QR code as 141 x 141. - IMAQ_QR_DIMENSIONS_145x145 = 145, //Specifies the dimensions of the QR code as 145 x 145. - IMAQ_QR_DIMENSIONS_149x149 = 149, //Specifies the dimensions of the QR code as 149 x 149. - IMAQ_QR_DIMENSIONS_153x153 = 153, //Specifies the dimensions of the QR code as 153 x 153. - IMAQ_QR_DIMENSIONS_157x157 = 157, //Specifies the dimensions of the QR code as 157 x 1537. - IMAQ_QR_DIMENSIONS_161x161 = 161, //Specifies the dimensions of the QR code as 161 x 161. - IMAQ_QR_DIMENSIONS_165x165 = 165, //Specifies the dimensions of the QR code as 165 x 165. - IMAQ_QR_DIMENSIONS_169x169 = 169, //Specifies the dimensions of the QR code as 169 x 169. - IMAQ_QR_DIMENSIONS_173x173 = 173, //Specifies the dimensions of the QR code as 173 x 173. - IMAQ_QR_DIMENSIONS_177x177 = 177, //Specifies the dimensions of the QR code as 177 x 177. - IMAQ_QR_DIMENSIONS_SIZE_GUARD = 0xFFFFFFFF + IMAQ_QR_DIMENSIONS_AUTO_DETECT = 0, // The function will automatically + // determine the dimensions of the QR + // code. + IMAQ_QR_DIMENSIONS_11x11 = + 11, // Specifies the dimensions of the QR code as 11 x 11. + IMAQ_QR_DIMENSIONS_13x13 = + 13, // Specifies the dimensions of the QR code as 13 x 13. + IMAQ_QR_DIMENSIONS_15x15 = + 15, // Specifies the dimensions of the QR code as 15 x 15. + IMAQ_QR_DIMENSIONS_17x17 = + 17, // Specifies the dimensions of the QR code as 17 x 17. + IMAQ_QR_DIMENSIONS_21x21 = + 21, // Specifies the dimensions of the QR code as 21 x 21. + IMAQ_QR_DIMENSIONS_25x25 = + 25, // Specifies the dimensions of the QR code as 25 x 25. + IMAQ_QR_DIMENSIONS_29x29 = + 29, // Specifies the dimensions of the QR code as 29 x 29. + IMAQ_QR_DIMENSIONS_33x33 = + 33, // Specifies the dimensions of the QR code as 33 x 33. + IMAQ_QR_DIMENSIONS_37x37 = + 37, // Specifies the dimensions of the QR code as 37 x 37. + IMAQ_QR_DIMENSIONS_41x41 = + 41, // Specifies the dimensions of the QR code as 41 x 41. + IMAQ_QR_DIMENSIONS_45x45 = + 45, // Specifies the dimensions of the QR code as 45 x 45. + IMAQ_QR_DIMENSIONS_49x49 = + 49, // Specifies the dimensions of the QR code as 49 x 49. + IMAQ_QR_DIMENSIONS_53x53 = + 53, // Specifies the dimensions of the QR code as 53 x 53. + IMAQ_QR_DIMENSIONS_57x57 = + 57, // Specifies the dimensions of the QR code as 57 x 57. + IMAQ_QR_DIMENSIONS_61x61 = + 61, // Specifies the dimensions of the QR code as 61 x 61. + IMAQ_QR_DIMENSIONS_65x65 = + 65, // Specifies the dimensions of the QR code as 65 x 65. + IMAQ_QR_DIMENSIONS_69x69 = + 69, // Specifies the dimensions of the QR code as 69 x 69. + IMAQ_QR_DIMENSIONS_73x73 = + 73, // Specifies the dimensions of the QR code as 73 x 73. + IMAQ_QR_DIMENSIONS_77x77 = + 77, // Specifies the dimensions of the QR code as 77 x 77. + IMAQ_QR_DIMENSIONS_81x81 = + 81, // Specifies the dimensions of the QR code as 81 x 81. + IMAQ_QR_DIMENSIONS_85x85 = + 85, // Specifies the dimensions of the QR code as 85 x 85. + IMAQ_QR_DIMENSIONS_89x89 = + 89, // Specifies the dimensions of the QR code as 89 x 89. + IMAQ_QR_DIMENSIONS_93x93 = + 93, // Specifies the dimensions of the QR code as 93 x 93. + IMAQ_QR_DIMENSIONS_97x97 = + 97, // Specifies the dimensions of the QR code as 97 x 97. + IMAQ_QR_DIMENSIONS_101x101 = + 101, // Specifies the dimensions of the QR code as 101 x 101. + IMAQ_QR_DIMENSIONS_105x105 = + 105, // Specifies the dimensions of the QR code as 105 x 105. + IMAQ_QR_DIMENSIONS_109x109 = + 109, // Specifies the dimensions of the QR code as 109 x 109. + IMAQ_QR_DIMENSIONS_113x113 = + 113, // Specifies the dimensions of the QR code as 113 x 113. + IMAQ_QR_DIMENSIONS_117x117 = + 117, // Specifies the dimensions of the QR code as 117 x 117. + IMAQ_QR_DIMENSIONS_121x121 = + 121, // Specifies the dimensions of the QR code as 121 x 121. + IMAQ_QR_DIMENSIONS_125x125 = + 125, // Specifies the dimensions of the QR code as 125 x 125. + IMAQ_QR_DIMENSIONS_129x129 = + 129, // Specifies the dimensions of the QR code as 129 x 129. + IMAQ_QR_DIMENSIONS_133x133 = + 133, // Specifies the dimensions of the QR code as 133 x 133. + IMAQ_QR_DIMENSIONS_137x137 = + 137, // Specifies the dimensions of the QR code as 137 x 137. + IMAQ_QR_DIMENSIONS_141x141 = + 141, // Specifies the dimensions of the QR code as 141 x 141. + IMAQ_QR_DIMENSIONS_145x145 = + 145, // Specifies the dimensions of the QR code as 145 x 145. + IMAQ_QR_DIMENSIONS_149x149 = + 149, // Specifies the dimensions of the QR code as 149 x 149. + IMAQ_QR_DIMENSIONS_153x153 = + 153, // Specifies the dimensions of the QR code as 153 x 153. + IMAQ_QR_DIMENSIONS_157x157 = + 157, // Specifies the dimensions of the QR code as 157 x 1537. + IMAQ_QR_DIMENSIONS_161x161 = + 161, // Specifies the dimensions of the QR code as 161 x 161. + IMAQ_QR_DIMENSIONS_165x165 = + 165, // Specifies the dimensions of the QR code as 165 x 165. + IMAQ_QR_DIMENSIONS_169x169 = + 169, // Specifies the dimensions of the QR code as 169 x 169. + IMAQ_QR_DIMENSIONS_173x173 = + 173, // Specifies the dimensions of the QR code as 173 x 173. + IMAQ_QR_DIMENSIONS_177x177 = + 177, // Specifies the dimensions of the QR code as 177 x 177. + IMAQ_QR_DIMENSIONS_SIZE_GUARD = 0xFFFFFFFF } QRDimensions; typedef enum QRCellFilterMode_enum { - IMAQ_QR_CELL_FILTER_MODE_AUTO_DETECT = -2, //The function will try all filter modes and uses the one that decodes the QR code within the fewest iterations and utilizing the least amount of error correction. - IMAQ_QR_CELL_FILTER_MODE_AVERAGE = 0, //The function sets the pixel value for the cell to the average of the sampled pixels. - IMAQ_QR_CELL_FILTER_MODE_MEDIAN = 1, //The function sets the pixel value for the cell to the median of the sampled pixels. - IMAQ_QR_CELL_FILTER_MODE_CENTRAL_AVERAGE = 2, //The function sets the pixel value for the cell to the average of the pixels in the center of the cell sample. - IMAQ_QR_CELL_FILTER_MODE_HIGH_AVERAGE = 3, //The function sets the pixel value for the cell to the average value of the half of the sampled pixels with the highest pixel values. - IMAQ_QR_CELL_FILTER_MODE_LOW_AVERAGE = 4, //The function sets the pixel value for the cell to the average value of the half of the sampled pixels with the lowest pixel values. - IMAQ_QR_CELL_FILTER_MODE_VERY_HIGH_AVERAGE = 5, //The function sets the pixel value for the cell to the average value of the ninth of the sampled pixels with the highest pixel values. - IMAQ_QR_CELL_FILTER_MODE_VERY_LOW_AVERAGE = 6, //The function sets the pixel value for the cell to the average value of the ninth of the sampled pixels with the lowest pixel values. - IMAQ_QR_CELL_FILTER_MODE_ALL = 8, //The function tries each filter mode, starting with IMAQ_QR_CELL_FILTER_MODE_AVERAGE and ending with IMAQ_QR_CELL_FILTER_MODE_VERY_LOW_AVERAGE, stopping once a filter mode decodes correctly. - IMAQ_QR_CELL_FILTER_MODE_SIZE_GUARD = 0xFFFFFFFF + IMAQ_QR_CELL_FILTER_MODE_AUTO_DETECT = + -2, // The function will try all filter modes and uses the one that + // decodes the QR code within the fewest iterations and utilizing the + // least amount of error correction. + IMAQ_QR_CELL_FILTER_MODE_AVERAGE = 0, // The function sets the pixel value + // for the cell to the average of the + // sampled pixels. + IMAQ_QR_CELL_FILTER_MODE_MEDIAN = 1, // The function sets the pixel value for + // the cell to the median of the sampled + // pixels. + IMAQ_QR_CELL_FILTER_MODE_CENTRAL_AVERAGE = + 2, // The function sets the pixel value for the cell to the average of + // the pixels in the center of the cell sample. + IMAQ_QR_CELL_FILTER_MODE_HIGH_AVERAGE = + 3, // The function sets the pixel value for the cell to the average value + // of the half of the sampled pixels with the highest pixel values. + IMAQ_QR_CELL_FILTER_MODE_LOW_AVERAGE = + 4, // The function sets the pixel value for the cell to the average value + // of the half of the sampled pixels with the lowest pixel values. + IMAQ_QR_CELL_FILTER_MODE_VERY_HIGH_AVERAGE = + 5, // The function sets the pixel value for the cell to the average value + // of the ninth of the sampled pixels with the highest pixel values. + IMAQ_QR_CELL_FILTER_MODE_VERY_LOW_AVERAGE = + 6, // The function sets the pixel value for the cell to the average value + // of the ninth of the sampled pixels with the lowest pixel values. + IMAQ_QR_CELL_FILTER_MODE_ALL = + 8, // The function tries each filter mode, starting with + // IMAQ_QR_CELL_FILTER_MODE_AVERAGE and ending with + // IMAQ_QR_CELL_FILTER_MODE_VERY_LOW_AVERAGE, stopping once a filter + // mode decodes correctly. + IMAQ_QR_CELL_FILTER_MODE_SIZE_GUARD = 0xFFFFFFFF } QRCellFilterMode; typedef enum RoundingMode_enum { - IMAQ_ROUNDING_MODE_OPTIMIZE = 0, //Rounds the result of a division using the best available method. - IMAQ_ROUNDING_MODE_TRUNCATE = 1, //Truncates the result of a division. - IMAQ_ROUNDING_MODE_SIZE_GUARD = 0xFFFFFFFF + IMAQ_ROUNDING_MODE_OPTIMIZE = + 0, // Rounds the result of a division using the best available method. + IMAQ_ROUNDING_MODE_TRUNCATE = 1, // Truncates the result of a division. + IMAQ_ROUNDING_MODE_SIZE_GUARD = 0xFFFFFFFF } RoundingMode; typedef enum QRDemodulationMode_enum { - IMAQ_QR_DEMODULATION_MODE_AUTO_DETECT = -2, //The function will try each demodulation mode and use the one which decodes the QR code within the fewest iterations and utilizing the least amount of error correction. - IMAQ_QR_DEMODULATION_MODE_HISTOGRAM = 0, //The function uses a histogram of all of the QR cells to calculate a threshold. - IMAQ_QR_DEMODULATION_MODE_LOCAL_CONTRAST = 1, //The function examines each of the cell's neighbors to determine if the cell is on or off. - IMAQ_QR_DEMODULATION_MODE_COMBINED = 2, //The function uses the histogram of the QR code to calculate a threshold. - IMAQ_QR_DEMODULATION_MODE_ALL = 3, //The function tries IMAQ_QR_DEMODULATION_MODE_HISTOGRAM, then IMAQ_QR_DEMODULATION_MODE_LOCAL_CONTRAST and then IMAQ_QR_DEMODULATION_MODE_COMBINED, stopping once one mode is successful. - IMAQ_QR_DEMODULATION_MODE_SIZE_GUARD = 0xFFFFFFFF + IMAQ_QR_DEMODULATION_MODE_AUTO_DETECT = + -2, // The function will try each demodulation mode and use the one which + // decodes the QR code within the fewest iterations and utilizing the + // least amount of error correction. + IMAQ_QR_DEMODULATION_MODE_HISTOGRAM = 0, // The function uses a histogram of + // all of the QR cells to calculate + // a threshold. + IMAQ_QR_DEMODULATION_MODE_LOCAL_CONTRAST = + 1, // The function examines each of the cell's neighbors to determine if + // the cell is on or off. + IMAQ_QR_DEMODULATION_MODE_COMBINED = 2, // The function uses the histogram of + // the QR code to calculate a + // threshold. + IMAQ_QR_DEMODULATION_MODE_ALL = + 3, // The function tries IMAQ_QR_DEMODULATION_MODE_HISTOGRAM, then + // IMAQ_QR_DEMODULATION_MODE_LOCAL_CONTRAST and then + // IMAQ_QR_DEMODULATION_MODE_COMBINED, stopping once one mode is + // successful. + IMAQ_QR_DEMODULATION_MODE_SIZE_GUARD = 0xFFFFFFFF } QRDemodulationMode; typedef enum ContrastMode_enum { - IMAQ_ORIGINAL_CONTRAST = 0, //Instructs the geometric matching algorithm to find matches with the same contrast as the template. - IMAQ_REVERSED_CONTRAST = 1, //Instructs the geometric matching algorithm to find matches with the inverted contrast of the template. - IMAQ_BOTH_CONTRASTS = 2, //Instructs the geometric matching algorithm to find matches with the same and inverted contrast of the template. + IMAQ_ORIGINAL_CONTRAST = 0, // Instructs the geometric matching algorithm to + // find matches with the same contrast as the + // template. + IMAQ_REVERSED_CONTRAST = 1, // Instructs the geometric matching algorithm to + // find matches with the inverted contrast of the + // template. + IMAQ_BOTH_CONTRASTS = 2, // Instructs the geometric matching algorithm to + // find matches with the same and inverted contrast + // of the template. } ContrastMode; typedef enum QRPolarities_enum { - IMAQ_QR_POLARITY_AUTO_DETECT = -2, //The function should determine the polarity of the QR code. - IMAQ_QR_POLARITY_BLACK_ON_WHITE = 0, //The function should search for a QR code with dark data on a bright background. - IMAQ_QR_POLARITY_WHITE_ON_BLACK = 1, //The function should search for a QR code with bright data on a dark background. - IMAQ_QR_POLARITY_MODE_SIZE_GUARD = 0xFFFFFFFF + IMAQ_QR_POLARITY_AUTO_DETECT = + -2, // The function should determine the polarity of the QR code. + IMAQ_QR_POLARITY_BLACK_ON_WHITE = 0, // The function should search for a QR + // code with dark data on a bright + // background. + IMAQ_QR_POLARITY_WHITE_ON_BLACK = 1, // The function should search for a QR + // code with bright data on a dark + // background. + IMAQ_QR_POLARITY_MODE_SIZE_GUARD = 0xFFFFFFFF } QRPolarities; typedef enum QRRotationMode_enum { - IMAQ_QR_ROTATION_MODE_UNLIMITED = 0, //The function allows for unlimited rotation. - IMAQ_QR_ROTATION_MODE_0_DEGREES = 1, //The function allows for ??? 5 degrees of rotation. - IMAQ_QR_ROTATION_MODE_90_DEGREES = 2, //The function allows for between 85 and 95 degrees of rotation. - IMAQ_QR_ROTATION_MODE_180_DEGREES = 3, //The function allows for between 175 and 185 degrees of rotation. - IMAQ_QR_ROTATION_MODE_270_DEGREES = 4, //The function allows for between 265 and 275 degrees of rotation. - IMAQ_QR_ROTATION_MODE_SIZE_GUARD = 0xFFFFFFFF + IMAQ_QR_ROTATION_MODE_UNLIMITED = + 0, // The function allows for unlimited rotation. + IMAQ_QR_ROTATION_MODE_0_DEGREES = + 1, // The function allows for ??? 5 degrees of rotation. + IMAQ_QR_ROTATION_MODE_90_DEGREES = + 2, // The function allows for between 85 and 95 degrees of rotation. + IMAQ_QR_ROTATION_MODE_180_DEGREES = + 3, // The function allows for between 175 and 185 degrees of rotation. + IMAQ_QR_ROTATION_MODE_270_DEGREES = + 4, // The function allows for between 265 and 275 degrees of rotation. + IMAQ_QR_ROTATION_MODE_SIZE_GUARD = 0xFFFFFFFF } QRRotationMode; typedef enum QRGradingMode_enum { - IMAQ_QR_NO_GRADING = 0, //The function does not make any preparatory calculations. - IMAQ_QR_GRADING_MODE_SIZE_GUARD = 0xFFFFFFFF + IMAQ_QR_NO_GRADING = + 0, // The function does not make any preparatory calculations. + IMAQ_QR_GRADING_MODE_SIZE_GUARD = 0xFFFFFFFF } QRGradingMode; typedef enum StraightEdgeSearchMode_enum { - IMAQ_USE_FIRST_RAKE_EDGES = 0, //Fits a straight edge on the first points detected using a rake. - IMAQ_USE_BEST_RAKE_EDGES = 1, //Fits a straight edge on the best points detected using a rake. - IMAQ_USE_BEST_HOUGH_LINE = 2, //Finds the strongest straight edge using all points detected on a rake. - IMAQ_USE_FIRST_PROJECTION_EDGE = 3, //Uses the location of the first projected edge as the straight edge. - IMAQ_USE_BEST_PROJECTION_EDGE = 4, //Finds the strongest projected edge location to determine the straight edge. - IMAQ_STRAIGHT_EDGE_SEARCH_SIZE_GUARD = 0xFFFFFFFF + IMAQ_USE_FIRST_RAKE_EDGES = + 0, // Fits a straight edge on the first points detected using a rake. + IMAQ_USE_BEST_RAKE_EDGES = + 1, // Fits a straight edge on the best points detected using a rake. + IMAQ_USE_BEST_HOUGH_LINE = 2, // Finds the strongest straight edge using all + // points detected on a rake. + IMAQ_USE_FIRST_PROJECTION_EDGE = + 3, // Uses the location of the first projected edge as the straight edge. + IMAQ_USE_BEST_PROJECTION_EDGE = 4, // Finds the strongest projected edge + // location to determine the straight + // edge. + IMAQ_STRAIGHT_EDGE_SEARCH_SIZE_GUARD = 0xFFFFFFFF } StraightEdgeSearchMode; typedef enum SearchDirection_enum { - IMAQ_SEARCH_DIRECTION_LEFT_TO_RIGHT = 0, //Searches from the left side of the search area to the right side of the search area. - IMAQ_SEARCH_DIRECTION_RIGHT_TO_LEFT = 1, //Searches from the right side of the search area to the left side of the search area. - IMAQ_SEARCH_DIRECTION_TOP_TO_BOTTOM = 2, //Searches from the top side of the search area to the bottom side of the search area. - IMAQ_SEARCH_DIRECTION_BOTTOM_TO_TOP = 3, //Searches from the bottom side of the search area to the top side of the search area. - IMAQ_SEARCH_DIRECTION_SIZE_GUARD = 0xFFFFFFFF + IMAQ_SEARCH_DIRECTION_LEFT_TO_RIGHT = 0, // Searches from the left side of + // the search area to the right side + // of the search area. + IMAQ_SEARCH_DIRECTION_RIGHT_TO_LEFT = 1, // Searches from the right side of + // the search area to the left side + // of the search area. + IMAQ_SEARCH_DIRECTION_TOP_TO_BOTTOM = 2, // Searches from the top side of the + // search area to the bottom side of + // the search area. + IMAQ_SEARCH_DIRECTION_BOTTOM_TO_TOP = 3, // Searches from the bottom side of + // the search area to the top side + // of the search area. + IMAQ_SEARCH_DIRECTION_SIZE_GUARD = 0xFFFFFFFF } SearchDirection; typedef enum QRStreamMode_enum { - IMAQ_QR_MODE_NUMERIC = 0, //Specifies that the data was encoded using numeric mode. - IMAQ_QR_MODE_ALPHANUMERIC = 1, //Specifies that the data was encoded using alpha-numeric mode. - IMAQ_QR_MODE_RAW_BYTE = 2, //Specifies that the data was not encoded but is only raw binary bytes, or encoded in JIS-8. - IMAQ_QR_MODE_EAN128_TOKEN = 3, //Specifies that the data has a special meaning represented by the application ID. - IMAQ_QR_MODE_EAN128_DATA = 4, //Specifies that the data has a special meaning represented by the application ID. - IMAQ_QR_MODE_ECI = 5, //Specifies that the data was meant to be read using the language represented in the language ID. - IMAQ_QR_MODE_KANJI = 6, //Specifies that the data was encoded in Shift-JIS16 Japanese. - IMAQ_QR_MODE_SIZE_GUARD = 0xFFFFFFFF + IMAQ_QR_MODE_NUMERIC = + 0, // Specifies that the data was encoded using numeric mode. + IMAQ_QR_MODE_ALPHANUMERIC = + 1, // Specifies that the data was encoded using alpha-numeric mode. + IMAQ_QR_MODE_RAW_BYTE = 2, // Specifies that the data was not encoded but is + // only raw binary bytes, or encoded in JIS-8. + IMAQ_QR_MODE_EAN128_TOKEN = 3, // Specifies that the data has a special + // meaning represented by the application ID. + IMAQ_QR_MODE_EAN128_DATA = 4, // Specifies that the data has a special + // meaning represented by the application ID. + IMAQ_QR_MODE_ECI = 5, // Specifies that the data was meant to be read using + // the language represented in the language ID. + IMAQ_QR_MODE_KANJI = + 6, // Specifies that the data was encoded in Shift-JIS16 Japanese. + IMAQ_QR_MODE_SIZE_GUARD = 0xFFFFFFFF } QRStreamMode; typedef enum ParticleClassifierType_enum { - IMAQ_PARTICLE_LARGEST = 0, //Use only the largest particle in the image. - IMAQ_PARTICLE_ALL = 1, //Use all particles in the image. - IMAQ_PARTICLE_CLASSIFIER_TYPE_SIZE_GUARD = 0xFFFFFFFF + IMAQ_PARTICLE_LARGEST = 0, // Use only the largest particle in the image. + IMAQ_PARTICLE_ALL = 1, // Use all particles in the image. + IMAQ_PARTICLE_CLASSIFIER_TYPE_SIZE_GUARD = 0xFFFFFFFF } ParticleClassifierType; typedef enum QRCellSampleSize_enum { - IMAQ_QR_CELL_SAMPLE_SIZE_AUTO_DETECT = -2, //The function will try each sample size and use the one which decodes the QR code within the fewest iterations and utilizing the least amount of error correction. - IMAQ_QR_CELL_SAMPLE_SIZE1X1 = 1, //The function will use a 1x1 sized sample from each cell. - IMAQ_QR_CELL_SAMPLE_SIZE2X2 = 2, //The function will use a 2x2 sized sample from each cell. - IMAQ_QR_CELL_SAMPLE_SIZE3X3 = 3, //The function will use a 3x3 sized sample from each cell. - IMAQ_QR_CELL_SAMPLE_SIZE4X4 = 4, //The function will use a 4x4 sized sample from each cell. - IMAQ_QR_CELL_SAMPLE_SIZE5X5 = 5, //The function will use a 5x5 sized sample from each cell. - IMAQ_QR_CELL_SAMPLE_SIZE6X6 = 6, //The function will use a 6x6 sized sample from each cell. - IMAQ_QR_CELL_SAMPLE_SIZE7X7 = 7, //The function will use a 7x7 sized sample from each cell. - IMAQ_QR_CELL_SAMPLE_TYPE_SIZE_GUARD = 0xFFFFFFFF + IMAQ_QR_CELL_SAMPLE_SIZE_AUTO_DETECT = + -2, // The function will try each sample size and use the one which + // decodes the QR code within the fewest iterations and utilizing the + // least amount of error correction. + IMAQ_QR_CELL_SAMPLE_SIZE1X1 = + 1, // The function will use a 1x1 sized sample from each cell. + IMAQ_QR_CELL_SAMPLE_SIZE2X2 = + 2, // The function will use a 2x2 sized sample from each cell. + IMAQ_QR_CELL_SAMPLE_SIZE3X3 = + 3, // The function will use a 3x3 sized sample from each cell. + IMAQ_QR_CELL_SAMPLE_SIZE4X4 = + 4, // The function will use a 4x4 sized sample from each cell. + IMAQ_QR_CELL_SAMPLE_SIZE5X5 = + 5, // The function will use a 5x5 sized sample from each cell. + IMAQ_QR_CELL_SAMPLE_SIZE6X6 = + 6, // The function will use a 6x6 sized sample from each cell. + IMAQ_QR_CELL_SAMPLE_SIZE7X7 = + 7, // The function will use a 7x7 sized sample from each cell. + IMAQ_QR_CELL_SAMPLE_TYPE_SIZE_GUARD = 0xFFFFFFFF } QRCellSampleSize; typedef enum RakeProcessType_enum { - IMAQ_GET_FIRST_EDGES = 0, - IMAQ_GET_FIRST_AND_LAST_EDGES = 1, - IMAQ_GET_ALL_EDGES = 2, - IMAQ_GET_BEST_EDGES = 3, - IMAQ_RAKE_PROCESS_TYPE_SIZE_GUARD = 0xFFFFFFFF + IMAQ_GET_FIRST_EDGES = 0, + IMAQ_GET_FIRST_AND_LAST_EDGES = 1, + IMAQ_GET_ALL_EDGES = 2, + IMAQ_GET_BEST_EDGES = 3, + IMAQ_RAKE_PROCESS_TYPE_SIZE_GUARD = 0xFFFFFFFF } RakeProcessType; typedef enum GeometricSetupDataItem_enum { - IMAQ_CURVE_EXTRACTION_MODE = 0, //Specifies how the function identifies curves in the image. - IMAQ_CURVE_EDGE_THRSHOLD = 1, //Specifies the minimum contrast an edge pixel must have for it to be considered part of a curve. - IMAQ_CURVE_EDGE_FILTER = 2, //Specifies the width of the edge filter that the function uses to identify curves in the image. - IMAQ_MINIMUM_CURVE_LENGTH = 3, //Specifies the length, in pixels, of the smallest curve that you want the function to identify. - IMAQ_CURVE_ROW_SEARCH_STEP_SIZE = 4, //Specifies the distance, in the y direction, between the image rows that the algorithm inspects for curve seed points. - IMAQ_CURVE_COL_SEARCH_STEP_SIZE = 5, //Specifies the distance, in the x direction, between the image columns that the algorithm inspects for curve seed points. - IMAQ_CURVE_MAX_END_POINT_GAP = 6, //Specifies the maximum gap, in pixels, between the endpoints of a curve that the function identifies as a closed curve. - IMAQ_EXTRACT_CLOSED_CURVES = 7, //Specifies whether to identify only closed curves in the image. - IMAQ_ENABLE_SUBPIXEL_CURVE_EXTRACTION = 8, //The function ignores this option. - IMAQ_ENABLE_CORRELATION_SCORE = 9, //Specifies that the function should calculate the Correlation Score and return it for each match result. - IMAQ_ENABLE_SUBPIXEL_ACCURACY = 10, //Determines whether to return the match results with subpixel accuracy. - IMAQ_SUBPIXEL_ITERATIONS = 11, //Specifies the maximum number of incremental improvements used to refine matches using subpixel information. - IMAQ_SUBPIXEL_TOLERANCE = 12, //Specifies the maximum amount of change, in pixels, between consecutive incremental improvements in the match position before the function stops refining the match position. - IMAQ_INITIAL_MATCH_LIST_LENGTH = 13, //Specifies the maximum size of the match list. - IMAQ_ENABLE_TARGET_TEMPLATE_CURVESCORE = 14, //Specifies whether the function should calculate the match curve to template curve score and return it for each match result. - IMAQ_MINIMUM_MATCH_SEPARATION_DISTANCE = 15, //Specifies the minimum separation distance, in pixels, between the origins of two matches that have unique positions. - IMAQ_MINIMUM_MATCH_SEPARATION_ANGLE = 16, //Specifies the minimum angular difference, in degrees, between two matches that have unique angles. - IMAQ_MINIMUM_MATCH_SEPARATION_SCALE = 17, //Specifies the minimum difference in scale, expressed as a percentage, between two matches that have unique scales. - IMAQ_MAXIMUM_MATCH_OVERLAP = 18, //Specifies whether you want the algorithm to spend less time accurately estimating the location of a match. - IMAQ_ENABLE_COARSE_RESULT = 19, //Specifies whether you want the algorithm to spend less time accurately estimating the location of a match. - IMAQ_ENABLE_CALIBRATION_SUPPORT = 20, //Specifies whether or not the algorithm treat the inspection image as a calibrated image. - IMAQ_ENABLE_CONTRAST_REVERSAL = 21, //Specifies the contrast of the matches to search for. - IMAQ_SEARCH_STRATEGY = 22, //Specifies the aggressiveness of the strategy used to find matches in the image. - IMAQ_REFINEMENT_MATCH_FACTOR = 23, //Specifies the factor applied to the number of matches requested to determine how many matches are refined in the pyramid stage. - IMAQ_SUBPIXEL_MATCH_FACTOR = 24, //Specifies the factor applied to the number for matches requested to determine how many matches are used for the final (subpixel) stage. - IMAQ_MAX_REFINEMENT_ITERATIONS = 25, //Specifies maximum refinement iteration. + IMAQ_CURVE_EXTRACTION_MODE = + 0, // Specifies how the function identifies curves in the image. + IMAQ_CURVE_EDGE_THRSHOLD = 1, // Specifies the minimum contrast an edge pixel + // must have for it to be considered part of a + // curve. + IMAQ_CURVE_EDGE_FILTER = 2, // Specifies the width of the edge filter that + // the function uses to identify curves in the + // image. + IMAQ_MINIMUM_CURVE_LENGTH = 3, // Specifies the length, in pixels, of the + // smallest curve that you want the function + // to identify. + IMAQ_CURVE_ROW_SEARCH_STEP_SIZE = + 4, // Specifies the distance, in the y direction, between the image rows + // that the algorithm inspects for curve seed points. + IMAQ_CURVE_COL_SEARCH_STEP_SIZE = + 5, // Specifies the distance, in the x direction, between the image + // columns that the algorithm inspects for curve seed points. + IMAQ_CURVE_MAX_END_POINT_GAP = + 6, // Specifies the maximum gap, in pixels, between the endpoints of a + // curve that the function identifies as a closed curve. + IMAQ_EXTRACT_CLOSED_CURVES = + 7, // Specifies whether to identify only closed curves in the image. + IMAQ_ENABLE_SUBPIXEL_CURVE_EXTRACTION = + 8, // The function ignores this option. + IMAQ_ENABLE_CORRELATION_SCORE = 9, // Specifies that the function should + // calculate the Correlation Score and + // return it for each match result. + IMAQ_ENABLE_SUBPIXEL_ACCURACY = 10, // Determines whether to return the match + // results with subpixel accuracy. + IMAQ_SUBPIXEL_ITERATIONS = 11, // Specifies the maximum number of incremental + // improvements used to refine matches using + // subpixel information. + IMAQ_SUBPIXEL_TOLERANCE = + 12, // Specifies the maximum amount of change, in pixels, between + // consecutive incremental improvements in the match position before + // the function stops refining the match position. + IMAQ_INITIAL_MATCH_LIST_LENGTH = + 13, // Specifies the maximum size of the match list. + IMAQ_ENABLE_TARGET_TEMPLATE_CURVESCORE = + 14, // Specifies whether the function should calculate the match curve to + // template curve score and return it for each match result. + IMAQ_MINIMUM_MATCH_SEPARATION_DISTANCE = + 15, // Specifies the minimum separation distance, in pixels, between the + // origins of two matches that have unique positions. + IMAQ_MINIMUM_MATCH_SEPARATION_ANGLE = + 16, // Specifies the minimum angular difference, in degrees, between two + // matches that have unique angles. + IMAQ_MINIMUM_MATCH_SEPARATION_SCALE = + 17, // Specifies the minimum difference in scale, expressed as a + // percentage, between two matches that have unique scales. + IMAQ_MAXIMUM_MATCH_OVERLAP = 18, // Specifies whether you want the algorithm + // to spend less time accurately estimating + // the location of a match. + IMAQ_ENABLE_COARSE_RESULT = 19, // Specifies whether you want the algorithm + // to spend less time accurately estimating + // the location of a match. + IMAQ_ENABLE_CALIBRATION_SUPPORT = 20, // Specifies whether or not the + // algorithm treat the inspection image + // as a calibrated image. + IMAQ_ENABLE_CONTRAST_REVERSAL = + 21, // Specifies the contrast of the matches to search for. + IMAQ_SEARCH_STRATEGY = 22, // Specifies the aggressiveness of the strategy + // used to find matches in the image. + IMAQ_REFINEMENT_MATCH_FACTOR = + 23, // Specifies the factor applied to the number of matches requested to + // determine how many matches are refined in the pyramid stage. + IMAQ_SUBPIXEL_MATCH_FACTOR = 24, // Specifies the factor applied to the + // number for matches requested to determine + // how many matches are used for the final + // (subpixel) stage. + IMAQ_MAX_REFINEMENT_ITERATIONS = + 25, // Specifies maximum refinement iteration. } GeometricSetupDataItem; typedef enum DistortionModel_enum { - IMAQ_POLYNOMIAL_MODEL = 0, //Polynomial model. - IMAQ_DIVISION_MODEL = 1, //Division Model. - IMAQ_NO_DISTORTION_MODEL = -1, //Not a distortion model. + IMAQ_POLYNOMIAL_MODEL = 0, // Polynomial model. + IMAQ_DIVISION_MODEL = 1, // Division Model. + IMAQ_NO_DISTORTION_MODEL = -1, // Not a distortion model. } DistortionModel; typedef enum CalibrationThumbnailType_enum { - IMAQ_CAMARA_MODEL_TYPE = 0, //Camara model thumbnail type. - IMAQ_PERSPECTIVE_TYPE = 1, //Perspective thumbnail type. - IMAQ_MICRO_PLANE_TYPE = 2, //Micro Plane thumbnail type. - IMAQ_CALIBRATION_THUMBNAIL_TYPE_SIZE_GUARD = 0xFFFFFFFF + IMAQ_CAMARA_MODEL_TYPE = 0, // Camara model thumbnail type. + IMAQ_PERSPECTIVE_TYPE = 1, // Perspective thumbnail type. + IMAQ_MICRO_PLANE_TYPE = 2, // Micro Plane thumbnail type. + IMAQ_CALIBRATION_THUMBNAIL_TYPE_SIZE_GUARD = 0xFFFFFFFF } CalibrationThumbnailType; typedef enum SettingType_enum { - IMAQ_ROTATION_ANGLE_RANGE = 0, //Set a range for this option to specify the angles at which you expect the Function to find template matches in the inspection image. - IMAQ_SCALE_RANGE = 1, //Set a range for this option to specify the sizes at which you expect the Function to find template matches in the inspection image. - IMAQ_OCCLUSION_RANGE = 2, //Set a range for this option to specify the amount of occlusion you expect for a match in the inspection image. - IMAQ_SETTING_TYPE_SIZE_GUARD = 0xFFFFFFFF + IMAQ_ROTATION_ANGLE_RANGE = 0, // Set a range for this option to specify the + // angles at which you expect the Function to + // find template matches in the inspection + // image. + IMAQ_SCALE_RANGE = 1, // Set a range for this option to specify the sizes at + // which you expect the Function to find template + // matches in the inspection image. + IMAQ_OCCLUSION_RANGE = 2, // Set a range for this option to specify the + // amount of occlusion you expect for a match in + // the inspection image. + IMAQ_SETTING_TYPE_SIZE_GUARD = 0xFFFFFFFF } SettingType; typedef enum SegmentationDistanceLevel_enum { - IMAQ_SEGMENTATION_LEVEL_CONSERVATIVE = 0, //Uses extensive criteria to determine the Maximum Distance. - IMAQ_SEGMENTATION_LEVEL_AGGRESSIVE = 1, //Uses few criteria to determine the Maximum Distance. - IMAQ_SEGMENTATION_LEVEL_SIZE_GUARD = 0xFFFFFFFF + IMAQ_SEGMENTATION_LEVEL_CONSERVATIVE = + 0, // Uses extensive criteria to determine the Maximum Distance. + IMAQ_SEGMENTATION_LEVEL_AGGRESSIVE = + 1, // Uses few criteria to determine the Maximum Distance. + IMAQ_SEGMENTATION_LEVEL_SIZE_GUARD = 0xFFFFFFFF } SegmentationDistanceLevel; typedef enum ExtractContourSelection_enum { - IMAQ_CLOSEST = 0, //Selects the curve closest to the ROI. - IMAQ_LONGEST = 1, //Selects the longest curve. - IMAQ_STRONGEST = 2, //Selects the curve with the highest edge strength averaged from each point on the curve. - IMAQ_EXTRACT_CONTOUR_SELECTION_SIZE_GUARD = 0xFFFFFFFF + IMAQ_CLOSEST = 0, // Selects the curve closest to the ROI. + IMAQ_LONGEST = 1, // Selects the longest curve. + IMAQ_STRONGEST = 2, // Selects the curve with the highest edge strength + // averaged from each point on the curve. + IMAQ_EXTRACT_CONTOUR_SELECTION_SIZE_GUARD = 0xFFFFFFFF } ExtractContourSelection; typedef enum FindTransformMode_enum { - IMAQ_FIND_REFERENCE = 0, //Update both parts of the coordinate system. - IMAQ_UPDATE_TRANSFORM = 1, //Update only the new reference system. - IMAQ_FIND_TRANSFORM_MODE_SIZE_GUARD = 0xFFFFFFFF + IMAQ_FIND_REFERENCE = 0, // Update both parts of the coordinate system. + IMAQ_UPDATE_TRANSFORM = 1, // Update only the new reference system. + IMAQ_FIND_TRANSFORM_MODE_SIZE_GUARD = 0xFFFFFFFF } FindTransformMode; typedef enum ExtractContourDirection_enum { - IMAQ_RECT_LEFT_RIGHT = 0, //Searches the ROI from left to right. - IMAQ_RECT_RIGHT_LEFT = 1, //Searches the ROI from right to left. - IMAQ_RECT_TOP_BOTTOM = 2, //Searches the ROI from top to bottom. - IMAQ_RECT_BOTTOM_TOP = 3, //Searches the ROI from bottom to top. - IMAQ_ANNULUS_INNER_OUTER = 4, //Searches the ROI from the inner radius to the outer radius. - IMAQ_ANNULUS_OUTER_INNER = 5, //Searches the ROI from the outer radius to the inner radius. - IMAQ_ANNULUS_START_STOP = 6, //Searches the ROI from start angle to end angle. - IMAQ_ANNULUS_STOP_START = 7, //Searches the ROI from end angle to start angle. - IMAQ_EXTRACT_CONTOUR_DIRECTION_SIZE_GUARD = 0xFFFFFFFF + IMAQ_RECT_LEFT_RIGHT = 0, // Searches the ROI from left to right. + IMAQ_RECT_RIGHT_LEFT = 1, // Searches the ROI from right to left. + IMAQ_RECT_TOP_BOTTOM = 2, // Searches the ROI from top to bottom. + IMAQ_RECT_BOTTOM_TOP = 3, // Searches the ROI from bottom to top. + IMAQ_ANNULUS_INNER_OUTER = + 4, // Searches the ROI from the inner radius to the outer radius. + IMAQ_ANNULUS_OUTER_INNER = + 5, // Searches the ROI from the outer radius to the inner radius. + IMAQ_ANNULUS_START_STOP = + 6, // Searches the ROI from start angle to end angle. + IMAQ_ANNULUS_STOP_START = + 7, // Searches the ROI from end angle to start angle. + IMAQ_EXTRACT_CONTOUR_DIRECTION_SIZE_GUARD = 0xFFFFFFFF } ExtractContourDirection; typedef enum EdgePolaritySearchMode_enum { - IMAQ_SEARCH_FOR_ALL_EDGES = 0, //Searches for all edges. - IMAQ_SEARCH_FOR_RISING_EDGES = 1, //Searches for rising edges only. - IMAQ_SEARCH_FOR_FALLING_EDGES = 2, //Searches for falling edges only. - IMAQ_EDGE_POLARITY_MODE_SIZE_GUARD = 0xFFFFFFFF + IMAQ_SEARCH_FOR_ALL_EDGES = 0, // Searches for all edges. + IMAQ_SEARCH_FOR_RISING_EDGES = 1, // Searches for rising edges only. + IMAQ_SEARCH_FOR_FALLING_EDGES = 2, // Searches for falling edges only. + IMAQ_EDGE_POLARITY_MODE_SIZE_GUARD = 0xFFFFFFFF } EdgePolaritySearchMode; typedef enum Connectivity_enum { - IMAQ_FOUR_CONNECTED = 0, //Morphological reconstruction is performed in connectivity mode 4. - IMAQ_EIGHT_CONNECTED = 1, //Morphological reconstruction is performed in connectivity mode 8. - IMAQ_CONNECTIVITY_SIZE_GUARD = 0xFFFFFFFF + IMAQ_FOUR_CONNECTED = + 0, // Morphological reconstruction is performed in connectivity mode 4. + IMAQ_EIGHT_CONNECTED = + 1, // Morphological reconstruction is performed in connectivity mode 8. + IMAQ_CONNECTIVITY_SIZE_GUARD = 0xFFFFFFFF } Connectivity; typedef enum MorphologyReconstructOperation_enum { - IMAQ_DILATE_RECONSTRUCT = 0, //Performs Reconstruction by dilation. - IMAQ_ERODE_RECONSTRUCT = 1, //Performs Reconstruction by erosion. - IMAQ_MORPHOLOGY_RECONSTRUCT_OPERATION_SIZE_GUARD = 0xFFFFFFFF + IMAQ_DILATE_RECONSTRUCT = 0, // Performs Reconstruction by dilation. + IMAQ_ERODE_RECONSTRUCT = 1, // Performs Reconstruction by erosion. + IMAQ_MORPHOLOGY_RECONSTRUCT_OPERATION_SIZE_GUARD = 0xFFFFFFFF } MorphologyReconstructOperation; typedef enum WaveletType_enum { - IMAQ_DB02 = 0, - IMAQ_DB03 = 1, - IMAQ_DB04 = 2, //Specifies the Wavelet Type as DB02. - IMAQ_DB05 = 3, - IMAQ_DB06 = 4, - IMAQ_DB07 = 5, - IMAQ_DB08 = 6, - IMAQ_DB09 = 7, - IMAQ_DB10 = 8, - IMAQ_DB11 = 9, - IMAQ_DB12 = 10, - IMAQ_DB13 = 11, - IMAQ_DB14 = 12, - IMAQ_HAAR = 13, - IMAQ_BIOR1_3 = 14, - IMAQ_BIOR1_5 = 15, - IMAQ_BIOR2_2 = 16, - IMAQ_BIOR2_4 = 17, - IMAQ_BIOR2_6 = 18, - IMAQ_BIOR2_8 = 19, - IMAQ_BIOR3_1 = 20, - IMAQ_BIOR3_3 = 21, - IMAQ_BIOR3_5 = 22, - IMAQ_BIOR3_7 = 23, - IMAQ_BIOR3_9 = 24, - IMAQ_BIOR4_4 = 25, - IMAQ_COIF1 = 26, - IMAQ_COIF2 = 27, - IMAQ_COIF3 = 28, - IMAQ_COIF4 = 29, - IMAQ_COIF5 = 30, - IMAQ_SYM2 = 31, - IMAQ_SYM3 = 32, - IMAQ_SYM4 = 33, - IMAQ_SYM5 = 34, - IMAQ_SYM6 = 35, - IMAQ_SYM7 = 36, - IMAQ_SYM8 = 37, - IMAQ_BIOR5_5 = 38, - IMAQ_BIOR6_8 = 39, - IMAQ_WAVE_TYPE_SIZE_GUARD = 0xFFFFFFFF + IMAQ_DB02 = 0, + IMAQ_DB03 = 1, + IMAQ_DB04 = 2, // Specifies the Wavelet Type as DB02. + IMAQ_DB05 = 3, + IMAQ_DB06 = 4, + IMAQ_DB07 = 5, + IMAQ_DB08 = 6, + IMAQ_DB09 = 7, + IMAQ_DB10 = 8, + IMAQ_DB11 = 9, + IMAQ_DB12 = 10, + IMAQ_DB13 = 11, + IMAQ_DB14 = 12, + IMAQ_HAAR = 13, + IMAQ_BIOR1_3 = 14, + IMAQ_BIOR1_5 = 15, + IMAQ_BIOR2_2 = 16, + IMAQ_BIOR2_4 = 17, + IMAQ_BIOR2_6 = 18, + IMAQ_BIOR2_8 = 19, + IMAQ_BIOR3_1 = 20, + IMAQ_BIOR3_3 = 21, + IMAQ_BIOR3_5 = 22, + IMAQ_BIOR3_7 = 23, + IMAQ_BIOR3_9 = 24, + IMAQ_BIOR4_4 = 25, + IMAQ_COIF1 = 26, + IMAQ_COIF2 = 27, + IMAQ_COIF3 = 28, + IMAQ_COIF4 = 29, + IMAQ_COIF5 = 30, + IMAQ_SYM2 = 31, + IMAQ_SYM3 = 32, + IMAQ_SYM4 = 33, + IMAQ_SYM5 = 34, + IMAQ_SYM6 = 35, + IMAQ_SYM7 = 36, + IMAQ_SYM8 = 37, + IMAQ_BIOR5_5 = 38, + IMAQ_BIOR6_8 = 39, + IMAQ_WAVE_TYPE_SIZE_GUARD = 0xFFFFFFFF } WaveletType; typedef enum ParticleClassifierThresholdType_enum { - IMAQ_THRESHOLD_MANUAL = 0, //The classifier performs a manual threshold on the image during preprocessing. - IMAQ_THRESHOLD_AUTO = 1, //The classifier performs an auto threshold on the image during preprocessing. - IMAQ_THRESHOLD_LOCAL = 2, //The classifier performs a local threshold on the image during preprocessing. + IMAQ_THRESHOLD_MANUAL = 0, // The classifier performs a manual threshold on + // the image during preprocessing. + IMAQ_THRESHOLD_AUTO = 1, // The classifier performs an auto threshold on the + // image during preprocessing. + IMAQ_THRESHOLD_LOCAL = 2, // The classifier performs a local threshold on the + // image during preprocessing. } ParticleClassifierThresholdType; typedef enum MeasureParticlesCalibrationMode_enum { - IMAQ_CALIBRATION_MODE_PIXEL = 0, //The function takes only pixel measurements on the particles in the image. - IMAQ_CALIBRATION_MODE_CALIBRATED = 1, //The function takes only calibrated measurements on the particles in the image. - IMAQ_CALIBRATION_MODE_BOTH = 2, //The function takes both pixel and calibrated measurements on the particles in the image. - IMAQ_MEASURE_PARTICLES_CALIBRATION_MODE_SIZE_GUARD = 0xFFFFFFFF + IMAQ_CALIBRATION_MODE_PIXEL = 0, // The function takes only pixel + // measurements on the particles in the + // image. + IMAQ_CALIBRATION_MODE_CALIBRATED = 1, // The function takes only calibrated + // measurements on the particles in the + // image. + IMAQ_CALIBRATION_MODE_BOTH = 2, // The function takes both pixel and + // calibrated measurements on the particles + // in the image. + IMAQ_MEASURE_PARTICLES_CALIBRATION_MODE_SIZE_GUARD = 0xFFFFFFFF } MeasureParticlesCalibrationMode; typedef enum GeometricMatchingSearchStrategy_enum { - IMAQ_GEOMETRIC_MATCHING_CONSERVATIVE = 0, //Instructs the pattern matching algorithm to use the largest possible amount of information from the image at the expense of slowing down the speed of the algorithm. - IMAQ_GEOMETRIC_MATCHING_BALANCED = 1, //Instructs the pattern matching algorithm to balance the amount of information from the image it uses with the speed of the algorithm. - IMAQ_GEOMETRIC_MATCHING_AGGRESSIVE = 2, //Instructs the pattern matching algorithm to use a lower amount of information from the image, which allows the algorithm to run quickly but at the expense of accuracy. - IMAQ_GEOMETRIC_MATCHING_SEARCH_STRATEGY_SIZE_GUARD = 0xFFFFFFFF + IMAQ_GEOMETRIC_MATCHING_CONSERVATIVE = + 0, // Instructs the pattern matching algorithm to use the largest + // possible amount of information from the image at the expense of + // slowing down the speed of the algorithm. + IMAQ_GEOMETRIC_MATCHING_BALANCED = + 1, // Instructs the pattern matching algorithm to balance the amount of + // information from the image it uses with the speed of the algorithm. + IMAQ_GEOMETRIC_MATCHING_AGGRESSIVE = + 2, // Instructs the pattern matching algorithm to use a lower amount of + // information from the image, which allows the algorithm to run + // quickly but at the expense of accuracy. + IMAQ_GEOMETRIC_MATCHING_SEARCH_STRATEGY_SIZE_GUARD = 0xFFFFFFFF } GeometricMatchingSearchStrategy; typedef enum ColorClassificationResolution_enum { - IMAQ_CLASSIFIER_LOW_RESOLUTION = 0, //Low resolution version of the color classifier. - IMAQ_CLASSIFIER_MEDIUM_RESOLUTION = 1, //Medium resolution version of the color classifier. - IMAQ_CLASSIFIER_HIGH_RESOLUTION = 2, //High resolution version of the color classifier. - IMAQ_CLASSIFIER_RESOLUTION_SIZE_GUARD = 0xFFFFFFFF + IMAQ_CLASSIFIER_LOW_RESOLUTION = + 0, // Low resolution version of the color classifier. + IMAQ_CLASSIFIER_MEDIUM_RESOLUTION = + 1, // Medium resolution version of the color classifier. + IMAQ_CLASSIFIER_HIGH_RESOLUTION = + 2, // High resolution version of the color classifier. + IMAQ_CLASSIFIER_RESOLUTION_SIZE_GUARD = 0xFFFFFFFF } ColorClassificationResolution; typedef enum ConnectionConstraintType_enum { - IMAQ_DISTANCE_CONSTRAINT = 0, //Specifies the distance, in pixels, within which the end points of two curves must lie in order to be considered part of a contour. - IMAQ_ANGLE_CONSTRAINT = 1, //Specifies the range, in degrees, within which the difference between the angle of two curves, measured at the end points, must lie in order for the two curves to be considered part of a contour. - IMAQ_CONNECTIVITY_CONSTRAINT = 2, //Specifies the distance, in pixels, within which a line extended from the end point of a curve must pass the end point of another curve in order for the two curves to be considered part of a contour. - IMAQ_GRADIENT_CONSTRAINT = 3, //Specifies the range, in degrees, within which the gradient angles of two curves, measured at the end points, must lie in order for the two curves to be considered part of a contour. - IMAQ_NUM_CONNECTION_CONSTRAINT_TYPES = 4, //. - IMAQ_CONNECTION_CONSTRAINT_SIZE_GUARD = 0xFFFFFFFF + IMAQ_DISTANCE_CONSTRAINT = 0, // Specifies the distance, in pixels, within + // which the end points of two curves must lie + // in order to be considered part of a contour. + IMAQ_ANGLE_CONSTRAINT = + 1, // Specifies the range, in degrees, within which the difference + // between the angle of two curves, measured at the end points, must + // lie in order for the two curves to be considered part of a contour. + IMAQ_CONNECTIVITY_CONSTRAINT = + 2, // Specifies the distance, in pixels, within which a line extended + // from the end point of a curve must pass the end point of another + // curve in order for the two curves to be considered part of a + // contour. + IMAQ_GRADIENT_CONSTRAINT = + 3, // Specifies the range, in degrees, within which the gradient angles + // of two curves, measured at the end points, must lie in order for + // the two curves to be considered part of a contour. + IMAQ_NUM_CONNECTION_CONSTRAINT_TYPES = 4, //. + IMAQ_CONNECTION_CONSTRAINT_SIZE_GUARD = 0xFFFFFFFF } ConnectionConstraintType; typedef enum Barcode2DContrast_enum { - IMAQ_ALL_BARCODE_2D_CONTRASTS = 0, //The function searches for barcodes of each contrast type. - IMAQ_BLACK_ON_WHITE_BARCODE_2D = 1, //The function searches for 2D barcodes containing black data on a white background. - IMAQ_WHITE_ON_BLACK_BARCODE_2D = 2, //The function searches for 2D barcodes containing white data on a black background. - IMAQ_BARCODE_2D_CONTRAST_SIZE_GUARD = 0xFFFFFFFF + IMAQ_ALL_BARCODE_2D_CONTRASTS = + 0, // The function searches for barcodes of each contrast type. + IMAQ_BLACK_ON_WHITE_BARCODE_2D = 1, // The function searches for 2D barcodes + // containing black data on a white + // background. + IMAQ_WHITE_ON_BLACK_BARCODE_2D = 2, // The function searches for 2D barcodes + // containing white data on a black + // background. + IMAQ_BARCODE_2D_CONTRAST_SIZE_GUARD = 0xFFFFFFFF } Barcode2DContrast; typedef enum QRModelType_enum { - IMAQ_QR_MODELTYPE_AUTO_DETECT = 0, //Specifies that the function will auto-detect the type of QR code. - IMAQ_QR_MODELTYPE_MICRO = 1, //Specifies the QR code is of a micro type. - IMAQ_QR_MODELTYPE_MODEL1 = 2, //Specifies the QR code is of a model1 type. - IMAQ_QR_MODELTYPE_MODEL2 = 3, //Specifies the QR code is of a model2 type. - IMAQ_QR_MODEL_TYPE_SIZE_GUARD = 0xFFFFFFFF + IMAQ_QR_MODELTYPE_AUTO_DETECT = + 0, // Specifies that the function will auto-detect the type of QR code. + IMAQ_QR_MODELTYPE_MICRO = 1, // Specifies the QR code is of a micro type. + IMAQ_QR_MODELTYPE_MODEL1 = 2, // Specifies the QR code is of a model1 type. + IMAQ_QR_MODELTYPE_MODEL2 = 3, // Specifies the QR code is of a model2 type. + IMAQ_QR_MODEL_TYPE_SIZE_GUARD = 0xFFFFFFFF } QRModelType; typedef enum WindowBackgroundFillStyle_enum { - IMAQ_FILL_STYLE_SOLID = 0, //Fill the display window with a solid color. - IMAQ_FILL_STYLE_HATCH = 2, //Fill the display window with a pattern defined by WindowBackgroundHatchStyle. - IMAQ_FILL_STYLE_DEFAULT = 3, //Fill the display window with the NI Vision default pattern. - IMAQ_FILL_STYLE_SIZE_GUARD = 0xFFFFFFFF + IMAQ_FILL_STYLE_SOLID = 0, // Fill the display window with a solid color. + IMAQ_FILL_STYLE_HATCH = 2, // Fill the display window with a pattern defined + // by WindowBackgroundHatchStyle. + IMAQ_FILL_STYLE_DEFAULT = + 3, // Fill the display window with the NI Vision default pattern. + IMAQ_FILL_STYLE_SIZE_GUARD = 0xFFFFFFFF } WindowBackgroundFillStyle; typedef enum ExtractionMode_enum { - IMAQ_NORMAL_IMAGE = 0, //Specifies that the function makes no assumptions about the uniformity of objects in the image or the image background. - IMAQ_UNIFORM_REGIONS = 1, //Specifies that the function assumes that either the objects in the image or the image background consists of uniform pixel values. - IMAQ_EXTRACTION_MODE_SIZE_GUARD = 0xFFFFFFFF + IMAQ_NORMAL_IMAGE = 0, // Specifies that the function makes no assumptions + // about the uniformity of objects in the image or the + // image background. + IMAQ_UNIFORM_REGIONS = 1, // Specifies that the function assumes that either + // the objects in the image or the image background + // consists of uniform pixel values. + IMAQ_EXTRACTION_MODE_SIZE_GUARD = 0xFFFFFFFF } ExtractionMode; typedef enum EdgeFilterSize_enum { - IMAQ_FINE = 0, //Specifies that the function uses a fine (narrow) edge filter. - IMAQ_NORMAL = 1, //Specifies that the function uses a normal edge filter. - IMAQ_CONTOUR_TRACING = 2, //Sets the Edge Filter Size to contour tracing, which provides the best results for contour extraction but increases the time required to process the image. - IMAQ_EDGE_FILTER_SIZE_SIZE_GUARD = 0xFFFFFFFF + IMAQ_FINE = + 0, // Specifies that the function uses a fine (narrow) edge filter. + IMAQ_NORMAL = 1, // Specifies that the function uses a normal edge filter. + IMAQ_CONTOUR_TRACING = 2, // Sets the Edge Filter Size to contour tracing, + // which provides the best results for contour + // extraction but increases the time required to + // process the image. + IMAQ_EDGE_FILTER_SIZE_SIZE_GUARD = 0xFFFFFFFF } EdgeFilterSize; typedef enum Barcode2DSearchMode_enum { - IMAQ_SEARCH_MULTIPLE = 0, //The function searches for multiple 2D barcodes. - IMAQ_SEARCH_SINGLE_CONSERVATIVE = 1, //The function searches for 2D barcodes using the same searching algorithm as IMAQ_SEARCH_MULTIPLE but stops searching after locating one valid barcode. - IMAQ_SEARCH_SINGLE_AGGRESSIVE = 2, //The function searches for a single 2D barcode using a method that assumes the barcode occupies a majority of the search region. - IMAQ_BARCODE_2D_SEARCH_MODE_SIZE_GUARD = 0xFFFFFFFF + IMAQ_SEARCH_MULTIPLE = 0, // The function searches for multiple 2D barcodes. + IMAQ_SEARCH_SINGLE_CONSERVATIVE = + 1, // The function searches for 2D barcodes using the same searching + // algorithm as IMAQ_SEARCH_MULTIPLE but stops searching after + // locating one valid barcode. + IMAQ_SEARCH_SINGLE_AGGRESSIVE = + 2, // The function searches for a single 2D barcode using a method that + // assumes the barcode occupies a majority of the search region. + IMAQ_BARCODE_2D_SEARCH_MODE_SIZE_GUARD = 0xFFFFFFFF } Barcode2DSearchMode; typedef enum DataMatrixSubtype_enum { - IMAQ_ALL_DATA_MATRIX_SUBTYPES = 0, //The function searches for Data Matrix barcodes of all subtypes. - IMAQ_DATA_MATRIX_SUBTYPES_ECC_000_ECC_140 = 1, //The function searches for Data Matrix barcodes of subtypes ECC 000, ECC 050, ECC 080, ECC 100 and ECC 140. - IMAQ_DATA_MATRIX_SUBTYPE_ECC_200 = 2, //The function searches for Data Matrix ECC 200 barcodes. - IMAQ_DATA_MATRIX_SUBTYPE_SIZE_GUARD = 0xFFFFFFFF + IMAQ_ALL_DATA_MATRIX_SUBTYPES = + 0, // The function searches for Data Matrix barcodes of all subtypes. + IMAQ_DATA_MATRIX_SUBTYPES_ECC_000_ECC_140 = + 1, // The function searches for Data Matrix barcodes of subtypes ECC 000, + // ECC 050, ECC 080, ECC 100 and ECC 140. + IMAQ_DATA_MATRIX_SUBTYPE_ECC_200 = + 2, // The function searches for Data Matrix ECC 200 barcodes. + IMAQ_DATA_MATRIX_SUBTYPE_SIZE_GUARD = 0xFFFFFFFF } DataMatrixSubtype; typedef enum FeatureType_enum { - IMAQ_NOT_FOUND_FEATURE = 0, //Specifies the feature is not found. - IMAQ_CIRCLE_FEATURE = 1, //Specifies the feature is a circle. - IMAQ_ELLIPSE_FEATURE = 2, //Specifies the feature is an ellipse. - IMAQ_CONST_CURVE_FEATURE = 3, //Specifies the features is a constant curve. - IMAQ_RECTANGLE_FEATURE = 4, //Specifies the feature is a rectangle. - IMAQ_LEG_FEATURE = 5, //Specifies the feature is a leg. - IMAQ_CORNER_FEATURE = 6, //Specifies the feature is a corner. - IMAQ_PARALLEL_LINE_PAIR_FEATURE = 7, //Specifies the feature is a parallel line pair. - IMAQ_PAIR_OF_PARALLEL_LINE_PAIRS_FEATURE = 8, //Specifies the feature is a pair of parallel line pairs. - IMAQ_LINE_FEATURE = 9, //Specifies the feature is a line. - IMAQ_CLOSED_CURVE_FEATURE = 10, //Specifies the feature is a closed curve. - IMAQ_FEATURE_TYPE_SIZE_GUARD = 0xFFFFFFFF + IMAQ_NOT_FOUND_FEATURE = 0, // Specifies the feature is not found. + IMAQ_CIRCLE_FEATURE = 1, // Specifies the feature is a circle. + IMAQ_ELLIPSE_FEATURE = 2, // Specifies the feature is an ellipse. + IMAQ_CONST_CURVE_FEATURE = 3, // Specifies the features is a constant curve. + IMAQ_RECTANGLE_FEATURE = 4, // Specifies the feature is a rectangle. + IMAQ_LEG_FEATURE = 5, // Specifies the feature is a leg. + IMAQ_CORNER_FEATURE = 6, // Specifies the feature is a corner. + IMAQ_PARALLEL_LINE_PAIR_FEATURE = + 7, // Specifies the feature is a parallel line pair. + IMAQ_PAIR_OF_PARALLEL_LINE_PAIRS_FEATURE = + 8, // Specifies the feature is a pair of parallel line pairs. + IMAQ_LINE_FEATURE = 9, // Specifies the feature is a line. + IMAQ_CLOSED_CURVE_FEATURE = 10, // Specifies the feature is a closed curve. + IMAQ_FEATURE_TYPE_SIZE_GUARD = 0xFFFFFFFF } FeatureType; typedef enum Barcode2DCellShape_enum { - IMAQ_SQUARE_CELLS = 0, //The function uses an algorithm for decoding the 2D barcode that works with square data cells. - IMAQ_ROUND_CELLS = 1, //The function uses an algorithm for decoding the 2D barcode that works with round data cells. - IMAQ_BARCODE_2D_CELL_SHAPE_SIZE_GUARD = 0xFFFFFFFF + IMAQ_SQUARE_CELLS = 0, // The function uses an algorithm for decoding the 2D + // barcode that works with square data cells. + IMAQ_ROUND_CELLS = 1, // The function uses an algorithm for decoding the 2D + // barcode that works with round data cells. + IMAQ_BARCODE_2D_CELL_SHAPE_SIZE_GUARD = 0xFFFFFFFF } Barcode2DCellShape; typedef enum LocalThresholdMethod_enum { - IMAQ_NIBLACK = 0, //The function computes thresholds for each pixel based on its local statistics using the Niblack local thresholding algorithm. - IMAQ_BACKGROUND_CORRECTION = 1, //The function performs background correction first to eliminate non-uniform lighting effects, then performs thresholding using the Otsu thresholding algorithm. - IMAQ_LOCAL_THRESHOLD_METHOD_SIZE_GUARD = 0xFFFFFFFF + IMAQ_NIBLACK = 0, // The function computes thresholds for each pixel based on + // its local statistics using the Niblack local + // thresholding algorithm. + IMAQ_BACKGROUND_CORRECTION = + 1, // The function performs background correction first to eliminate + // non-uniform lighting effects, then performs thresholding using the + // Otsu thresholding algorithm. + IMAQ_LOCAL_THRESHOLD_METHOD_SIZE_GUARD = 0xFFFFFFFF } LocalThresholdMethod; typedef enum Barcode2DType_enum { - IMAQ_PDF417 = 0, //The 2D barcode is of type PDF417. - IMAQ_DATA_MATRIX_ECC_000 = 1, //The 2D barcode is of type Data Matrix ECC 000. - IMAQ_DATA_MATRIX_ECC_050 = 2, //The 2D barcode is of type Data Matrix ECC 050. - IMAQ_DATA_MATRIX_ECC_080 = 3, //The 2D barcode is of type Data Matrix ECC 080. - IMAQ_DATA_MATRIX_ECC_100 = 4, //The 2D barcode is of type Data Matrix ECC 100. - IMAQ_DATA_MATRIX_ECC_140 = 5, //The 2D barcode is of type Data Matrix ECC 140. - IMAQ_DATA_MATRIX_ECC_200 = 6, //The 2D barcode is of type Data Matrix ECC 200. - IMAQ_BARCODE_2D_TYPE_SIZE_GUARD = 0xFFFFFFFF + IMAQ_PDF417 = 0, // The 2D barcode is of type PDF417. + IMAQ_DATA_MATRIX_ECC_000 = + 1, // The 2D barcode is of type Data Matrix ECC 000. + IMAQ_DATA_MATRIX_ECC_050 = + 2, // The 2D barcode is of type Data Matrix ECC 050. + IMAQ_DATA_MATRIX_ECC_080 = + 3, // The 2D barcode is of type Data Matrix ECC 080. + IMAQ_DATA_MATRIX_ECC_100 = + 4, // The 2D barcode is of type Data Matrix ECC 100. + IMAQ_DATA_MATRIX_ECC_140 = + 5, // The 2D barcode is of type Data Matrix ECC 140. + IMAQ_DATA_MATRIX_ECC_200 = + 6, // The 2D barcode is of type Data Matrix ECC 200. + IMAQ_BARCODE_2D_TYPE_SIZE_GUARD = 0xFFFFFFFF } Barcode2DType; typedef enum ClassifierEngineType_enum { - IMAQ_ENGINE_NONE = 0, //No engine has been set on this classifier session. - IMAQ_ENGINE_NEAREST_NEIGHBOR = 1, //Nearest neighbor engine. - IMAQ_ENGINE_SUPPORT_VECTOR_MACHINE = 2, - IMAQ_CLASSIFIER_ENGINE_TYPE_SIZE_GUARD = 0xFFFFFFFF + IMAQ_ENGINE_NONE = 0, // No engine has been set on this classifier session. + IMAQ_ENGINE_NEAREST_NEIGHBOR = 1, // Nearest neighbor engine. + IMAQ_ENGINE_SUPPORT_VECTOR_MACHINE = 2, + IMAQ_CLASSIFIER_ENGINE_TYPE_SIZE_GUARD = 0xFFFFFFFF } ClassifierEngineType; typedef enum ClassifierType_enum { - IMAQ_CLASSIFIER_CUSTOM = 0, //The classifier session classifies vectors of doubles. - IMAQ_CLASSIFIER_PARTICLE = 1, //The classifier session classifies particles in binary images. - IMAQ_CLASSIFIER_COLOR = 2, //The classifier session classifies an image based on its color. - IMAQ_CLASSIFIER_TEXTURE = 3, //The classifier session classifies an image based on its texture. - IMAQ_CLASSIFIER_TYPE_SIZE_GUARD = 0xFFFFFFFF + IMAQ_CLASSIFIER_CUSTOM = + 0, // The classifier session classifies vectors of doubles. + IMAQ_CLASSIFIER_PARTICLE = + 1, // The classifier session classifies particles in binary images. + IMAQ_CLASSIFIER_COLOR = + 2, // The classifier session classifies an image based on its color. + IMAQ_CLASSIFIER_TEXTURE = + 3, // The classifier session classifies an image based on its texture. + IMAQ_CLASSIFIER_TYPE_SIZE_GUARD = 0xFFFFFFFF } ClassifierType; typedef enum ParticleType_enum { - IMAQ_PARTICLE_BRIGHT = 0, //Bright particles. - IMAQ_PARTICLE_DARK = 1, //Dark particles. - IMAQ_PARTICLE_TYPE_SIZE_GUARD = 0xFFFFFFFF + IMAQ_PARTICLE_BRIGHT = 0, // Bright particles. + IMAQ_PARTICLE_DARK = 1, // Dark particles. + IMAQ_PARTICLE_TYPE_SIZE_GUARD = 0xFFFFFFFF } ParticleType; typedef enum VisionInfoType2_enum { - IMAQ_VISIONINFO_CALIBRATION = 0x01, //Used to indicate interaction with the Calibration information in an image. - IMAQ_VISIONINFO_OVERLAY = 0x02, //Used to indicate interaction with the Overlay information in an image. - IMAQ_VISIONINFO_GRAYTEMPLATE = 0x04, //Used to indicate interaction with the grayscale template information in an image. - IMAQ_VISIONINFO_COLORTEMPLATE = 0x08, //Used to indicate interaction with the color template information in an image. - IMAQ_VISIONINFO_GEOMETRICTEMPLATE = 0x10, //Used to indicate interaction with the geometric template information in an image. - IMAQ_VISIONINFO_CUSTOMDATA = 0x20, //Used to indicate interaction with the binary or text Custom Data in an image. - IMAQ_VISIONINFO_GOLDENTEMPLATE = 0x40, //Used to indicate interaction with the golden template information in an image. - IMAQ_VISIONINFO_GEOMETRICTEMPLATE2 = 0x80, //Used to indicate interaction with the geometric template 2 information in an image. - IMAQ_VISIONINFO_ALL = 0xFFFFFFFF, //Removes, checks for, or indicates the presence of all types of extra information in an image. + IMAQ_VISIONINFO_CALIBRATION = 0x01, // Used to indicate interaction with the + // Calibration information in an image. + IMAQ_VISIONINFO_OVERLAY = 0x02, // Used to indicate interaction with the + // Overlay information in an image. + IMAQ_VISIONINFO_GRAYTEMPLATE = 0x04, // Used to indicate interaction with the + // grayscale template information in an + // image. + IMAQ_VISIONINFO_COLORTEMPLATE = 0x08, // Used to indicate interaction with + // the color template information in an + // image. + IMAQ_VISIONINFO_GEOMETRICTEMPLATE = 0x10, // Used to indicate interaction + // with the geometric template + // information in an image. + IMAQ_VISIONINFO_CUSTOMDATA = 0x20, // Used to indicate interaction with the + // binary or text Custom Data in an image. + IMAQ_VISIONINFO_GOLDENTEMPLATE = 0x40, // Used to indicate interaction with + // the golden template information in + // an image. + IMAQ_VISIONINFO_GEOMETRICTEMPLATE2 = 0x80, // Used to indicate interaction + // with the geometric template 2 + // information in an image. + IMAQ_VISIONINFO_ALL = 0xFFFFFFFF, // Removes, checks for, or indicates the + // presence of all types of extra + // information in an image. } VisionInfoType2; typedef enum ReadClassifierFileMode_enum { - IMAQ_CLASSIFIER_READ_ALL = 0, //Read all information from the classifier file. - IMAQ_CLASSIFIER_READ_SAMPLES = 1, //Read only the samples from the classifier file. - IMAQ_CLASSIFIER_READ_PROPERTIES = 2, //Read only the properties from the classifier file. - IMAQ_READ_CLASSIFIER_FILE_MODES_SIZE_GUARD = 0xFFFFFFFF + IMAQ_CLASSIFIER_READ_ALL = + 0, // Read all information from the classifier file. + IMAQ_CLASSIFIER_READ_SAMPLES = + 1, // Read only the samples from the classifier file. + IMAQ_CLASSIFIER_READ_PROPERTIES = + 2, // Read only the properties from the classifier file. + IMAQ_READ_CLASSIFIER_FILE_MODES_SIZE_GUARD = 0xFFFFFFFF } ReadClassifierFileMode; typedef enum WriteClassifierFileMode_enum { - IMAQ_CLASSIFIER_WRITE_ALL = 0, //Writes all information to the classifier file. - IMAQ_CLASSIFIER_WRITE_CLASSIFY_ONLY = 1, //Write only the information needed to classify to the classifier file. - IMAQ_WRITE_CLASSIFIER_FILE_MODES_SIZE_GUARD = 0xFFFFFFFF + IMAQ_CLASSIFIER_WRITE_ALL = + 0, // Writes all information to the classifier file. + IMAQ_CLASSIFIER_WRITE_CLASSIFY_ONLY = 1, // Write only the information needed + // to classify to the classifier + // file. + IMAQ_WRITE_CLASSIFIER_FILE_MODES_SIZE_GUARD = 0xFFFFFFFF } WriteClassifierFileMode; typedef enum Barcode2DShape_enum { - IMAQ_SQUARE_BARCODE_2D = 0, //The function searches for square 2D barcodes. - IMAQ_RECTANGULAR_BARCODE_2D = 1, //The function searches for rectangular 2D barcodes. - IMAQ_BARCODE_2D_SHAPE_SIZE_GUARD = 0xFFFFFFFF + IMAQ_SQUARE_BARCODE_2D = 0, // The function searches for square 2D barcodes. + IMAQ_RECTANGULAR_BARCODE_2D = + 1, // The function searches for rectangular 2D barcodes. + IMAQ_BARCODE_2D_SHAPE_SIZE_GUARD = 0xFFFFFFFF } Barcode2DShape; typedef enum DataMatrixRotationMode_enum { - IMAQ_UNLIMITED_ROTATION = 0, //The function allows for unlimited rotation. - IMAQ_0_DEGREES = 1, //The function allows for between -5 and 5 degrees of rotation. - IMAQ_90_DEGREES = 2, //The function allows for between 85 and 95 degrees of rotation. - IMAQ_180_DEGREES = 3, //The function allows for between 175 and 185 degrees of rotation. - IMAQ_270_DEGREES = 4, //The function allows for between 265 and 275 degrees of rotation. - IMAQ_DATA_MATRIX_ROTATION_MODE_SIZE_GUARD = 0xFFFFFFFF + IMAQ_UNLIMITED_ROTATION = 0, // The function allows for unlimited rotation. + IMAQ_0_DEGREES = + 1, // The function allows for between -5 and 5 degrees of rotation. + IMAQ_90_DEGREES = + 2, // The function allows for between 85 and 95 degrees of rotation. + IMAQ_180_DEGREES = + 3, // The function allows for between 175 and 185 degrees of rotation. + IMAQ_270_DEGREES = + 4, // The function allows for between 265 and 275 degrees of rotation. + IMAQ_DATA_MATRIX_ROTATION_MODE_SIZE_GUARD = 0xFFFFFFFF } DataMatrixRotationMode; typedef enum AIMGrade_enum { - IMAQ_AIM_GRADE_F = 0, //The Data Matrix barcode received a grade of F. - IMAQ_AIM_GRADE_D = 1, //The Data Matrix barcode received a grade of D. - IMAQ_AIM_GRADE_C = 2, //The Data Matrix barcode received a grade of C. - IMAQ_AIM_GRADE_B = 3, //The Data Matrix barcode received a grade of B. - IMAQ_AIM_GRADE_A = 4, //The Data Matrix barcode received a grade of A. - IMAQ_DATA_MATRIX_AIM_GRADE_SIZE_GUARD = 0xFFFFFFFF + IMAQ_AIM_GRADE_F = 0, // The Data Matrix barcode received a grade of F. + IMAQ_AIM_GRADE_D = 1, // The Data Matrix barcode received a grade of D. + IMAQ_AIM_GRADE_C = 2, // The Data Matrix barcode received a grade of C. + IMAQ_AIM_GRADE_B = 3, // The Data Matrix barcode received a grade of B. + IMAQ_AIM_GRADE_A = 4, // The Data Matrix barcode received a grade of A. + IMAQ_DATA_MATRIX_AIM_GRADE_SIZE_GUARD = 0xFFFFFFFF } AIMGrade; typedef enum DataMatrixCellFillMode_enum { - IMAQ_AUTO_DETECT_CELL_FILL_MODE = -2, //Sets the function to determine the Data Matrix barcode cell fill percentage automatically. - IMAQ_LOW_FILL = 0, //Sets the function to read Data Matrix barcodes with a cell fill percentage of less than 30 percent. - IMAQ_NORMAL_FILL = 1, //Sets the function to read Data Matrix barcodes with a cell fill percentage greater than or equal to 30 percent. - IMAQ_DATA_MATRIX_CELL_FILL_MODE_SIZE_GUARD = 0xFFFFFFFF + IMAQ_AUTO_DETECT_CELL_FILL_MODE = -2, // Sets the function to determine the + // Data Matrix barcode cell fill + // percentage automatically. + IMAQ_LOW_FILL = 0, // Sets the function to read Data Matrix barcodes with a + // cell fill percentage of less than 30 percent. + IMAQ_NORMAL_FILL = 1, // Sets the function to read Data Matrix barcodes with + // a cell fill percentage greater than or equal to 30 + // percent. + IMAQ_DATA_MATRIX_CELL_FILL_MODE_SIZE_GUARD = 0xFFFFFFFF } DataMatrixCellFillMode; typedef enum DataMatrixDemodulationMode_enum { - IMAQ_AUTO_DETECT_DEMODULATION_MODE = -2, //The function will try each demodulation mode and use the one which decodes the Data Matrix barcode within the fewest iterations and utilizing the least amount of error correction. - IMAQ_HISTOGRAM = 0, //The function uses a histogram of all of the Data Matrix cells to calculate a threshold. - IMAQ_LOCAL_CONTRAST = 1, //The function examines each of the cell's neighbors to determine if the cell is on or off. - IMAQ_COMBINED = 2, //The function uses the histogram of the Data Matrix barcode to calculate a threshold. - IMAQ_ALL_DEMODULATION_MODES = 3, //The function tries IMAQ_HISTOGRAM, then IMAQ_LOCAL_CONTRAST and then IMAQ_COMBINATION, stopping once one mode is successful. - IMAQ_DATA_MATRIX_DEMODULATION_MODE_SIZE_GUARD = 0xFFFFFFFF + IMAQ_AUTO_DETECT_DEMODULATION_MODE = + -2, // The function will try each demodulation mode and use the one which + // decodes the Data Matrix barcode within the fewest iterations and + // utilizing the least amount of error correction. + IMAQ_HISTOGRAM = 0, // The function uses a histogram of all of the Data + // Matrix cells to calculate a threshold. + IMAQ_LOCAL_CONTRAST = 1, // The function examines each of the cell's + // neighbors to determine if the cell is on or off. + IMAQ_COMBINED = 2, // The function uses the histogram of the Data Matrix + // barcode to calculate a threshold. + IMAQ_ALL_DEMODULATION_MODES = + 3, // The function tries IMAQ_HISTOGRAM, then IMAQ_LOCAL_CONTRAST and + // then IMAQ_COMBINATION, stopping once one mode is successful. + IMAQ_DATA_MATRIX_DEMODULATION_MODE_SIZE_GUARD = 0xFFFFFFFF } DataMatrixDemodulationMode; typedef enum DataMatrixECC_enum { - IMAQ_AUTO_DETECT_ECC = -2, //Sets the function to determine the Data Matrix barcode ECC automatically. - IMAQ_ECC_000 = 0, //Sets the function to read Data Matrix barcodes of ECC 000 only. - IMAQ_ECC_050 = 50, //Sets the function to read Data Matrix barcodes of ECC 050 only. - IMAQ_ECC_080 = 80, //Sets the function to read Data Matrix barcodes of ECC 080 only. - IMAQ_ECC_100 = 100, //Sets the function to read Data Matrix barcodes of ECC 100 only. - IMAQ_ECC_140 = 140, //Sets the function to read Data Matrix barcodes of ECC 140 only. - IMAQ_ECC_000_140 = 190, //Sets the function to read Data Matrix barcodes of ECC 000, ECC 050, ECC 080, ECC 100, and ECC 140 only. - IMAQ_ECC_200 = 200, //Sets the function to read Data Matrix barcodes of ECC 200 only. - IMAQ_DATA_MATRIX_ECC_SIZE_GUARD = 0xFFFFFFFF + IMAQ_AUTO_DETECT_ECC = -2, // Sets the function to determine the Data Matrix + // barcode ECC automatically. + IMAQ_ECC_000 = + 0, // Sets the function to read Data Matrix barcodes of ECC 000 only. + IMAQ_ECC_050 = + 50, // Sets the function to read Data Matrix barcodes of ECC 050 only. + IMAQ_ECC_080 = + 80, // Sets the function to read Data Matrix barcodes of ECC 080 only. + IMAQ_ECC_100 = + 100, // Sets the function to read Data Matrix barcodes of ECC 100 only. + IMAQ_ECC_140 = + 140, // Sets the function to read Data Matrix barcodes of ECC 140 only. + IMAQ_ECC_000_140 = 190, // Sets the function to read Data Matrix barcodes of + // ECC 000, ECC 050, ECC 080, ECC 100, and ECC 140 + // only. + IMAQ_ECC_200 = + 200, // Sets the function to read Data Matrix barcodes of ECC 200 only. + IMAQ_DATA_MATRIX_ECC_SIZE_GUARD = 0xFFFFFFFF } DataMatrixECC; typedef enum DataMatrixPolarity_enum { - IMAQ_AUTO_DETECT_POLARITY = -2, //Sets the function to determine the Data Matrix barcode polarity automatically. - IMAQ_BLACK_DATA_ON_WHITE_BACKGROUND = 0, //Sets the function to read Data Matrix barcodes with dark data on a bright background. - IMAQ_WHITE_DATA_ON_BLACK_BACKGROUND = 1, //Sets the function to read Data Matrix barcodes with bright data on a dark background. - IMAQ_DATA_MATRIX_POLARITY_SIZE_GUARD = 0xFFFFFFFF + IMAQ_AUTO_DETECT_POLARITY = -2, // Sets the function to determine the Data + // Matrix barcode polarity automatically. + IMAQ_BLACK_DATA_ON_WHITE_BACKGROUND = 0, // Sets the function to read Data + // Matrix barcodes with dark data on + // a bright background. + IMAQ_WHITE_DATA_ON_BLACK_BACKGROUND = 1, // Sets the function to read Data + // Matrix barcodes with bright data + // on a dark background. + IMAQ_DATA_MATRIX_POLARITY_SIZE_GUARD = 0xFFFFFFFF } DataMatrixPolarity; typedef enum DataMatrixCellFilterMode_enum { - IMAQ_AUTO_DETECT_CELL_FILTER_MODE = -2, //The function will try all filter modes and uses the one that decodes the Data Matrix barcode within the fewest iterations and utilizing the least amount of error correction. - IMAQ_AVERAGE_FILTER = 0, //The function sets the pixel value for the cell to the average of the sampled pixels. - IMAQ_MEDIAN_FILTER = 1, //The function sets the pixel value for the cell to the median of the sampled pixels. - IMAQ_CENTRAL_AVERAGE_FILTER = 2, //The function sets the pixel value for the cell to the average of the pixels in the center of the cell sample. - IMAQ_HIGH_AVERAGE_FILTER = 3, //The function sets the pixel value for the cell to the average value of the half of the sampled pixels with the highest pixel values. - IMAQ_LOW_AVERAGE_FILTER = 4, //The function sets the pixel value for the cell to the average value of the half of the sampled pixels with the lowest pixel values. - IMAQ_VERY_HIGH_AVERAGE_FILTER = 5, //The function sets the pixel value for the cell to the average value of the ninth of the sampled pixels with the highest pixel values. - IMAQ_VERY_LOW_AVERAGE_FILTER = 6, //The function sets the pixel value for the cell to the average value of the ninth of the sampled pixels with the lowest pixel values. - IMAQ_ALL_CELL_FILTERS = 8, //The function tries each filter mode, starting with IMAQ_AVERAGE_FILTER and ending with IMAQ_VERY_LOW_AVERAGE_FILTER, stopping once a filter mode decodes correctly. - IMAQ_DATA_MATRIX_CELL_FILTER_MODE_SIZE_GUARD = 0xFFFFFFFF + IMAQ_AUTO_DETECT_CELL_FILTER_MODE = + -2, // The function will try all filter modes and uses the one that + // decodes the Data Matrix barcode within the fewest iterations and + // utilizing the least amount of error correction. + IMAQ_AVERAGE_FILTER = 0, // The function sets the pixel value for the cell to + // the average of the sampled pixels. + IMAQ_MEDIAN_FILTER = 1, // The function sets the pixel value for the cell to + // the median of the sampled pixels. + IMAQ_CENTRAL_AVERAGE_FILTER = 2, // The function sets the pixel value for the + // cell to the average of the pixels in the + // center of the cell sample. + IMAQ_HIGH_AVERAGE_FILTER = + 3, // The function sets the pixel value for the cell to the average value + // of the half of the sampled pixels with the highest pixel values. + IMAQ_LOW_AVERAGE_FILTER = 4, // The function sets the pixel value for the + // cell to the average value of the half of the + // sampled pixels with the lowest pixel values. + IMAQ_VERY_HIGH_AVERAGE_FILTER = + 5, // The function sets the pixel value for the cell to the average value + // of the ninth of the sampled pixels with the highest pixel values. + IMAQ_VERY_LOW_AVERAGE_FILTER = + 6, // The function sets the pixel value for the cell to the average value + // of the ninth of the sampled pixels with the lowest pixel values. + IMAQ_ALL_CELL_FILTERS = 8, // The function tries each filter mode, starting + // with IMAQ_AVERAGE_FILTER and ending with + // IMAQ_VERY_LOW_AVERAGE_FILTER, stopping once a + // filter mode decodes correctly. + IMAQ_DATA_MATRIX_CELL_FILTER_MODE_SIZE_GUARD = 0xFFFFFFFF } DataMatrixCellFilterMode; typedef enum WindowBackgroundHatchStyle_enum { - IMAQ_HATCH_STYLE_HORIZONTAL = 0, //The background of the display window will be horizontal bars. - IMAQ_HATCH_STYLE_VERTICAL = 1, //The background of the display window will be vertical bars. - IMAQ_HATCH_STYLE_FORWARD_DIAGONAL = 2, //The background of the display window will be diagonal bars. - IMAQ_HATCH_STYLE_BACKWARD_DIAGONAL = 3, //The background of the display window will be diagonal bars. - IMAQ_HATCH_STYLE_CROSS = 4, //The background of the display window will be intersecting horizontal and vertical bars. - IMAQ_HATCH_STYLE_CROSS_HATCH = 5, //The background of the display window will be intersecting forward and backward diagonal bars. - IMAQ_HATCH_STYLE_SIZE_GUARD = 0xFFFFFFFF + IMAQ_HATCH_STYLE_HORIZONTAL = + 0, // The background of the display window will be horizontal bars. + IMAQ_HATCH_STYLE_VERTICAL = + 1, // The background of the display window will be vertical bars. + IMAQ_HATCH_STYLE_FORWARD_DIAGONAL = + 2, // The background of the display window will be diagonal bars. + IMAQ_HATCH_STYLE_BACKWARD_DIAGONAL = + 3, // The background of the display window will be diagonal bars. + IMAQ_HATCH_STYLE_CROSS = 4, // The background of the display window will be + // intersecting horizontal and vertical bars. + IMAQ_HATCH_STYLE_CROSS_HATCH = 5, // The background of the display window + // will be intersecting forward and + // backward diagonal bars. + IMAQ_HATCH_STYLE_SIZE_GUARD = 0xFFFFFFFF } WindowBackgroundHatchStyle; typedef enum DataMatrixMirrorMode_enum { - IMAQ_AUTO_DETECT_MIRROR = -2, //Specifies that the function should determine if the Data Matrix barcode is mirrored. - IMAQ_APPEARS_NORMAL = 0, //Specifies that the function should expect the Data Matrix barcode to appear normal. - IMAQ_APPEARS_MIRRORED = 1, //Specifies that the function should expect the Data Matrix barcode to appear mirrored. - IMAQ_DATA_MATRIX_MIRROR_MODE_SIZE_GUARD = 0xFFFFFFFF + IMAQ_AUTO_DETECT_MIRROR = -2, // Specifies that the function should determine + // if the Data Matrix barcode is mirrored. + IMAQ_APPEARS_NORMAL = 0, // Specifies that the function should expect the + // Data Matrix barcode to appear normal. + IMAQ_APPEARS_MIRRORED = 1, // Specifies that the function should expect the + // Data Matrix barcode to appear mirrored. + IMAQ_DATA_MATRIX_MIRROR_MODE_SIZE_GUARD = 0xFFFFFFFF } DataMatrixMirrorMode; typedef enum CalibrationMode2_enum { - IMAQ_PERSPECTIVE_MODE = 0, //Functions correct for distortion caused by the camera's perspective. - IMAQ_MICROPLANE_MODE = 1, //Functions correct for distortion caused by the camera's lens. - IMAQ_SIMPLE_CALIBRATION_MODE = 2, //Functions do not correct for distortion. - IMAQ_CORRECTED_IMAGE_MODE = 3, //The image is already corrected. - IMAQ_NO_CALIBRATION_MODE = 4, //Image with No calibration. - IMAQ_CALIBRATION_MODE2_SIZE_GUARD = 0xFFFFFFFF + IMAQ_PERSPECTIVE_MODE = 0, // Functions correct for distortion caused by the + // camera's perspective. + IMAQ_MICROPLANE_MODE = + 1, // Functions correct for distortion caused by the camera's lens. + IMAQ_SIMPLE_CALIBRATION_MODE = 2, // Functions do not correct for distortion. + IMAQ_CORRECTED_IMAGE_MODE = 3, // The image is already corrected. + IMAQ_NO_CALIBRATION_MODE = 4, // Image with No calibration. + IMAQ_CALIBRATION_MODE2_SIZE_GUARD = 0xFFFFFFFF } CalibrationMode2; typedef enum DataMatrixGradingMode_enum { - IMAQ_NO_GRADING = 0, //The function does not make any preparatory calculations. - IMAQ_PREPARE_FOR_AIM = 1, //The function prepares the image for grading using the AIM Print Quality metrics. - IMAQ_DATA_MATRIX_GRADING_MODE_SIZE_GUARD = 0xFFFFFFFF + IMAQ_NO_GRADING = + 0, // The function does not make any preparatory calculations. + IMAQ_PREPARE_FOR_AIM = 1, // The function prepares the image for grading + // using the AIM Print Quality metrics. + IMAQ_DATA_MATRIX_GRADING_MODE_SIZE_GUARD = 0xFFFFFFFF } DataMatrixGradingMode; typedef enum WaveletTransformMode_enum { - IMAQ_WAVELET_TRANSFORM_INTEGER = 0, //Uses a 5-3 reversible integer transform. - IMAQ_WAVELET_TRANSFORM_FLOATING_POINT = 1, //Performs a 9-7 irreversible floating-point transform. - IMAQ_WAVELET_TRANSFORM_MODE_SIZE_GUARD = 0xFFFFFFFF + IMAQ_WAVELET_TRANSFORM_INTEGER = + 0, // Uses a 5-3 reversible integer transform. + IMAQ_WAVELET_TRANSFORM_FLOATING_POINT = + 1, // Performs a 9-7 irreversible floating-point transform. + IMAQ_WAVELET_TRANSFORM_MODE_SIZE_GUARD = 0xFFFFFFFF } WaveletTransformMode; typedef enum NormalizationMethod_enum { - IMAQ_NORMALIZATION_NONE = 0, //No normalization. - IMAQ_NORMALIZATION_HISTOGRAM_MATCHING = 1, //Adjust image so its histogram is similar to the golden template's histogram. - IMAQ_NORMALIZATION_AVERAGE_MATCHING = 2, //Adjust image so its mean pixel value equals the golden template's mean pixel value. - IMAQ_NORMALIZATION_SIZE_GUARD = 0xFFFFFFFF + IMAQ_NORMALIZATION_NONE = 0, // No normalization. + IMAQ_NORMALIZATION_HISTOGRAM_MATCHING = 1, // Adjust image so its histogram + // is similar to the golden + // template's histogram. + IMAQ_NORMALIZATION_AVERAGE_MATCHING = 2, // Adjust image so its mean pixel + // value equals the golden + // template's mean pixel value. + IMAQ_NORMALIZATION_SIZE_GUARD = 0xFFFFFFFF } NormalizationMethod; typedef enum RegistrationMethod_enum { - IMAQ_REGISTRATION_NONE = 0, //No registration. - IMAQ_REGISTRATION_PERSPECTIVE = 1, //Adjust image to correct for minor variations in alignment or perspective. - IMAQ_REGISTRATION_SIZE_GUARD = 0xFFFFFFFF + IMAQ_REGISTRATION_NONE = 0, // No registration. + IMAQ_REGISTRATION_PERSPECTIVE = 1, // Adjust image to correct for minor + // variations in alignment or perspective. + IMAQ_REGISTRATION_SIZE_GUARD = 0xFFFFFFFF } RegistrationMethod; typedef enum LinearAveragesMode_enum { - IMAQ_COLUMN_AVERAGES = 1, //Specifies that the function calculates the mean pixel value of each column. - IMAQ_ROW_AVERAGES = 2, //Specifies that the function calculates the mean pixel value of each row. - IMAQ_RISING_DIAGONAL_AVERAGES = 4, //Specifies that the function calculates the mean pixel value of each diagonal running from the lower left to the upper right of the inspected area of the image. - IMAQ_FALLING_DIAGONAL_AVERAGES = 8, //Specifies that the function calculates the mean pixel value of each diagonal running from the upper left to the lower right of the inspected area of the image. - IMAQ_ALL_LINEAR_AVERAGES = 15, //Specifies that the function calculates all four linear mean pixel values. - IMAQ_LINEAR_AVERAGES_MODE_SIZE_GUARD = 0xFFFFFFFF + IMAQ_COLUMN_AVERAGES = 1, // Specifies that the function calculates the mean + // pixel value of each column. + IMAQ_ROW_AVERAGES = 2, // Specifies that the function calculates the mean + // pixel value of each row. + IMAQ_RISING_DIAGONAL_AVERAGES = + 4, // Specifies that the function calculates the mean pixel value of each + // diagonal running from the lower left to the upper right of the + // inspected area of the image. + IMAQ_FALLING_DIAGONAL_AVERAGES = + 8, // Specifies that the function calculates the mean pixel value of each + // diagonal running from the upper left to the lower right of the + // inspected area of the image. + IMAQ_ALL_LINEAR_AVERAGES = 15, // Specifies that the function calculates all + // four linear mean pixel values. + IMAQ_LINEAR_AVERAGES_MODE_SIZE_GUARD = 0xFFFFFFFF } LinearAveragesMode; typedef enum CompressionType_enum { - IMAQ_COMPRESSION_NONE = 0, //Specifies that the function should not compress the image. - IMAQ_COMPRESSION_JPEG = 1, //Specifies that the function should use lossy JPEG compression on the image. - IMAQ_COMPRESSION_PACKED_BINARY = 2, //Specifies that the function should use lossless binary packing on the image. - IMAQ_COMPRESSION_TYPE_SIZE_GUARD = 0xFFFFFFFF + IMAQ_COMPRESSION_NONE = + 0, // Specifies that the function should not compress the image. + IMAQ_COMPRESSION_JPEG = 1, // Specifies that the function should use lossy + // JPEG compression on the image. + IMAQ_COMPRESSION_PACKED_BINARY = 2, // Specifies that the function should use + // lossless binary packing on the image. + IMAQ_COMPRESSION_TYPE_SIZE_GUARD = 0xFFFFFFFF } CompressionType; typedef enum FlattenType_enum { - IMAQ_FLATTEN_IMAGE = 0, //Flattens just the image data. - IMAQ_FLATTEN_IMAGE_AND_VISION_INFO = 1, //Flattens the image data and any Vision information associated with the image. - IMAQ_FLATTEN_TYPE_SIZE_GUARD = 0xFFFFFFFF + IMAQ_FLATTEN_IMAGE = 0, // Flattens just the image data. + IMAQ_FLATTEN_IMAGE_AND_VISION_INFO = 1, // Flattens the image data and any + // Vision information associated with + // the image. + IMAQ_FLATTEN_TYPE_SIZE_GUARD = 0xFFFFFFFF } FlattenType; typedef enum DataMatrixCellSampleSize_enum { - IMAQ_AUTO_DETECT_CELL_SAMPLE_SIZE = -2, //The function will try each sample size and use the one which decodes the Data Matrix barcode within the fewest iterations and utilizing the least amount of error correction. - IMAQ_1x1 = 1, //The function will use a 1x1 sized sample from each cell. - IMAQ_2x2 = 2, //The function will use a 2x2 sized sample from each cell. - IMAQ_3x3 = 3, //The function will use a 3x3 sized sample from each cell. - IMAQ_4x4 = 4, //The function will use a 4x4 sized sample from each cell. - IMAQ_5x5 = 5, //The function will use a 5x5 sized sample from each cell. - IMAQ_6x6 = 6, //The function will use a 6x6 sized sample from each cell. - IMAQ_7x7 = 7, //The function will use a 7x7 sized sample from each cell. - IMAQ_DATA_MATRIX_CELL_SAMPLE_SIZE_SIZE_GUARD = 0xFFFFFFFF + IMAQ_AUTO_DETECT_CELL_SAMPLE_SIZE = + -2, // The function will try each sample size and use the one which + // decodes the Data Matrix barcode within the fewest iterations and + // utilizing the least amount of error correction. + IMAQ_1x1 = 1, // The function will use a 1x1 sized sample from each cell. + IMAQ_2x2 = 2, // The function will use a 2x2 sized sample from each cell. + IMAQ_3x3 = 3, // The function will use a 3x3 sized sample from each cell. + IMAQ_4x4 = 4, // The function will use a 4x4 sized sample from each cell. + IMAQ_5x5 = 5, // The function will use a 5x5 sized sample from each cell. + IMAQ_6x6 = 6, // The function will use a 6x6 sized sample from each cell. + IMAQ_7x7 = 7, // The function will use a 7x7 sized sample from each cell. + IMAQ_DATA_MATRIX_CELL_SAMPLE_SIZE_SIZE_GUARD = 0xFFFFFFFF } DataMatrixCellSampleSize; - //============================================================================ // Forward Declare Data Structures //============================================================================ @@ -2227,7 +3861,7 @@ typedef struct ClassifierSession_struct ClassifierSession; typedef struct MultipleGeometricPattern_struct MultipleGeometricPattern; typedef int ContourID; typedef unsigned long SESSION_ID; -typedef int AVISession; +typedef int AVISession; typedef char* FilterName; typedef char String255[256]; typedef struct CharSet_struct CharSet; @@ -2270,10 +3904,12 @@ typedef struct PartialCircle_struct PartialCircle; typedef struct PartialEllipse_struct PartialEllipse; typedef struct SetupMatchPatternData_struct SetupMatchPatternData; typedef struct RangeSettingDouble_struct RangeSettingDouble; -typedef struct GeometricAdvancedSetupDataOption_struct GeometricAdvancedSetupDataOption; +typedef struct GeometricAdvancedSetupDataOption_struct + GeometricAdvancedSetupDataOption; typedef struct ContourInfoReport_struct ContourInfoReport; typedef struct ROILabel_struct ROILabel; -typedef struct SupervisedColorSegmentationReport_struct SupervisedColorSegmentationReport; +typedef struct SupervisedColorSegmentationReport_struct + SupervisedColorSegmentationReport; typedef struct LabelToROIReport_struct LabelToROIReport; typedef struct ColorSegmenationOptions_struct ColorSegmenationOptions; typedef struct ClassifiedCurve_struct ClassifiedCurve; @@ -2285,7 +3921,8 @@ typedef struct ComputeDistancesReport_struct ComputeDistancesReport; typedef struct MatchMode_struct MatchMode; typedef struct ClassifiedDisparity_struct ClassifiedDisparity; typedef struct ClassifyDistancesReport_struct ClassifyDistancesReport; -typedef struct ContourComputeCurvatureReport_struct ContourComputeCurvatureReport; +typedef struct ContourComputeCurvatureReport_struct + ContourComputeCurvatureReport; typedef struct ContourOverlaySettings_struct ContourOverlaySettings; typedef struct CurveParameters_struct CurveParameters; typedef struct ExtractContourReport_struct ExtractContourReport; @@ -2303,17 +3940,22 @@ typedef struct WindowSize_struct WindowSize; typedef struct DisplacementVector_struct DisplacementVector; typedef struct WaveletOptions_struct WaveletOptions; typedef struct CooccurrenceOptions_struct CooccurrenceOptions; -typedef struct ParticleClassifierLocalThresholdOptions_struct ParticleClassifierLocalThresholdOptions; +typedef struct ParticleClassifierLocalThresholdOptions_struct + ParticleClassifierLocalThresholdOptions; typedef struct RangeFloat_struct RangeFloat; -typedef struct ParticleClassifierAutoThresholdOptions_struct ParticleClassifierAutoThresholdOptions; -typedef struct ParticleClassifierPreprocessingOptions2_struct ParticleClassifierPreprocessingOptions2; +typedef struct ParticleClassifierAutoThresholdOptions_struct + ParticleClassifierAutoThresholdOptions; +typedef struct ParticleClassifierPreprocessingOptions2_struct + ParticleClassifierPreprocessingOptions2; typedef struct MeasureParticlesReport_struct MeasureParticlesReport; typedef struct GeometricPatternMatch3_struct GeometricPatternMatch3; -typedef struct MatchGeometricPatternAdvancedOptions3_struct MatchGeometricPatternAdvancedOptions3; +typedef struct MatchGeometricPatternAdvancedOptions3_struct + MatchGeometricPatternAdvancedOptions3; typedef struct ColorOptions_struct ColorOptions; typedef struct SampleScore_struct SampleScore; typedef struct ClassifierReportAdvanced_struct ClassifierReportAdvanced; -typedef struct LearnGeometricPatternAdvancedOptions2_struct LearnGeometricPatternAdvancedOptions2; +typedef struct LearnGeometricPatternAdvancedOptions2_struct + LearnGeometricPatternAdvancedOptions2; typedef struct ParticleFilterOptions2_struct ParticleFilterOptions2; typedef struct FindEdgeOptions2_struct FindEdgeOptions2; typedef struct FindEdgeReport_struct FindEdgeReport; @@ -2346,7 +3988,8 @@ typedef struct DataMatrixDescriptionOptions_struct DataMatrixDescriptionOptions; typedef struct DataMatrixSearchOptions_struct DataMatrixSearchOptions; typedef struct DataMatrixReport_struct DataMatrixReport; typedef struct JPEG2000FileAdvancedOptions_struct JPEG2000FileAdvancedOptions; -typedef struct MatchGeometricPatternAdvancedOptions2_struct MatchGeometricPatternAdvancedOptions2; +typedef struct MatchGeometricPatternAdvancedOptions2_struct + MatchGeometricPatternAdvancedOptions2; typedef struct InspectionAlignment_struct InspectionAlignment; typedef struct InspectionOptions_struct InspectionOptions; typedef struct CharReport2_struct CharReport2; @@ -2360,7 +4003,8 @@ typedef struct LegFeature_struct LegFeature; typedef struct CornerFeature_struct CornerFeature; typedef struct LineFeature_struct LineFeature; typedef struct ParallelLinePairFeature_struct ParallelLinePairFeature; -typedef struct PairOfParallelLinePairsFeature_struct PairOfParallelLinePairsFeature; +typedef struct PairOfParallelLinePairsFeature_struct + PairOfParallelLinePairsFeature; typedef union GeometricFeature_union GeometricFeature; typedef struct FeatureData_struct FeatureData; typedef struct GeometricPatternMatch2_struct GeometricPatternMatch2; @@ -2380,8 +4024,10 @@ typedef struct Barcode2DInfo_struct Barcode2DInfo; typedef struct DataMatrixOptions_struct DataMatrixOptions; typedef struct ClassifierAccuracyReport_struct ClassifierAccuracyReport; typedef struct NearestNeighborClassResult_struct NearestNeighborClassResult; -typedef struct NearestNeighborTrainingReport_struct NearestNeighborTrainingReport; -typedef struct ParticleClassifierPreprocessingOptions_struct ParticleClassifierPreprocessingOptions; +typedef struct NearestNeighborTrainingReport_struct + NearestNeighborTrainingReport; +typedef struct ParticleClassifierPreprocessingOptions_struct + ParticleClassifierPreprocessingOptions; typedef struct ClassifierSampleInfo_struct ClassifierSampleInfo; typedef struct ClassScore_struct ClassScore; typedef struct ClassifierReport_struct ClassifierReport; @@ -2389,9 +4035,11 @@ typedef struct NearestNeighborOptions_struct NearestNeighborOptions; typedef struct ParticleClassifierOptions_struct ParticleClassifierOptions; typedef struct RGBU64Value_struct RGBU64Value; typedef struct GeometricPatternMatch_struct GeometricPatternMatch; -typedef struct MatchGeometricPatternAdvancedOptions_struct MatchGeometricPatternAdvancedOptions; +typedef struct MatchGeometricPatternAdvancedOptions_struct + MatchGeometricPatternAdvancedOptions; typedef struct MatchGeometricPatternOptions_struct MatchGeometricPatternOptions; -typedef struct LearnGeometricPatternAdvancedOptions_struct LearnGeometricPatternAdvancedOptions; +typedef struct LearnGeometricPatternAdvancedOptions_struct + LearnGeometricPatternAdvancedOptions; typedef struct FitEllipseOptions_struct FitEllipseOptions; typedef struct FitCircleOptions_struct FitCircleOptions; typedef struct ConstructROIOptions2_struct ConstructROIOptions2; @@ -2404,8 +4052,10 @@ typedef union Color2_union Color2; typedef struct BestEllipse2_struct BestEllipse2; typedef struct LearnPatternAdvancedOptions_struct LearnPatternAdvancedOptions; typedef struct AVIInfo_struct AVIInfo; -typedef struct LearnPatternAdvancedShiftOptions_struct LearnPatternAdvancedShiftOptions; -typedef struct LearnPatternAdvancedRotationOptions_struct LearnPatternAdvancedRotationOptions; +typedef struct LearnPatternAdvancedShiftOptions_struct + LearnPatternAdvancedShiftOptions; +typedef struct LearnPatternAdvancedRotationOptions_struct + LearnPatternAdvancedRotationOptions; typedef struct MatchPatternAdvancedOptions_struct MatchPatternAdvancedOptions; typedef struct ParticleFilterCriteria2_struct ParticleFilterCriteria2; typedef struct BestCircle2_struct BestCircle2; @@ -2503,2138 +4153,3171 @@ typedef struct SpokeOptions_struct SpokeOptions; // Data Structures //============================================================================ #if !defined __GNUC__ && !defined _M_X64 -#pragma pack(push,1) +#pragma pack(push, 1) #endif typedef struct DivisionModel_struct { - float kappa; //The learned kappa coefficient of division model. + float kappa; // The learned kappa coefficient of division model. } DivisionModel; typedef struct FocalLength_struct { - float fx; //Focal length in X direction. - float fy; //Focal length in Y direction. + float fx; // Focal length in X direction. + float fy; // Focal length in Y direction. } FocalLength; typedef struct PolyModel_struct { - float* kCoeffs; //The learned radial coefficients of polynomial model. - unsigned int numKCoeffs; //Number of K coefficients. - float p1; //The P1(learned tangential coefficients of polynomial model). - float p2; //The P2(learned tangential coefficients of polynomial model). + float* kCoeffs; // The learned radial coefficients of polynomial model. + unsigned int numKCoeffs; // Number of K coefficients. + float p1; // The P1(learned tangential coefficients of polynomial model). + float p2; // The P2(learned tangential coefficients of polynomial model). } PolyModel; typedef struct DistortionModelParams_struct { - DistortionModel distortionModel; //Type of learned distortion model. - PolyModel polyModel; //The learned coefficients of polynomial model. - DivisionModel divisionModel; //The learned coefficient of division model. + DistortionModel distortionModel; // Type of learned distortion model. + PolyModel polyModel; // The learned coefficients of polynomial model. + DivisionModel divisionModel; // The learned coefficient of division model. } DistortionModelParams; typedef struct PointFloat_struct { - float x; //The x-coordinate of the point. - float y; //The y-coordinate of the point. + float x; // The x-coordinate of the point. + float y; // The y-coordinate of the point. } PointFloat; typedef struct InternalParameters_struct { - char isInsufficientData; - FocalLength focalLength; - PointFloat opticalCenter; + char isInsufficientData; + FocalLength focalLength; + PointFloat opticalCenter; } InternalParameters; typedef struct MaxGridSize_struct { - unsigned int xMax; //Maximum x limit for the grid size. - unsigned int yMax; //Maximum y limit for the grid size. + unsigned int xMax; // Maximum x limit for the grid size. + unsigned int yMax; // Maximum y limit for the grid size. } MaxGridSize; typedef struct ImageSize_struct { - unsigned int xRes; //X resolution of the image. - unsigned int yRes; //Y resolution of the image. + unsigned int xRes; // X resolution of the image. + unsigned int yRes; // Y resolution of the image. } ImageSize; typedef struct CalibrationReferencePoints_struct { - PointDouble* pixelCoords; //Specifies the coordinates of the pixel reference points. - unsigned int numPixelCoords; //Number of pixel coordinates. - PointDouble* realCoords; //Specifies the measuring unit associated with the image. - unsigned int numRealCoords; //Number of real coordinates. - CalibrationUnit units; //Specifies the units of X Step and Y Step. - ImageSize imageSize; //Specifies the size of calibration template image. + PointDouble* + pixelCoords; // Specifies the coordinates of the pixel reference points. + unsigned int numPixelCoords; // Number of pixel coordinates. + PointDouble* + realCoords; // Specifies the measuring unit associated with the image. + unsigned int numRealCoords; // Number of real coordinates. + CalibrationUnit units; // Specifies the units of X Step and Y Step. + ImageSize imageSize; // Specifies the size of calibration template image. } CalibrationReferencePoints; typedef struct GetCameraParametersReport_struct { - double* projectionMatrix; //The projection(homography) matrix of working plane. - unsigned int projectionMatrixRows; //Number of rows in projection matrix. - unsigned int projectionMatrixCols; //Number of columns in projection matrix. - DistortionModelParams distortion; //Distortion model Coefficients. - InternalParameters internalParams; //The learned internal paramters of camera model such as focal length and optical center. + double* + projectionMatrix; // The projection(homography) matrix of working plane. + unsigned int projectionMatrixRows; // Number of rows in projection matrix. + unsigned int projectionMatrixCols; // Number of columns in projection matrix. + DistortionModelParams distortion; // Distortion model Coefficients. + InternalParameters internalParams; // The learned internal paramters of + // camera model such as focal length and + // optical center. } GetCameraParametersReport; typedef struct CalibrationAxisInfo_struct { - PointFloat center; //The origin of the reference coordinate system, expressed in pixel units. - float rotationAngle; //The angle of the x-axis of the real-world coordinate system, in relation to the horizontal. - AxisOrientation axisDirection; //Specifies the direction of the calibraiton axis which is either Direct or Indirect. + PointFloat center; // The origin of the reference coordinate system, + // expressed in pixel units. + float rotationAngle; // The angle of the x-axis of the real-world coordinate + // system, in relation to the horizontal. + AxisOrientation axisDirection; // Specifies the direction of the calibraiton + // axis which is either Direct or Indirect. } CalibrationAxisInfo; typedef struct CalibrationLearnSetupInfo_struct { - CalibrationMode2 calibrationMethod; //Type of calibration method used. - DistortionModel distortionModel; //Type of learned distortion model. - ScalingMethod scaleMode; //The aspect scaling to use when correcting an image. - CalibrationROI roiMode; //The ROI to use when correcting an image. - char learnCorrectionTable; //Set this input to true value if you want the correction table to be determined and stored. + CalibrationMode2 calibrationMethod; // Type of calibration method used. + DistortionModel distortionModel; // Type of learned distortion model. + ScalingMethod + scaleMode; // The aspect scaling to use when correcting an image. + CalibrationROI roiMode; // The ROI to use when correcting an image. + char learnCorrectionTable; // Set this input to true value if you want the + // correction table to be determined and stored. } CalibrationLearnSetupInfo; typedef struct GridDescriptor_struct { - float xStep; //The distance in the x direction between two adjacent pixels in units specified by unit. - float yStep; //The distance in the y direction between two adjacent pixels in units specified by unit. - CalibrationUnit unit; //The unit of measure for the image. + float xStep; // The distance in the x direction between two adjacent pixels + // in units specified by unit. + float yStep; // The distance in the y direction between two adjacent pixels + // in units specified by unit. + CalibrationUnit unit; // The unit of measure for the image. } GridDescriptor; typedef struct ErrorStatistics_struct { - double mean; //Mean error statistics value. - double maximum; //Maximum value of error. - double standardDeviation; //The standard deviation error statistiscs value. - double distortion; //The distortion error statistics value. + double mean; // Mean error statistics value. + double maximum; // Maximum value of error. + double standardDeviation; // The standard deviation error statistiscs value. + double distortion; // The distortion error statistics value. } ErrorStatistics; typedef struct GetCalibrationInfoReport_struct { - ROI* userRoi; //Specifies the ROI the user provided when learning the calibration. - ROI* calibrationRoi; //Specifies the ROI that corresponds to the region of the image where the calibration information is accurate. - CalibrationAxisInfo axisInfo; //Reference Coordinate System for the real-world coordinates. - CalibrationLearnSetupInfo learnSetupInfo; //Calibration learn setup information. - GridDescriptor gridDescriptor; //Specifies scaling constants used to calibrate the image. - float* errorMap; //The the error map of calibration template image. - unsigned int errorMapRows; //Number of rows in error map. - unsigned int errorMapCols; //Number of Columns in error map. - ErrorStatistics errorStatistics; //Error statistics of the calibration. + ROI* userRoi; // Specifies the ROI the user provided when learning the + // calibration. + ROI* calibrationRoi; // Specifies the ROI that corresponds to the region of + // the image where the calibration information is + // accurate. + CalibrationAxisInfo + axisInfo; // Reference Coordinate System for the real-world coordinates. + CalibrationLearnSetupInfo + learnSetupInfo; // Calibration learn setup information. + GridDescriptor gridDescriptor; // Specifies scaling constants used to + // calibrate the image. + float* errorMap; // The the error map of calibration template image. + unsigned int errorMapRows; // Number of rows in error map. + unsigned int errorMapCols; // Number of Columns in error map. + ErrorStatistics errorStatistics; // Error statistics of the calibration. } GetCalibrationInfoReport; typedef struct EdgePolarity_struct { - EdgePolaritySearchMode start; - EdgePolaritySearchMode end; + EdgePolaritySearchMode start; + EdgePolaritySearchMode end; } EdgePolarity; typedef struct ClampSettings_struct { - double angleRange; //Specifies the angle range. - EdgePolarity edgePolarity; //Specifies the edge polarity. + double angleRange; // Specifies the angle range. + EdgePolarity edgePolarity; // Specifies the edge polarity. } ClampSettings; typedef struct PointDouble_struct { - double x; //The x-coordinate of the point. - double y; //The y-coordinate of the point. + double x; // The x-coordinate of the point. + double y; // The y-coordinate of the point. } PointDouble; typedef struct PointDoublePair_struct { - PointDouble start; //The Start co-ordinate of the pair. - PointDouble end; //The End co-ordinate of the pair. + PointDouble start; // The Start co-ordinate of the pair. + PointDouble end; // The End co-ordinate of the pair. } PointDoublePair; typedef struct ClampResults_struct { - double distancePix; //Defines the Pixel world distance. - double distanceRealWorld; //Defines the real world distance. - double angleAbs; //Defines the absolute angle. - double angleRelative; //Defines the relative angle. + double distancePix; // Defines the Pixel world distance. + double distanceRealWorld; // Defines the real world distance. + double angleAbs; // Defines the absolute angle. + double angleRelative; // Defines the relative angle. } ClampResults; typedef struct ClampPoints_struct { - PointDoublePair pixel; //Specifies the pixel world point pair for clamp. - PointDoublePair realWorld; //Specifies the real world point pair for clamp. + PointDoublePair pixel; // Specifies the pixel world point pair for clamp. + PointDoublePair realWorld; // Specifies the real world point pair for clamp. } ClampPoints; typedef struct RGBValue_struct { - unsigned char B; //The blue value of the color. - unsigned char G; //The green value of the color. - unsigned char R; //The red value of the color. - unsigned char alpha; //The alpha value of the color, which represents extra information about a color image, such as gamma correction. + unsigned char B; // The blue value of the color. + unsigned char G; // The green value of the color. + unsigned char R; // The red value of the color. + unsigned char alpha; // The alpha value of the color, which represents extra + // information about a color image, such as gamma + // correction. } RGBValue; typedef struct ClampOverlaySettings_struct { - int showSearchArea; //If TRUE, the function overlays the search area on the image. - int showCurves; //If TRUE, the function overlays the curves on the image. - int showClampLocation; //If TRUE, the function overlays the clamp location on the image. - int showResult; //If TRUE, the function overlays the hit lines to the object and the edge used to generate the hit line on the result image. - RGBValue searchAreaColor; //Specifies the RGB color value to use to overlay the search area. - RGBValue curvesColor; //Specifies the RGB color value to use to overlay the curves. - RGBValue clampLocationsColor; //Specifies the RGB color value to use to overlay the clamp locations. - RGBValue resultColor; //Specifies the RGB color value to use to overlay the results. - char* overlayGroupName; //Specifies the group overlay name for the step overlays. + int showSearchArea; // If TRUE, the function overlays the search area on the + // image. + int showCurves; // If TRUE, the function overlays the curves on the image. + int showClampLocation; // If TRUE, the function overlays the clamp location + // on the image. + int showResult; // If TRUE, the function overlays the hit lines to the object + // and the edge used to generate the hit line on the result + // image. + RGBValue searchAreaColor; // Specifies the RGB color value to use to overlay + // the search area. + RGBValue curvesColor; // Specifies the RGB color value to use to overlay the + // curves. + RGBValue clampLocationsColor; // Specifies the RGB color value to use to + // overlay the clamp locations. + RGBValue resultColor; // Specifies the RGB color value to use to overlay the + // results. + char* overlayGroupName; // Specifies the group overlay name for the step + // overlays. } ClampOverlaySettings; typedef struct ClampMax2Report_struct { - ClampResults clampResults; //Specifies the Clamp results information returned by the function. - ClampPoints clampPoints; //Specifies the clamp points information returned by the function. - unsigned int calibrationValid; //Specifies if the calibration information is valid or not. + ClampResults clampResults; // Specifies the Clamp results information + // returned by the function. + ClampPoints clampPoints; // Specifies the clamp points information returned + // by the function. + unsigned int calibrationValid; // Specifies if the calibration information is + // valid or not. } ClampMax2Report; typedef struct ContourFitSplineReport_struct { - PointDouble* points; //It returns the points of the best-fit B-spline curve. - int numberOfPoints; //Number of Best fit points returned. + PointDouble* points; // It returns the points of the best-fit B-spline curve. + int numberOfPoints; // Number of Best fit points returned. } ContourFitSplineReport; typedef struct LineFloat_struct { - PointFloat start; //The coordinate location of the start of the line. - PointFloat end; //The coordinate location of the end of the line. + PointFloat start; // The coordinate location of the start of the line. + PointFloat end; // The coordinate location of the end of the line. } LineFloat; typedef struct LineEquation_struct { - double a; //The a coefficient of the line equation. - double b; //The b coefficient of the line equation. - double c; //The c coefficient of the line equation. + double a; // The a coefficient of the line equation. + double b; // The b coefficient of the line equation. + double c; // The c coefficient of the line equation. } LineEquation; typedef struct ContourFitLineReport_struct { - LineFloat lineSegment; //Line Segment represents the intersection of the line equation and the contour. - LineEquation lineEquation; //Line Equation is a structure of three coefficients A, B, and C of the equation in the normal form (Ax + By + C=0) of the best fit line. + LineFloat lineSegment; // Line Segment represents the intersection of the + // line equation and the contour. + LineEquation lineEquation; // Line Equation is a structure of three + // coefficients A, B, and C of the equation in the + // normal form (Ax + By + C=0) of the best fit + // line. } ContourFitLineReport; typedef struct ContourFitPolynomialReport_struct { - PointDouble* bestFit; //It returns the points of the best-fit polynomial. - int numberOfPoints; //Number of Best fit points returned. - double* polynomialCoefficients; //Polynomial Coefficients returns the coefficients of the polynomial equation. - int numberOfCoefficients; //Number of Coefficients returned in the polynomial coefficients array. + PointDouble* bestFit; // It returns the points of the best-fit polynomial. + int numberOfPoints; // Number of Best fit points returned. + double* polynomialCoefficients; // Polynomial Coefficients returns the + // coefficients of the polynomial equation. + int numberOfCoefficients; // Number of Coefficients returned in the + // polynomial coefficients array. } ContourFitPolynomialReport; typedef struct PartialCircle_struct { - PointFloat center; //Center of the circle. - double radius; //Radius of the circle. - double startAngle; //Start angle of the fitted structure. - double endAngle; //End angle of the fitted structure. + PointFloat center; // Center of the circle. + double radius; // Radius of the circle. + double startAngle; // Start angle of the fitted structure. + double endAngle; // End angle of the fitted structure. } PartialCircle; typedef struct PartialEllipse_struct { - PointFloat center; //Center of the Ellipse. - double angle; //Angle of the ellipse. - double majorRadius; //The length of the semi-major axis of the ellipse. - double minorRadius; //The length of the semi-minor axis of the ellipse. - double startAngle; //Start angle of the fitted structure. - double endAngle; //End angle of the fitted structure. + PointFloat center; // Center of the Ellipse. + double angle; // Angle of the ellipse. + double majorRadius; // The length of the semi-major axis of the ellipse. + double minorRadius; // The length of the semi-minor axis of the ellipse. + double startAngle; // Start angle of the fitted structure. + double endAngle; // End angle of the fitted structure. } PartialEllipse; typedef struct SetupMatchPatternData_struct { - unsigned char* matchSetupData; //String containing the match setup data. - int numMatchSetupData; //Number of match setup data. + unsigned char* matchSetupData; // String containing the match setup data. + int numMatchSetupData; // Number of match setup data. } SetupMatchPatternData; typedef struct RangeSettingDouble_struct { - SettingType settingType; //Match Constraints specifies the match option whose values you want to constrain by the given range. - double min; //Min is the minimum value of the range for a given Match Constraint. - double max; //Max is the maximum value of the range for a given Match Constraint. + SettingType settingType; // Match Constraints specifies the match option + // whose values you want to constrain by the given + // range. + double min; // Min is the minimum value of the range for a given Match + // Constraint. + double max; // Max is the maximum value of the range for a given Match + // Constraint. } RangeSettingDouble; typedef struct GeometricAdvancedSetupDataOption_struct { - GeometricSetupDataItem type; //It determines the option you want to use during the matching phase. - double value; //Value is the value for the option you want to use during the matching phase. + GeometricSetupDataItem type; // It determines the option you want to use + // during the matching phase. + double value; // Value is the value for the option you want to use during the + // matching phase. } GeometricAdvancedSetupDataOption; typedef struct ContourInfoReport_struct { - PointDouble* pointsPixel; //Points (pixel) specifies the location of every point detected on the curve, in pixels. - unsigned int numPointsPixel; //Number of points pixel elements. - PointDouble* pointsReal; //Points (real) specifies the location of every point detected on the curve, in calibrated units. - unsigned int numPointsReal; //Number of points real elements. - double* curvaturePixel; //Curvature Pixel displays the curvature profile for the selected contour, in pixels. - unsigned int numCurvaturePixel; //Number of curvature pixels. - double* curvatureReal; //Curvature Real displays the curvature profile for the selected contour, in calibrated units. - unsigned int numCurvatureReal; //Number of curvature Real elements. - double length; //Length (pixel) specifies the length, in pixels, of the curves in the image. - double lengthReal; //Length (real) specifies the length, in calibrated units, of the curves within the curvature range. - unsigned int hasEquation; //Has Equation specifies whether the contour has a fitted equation. + PointDouble* pointsPixel; // Points (pixel) specifies the location of every + // point detected on the curve, in pixels. + unsigned int numPointsPixel; // Number of points pixel elements. + PointDouble* pointsReal; // Points (real) specifies the location of every + // point detected on the curve, in calibrated units. + unsigned int numPointsReal; // Number of points real elements. + double* curvaturePixel; // Curvature Pixel displays the curvature profile for + // the selected contour, in pixels. + unsigned int numCurvaturePixel; // Number of curvature pixels. + double* curvatureReal; // Curvature Real displays the curvature profile for + // the selected contour, in calibrated units. + unsigned int numCurvatureReal; // Number of curvature Real elements. + double length; // Length (pixel) specifies the length, in pixels, of the + // curves in the image. + double lengthReal; // Length (real) specifies the length, in calibrated + // units, of the curves within the curvature range. + unsigned int hasEquation; // Has Equation specifies whether the contour has a + // fitted equation. } ContourInfoReport; typedef struct ROILabel_struct { - char* className; //Specifies the classname you want to segment. - unsigned int label; //Label is the label number associated with the Class Name. + char* className; // Specifies the classname you want to segment. + unsigned int + label; // Label is the label number associated with the Class Name. } ROILabel; typedef struct SupervisedColorSegmentationReport_struct { - ROILabel* labelOut; //The Roi labels array. - unsigned int numLabelOut; //The number of elements in labelOut array. + ROILabel* labelOut; // The Roi labels array. + unsigned int numLabelOut; // The number of elements in labelOut array. } SupervisedColorSegmentationReport; typedef struct LabelToROIReport_struct { - ROI** roiArray; //Array of ROIs. - unsigned int numOfROIs; //Number of ROIs in the roiArray. - unsigned int* labelsOutArray; //Array of labels. - unsigned int numOfLabels; //Number of labels. - int* isTooManyVectorsArray; //isTooManyVectorsArray array. - unsigned int isTooManyVectorsArraySize; //Number of elements in isTooManyVectorsArray. + ROI** roiArray; // Array of ROIs. + unsigned int numOfROIs; // Number of ROIs in the roiArray. + unsigned int* labelsOutArray; // Array of labels. + unsigned int numOfLabels; // Number of labels. + int* isTooManyVectorsArray; // isTooManyVectorsArray array. + unsigned int isTooManyVectorsArraySize; // Number of elements in + // isTooManyVectorsArray. } LabelToROIReport; typedef struct ColorSegmenationOptions_struct { - unsigned int windowX; //X is the window size in x direction. - unsigned int windowY; //Y is the window size in y direction. - unsigned int stepSize; //Step Size is the distance between two windows. - unsigned int minParticleArea; //Min Particle Area is the minimum number of allowed pixels. - unsigned int maxParticleArea; //Max Particle Area is the maximum number of allowed pixels. - short isFineSegment; //When enabled, the step processes the boundary pixels of each segmentation cluster using a step size of 1. + unsigned int windowX; // X is the window size in x direction. + unsigned int windowY; // Y is the window size in y direction. + unsigned int stepSize; // Step Size is the distance between two windows. + unsigned int minParticleArea; // Min Particle Area is the minimum number of + // allowed pixels. + unsigned int maxParticleArea; // Max Particle Area is the maximum number of + // allowed pixels. + short isFineSegment; // When enabled, the step processes the boundary pixels + // of each segmentation cluster using a step size of 1. } ColorSegmenationOptions; typedef struct ClassifiedCurve_struct { - double length; //Specifies the length, in pixels, of the curves within the curvature range. - double lengthReal; //specifies the length, in calibrated units, of the curves within the curvature range. - double maxCurvature; //specifies the maximum curvature, in pixels, for the selected curvature range. - double maxCurvatureReal; //specifies the maximum curvature, in calibrated units, for the selected curvature range. - unsigned int label; //specifies the class to which the the sample belongs. - PointDouble* curvePoints; //Curve Points is a point-coordinate cluster that defines the points of the curve. - unsigned int numCurvePoints; //Number of curve points. + double length; // Specifies the length, in pixels, of the curves within the + // curvature range. + double lengthReal; // specifies the length, in calibrated units, of the + // curves within the curvature range. + double maxCurvature; // specifies the maximum curvature, in pixels, for the + // selected curvature range. + double maxCurvatureReal; // specifies the maximum curvature, in calibrated + // units, for the selected curvature range. + unsigned int label; // specifies the class to which the the sample belongs. + PointDouble* curvePoints; // Curve Points is a point-coordinate cluster that + // defines the points of the curve. + unsigned int numCurvePoints; // Number of curve points. } ClassifiedCurve; typedef struct RangeDouble_struct { - double minValue; //The minimum value of the range. - double maxValue; //The maximum value of the range. + double minValue; // The minimum value of the range. + double maxValue; // The maximum value of the range. } RangeDouble; typedef struct RangeLabel_struct { - RangeDouble range; //Specifies the range of curvature values. - unsigned int label; //Class Label specifies the class to which the the sample belongs. + RangeDouble range; // Specifies the range of curvature values. + unsigned int label; // Class Label specifies the class to which the the + // sample belongs. } RangeLabel; typedef struct CurvatureAnalysisReport_struct { - ClassifiedCurve* curves; - unsigned int numCurves; + ClassifiedCurve* curves; + unsigned int numCurves; } CurvatureAnalysisReport; typedef struct Disparity_struct { - PointDouble current; //Current is a array of points that defines the target contour. - PointDouble reference; //reference is a array of points that defines the template contour. - double distance; //Specifies the distance, in pixels, between the template contour point and the target contour point. + PointDouble + current; // Current is a array of points that defines the target contour. + PointDouble reference; // reference is a array of points that defines the + // template contour. + double distance; // Specifies the distance, in pixels, between the template + // contour point and the target contour point. } Disparity; typedef struct ComputeDistancesReport_struct { - Disparity* distances; //Distances is an array containing the computed distances. - unsigned int numDistances; //Number elements in the distances array. - Disparity* distancesReal; //Distances Real is an array containing the computed distances in calibrated units. - unsigned int numDistancesReal; //Number of elements in real distances array. + Disparity* + distances; // Distances is an array containing the computed distances. + unsigned int numDistances; // Number elements in the distances array. + Disparity* distancesReal; // Distances Real is an array containing the + // computed distances in calibrated units. + unsigned int numDistancesReal; // Number of elements in real distances array. } ComputeDistancesReport; typedef struct MatchMode_struct { - unsigned int rotation; //Rotation When enabled, the Function searches for occurrences of the template in the inspection image, allowing for template matches to be rotated. - unsigned int scale; //Rotation When enabled, the Function searches for occurrences of the template in the inspection image, allowing for template matches to be rotated. - unsigned int occlusion; //Occlusion specifies whether or not to search for occluded versions of the shape. + unsigned int rotation; // Rotation When enabled, the Function searches for + // occurrences of the template in the inspection + // image, allowing for template matches to be rotated. + unsigned int scale; // Rotation When enabled, the Function searches for + // occurrences of the template in the inspection image, + // allowing for template matches to be rotated. + unsigned int occlusion; // Occlusion specifies whether or not to search for + // occluded versions of the shape. } MatchMode; typedef struct ClassifiedDisparity_struct { - double length; //Length (pixel) specifies the length, in pixels, of the curves within the curvature range. - double lengthReal; //Length (real) specifies the length, in calibrated units, of the curves within the curvature range. - double maxDistance; //Maximum Distance (pixel) specifies the maximum distance, in pixels, between points along the selected contour and the template contour. - double maxDistanceReal; //Maximum Distance (real) specifies the maximum distance, in calibrated units, between points along the selected contour and the template contour. - unsigned int label; //Class Label specifies the class to which the the sample belongs. - PointDouble* templateSubsection; //Template subsection points is an array of points that defines the boundary of the template. - unsigned int numTemplateSubsection; //Number of reference points. - PointDouble* targetSubsection; //Current Points(Target subsection points) is an array of points that defines the boundary of the target. - unsigned int numTargetSubsection; //Number of current points. + double length; // Length (pixel) specifies the length, in pixels, of the + // curves within the curvature range. + double lengthReal; // Length (real) specifies the length, in calibrated + // units, of the curves within the curvature range. + double maxDistance; // Maximum Distance (pixel) specifies the maximum + // distance, in pixels, between points along the selected + // contour and the template contour. + double maxDistanceReal; // Maximum Distance (real) specifies the maximum + // distance, in calibrated units, between points + // along the selected contour and the template + // contour. + unsigned int label; // Class Label specifies the class to which the the + // sample belongs. + PointDouble* templateSubsection; // Template subsection points is an array of + // points that defines the boundary of the + // template. + unsigned int numTemplateSubsection; // Number of reference points. + PointDouble* targetSubsection; // Current Points(Target subsection points) is + // an array of points that defines the + // boundary of the target. + unsigned int numTargetSubsection; // Number of current points. } ClassifiedDisparity; typedef struct ClassifyDistancesReport_struct { - ClassifiedDisparity* classifiedDistances; //Disparity array containing the classified distances. - unsigned int numClassifiedDistances; //Number of elements in the disparity array. + ClassifiedDisparity* classifiedDistances; // Disparity array containing the + // classified distances. + unsigned int + numClassifiedDistances; // Number of elements in the disparity array. } ClassifyDistancesReport; typedef struct ContourComputeCurvatureReport_struct { - double* curvaturePixel; //Curvature Pixel displays the curvature profile for the selected contour, in pixels. - unsigned int numCurvaturePixel; //Number of curvature pixels. - double* curvatureReal; //Curvature Real displays the curvature profile for the selected contour, in calibrated units. - unsigned int numCurvatureReal; //Number of curvature Real elements. + double* curvaturePixel; // Curvature Pixel displays the curvature profile for + // the selected contour, in pixels. + unsigned int numCurvaturePixel; // Number of curvature pixels. + double* curvatureReal; // Curvature Real displays the curvature profile for + // the selected contour, in calibrated units. + unsigned int numCurvatureReal; // Number of curvature Real elements. } ContourComputeCurvatureReport; typedef struct ContourOverlaySettings_struct { - unsigned int overlay; //Overlay specifies whether to display the overlay on the image. - RGBValue color; //Color is the color of the overlay. - unsigned int width; //Width specifies the width of the overlay in pixels. - unsigned int maintainWidth; //Maintain Width? specifies whether you want the overlay measured in screen pixels or image pixels. + unsigned int overlay; // Overlay specifies whether to display the overlay on + // the image. + RGBValue color; // Color is the color of the overlay. + unsigned int width; // Width specifies the width of the overlay in pixels. + unsigned int maintainWidth; // Maintain Width? specifies whether you want the + // overlay measured in screen pixels or image + // pixels. } ContourOverlaySettings; typedef struct CurveParameters_struct { - ExtractionMode extractionMode; //Specifies the method the function uses to identify curves in the image. - int threshold; //Specifies the minimum contrast a seed point must have in order to begin a curve. - EdgeFilterSize filterSize; //Specifies the width of the edge filter the function uses to identify curves in the image. - int minLength; //Specifies the length, in pixels, of the smallest curve the function will extract. - int searchStep; //Search Step Size specifies the distance, in the y direction, between the image rows that the algorithm inspects for curve seed points. - int maxEndPointGap; //Specifies the maximum gap, in pixels, between the endpoints of a curve that the function identifies as a closed curve. - int subpixel; //Subpixel specifies whether to detect curve points with subpixel accuracy. + ExtractionMode extractionMode; // Specifies the method the function uses to + // identify curves in the image. + int threshold; // Specifies the minimum contrast a seed point must have in + // order to begin a curve. + EdgeFilterSize filterSize; // Specifies the width of the edge filter the + // function uses to identify curves in the image. + int minLength; // Specifies the length, in pixels, of the smallest curve the + // function will extract. + int searchStep; // Search Step Size specifies the distance, in the y + // direction, between the image rows that the algorithm + // inspects for curve seed points. + int maxEndPointGap; // Specifies the maximum gap, in pixels, between the + // endpoints of a curve that the function identifies as a + // closed curve. + int subpixel; // Subpixel specifies whether to detect curve points with + // subpixel accuracy. } CurveParameters; typedef struct ExtractContourReport_struct { - PointDouble* contourPoints; //Contour Points specifies every point found on the contour. - int numContourPoints; //Number of contour points. - PointDouble* sourcePoints; //Source Image Points specifies every point found on the contour in the source image. - int numSourcePoints; //Number of source points. + PointDouble* contourPoints; // Contour Points specifies every point found on + // the contour. + int numContourPoints; // Number of contour points. + PointDouble* sourcePoints; // Source Image Points specifies every point found + // on the contour in the source image. + int numSourcePoints; // Number of source points. } ExtractContourReport; typedef struct ConnectionConstraint_struct { - ConnectionConstraintType constraintType; //Constraint Type specifies what criteria to use to consider two curves part of a contour. - RangeDouble range; //Specifies range for a given Match Constraint. + ConnectionConstraintType constraintType; // Constraint Type specifies what + // criteria to use to consider two + // curves part of a contour. + RangeDouble range; // Specifies range for a given Match Constraint. } ConnectionConstraint; typedef struct ExtractTextureFeaturesReport_struct { - int* waveletBands; //The array having all the Wavelet Banks used for extraction. - int numWaveletBands; //Number of wavelet banks in the Array. - double** textureFeatures; //2-D array to store all the Texture features extracted. - int textureFeaturesRows; //Number of Rows in the Texture Features array. - int textureFeaturesCols; //Number of Cols in Texture Features array. + int* waveletBands; // The array having all the Wavelet Banks used for + // extraction. + int numWaveletBands; // Number of wavelet banks in the Array. + double** textureFeatures; // 2-D array to store all the Texture features + // extracted. + int textureFeaturesRows; // Number of Rows in the Texture Features array. + int textureFeaturesCols; // Number of Cols in Texture Features array. } ExtractTextureFeaturesReport; typedef struct WaveletBandsReport_struct { - float** LLBand; //2-D array for LL Band. - float** LHBand; //2-D array for LH Band. - float** HLBand; //2-D array for HL Band. - float** HHBand; //2-D array for HH Band. - float** LLLBand; //2-D array for LLL Band. - float** LLHBand; //2-D array for LLH Band. - float LHLBand; //2-D array for LHL Band. - float** LHHBand; //2-D array for LHH Band. - int rows; //Number of Rows for each of the 2-D arrays. - int cols; //Number of Columns for each of the 2-D arrays. + float** LLBand; // 2-D array for LL Band. + float** LHBand; // 2-D array for LH Band. + float** HLBand; // 2-D array for HL Band. + float** HHBand; // 2-D array for HH Band. + float** LLLBand; // 2-D array for LLL Band. + float** LLHBand; // 2-D array for LLH Band. + float LHLBand; // 2-D array for LHL Band. + float** LHHBand; // 2-D array for LHH Band. + int rows; // Number of Rows for each of the 2-D arrays. + int cols; // Number of Columns for each of the 2-D arrays. } WaveletBandsReport; typedef struct CircleFitOptions_struct { - int maxRadius; //Specifies the acceptable distance, in pixels, that a point determined to belong to the circle can be from the perimeter of the circle. - double stepSize; //Step Size is the angle, in degrees, between each radial line in the annular region. - RakeProcessType processType; //Method used to process the data extracted for edge detection. + int maxRadius; // Specifies the acceptable distance, in pixels, that a point + // determined to belong to the circle can be from the + // perimeter of the circle. + double stepSize; // Step Size is the angle, in degrees, between each radial + // line in the annular region. + RakeProcessType processType; // Method used to process the data extracted for + // edge detection. } CircleFitOptions; typedef struct EdgeOptions2_struct { - EdgePolaritySearchMode polarity; //Specifies the polarity of the edges to be found. - unsigned int kernelSize; //Specifies the size of the edge detection kernel. - unsigned int width; //Specifies the number of pixels averaged perpendicular to the search direction to compute the edge profile strength at each point along the search ROI. - float minThreshold; //Specifies the minimum edge strength (gradient magnitude) required for a detected edge. - InterpolationMethod interpolationType; //Specifies the interpolation method used to locate the edge position. - ColumnProcessingMode columnProcessingMode; //Specifies the method used to find the straight edge. + EdgePolaritySearchMode + polarity; // Specifies the polarity of the edges to be found. + unsigned int kernelSize; // Specifies the size of the edge detection kernel. + unsigned int width; // Specifies the number of pixels averaged perpendicular + // to the search direction to compute the edge profile + // strength at each point along the search ROI. + float minThreshold; // Specifies the minimum edge strength (gradient + // magnitude) required for a detected edge. + InterpolationMethod interpolationType; // Specifies the interpolation method + // used to locate the edge position. + ColumnProcessingMode columnProcessingMode; // Specifies the method used to + // find the straight edge. } EdgeOptions2; typedef struct FindCircularEdgeOptions_struct { - SpokeDirection direction; //Specifies the Spoke direction to search in the ROI. - int showSearchArea; //If TRUE, the function overlays the search area on the image. - int showSearchLines; //If TRUE, the function overlays the search lines used to locate the edges on the image. - int showEdgesFound; //If TRUE, the function overlays the locations of the edges found on the image. - int showResult; //If TRUE, the function overlays the hit lines to the object and the edge used to generate the hit line on the result image. - RGBValue searchAreaColor; //Specifies the RGB color value to use to overlay the search area. - RGBValue searchLinesColor; //Specifies the RGB color value to use to overlay the search lines. - RGBValue searchEdgesColor; //Specifies the RGB color value to use to overlay the search edges. - RGBValue resultColor; //Specifies the RGB color value to use to overlay the results. - char* overlayGroupName; //Specifies the overlay group name to assign to the overlays. - EdgeOptions2 edgeOptions; //Specifies the edge detection options along a single search line. + SpokeDirection + direction; // Specifies the Spoke direction to search in the ROI. + int showSearchArea; // If TRUE, the function overlays the search area on the + // image. + int showSearchLines; // If TRUE, the function overlays the search lines used + // to locate the edges on the image. + int showEdgesFound; // If TRUE, the function overlays the locations of the + // edges found on the image. + int showResult; // If TRUE, the function overlays the hit lines to the object + // and the edge used to generate the hit line on the result + // image. + RGBValue searchAreaColor; // Specifies the RGB color value to use to overlay + // the search area. + RGBValue searchLinesColor; // Specifies the RGB color value to use to overlay + // the search lines. + RGBValue searchEdgesColor; // Specifies the RGB color value to use to overlay + // the search edges. + RGBValue resultColor; // Specifies the RGB color value to use to overlay the + // results. + char* overlayGroupName; // Specifies the overlay group name to assign to the + // overlays. + EdgeOptions2 edgeOptions; // Specifies the edge detection options along a + // single search line. } FindCircularEdgeOptions; typedef struct FindConcentricEdgeOptions_struct { - ConcentricRakeDirection direction; //Specifies the Concentric Rake direction. - int showSearchArea; //If TRUE, the function overlays the search area on the image. - int showSearchLines; //If TRUE, the function overlays the search lines used to locate the edges on the image. - int showEdgesFound; //If TRUE, the function overlays the locations of the edges found on the image. - int showResult; //If TRUE, the function overlays the hit lines to the object and the edge used to generate the hit line on the result image. - RGBValue searchAreaColor; //Specifies the RGB color value to use to overlay the search area. - RGBValue searchLinesColor; //Specifies the RGB color value to use to overlay the search lines. - RGBValue searchEdgesColor; //Specifies the RGB color value to use to overlay the search edges. - RGBValue resultColor; //Specifies the RGB color value to use to overlay the results. - char* overlayGroupName; //Specifies the overlay group name to assign to the overlays. - EdgeOptions2 edgeOptions; //Specifies the edge detection options along a single search line. + ConcentricRakeDirection direction; // Specifies the Concentric Rake + // direction. + int showSearchArea; // If TRUE, the function overlays the search area on the + // image. + int showSearchLines; // If TRUE, the function overlays the search lines used + // to locate the edges on the image. + int showEdgesFound; // If TRUE, the function overlays the locations of the + // edges found on the image. + int showResult; // If TRUE, the function overlays the hit lines to the object + // and the edge used to generate the hit line on the result + // image. + RGBValue searchAreaColor; // Specifies the RGB color value to use to overlay + // the search area. + RGBValue searchLinesColor; // Specifies the RGB color value to use to overlay + // the search lines. + RGBValue searchEdgesColor; // Specifies the RGB color value to use to overlay + // the search edges. + RGBValue resultColor; // Specifies the RGB color value to use to overlay the + // results. + char* overlayGroupName; // Specifies the overlay group name to assign to the + // overlays. + EdgeOptions2 edgeOptions; // Specifies the edge detection options along a + // single search line. } FindConcentricEdgeOptions; typedef struct ConcentricEdgeFitOptions_struct { - int maxRadius; //Specifies the acceptable distance, in pixels, that a point determined to belong to the circle can be from the perimeter of the circle. - double stepSize; //The sampling factor that determines the gap between the rake lines. - RakeProcessType processType; //Method used to process the data extracted for edge detection. + int maxRadius; // Specifies the acceptable distance, in pixels, that a point + // determined to belong to the circle can be from the + // perimeter of the circle. + double stepSize; // The sampling factor that determines the gap between the + // rake lines. + RakeProcessType processType; // Method used to process the data extracted for + // edge detection. } ConcentricEdgeFitOptions; typedef struct FindConcentricEdgeReport_struct { - PointFloat startPt; //Pixel Coordinates for starting point of the edge. - PointFloat endPt; //Pixel Coordinates for end point of the edge. - PointFloat startPtCalibrated; //Real world Coordinates for starting point of the edge. - PointFloat endPtCalibrated; //Real world Coordinates for end point of the edge. - double angle; //Angle of the edge found. - double angleCalibrated; //Calibrated angle of the edge found. - double straightness; //The straightness value of the detected straight edge. - double avgStrength; //Average strength of the egde found. - double avgSNR; //Average SNR(Signal to Noise Ratio) for the edge found. - int lineFound; //If the edge is found or not. + PointFloat startPt; // Pixel Coordinates for starting point of the edge. + PointFloat endPt; // Pixel Coordinates for end point of the edge. + PointFloat startPtCalibrated; // Real world Coordinates for starting point of + // the edge. + PointFloat + endPtCalibrated; // Real world Coordinates for end point of the edge. + double angle; // Angle of the edge found. + double angleCalibrated; // Calibrated angle of the edge found. + double straightness; // The straightness value of the detected straight edge. + double avgStrength; // Average strength of the egde found. + double avgSNR; // Average SNR(Signal to Noise Ratio) for the edge found. + int lineFound; // If the edge is found or not. } FindConcentricEdgeReport; typedef struct FindCircularEdgeReport_struct { - PointFloat centerCalibrated; //Real world Coordinates of the Center. - double radiusCalibrated; //Real world radius of the Circular Edge found. - PointFloat center; //Pixel Coordinates of the Center. - double radius; //Radius in pixels of the Circular Edge found. - double roundness; //The roundness of the calculated circular edge. - double avgStrength; //Average strength of the egde found. - double avgSNR; //Average SNR(Signal to Noise Ratio) for the edge found. - int circleFound; //If the circlular edge is found or not. + PointFloat centerCalibrated; // Real world Coordinates of the Center. + double radiusCalibrated; // Real world radius of the Circular Edge found. + PointFloat center; // Pixel Coordinates of the Center. + double radius; // Radius in pixels of the Circular Edge found. + double roundness; // The roundness of the calculated circular edge. + double avgStrength; // Average strength of the egde found. + double avgSNR; // Average SNR(Signal to Noise Ratio) for the edge found. + int circleFound; // If the circlular edge is found or not. } FindCircularEdgeReport; typedef struct WindowSize_struct { - int x; //Window lenght on X direction. - int y; //Window lenght on Y direction. - int stepSize; //Distance between windows. + int x; // Window lenght on X direction. + int y; // Window lenght on Y direction. + int stepSize; // Distance between windows. } WindowSize; typedef struct DisplacementVector_struct { - int x; //length on X direction. - int y; //length on Y direction. + int x; // length on X direction. + int y; // length on Y direction. } DisplacementVector; typedef struct WaveletOptions_struct { - WaveletType typeOfWavelet; //Type of wavelet(db, bior. - float minEnergy; //Minimum Energy in the bands to consider for texture defect detection. + WaveletType typeOfWavelet; // Type of wavelet(db, bior. + float minEnergy; // Minimum Energy in the bands to consider for texture + // defect detection. } WaveletOptions; typedef struct CooccurrenceOptions_struct { - int level; //Level/size of matrix. - DisplacementVector displacement; //Displacemnet between pixels to accumulate the matrix. + int level; // Level/size of matrix. + DisplacementVector + displacement; // Displacemnet between pixels to accumulate the matrix. } CooccurrenceOptions; typedef struct ParticleClassifierLocalThresholdOptions_struct { - LocalThresholdMethod method; //Specifies the local thresholding method the function uses. - ParticleType particleType; //Specifies what kind of particles to look for. - unsigned int windowWidth; //The width of the rectangular window around the pixel on which the function performs the local threshold. - unsigned int windowHeight; //The height of the rectangular window around the pixel on which the function performs the local threshold. - double deviationWeight; //Specifies the k constant used in the Niblack local thresholding algorithm, which determines the weight applied to the variance calculation. + LocalThresholdMethod + method; // Specifies the local thresholding method the function uses. + ParticleType particleType; // Specifies what kind of particles to look for. + unsigned int windowWidth; // The width of the rectangular window around the + // pixel on which the function performs the local + // threshold. + unsigned int windowHeight; // The height of the rectangular window around the + // pixel on which the function performs the local + // threshold. + double deviationWeight; // Specifies the k constant used in the Niblack local + // thresholding algorithm, which determines the + // weight applied to the variance calculation. } ParticleClassifierLocalThresholdOptions; typedef struct RangeFloat_struct { - float minValue; //The minimum value of the range. - float maxValue; //The maximum value of the range. + float minValue; // The minimum value of the range. + float maxValue; // The maximum value of the range. } RangeFloat; typedef struct ParticleClassifierAutoThresholdOptions_struct { - ThresholdMethod method; //The method for binary thresholding, which specifies how to calculate the classes. - ParticleType particleType; //Specifies what kind of particles to look for. - RangeFloat limits; //The limits on the automatic threshold range. + ThresholdMethod method; // The method for binary thresholding, which + // specifies how to calculate the classes. + ParticleType particleType; // Specifies what kind of particles to look for. + RangeFloat limits; // The limits on the automatic threshold range. } ParticleClassifierAutoThresholdOptions; typedef struct ParticleClassifierPreprocessingOptions2_struct { - ParticleClassifierThresholdType thresholdType; //The type of threshold to perform on the image. - RangeFloat manualThresholdRange; //The range of pixels to keep if manually thresholding the image. - ParticleClassifierAutoThresholdOptions autoThresholdOptions; //The options used to auto threshold the image. - ParticleClassifierLocalThresholdOptions localThresholdOptions; //The options used to local threshold the image. - int rejectBorder; //Set this element to TRUE to reject border particles. - int numErosions; //The number of erosions to perform. + ParticleClassifierThresholdType + thresholdType; // The type of threshold to perform on the image. + RangeFloat manualThresholdRange; // The range of pixels to keep if manually + // thresholding the image. + ParticleClassifierAutoThresholdOptions + autoThresholdOptions; // The options used to auto threshold the image. + ParticleClassifierLocalThresholdOptions + localThresholdOptions; // The options used to local threshold the image. + int rejectBorder; // Set this element to TRUE to reject border particles. + int numErosions; // The number of erosions to perform. } ParticleClassifierPreprocessingOptions2; typedef struct MeasureParticlesReport_struct { - double** pixelMeasurements; //The measurements on the particles in the image, in pixel coordinates. - double** calibratedMeasurements; //The measurements on the particles in the image, in real-world coordinates. - size_t numParticles; //The number of particles on which measurements were taken. - size_t numMeasurements; //The number of measurements taken. + double** pixelMeasurements; // The measurements on the particles in the + // image, in pixel coordinates. + double** calibratedMeasurements; // The measurements on the particles in the + // image, in real-world coordinates. + size_t numParticles; // The number of particles on which measurements were + // taken. + size_t numMeasurements; // The number of measurements taken. } MeasureParticlesReport; typedef struct GeometricPatternMatch3_struct { - PointFloat position; //The location of the origin of the template in the match. - float rotation; //The rotation of the match relative to the template image, in degrees. - float scale; //The size of the match relative to the size of the template image, expressed as a percentage. - float score; //The accuracy of the match. - PointFloat corner[4]; //An array of four points describing the rectangle surrounding the template image. - int inverse; //This element is TRUE if the match is an inverse of the template image. - float occlusion; //The percentage of the match that is occluded. - float templateMatchCurveScore; //The accuracy of the match obtained by comparing the template curves to the curves in the match region. - float matchTemplateCurveScore; //The accuracy of the match obtained by comparing the curves in the match region to the template curves. - float correlationScore; //The accuracy of the match obtained by comparing the template image to the match region using a correlation metric that compares the two regions as a function of their pixel values. - PointFloat calibratedPosition; //The location of the origin of the template in the match. - float calibratedRotation; //The rotation of the match relative to the template image, in degrees. - PointFloat calibratedCorner[4]; //An array of four points describing the rectangle surrounding the template image. + PointFloat + position; // The location of the origin of the template in the match. + float rotation; // The rotation of the match relative to the template image, + // in degrees. + float scale; // The size of the match relative to the size of the template + // image, expressed as a percentage. + float score; // The accuracy of the match. + PointFloat corner[4]; // An array of four points describing the rectangle + // surrounding the template image. + int inverse; // This element is TRUE if the match is an inverse of the + // template image. + float occlusion; // The percentage of the match that is occluded. + float templateMatchCurveScore; // The accuracy of the match obtained by + // comparing the template curves to the curves + // in the match region. + float matchTemplateCurveScore; // The accuracy of the match obtained by + // comparing the curves in the match region to + // the template curves. + float correlationScore; // The accuracy of the match obtained by comparing + // the template image to the match region using a + // correlation metric that compares the two regions + // as a function of their pixel values. + PointFloat calibratedPosition; // The location of the origin of the template + // in the match. + float calibratedRotation; // The rotation of the match relative to the + // template image, in degrees. + PointFloat calibratedCorner[4]; // An array of four points describing the + // rectangle surrounding the template image. } GeometricPatternMatch3; typedef struct MatchGeometricPatternAdvancedOptions3_struct { - unsigned int subpixelIterations; //Specifies the maximum number of incremental improvements used to refine matches with subpixel information. - double subpixelTolerance; //Specifies the maximum amount of change, in pixels, between consecutive incremental improvements in the match position before the function stops refining the match position. - unsigned int initialMatchListLength; //Specifies the maximum size of the match list. - int targetTemplateCurveScore; //Set this element to TRUE to specify that the function should calculate the match curve to template curve score and return it for each match result. - int correlationScore; //Set this element to TRUE to specify that the function should calculate the correlation score and return it for each match result. - double minMatchSeparationDistance; //Specifies the minimum separation distance, in pixels, between the origins of two matches that have unique positions. - double minMatchSeparationAngle; //Specifies the minimum angular difference, in degrees, between two matches that have unique angles. - double minMatchSeparationScale; //Specifies the minimum difference in scale, expressed as a percentage, between two matches that have unique scales. - double maxMatchOverlap; //Specifies the maximum amount of overlap, expressed as a percentage, allowed between the bounding rectangles of two unique matches. - int coarseResult; //Specifies whether you want the function to spend less time accurately estimating the location of a match. - int enableCalibrationSupport; //Set this element to TRUE to specify the algorithm treat the inspection image as a calibrated image. - ContrastMode enableContrastReversal; //Use this element to specify the contrast of the matches to search for in the image. - GeometricMatchingSearchStrategy matchStrategy; //Specifies the aggressiveness of the search strategy. - unsigned int refineMatchFactor; //Specifies the factor that is applied to the number of matches requested by the user to determine the number of matches that are refined at the initial matching stage. - unsigned int subpixelMatchFactor; //Specifies the factor that is applied to the number of matches requested by the user to determine the number of matches that are evaluated at the final subpixel matching stage. + unsigned int subpixelIterations; // Specifies the maximum number of + // incremental improvements used to refine + // matches with subpixel information. + double subpixelTolerance; // Specifies the maximum amount of change, in + // pixels, between consecutive incremental + // improvements in the match position before the + // function stops refining the match position. + unsigned int + initialMatchListLength; // Specifies the maximum size of the match list. + int targetTemplateCurveScore; // Set this element to TRUE to specify that the + // function should calculate the match curve to + // template curve score and return it for each + // match result. + int correlationScore; // Set this element to TRUE to specify that the + // function should calculate the correlation score and + // return it for each match result. + double minMatchSeparationDistance; // Specifies the minimum separation + // distance, in pixels, between the + // origins of two matches that have unique + // positions. + double minMatchSeparationAngle; // Specifies the minimum angular difference, + // in degrees, between two matches that have + // unique angles. + double minMatchSeparationScale; // Specifies the minimum difference in scale, + // expressed as a percentage, between two + // matches that have unique scales. + double maxMatchOverlap; // Specifies the maximum amount of overlap, expressed + // as a percentage, allowed between the bounding + // rectangles of two unique matches. + int coarseResult; // Specifies whether you want the function to spend less + // time accurately estimating the location of a match. + int enableCalibrationSupport; // Set this element to TRUE to specify the + // algorithm treat the inspection image as a + // calibrated image. + ContrastMode enableContrastReversal; // Use this element to specify the + // contrast of the matches to search for + // in the image. + GeometricMatchingSearchStrategy + matchStrategy; // Specifies the aggressiveness of the search strategy. + unsigned int refineMatchFactor; // Specifies the factor that is applied to + // the number of matches requested by the + // user to determine the number of matches + // that are refined at the initial matching + // stage. + unsigned int subpixelMatchFactor; // Specifies the factor that is applied to + // the number of matches requested by the + // user to determine the number of matches + // that are evaluated at the final subpixel + // matching stage. } MatchGeometricPatternAdvancedOptions3; typedef struct ColorOptions_struct { - ColorClassificationResolution colorClassificationResolution; //Specifies the color resolution of the classifier. - unsigned int useLuminance; //Specifies if the luminance band is going to be used in the feature vector. - ColorMode colorMode; //Specifies the color mode of the classifier. + ColorClassificationResolution colorClassificationResolution; // Specifies the + // color + // resolution of + // the + // classifier. + unsigned int useLuminance; // Specifies if the luminance band is going to be + // used in the feature vector. + ColorMode colorMode; // Specifies the color mode of the classifier. } ColorOptions; typedef struct SampleScore_struct { - char* className; //The name of the class. - float distance; //The distance from the item to this class. - unsigned int index; //index of this sample. + char* className; // The name of the class. + float distance; // The distance from the item to this class. + unsigned int index; // index of this sample. } SampleScore; typedef struct ClassifierReportAdvanced_struct { - char* bestClassName; //The name of the best class for the sample. - float classificationScore; //The similarity of the sample and the two closest classes in the classifier. - float identificationScore; //The similarity of the sample and the assigned class. - ClassScore* allScores; //All classes and their scores. - int allScoresSize; //The number of entries in allScores. - SampleScore* sampleScores; //All samples and their scores. - int sampleScoresSize; //The number of entries in sampleScores. + char* bestClassName; // The name of the best class for the sample. + float classificationScore; // The similarity of the sample and the two + // closest classes in the classifier. + float identificationScore; // The similarity of the sample and the assigned + // class. + ClassScore* allScores; // All classes and their scores. + int allScoresSize; // The number of entries in allScores. + SampleScore* sampleScores; // All samples and their scores. + int sampleScoresSize; // The number of entries in sampleScores. } ClassifierReportAdvanced; typedef struct LearnGeometricPatternAdvancedOptions2_struct { - double minScaleFactor; //Specifies the minimum scale factor that the template is learned for. - double maxScaleFactor; //Specifies the maximum scale factor the template is learned for. - double minRotationAngleValue; //Specifies the minimum rotation angle the template is learned for. - double maxRotationAngleValue; //Specifies the maximum rotation angle the template is learned for. - unsigned int imageSamplingFactor; //Specifies the factor that is used to subsample the template and the image for the initial matching phase. + double minScaleFactor; // Specifies the minimum scale factor that the + // template is learned for. + double maxScaleFactor; // Specifies the maximum scale factor the template is + // learned for. + double minRotationAngleValue; // Specifies the minimum rotation angle the + // template is learned for. + double maxRotationAngleValue; // Specifies the maximum rotation angle the + // template is learned for. + unsigned int imageSamplingFactor; // Specifies the factor that is used to + // subsample the template and the image for + // the initial matching phase. } LearnGeometricPatternAdvancedOptions2; typedef struct ParticleFilterOptions2_struct { - int rejectMatches; //Set this parameter to TRUE to transfer only those particles that do not meet all the criteria. - int rejectBorder; //Set this element to TRUE to reject border particles. - int fillHoles; //Set this element to TRUE to fill holes in particles. - int connectivity8; //Set this parameter to TRUE to use connectivity-8 to determine whether particles are touching. + int rejectMatches; // Set this parameter to TRUE to transfer only those + // particles that do not meet all the criteria. + int rejectBorder; // Set this element to TRUE to reject border particles. + int fillHoles; // Set this element to TRUE to fill holes in particles. + int connectivity8; // Set this parameter to TRUE to use connectivity-8 to + // determine whether particles are touching. } ParticleFilterOptions2; typedef struct FindEdgeOptions2_struct { - RakeDirection direction; //The direction to search in the ROI. - int showSearchArea; //If TRUE, the function overlays the search area on the image. - int showSearchLines; //If TRUE, the function overlays the search lines used to locate the edges on the image. - int showEdgesFound; //If TRUE, the function overlays the locations of the edges found on the image. - int showResult; //If TRUE, the function overlays the hit lines to the object and the edge used to generate the hit line on the result image. - RGBValue searchAreaColor; //Specifies the RGB color value to use to overlay the search area. - RGBValue searchLinesColor; //Specifies the RGB color value to use to overlay the search lines. - RGBValue searchEdgesColor; //Specifies the RGB color value to use to overlay the search edges. - RGBValue resultColor; //Specifies the RGB color value to use to overlay the results. - char* overlayGroupName; //Specifies the overlay group name to assign to the overlays. - EdgeOptions2 edgeOptions; //Specifies the edge detection options along a single search line. + RakeDirection direction; // The direction to search in the ROI. + int showSearchArea; // If TRUE, the function overlays the search area on the + // image. + int showSearchLines; // If TRUE, the function overlays the search lines used + // to locate the edges on the image. + int showEdgesFound; // If TRUE, the function overlays the locations of the + // edges found on the image. + int showResult; // If TRUE, the function overlays the hit lines to the object + // and the edge used to generate the hit line on the result + // image. + RGBValue searchAreaColor; // Specifies the RGB color value to use to overlay + // the search area. + RGBValue searchLinesColor; // Specifies the RGB color value to use to overlay + // the search lines. + RGBValue searchEdgesColor; // Specifies the RGB color value to use to overlay + // the search edges. + RGBValue resultColor; // Specifies the RGB color value to use to overlay the + // results. + char* overlayGroupName; // Specifies the overlay group name to assign to the + // overlays. + EdgeOptions2 edgeOptions; // Specifies the edge detection options along a + // single search line. } FindEdgeOptions2; typedef struct FindEdgeReport_struct { - StraightEdge* straightEdges; //An array of straight edges detected. - unsigned int numStraightEdges; //Indicates the number of straight edges found. + StraightEdge* straightEdges; // An array of straight edges detected. + unsigned int + numStraightEdges; // Indicates the number of straight edges found. } FindEdgeReport; typedef struct FindTransformRectOptions2_struct { - FindReferenceDirection direction; //Specifies the direction and orientation in which the function searches for the primary axis. - int showSearchArea; //If TRUE, the function overlays the search area on the image. - int showSearchLines; //If TRUE, the function overlays the search lines used to locate the edges on the image. - int showEdgesFound; //If TRUE, the function overlays the locations of the edges found on the image. - int showResult; //If TRUE, the function overlays the hit lines to the object and the edge used to generate the hit line on the result image. - RGBValue searchAreaColor; //Specifies the RGB color value to use to overlay the search area. - RGBValue searchLinesColor; //Specifies the RGB color value to use to overlay the search lines. - RGBValue searchEdgesColor; //Specifies the RGB color value to use to overlay the search edges. - RGBValue resultColor; //Specifies the RGB color value to use to overlay the results. - char* overlayGroupName; //Specifies the overlay group name to assign to the overlays. - EdgeOptions2 edgeOptions; //Specifies the edge detection options along a single search line. + FindReferenceDirection direction; // Specifies the direction and orientation + // in which the function searches for the + // primary axis. + int showSearchArea; // If TRUE, the function overlays the search area on the + // image. + int showSearchLines; // If TRUE, the function overlays the search lines used + // to locate the edges on the image. + int showEdgesFound; // If TRUE, the function overlays the locations of the + // edges found on the image. + int showResult; // If TRUE, the function overlays the hit lines to the object + // and the edge used to generate the hit line on the result + // image. + RGBValue searchAreaColor; // Specifies the RGB color value to use to overlay + // the search area. + RGBValue searchLinesColor; // Specifies the RGB color value to use to overlay + // the search lines. + RGBValue searchEdgesColor; // Specifies the RGB color value to use to overlay + // the search edges. + RGBValue resultColor; // Specifies the RGB color value to use to overlay the + // results. + char* overlayGroupName; // Specifies the overlay group name to assign to the + // overlays. + EdgeOptions2 edgeOptions; // Specifies the edge detection options along a + // single search line. } FindTransformRectOptions2; typedef struct FindTransformRectsOptions2_struct { - FindReferenceDirection direction; //Specifies the direction and orientation in which the function searches for the primary axis. - int showSearchArea; //If TRUE, the function overlays the search area on the image. - int showSearchLines; //If TRUE, the function overlays the search lines used to locate the edges on the image. - int showEdgesFound; //If TRUE, the function overlays the locations of the edges found on the image. - int showResult; //If TRUE, the function overlays the hit lines to the object and the edge used to generate the hit line on the result image. - RGBValue searchAreaColor; //Specifies the RGB color value to use to overlay the search area. - RGBValue searchLinesColor; //Specifies the RGB color value to use to overlay the search lines. - RGBValue searchEdgesColor; //Specifies the RGB color value to use to overlay the search edges. - RGBValue resultColor; //Specifies the RGB color value to use to overlay the results. - char* overlayGroupName; //Specifies the overlay group name to assign to the overlays. - EdgeOptions2 primaryEdgeOptions; //Specifies the parameters used to compute the edge gradient information and detect the edges for the primary ROI. - EdgeOptions2 secondaryEdgeOptions; //Specifies the parameters used to compute the edge gradient information and detect the edges for the secondary ROI. + FindReferenceDirection direction; // Specifies the direction and orientation + // in which the function searches for the + // primary axis. + int showSearchArea; // If TRUE, the function overlays the search area on the + // image. + int showSearchLines; // If TRUE, the function overlays the search lines used + // to locate the edges on the image. + int showEdgesFound; // If TRUE, the function overlays the locations of the + // edges found on the image. + int showResult; // If TRUE, the function overlays the hit lines to the object + // and the edge used to generate the hit line on the result + // image. + RGBValue searchAreaColor; // Specifies the RGB color value to use to overlay + // the search area. + RGBValue searchLinesColor; // Specifies the RGB color value to use to overlay + // the search lines. + RGBValue searchEdgesColor; // Specifies the RGB color value to use to overlay + // the search edges. + RGBValue resultColor; // Specifies the RGB color value to use to overlay the + // results. + char* overlayGroupName; // Specifies the overlay group name to assign to the + // overlays. + EdgeOptions2 primaryEdgeOptions; // Specifies the parameters used to compute + // the edge gradient information and detect + // the edges for the primary ROI. + EdgeOptions2 secondaryEdgeOptions; // Specifies the parameters used to + // compute the edge gradient information + // and detect the edges for the secondary + // ROI. } FindTransformRectsOptions2; typedef struct ReadTextReport3_struct { - const char* readString; //The read string. - CharReport3* characterReport; //An array of reports describing the properties of each identified character. - int numCharacterReports; //The number of identified characters. - ROI* roiBoundingCharacters; //An array specifying the coordinates of the character bounding ROI. + const char* readString; // The read string. + CharReport3* characterReport; // An array of reports describing the + // properties of each identified character. + int numCharacterReports; // The number of identified characters. + ROI* roiBoundingCharacters; // An array specifying the coordinates of the + // character bounding ROI. } ReadTextReport3; typedef struct CharacterStatistics_struct { - int left; //The left offset of the character bounding rectangles in the current ROI. - int top; //The top offset of the character bounding rectangles in the current ROI. - int width; //The width of each of the characters you trained in the current ROI. - int height; //The height of each trained character in the current ROI. - int characterSize; //The size of the character in pixels. + int left; // The left offset of the character bounding rectangles in the + // current ROI. + int top; // The top offset of the character bounding rectangles in the + // current ROI. + int width; // The width of each of the characters you trained in the current + // ROI. + int height; // The height of each trained character in the current ROI. + int characterSize; // The size of the character in pixels. } CharacterStatistics; typedef struct CharReport3_struct { - const char* character; //The character value. - int classificationScore; //The degree to which the assigned character class represents the object better than the other character classes in the character set. - int verificationScore; //The similarity of the character and the reference character for the character class. - int verified; //This element is TRUE if a reference character was found for the character class and FALSE if a reference character was not found. - int lowThreshold; //The minimum value of the threshold range used for this character. - int highThreshold; //The maximum value of the threshold range used for this character. - CharacterStatistics characterStats; //Describes the characters segmented in the ROI. + const char* character; // The character value. + int classificationScore; // The degree to which the assigned character class + // represents the object better than the other + // character classes in the character set. + int verificationScore; // The similarity of the character and the reference + // character for the character class. + int verified; // This element is TRUE if a reference character was found for + // the character class and FALSE if a reference character was + // not found. + int lowThreshold; // The minimum value of the threshold range used for this + // character. + int highThreshold; // The maximum value of the threshold range used for this + // character. + CharacterStatistics + characterStats; // Describes the characters segmented in the ROI. } CharReport3; typedef struct ArcInfo2_struct { - PointFloat center; //The center point of the arc. - double radius; //The radius of the arc. - double startAngle; //The starting angle of the arc, specified counter-clockwise from the x-axis. - double endAngle; //The ending angle of the arc, specified counter-clockwise from the x-axis. + PointFloat center; // The center point of the arc. + double radius; // The radius of the arc. + double startAngle; // The starting angle of the arc, specified + // counter-clockwise from the x-axis. + double endAngle; // The ending angle of the arc, specified counter-clockwise + // from the x-axis. } ArcInfo2; typedef struct EdgeReport2_struct { - EdgeInfo* edges; //An array of edges detected. - unsigned int numEdges; //Indicates the number of edges detected. - double* gradientInfo; //An array that contains the calculated edge strengths along the user-defined search area. - unsigned int numGradientInfo; //Indicates the number of elements contained in gradientInfo. - int calibrationValid; //Indicates if the calibration data corresponding to the location of the edges is correct. + EdgeInfo* edges; // An array of edges detected. + unsigned int numEdges; // Indicates the number of edges detected. + double* gradientInfo; // An array that contains the calculated edge strengths + // along the user-defined search area. + unsigned int numGradientInfo; // Indicates the number of elements contained + // in gradientInfo. + int calibrationValid; // Indicates if the calibration data corresponding to + // the location of the edges is correct. } EdgeReport2; typedef struct SearchArcInfo_struct { - ArcInfo2 arcCoordinates; //Describes the arc used for edge detection. - EdgeReport2 edgeReport; //Describes the edges found in this search line. + ArcInfo2 arcCoordinates; // Describes the arc used for edge detection. + EdgeReport2 edgeReport; // Describes the edges found in this search line. } SearchArcInfo; typedef struct ConcentricRakeReport2_struct { - EdgeInfo* firstEdges; //The first edge point detected along each search line in the ROI. - unsigned int numFirstEdges; //The number of points in the firstEdges array. - EdgeInfo* lastEdges; //The last edge point detected along each search line in the ROI. - unsigned int numLastEdges; //The number of points in the lastEdges array. - SearchArcInfo* searchArcs; //Contains the arcs used for edge detection and the edge information for each arc. - unsigned int numSearchArcs; //The number of arcs in the searchArcs array. + EdgeInfo* firstEdges; // The first edge point detected along each search line + // in the ROI. + unsigned int numFirstEdges; // The number of points in the firstEdges array. + EdgeInfo* lastEdges; // The last edge point detected along each search line + // in the ROI. + unsigned int numLastEdges; // The number of points in the lastEdges array. + SearchArcInfo* searchArcs; // Contains the arcs used for edge detection and + // the edge information for each arc. + unsigned int numSearchArcs; // The number of arcs in the searchArcs array. } ConcentricRakeReport2; typedef struct SpokeReport2_struct { - EdgeInfo* firstEdges; //The first edge point detected along each search line in the ROI. - unsigned int numFirstEdges; //The number of points in the firstEdges array. - EdgeInfo* lastEdges; //The last edge point detected along each search line in the ROI. - unsigned int numLastEdges; //The number of points in the lastEdges array. - SearchLineInfo* searchLines; //The search lines used for edge detection. - unsigned int numSearchLines; //The number of search lines used in the edge detection. + EdgeInfo* firstEdges; // The first edge point detected along each search line + // in the ROI. + unsigned int numFirstEdges; // The number of points in the firstEdges array. + EdgeInfo* lastEdges; // The last edge point detected along each search line + // in the ROI. + unsigned int numLastEdges; // The number of points in the lastEdges array. + SearchLineInfo* searchLines; // The search lines used for edge detection. + unsigned int + numSearchLines; // The number of search lines used in the edge detection. } SpokeReport2; typedef struct EdgeInfo_struct { - PointFloat position; //The location of the edge in the image. - PointFloat calibratedPosition; //The position of the edge in the image in real-world coordinates. - double distance; //The location of the edge from the first point along the boundary of the input ROI. - double calibratedDistance; //The location of the edge from the first point along the boundary of the input ROI in real-world coordinates. - double magnitude; //The intensity contrast at the edge. - double noisePeak; //The strength of the noise associated with the current edge. - int rising; //Indicates the polarity of the edge. + PointFloat position; // The location of the edge in the image. + PointFloat calibratedPosition; // The position of the edge in the image in + // real-world coordinates. + double distance; // The location of the edge from the first point along the + // boundary of the input ROI. + double calibratedDistance; // The location of the edge from the first point + // along the boundary of the input ROI in + // real-world coordinates. + double magnitude; // The intensity contrast at the edge. + double + noisePeak; // The strength of the noise associated with the current edge. + int rising; // Indicates the polarity of the edge. } EdgeInfo; typedef struct SearchLineInfo_struct { - LineFloat lineCoordinates; //The endpoints of the search line. - EdgeReport2 edgeReport; //Describes the edges found in this search line. + LineFloat lineCoordinates; // The endpoints of the search line. + EdgeReport2 edgeReport; // Describes the edges found in this search line. } SearchLineInfo; typedef struct RakeReport2_struct { - EdgeInfo* firstEdges; //The first edge point detected along each search line in the ROI. - unsigned int numFirstEdges; //The number of points in the firstEdges array. - EdgeInfo* lastEdges; //The last edge point detected along each search line in the ROI. - unsigned int numLastEdges; //The number of points in the lastEdges array. - SearchLineInfo* searchLines; //The search lines used for edge detection. - unsigned int numSearchLines; //The number of search lines used in the edge detection. + EdgeInfo* firstEdges; // The first edge point detected along each search line + // in the ROI. + unsigned int numFirstEdges; // The number of points in the firstEdges array. + EdgeInfo* lastEdges; // The last edge point detected along each search line + // in the ROI. + unsigned int numLastEdges; // The number of points in the lastEdges array. + SearchLineInfo* searchLines; // The search lines used for edge detection. + unsigned int + numSearchLines; // The number of search lines used in the edge detection. } RakeReport2; typedef struct TransformBehaviors_struct { - GroupBehavior ShiftBehavior; //Specifies the behavior of an overlay group when a shift operation is applied to an image. - GroupBehavior ScaleBehavior; //Specifies the behavior of an overlay group when a scale operation is applied to an image. - GroupBehavior RotateBehavior; //Specifies the behavior of an overlay group when a rotate operation is applied to an image. - GroupBehavior SymmetryBehavior; //Specifies the behavior of an overlay group when a symmetry operation is applied to an image. + GroupBehavior ShiftBehavior; // Specifies the behavior of an overlay group + // when a shift operation is applied to an + // image. + GroupBehavior ScaleBehavior; // Specifies the behavior of an overlay group + // when a scale operation is applied to an + // image. + GroupBehavior RotateBehavior; // Specifies the behavior of an overlay group + // when a rotate operation is applied to an + // image. + GroupBehavior SymmetryBehavior; // Specifies the behavior of an overlay group + // when a symmetry operation is applied to an + // image. } TransformBehaviors; typedef struct QRCodeDataToken_struct { - QRStreamMode mode; //Specifies the stream mode or the format of the data that is encoded in the QR code. - unsigned int modeData; //Indicates specifiers used by the user to postprocess the data if it requires it. - unsigned char* data; //Shows the encoded data in the QR code. - unsigned int dataLength; //Specifies the length of the data found in the QR code. + QRStreamMode mode; // Specifies the stream mode or the format of the data + // that is encoded in the QR code. + unsigned int modeData; // Indicates specifiers used by the user to + // postprocess the data if it requires it. + unsigned char* data; // Shows the encoded data in the QR code. + unsigned int + dataLength; // Specifies the length of the data found in the QR code. } QRCodeDataToken; typedef struct ParticleFilterOptions_struct { - int rejectMatches; //Set this parameter to TRUE to transfer only those particles that do not meet all the criteria. - int rejectBorder; //Set this element to TRUE to reject border particles. - int connectivity8; //Set this parameter to TRUE to use connectivity-8 to determine whether particles are touching. + int rejectMatches; // Set this parameter to TRUE to transfer only those + // particles that do not meet all the criteria. + int rejectBorder; // Set this element to TRUE to reject border particles. + int connectivity8; // Set this parameter to TRUE to use connectivity-8 to + // determine whether particles are touching. } ParticleFilterOptions; typedef struct StraightEdgeReport2_struct { - StraightEdge* straightEdges; //Contains an array of found straight edges. - unsigned int numStraightEdges; //Indicates the number of straight edges found. - SearchLineInfo* searchLines; //Contains an array of all search lines used in the detection. - unsigned int numSearchLines; //The number of search lines used in the edge detection. + StraightEdge* straightEdges; // Contains an array of found straight edges. + unsigned int + numStraightEdges; // Indicates the number of straight edges found. + SearchLineInfo* searchLines; // Contains an array of all search lines used in + // the detection. + unsigned int + numSearchLines; // The number of search lines used in the edge detection. } StraightEdgeReport2; typedef struct StraightEdgeOptions_struct { - unsigned int numLines; //Specifies the number of straight edges to find. - StraightEdgeSearchMode searchMode; //Specifies the method used to find the straight edge. - double minScore; //Specifies the minimum score of a detected straight edge. - double maxScore; //Specifies the maximum score of a detected edge. - double orientation; //Specifies the angle at which the straight edge is expected to be found. - double angleRange; //Specifies the +/- range around the orientation within which the straight edge is expected to be found. - double angleTolerance; //Specifies the expected angular accuracy of the straight edge. - unsigned int stepSize; //Specifies the gap in pixels between the search lines used with the rake-based methods. - double minSignalToNoiseRatio; //Specifies the minimum signal to noise ratio (SNR) of the edge points used to fit the straight edge. - double minCoverage; //Specifies the minimum number of points as a percentage of the number of search lines that need to be included in the detected straight edge. - unsigned int houghIterations; //Specifies the number of iterations used in the Hough-based method. + unsigned int numLines; // Specifies the number of straight edges to find. + StraightEdgeSearchMode + searchMode; // Specifies the method used to find the straight edge. + double minScore; // Specifies the minimum score of a detected straight edge. + double maxScore; // Specifies the maximum score of a detected edge. + double orientation; // Specifies the angle at which the straight edge is + // expected to be found. + double angleRange; // Specifies the +/- range around the orientation within + // which the straight edge is expected to be found. + double angleTolerance; // Specifies the expected angular accuracy of the + // straight edge. + unsigned int stepSize; // Specifies the gap in pixels between the search + // lines used with the rake-based methods. + double minSignalToNoiseRatio; // Specifies the minimum signal to noise ratio + // (SNR) of the edge points used to fit the + // straight edge. + double minCoverage; // Specifies the minimum number of points as a percentage + // of the number of search lines that need to be included + // in the detected straight edge. + unsigned int houghIterations; // Specifies the number of iterations used in + // the Hough-based method. } StraightEdgeOptions; typedef struct StraightEdge_struct { - LineFloat straightEdgeCoordinates; //End points of the detected straight edge in pixel coordinates. - LineFloat calibratedStraightEdgeCoordinates; //End points of the detected straight edge in real-world coordinates. - double angle; //Angle of the found edge using the pixel coordinates. - double calibratedAngle; //Angle of the found edge using the real-world coordinates. - double score; //Describes the score of the detected edge. - double straightness; //The straightness value of the detected straight edge. - double averageSignalToNoiseRatio; //Describes the average signal to noise ratio (SNR) of the detected edge. - int calibrationValid; //Indicates if the calibration data for the straight edge is valid. - EdgeInfo* usedEdges; //An array of edges that were used to determine this straight line. - unsigned int numUsedEdges; //Indicates the number of edges in the usedEdges array. + LineFloat straightEdgeCoordinates; // End points of the detected straight + // edge in pixel coordinates. + LineFloat calibratedStraightEdgeCoordinates; // End points of the detected + // straight edge in real-world + // coordinates. + double angle; // Angle of the found edge using the pixel coordinates. + double calibratedAngle; // Angle of the found edge using the real-world + // coordinates. + double score; // Describes the score of the detected edge. + double straightness; // The straightness value of the detected straight edge. + double averageSignalToNoiseRatio; // Describes the average signal to noise + // ratio (SNR) of the detected edge. + int calibrationValid; // Indicates if the calibration data for the straight + // edge is valid. + EdgeInfo* usedEdges; // An array of edges that were used to determine this + // straight line. + unsigned int + numUsedEdges; // Indicates the number of edges in the usedEdges array. } StraightEdge; typedef struct QRCodeSearchOptions_struct { - QRRotationMode rotationMode; //Specifies the amount of QR code rotation the function should allow for. - unsigned int skipLocation; //If set to TRUE, specifies that the function should assume that the QR code occupies the entire image (or the entire search region). - unsigned int edgeThreshold; //The strength of the weakest edge the function uses to find the coarse location of the QR code in the image. - QRDemodulationMode demodulationMode; //The demodulation mode the function uses to locate the QR code. - QRCellSampleSize cellSampleSize; //The cell sample size the function uses to locate the QR code. - QRCellFilterMode cellFilterMode; //The cell filter mode the function uses to locate the QR code. - unsigned int skewDegreesAllowed; //Specifies the amount of skew in the QR code the function should allow for. + QRRotationMode rotationMode; // Specifies the amount of QR code rotation the + // function should allow for. + unsigned int skipLocation; // If set to TRUE, specifies that the function + // should assume that the QR code occupies the + // entire image (or the entire search region). + unsigned int edgeThreshold; // The strength of the weakest edge the function + // uses to find the coarse location of the QR + // code in the image. + QRDemodulationMode demodulationMode; // The demodulation mode the function + // uses to locate the QR code. + QRCellSampleSize cellSampleSize; // The cell sample size the function uses to + // locate the QR code. + QRCellFilterMode cellFilterMode; // The cell filter mode the function uses to + // locate the QR code. + unsigned int skewDegreesAllowed; // Specifies the amount of skew in the QR + // code the function should allow for. } QRCodeSearchOptions; typedef struct QRCodeSizeOptions_struct { - unsigned int minSize; //Specifies the minimum size (in pixels) of the QR code in the image. - unsigned int maxSize; //Specifies the maximum size (in pixels) of the QR code in the image. + unsigned int minSize; // Specifies the minimum size (in pixels) of the QR + // code in the image. + unsigned int maxSize; // Specifies the maximum size (in pixels) of the QR + // code in the image. } QRCodeSizeOptions; typedef struct QRCodeDescriptionOptions_struct { - QRDimensions dimensions; //The number of rows and columns that are populated for the QR code, measured in cells. - QRPolarities polarity; //The polarity of the QR code. - QRMirrorMode mirror; //This element is TRUE if the QR code appears mirrored in the image and FALSE if the QR code appears normally in the image. - QRModelType modelType; //This option allows you to specify the type of QR code. + QRDimensions dimensions; // The number of rows and columns that are populated + // for the QR code, measured in cells. + QRPolarities polarity; // The polarity of the QR code. + QRMirrorMode mirror; // This element is TRUE if the QR code appears mirrored + // in the image and FALSE if the QR code appears + // normally in the image. + QRModelType + modelType; // This option allows you to specify the type of QR code. } QRCodeDescriptionOptions; typedef struct QRCodeReport_struct { - unsigned int found; //This element is TRUE if the function located and decoded a QR code and FALSE if the function failed to locate and decode a QR code. - unsigned char* data; //The data encoded in the QR code. - unsigned int dataLength; //The length of the data array. - PointFloat boundingBox[4]; //An array of four points describing the rectangle surrounding the QR code. - QRCodeDataToken* tokenizedData; //Contains the data tokenized in exactly the way it was encoded in the code. - unsigned int sizeOfTokenizedData; //Size of the tokenized data. - unsigned int numErrorsCorrected; //The number of errors the function corrected when decoding the QR code. - unsigned int dimensions; //The number of rows and columns that are populated for the QR code, measured in cells. - unsigned int version; //The version of the QR code. - QRModelType modelType; //This option allows you to specify what type of QR code this is. - QRStreamMode streamMode; //The format of the data encoded in the stream. - QRPolarities matrixPolarity; //The polarity of the QR code. - unsigned int mirrored; //This element is TRUE if the QR code appears mirrored in the image and FALSE if the QR code appears normally in the image. - unsigned int positionInAppendStream; //Indicates what position the QR code is in with respect to the stream of data in all codes. - unsigned int sizeOfAppendStream; //Specifies how many QR codes are part of a larger array of codes. - int firstEAN128ApplicationID; //The first EAN-128 Application ID encountered in the stream. - int firstECIDesignator; //The first Regional Language Designator encountered in the stream. - unsigned int appendStreamIdentifier; //Specifies what stream the QR code is in relation to when the code is part of a larger array of codes. - unsigned int minimumEdgeStrength; //The strength of the weakest edge the function used to find the coarse location of the QR code in the image. - QRDemodulationMode demodulationMode; //The demodulation mode the function used to locate the QR code. - QRCellSampleSize cellSampleSize; //The cell sample size the function used to locate the QR code. - QRCellFilterMode cellFilterMode; //The cell filter mode the function used to locate the QR code. + unsigned int found; // This element is TRUE if the function located and + // decoded a QR code and FALSE if the function failed to + // locate and decode a QR code. + unsigned char* data; // The data encoded in the QR code. + unsigned int dataLength; // The length of the data array. + PointFloat boundingBox[4]; // An array of four points describing the + // rectangle surrounding the QR code. + QRCodeDataToken* tokenizedData; // Contains the data tokenized in exactly the + // way it was encoded in the code. + unsigned int sizeOfTokenizedData; // Size of the tokenized data. + unsigned int numErrorsCorrected; // The number of errors the function + // corrected when decoding the QR code. + unsigned int dimensions; // The number of rows and columns that are populated + // for the QR code, measured in cells. + unsigned int version; // The version of the QR code. + QRModelType modelType; // This option allows you to specify what type of QR + // code this is. + QRStreamMode streamMode; // The format of the data encoded in the stream. + QRPolarities matrixPolarity; // The polarity of the QR code. + unsigned int mirrored; // This element is TRUE if the QR code appears + // mirrored in the image and FALSE if the QR code + // appears normally in the image. + unsigned int positionInAppendStream; // Indicates what position the QR code + // is in with respect to the stream of + // data in all codes. + unsigned int sizeOfAppendStream; // Specifies how many QR codes are part of a + // larger array of codes. + int firstEAN128ApplicationID; // The first EAN-128 Application ID encountered + // in the stream. + int firstECIDesignator; // The first Regional Language Designator encountered + // in the stream. + unsigned int appendStreamIdentifier; // Specifies what stream the QR code is + // in relation to when the code is part + // of a larger array of codes. + unsigned int minimumEdgeStrength; // The strength of the weakest edge the + // function used to find the coarse + // location of the QR code in the image. + QRDemodulationMode demodulationMode; // The demodulation mode the function + // used to locate the QR code. + QRCellSampleSize cellSampleSize; // The cell sample size the function used to + // locate the QR code. + QRCellFilterMode cellFilterMode; // The cell filter mode the function used to + // locate the QR code. } QRCodeReport; typedef struct AIMGradeReport_struct { - AIMGrade overallGrade; //The overall letter grade, which is equal to the lowest of the other five letter grades. - AIMGrade decodingGrade; //The letter grade assigned to a Data Matrix barcode based on the success of the function in decoding the Data Matrix barcode. - AIMGrade symbolContrastGrade; //The letter grade assigned to a Data Matrix barcode based on the symbol contrast raw score. - float symbolContrast; //The symbol contrast raw score representing the percentage difference between the mean of the reflectance of the darkest 10 percent and lightest 10 percent of the Data Matrix barcode. - AIMGrade printGrowthGrade; //The print growth letter grade for the Data Matrix barcode. - float printGrowth; //The print growth raw score for the barcode, which is based on the extent to which dark or light markings appropriately fill their module boundaries. - AIMGrade axialNonuniformityGrade; //The axial nonuniformity grade for the Data Matrix barcode. - float axialNonuniformity; //The axial nonuniformity raw score for the barcode, which is based on how much the sampling point spacing differs from one axis to another. - AIMGrade unusedErrorCorrectionGrade; //The unused error correction letter grade for the Data Matrix barcode. - float unusedErrorCorrection; //The unused error correction raw score for the Data Matrix barcode, which is based on the extent to which regional or spot damage in the Data Matrix barcode has eroded the reading safety margin provided by the error correction. + AIMGrade overallGrade; // The overall letter grade, which is equal to the + // lowest of the other five letter grades. + AIMGrade decodingGrade; // The letter grade assigned to a Data Matrix barcode + // based on the success of the function in decoding + // the Data Matrix barcode. + AIMGrade symbolContrastGrade; // The letter grade assigned to a Data Matrix + // barcode based on the symbol contrast raw + // score. + float symbolContrast; // The symbol contrast raw score representing the + // percentage difference between the mean of the + // reflectance of the darkest 10 percent and lightest + // 10 percent of the Data Matrix barcode. + AIMGrade printGrowthGrade; // The print growth letter grade for the Data + // Matrix barcode. + float printGrowth; // The print growth raw score for the barcode, which is + // based on the extent to which dark or light markings + // appropriately fill their module boundaries. + AIMGrade axialNonuniformityGrade; // The axial nonuniformity grade for the + // Data Matrix barcode. + float axialNonuniformity; // The axial nonuniformity raw score for the + // barcode, which is based on how much the sampling + // point spacing differs from one axis to another. + AIMGrade unusedErrorCorrectionGrade; // The unused error correction letter + // grade for the Data Matrix barcode. + float unusedErrorCorrection; // The unused error correction raw score for the + // Data Matrix barcode, which is based on the + // extent to which regional or spot damage in + // the Data Matrix barcode has eroded the + // reading safety margin provided by the error + // correction. } AIMGradeReport; typedef struct DataMatrixSizeOptions_struct { - unsigned int minSize; //Specifies the minimum size (in pixels) of the Data Matrix barcode in the image. - unsigned int maxSize; //Specifies the maximum size (in pixels) of the Data Matrix barcode in the image. - unsigned int quietZoneWidth; //Specifies the expected minimum size of the quiet zone, in pixels. + unsigned int minSize; // Specifies the minimum size (in pixels) of the Data + // Matrix barcode in the image. + unsigned int maxSize; // Specifies the maximum size (in pixels) of the Data + // Matrix barcode in the image. + unsigned int quietZoneWidth; // Specifies the expected minimum size of the + // quiet zone, in pixels. } DataMatrixSizeOptions; typedef struct DataMatrixDescriptionOptions_struct { - float aspectRatio; //Specifies the ratio of the width of each Data Matrix barcode cell (in pixels) to the height of the Data Matrix barcode (in pixels). - unsigned int rows; //Specifies the number of rows in the Data Matrix barcode. - unsigned int columns; //Specifies the number of columns in the Data Matrix barcode. - int rectangle; //Set this element to TRUE to specify that the Data Matrix barcode is rectangular. - DataMatrixECC ecc; //Specifies the ECC used for this Data Matrix barcode. - DataMatrixPolarity polarity; //Specifies the data-to-background contrast for the Data Matrix barcode. - DataMatrixCellFillMode cellFill; //Specifies the fill percentage for a cell of the Data Matrix barcode that is in the "ON" state. - float minBorderIntegrity; //Specifies the minimum percentage of the border (locator pattern and timing pattern) the function should expect in the Data Matrix barcode. - DataMatrixMirrorMode mirrorMode; //Specifies if the Data Matrix barcode appears normally in the image or if the barcode appears mirrored in the image. + float aspectRatio; // Specifies the ratio of the width of each Data Matrix + // barcode cell (in pixels) to the height of the Data + // Matrix barcode (in pixels). + unsigned int rows; // Specifies the number of rows in the Data Matrix + // barcode. + unsigned int + columns; // Specifies the number of columns in the Data Matrix barcode. + int rectangle; // Set this element to TRUE to specify that the Data Matrix + // barcode is rectangular. + DataMatrixECC ecc; // Specifies the ECC used for this Data Matrix barcode. + DataMatrixPolarity polarity; // Specifies the data-to-background contrast for + // the Data Matrix barcode. + DataMatrixCellFillMode cellFill; // Specifies the fill percentage for a cell + // of the Data Matrix barcode that is in the + // "ON" state. + float minBorderIntegrity; // Specifies the minimum percentage of the border + // (locator pattern and timing pattern) the + // function should expect in the Data Matrix + // barcode. + DataMatrixMirrorMode mirrorMode; // Specifies if the Data Matrix barcode + // appears normally in the image or if the + // barcode appears mirrored in the image. } DataMatrixDescriptionOptions; typedef struct DataMatrixSearchOptions_struct { - DataMatrixRotationMode rotationMode; //Specifies the amount of Data Matrix barcode rotation the function should allow for. - int skipLocation; //If set to TRUE, specifies that the function should assume that the Data Matrix barcode occupies the entire image (or the entire search region). - unsigned int edgeThreshold; //Specifies the minimum contrast a pixel must have in order to be considered part of a matrix cell edge. - DataMatrixDemodulationMode demodulationMode; //Specifies the mode the function should use to demodulate (determine which cells are on and which cells are off) the Data Matrix barcode. - DataMatrixCellSampleSize cellSampleSize; //Specifies the sample size, in pixels, the function should take to determine if each cell is on or off. - DataMatrixCellFilterMode cellFilterMode; //Specifies the mode the function uses to determine the pixel value for each cell. - unsigned int skewDegreesAllowed; //Specifies the amount of skew in the Data Matrix barcode the function should allow for. - unsigned int maxIterations; //Specifies the maximum number of iterations before the function stops looking for the Data Matrix barcode. - unsigned int initialSearchVectorWidth; //Specifies the number of pixels the function should average together to determine the location of an edge. + DataMatrixRotationMode rotationMode; // Specifies the amount of Data Matrix + // barcode rotation the function should + // allow for. + int skipLocation; // If set to TRUE, specifies that the function should + // assume that the Data Matrix barcode occupies the entire + // image (or the entire search region). + unsigned int edgeThreshold; // Specifies the minimum contrast a pixel must + // have in order to be considered part of a + // matrix cell edge. + DataMatrixDemodulationMode demodulationMode; // Specifies the mode the + // function should use to + // demodulate (determine which + // cells are on and which cells + // are off) the Data Matrix + // barcode. + DataMatrixCellSampleSize cellSampleSize; // Specifies the sample size, in + // pixels, the function should take + // to determine if each cell is on + // or off. + DataMatrixCellFilterMode cellFilterMode; // Specifies the mode the function + // uses to determine the pixel value + // for each cell. + unsigned int skewDegreesAllowed; // Specifies the amount of skew in the Data + // Matrix barcode the function should allow + // for. + unsigned int maxIterations; // Specifies the maximum number of iterations + // before the function stops looking for the Data + // Matrix barcode. + unsigned int initialSearchVectorWidth; // Specifies the number of pixels the + // function should average together to + // determine the location of an edge. } DataMatrixSearchOptions; typedef struct DataMatrixReport_struct { - int found; //This element is TRUE if the function located and decoded a Data Matrix barcode and FALSE if the function failed to locate and decode a Data Matrix barcode. - int binary; //This element is TRUE if the Data Matrix barcode contains binary data and FALSE if the Data Matrix barcode contains text data. - unsigned char* data; //The data encoded in the Data Matrix barcode. - unsigned int dataLength; //The length of the data array. - PointFloat boundingBox[4]; //An array of four points describing the rectangle surrounding the Data Matrix barcode. - unsigned int numErrorsCorrected; //The number of errors the function corrected when decoding the Data Matrix barcode. - unsigned int numErasuresCorrected; //The number of erasures the function corrected when decoding the Data Matrix barcode. - float aspectRatio; //Specifies the aspect ratio of the Data Matrix barcode in the image, which equals the ratio of the width of a Data Matrix barcode cell (in pixels) to the height of a Data Matrix barcode cell (in pixels). - unsigned int rows; //The number of rows in the Data Matrix barcode. - unsigned int columns; //The number of columns in the Data Matrix barcode. - DataMatrixECC ecc; //The Error Correction Code (ECC) used by the Data Matrix barcode. - DataMatrixPolarity polarity; //The polarity of the Data Matrix barcode. - DataMatrixCellFillMode cellFill; //The cell fill percentage of the Data Matrix barcode. - float borderIntegrity; //The percentage of the Data Matrix barcode border that appears correctly in the image. - int mirrored; //This element is TRUE if the Data Matrix barcode appears mirrored in the image and FALSE if the Data Matrix barcode appears normally in the image. - unsigned int minimumEdgeStrength; //The strength of the weakest edge the function used to find the coarse location of the Data Matrix barcode in the image. - DataMatrixDemodulationMode demodulationMode; //The demodulation mode the function used to locate the Data Matrix barcode. - DataMatrixCellSampleSize cellSampleSize; //The cell sample size the function used to locate the Data Matrix barcode. - DataMatrixCellFilterMode cellFilterMode; //The cell filter mode the function used to locate the Data Matrix barcode. - unsigned int iterations; //The number of iterations the function took in attempting to locate the Data Matrix barcode. + int found; // This element is TRUE if the function located and decoded a Data + // Matrix barcode and FALSE if the function failed to locate and + // decode a Data Matrix barcode. + int binary; // This element is TRUE if the Data Matrix barcode contains + // binary data and FALSE if the Data Matrix barcode contains text + // data. + unsigned char* data; // The data encoded in the Data Matrix barcode. + unsigned int dataLength; // The length of the data array. + PointFloat boundingBox[4]; // An array of four points describing the + // rectangle surrounding the Data Matrix barcode. + unsigned int numErrorsCorrected; // The number of errors the function + // corrected when decoding the Data Matrix + // barcode. + unsigned int numErasuresCorrected; // The number of erasures the function + // corrected when decoding the Data Matrix + // barcode. + float aspectRatio; // Specifies the aspect ratio of the Data Matrix barcode + // in the image, which equals the ratio of the width of a + // Data Matrix barcode cell (in pixels) to the height of a + // Data Matrix barcode cell (in pixels). + unsigned int rows; // The number of rows in the Data Matrix barcode. + unsigned int columns; // The number of columns in the Data Matrix barcode. + DataMatrixECC + ecc; // The Error Correction Code (ECC) used by the Data Matrix barcode. + DataMatrixPolarity polarity; // The polarity of the Data Matrix barcode. + DataMatrixCellFillMode + cellFill; // The cell fill percentage of the Data Matrix barcode. + float borderIntegrity; // The percentage of the Data Matrix barcode border + // that appears correctly in the image. + int mirrored; // This element is TRUE if the Data Matrix barcode appears + // mirrored in the image and FALSE if the Data Matrix barcode + // appears normally in the image. + unsigned int minimumEdgeStrength; // The strength of the weakest edge the + // function used to find the coarse + // location of the Data Matrix barcode in + // the image. + DataMatrixDemodulationMode demodulationMode; // The demodulation mode the + // function used to locate the + // Data Matrix barcode. + DataMatrixCellSampleSize cellSampleSize; // The cell sample size the function + // used to locate the Data Matrix + // barcode. + DataMatrixCellFilterMode cellFilterMode; // The cell filter mode the function + // used to locate the Data Matrix + // barcode. + unsigned int iterations; // The number of iterations the function took in + // attempting to locate the Data Matrix barcode. } DataMatrixReport; typedef struct JPEG2000FileAdvancedOptions_struct { - WaveletTransformMode waveletMode; //Determines which wavelet transform to use when writing the file. - int useMultiComponentTransform; //Set this parameter to TRUE to use an additional transform on RGB images. - unsigned int maxWaveletTransformLevel; //Specifies the maximum allowed level of wavelet transform. - float quantizationStepSize; //Specifies the absolute base quantization step size for derived quantization mode. + WaveletTransformMode waveletMode; // Determines which wavelet transform to + // use when writing the file. + int useMultiComponentTransform; // Set this parameter to TRUE to use an + // additional transform on RGB images. + unsigned int maxWaveletTransformLevel; // Specifies the maximum allowed level + // of wavelet transform. + float quantizationStepSize; // Specifies the absolute base quantization step + // size for derived quantization mode. } JPEG2000FileAdvancedOptions; typedef struct MatchGeometricPatternAdvancedOptions2_struct { - int minFeaturesUsed; //Specifies the minimum number of features the function uses when matching. - int maxFeaturesUsed; //Specifies the maximum number of features the function uses when matching. - int subpixelIterations; //Specifies the maximum number of incremental improvements used to refine matches with subpixel information. - double subpixelTolerance; //Specifies the maximum amount of change, in pixels, between consecutive incremental improvements in the match position before the function stops refining the match position. - int initialMatchListLength; //Specifies the maximum size of the match list. - float matchTemplateCurveScore; //Set this element to TRUE to specify that the function should calculate the match curve to template curve score and return it for each match result. - int correlationScore; //Set this element to TRUE to specify that the function should calculate the correlation score and return it for each match result. - double minMatchSeparationDistance; //Specifies the minimum separation distance, in pixels, between the origins of two matches that have unique positions. - double minMatchSeparationAngle; //Specifies the minimum angular difference, in degrees, between two matches that have unique angles. - double minMatchSeparationScale; //Specifies the minimum difference in scale, expressed as a percentage, between two matches that have unique scales. - double maxMatchOverlap; //Specifies the maximum amount of overlap, expressed as a percentage, allowed between the bounding rectangles of two unique matches. - int coarseResult; //Specifies whether you want the function to spend less time accurately estimating the location of a match. - int smoothContours; //Set this element to TRUE to specify smoothing be done on the contours of the inspection image before feature extraction. - int enableCalibrationSupport; //Set this element to TRUE to specify the algorithm treat the inspection image as a calibrated image. + int minFeaturesUsed; // Specifies the minimum number of features the function + // uses when matching. + int maxFeaturesUsed; // Specifies the maximum number of features the function + // uses when matching. + int subpixelIterations; // Specifies the maximum number of incremental + // improvements used to refine matches with subpixel + // information. + double subpixelTolerance; // Specifies the maximum amount of change, in + // pixels, between consecutive incremental + // improvements in the match position before the + // function stops refining the match position. + int initialMatchListLength; // Specifies the maximum size of the match list. + float matchTemplateCurveScore; // Set this element to TRUE to specify that + // the function should calculate the match + // curve to template curve score and return it + // for each match result. + int correlationScore; // Set this element to TRUE to specify that the + // function should calculate the correlation score and + // return it for each match result. + double minMatchSeparationDistance; // Specifies the minimum separation + // distance, in pixels, between the + // origins of two matches that have unique + // positions. + double minMatchSeparationAngle; // Specifies the minimum angular difference, + // in degrees, between two matches that have + // unique angles. + double minMatchSeparationScale; // Specifies the minimum difference in scale, + // expressed as a percentage, between two + // matches that have unique scales. + double maxMatchOverlap; // Specifies the maximum amount of overlap, expressed + // as a percentage, allowed between the bounding + // rectangles of two unique matches. + int coarseResult; // Specifies whether you want the function to spend less + // time accurately estimating the location of a match. + int smoothContours; // Set this element to TRUE to specify smoothing be done + // on the contours of the inspection image before feature + // extraction. + int enableCalibrationSupport; // Set this element to TRUE to specify the + // algorithm treat the inspection image as a + // calibrated image. } MatchGeometricPatternAdvancedOptions2; typedef struct InspectionAlignment_struct { - PointFloat position; //The location of the center of the golden template in the image under inspection. - float rotation; //The rotation of the golden template in the image under inspection, in degrees. - float scale; //The percentage of the size of the area under inspection compared to the size of the golden template. + PointFloat position; // The location of the center of the golden template in + // the image under inspection. + float rotation; // The rotation of the golden template in the image under + // inspection, in degrees. + float scale; // The percentage of the size of the area under inspection + // compared to the size of the golden template. } InspectionAlignment; typedef struct InspectionOptions_struct { - RegistrationMethod registrationMethod; //Specifies how the function registers the golden template and the target image. - NormalizationMethod normalizationMethod; //Specifies how the function normalizes the golden template to the target image. - int edgeThicknessToIgnore; //Specifies desired thickness of edges to be ignored. - float brightThreshold; //Specifies the threshold for areas where the target image is brighter than the golden template. - float darkThreshold; //Specifies the threshold for areas where the target image is darker than the golden template. - int binary; //Specifies whether the function should return a binary image giving the location of defects, or a grayscale image giving the intensity of defects. + RegistrationMethod registrationMethod; // Specifies how the function + // registers the golden template and + // the target image. + NormalizationMethod normalizationMethod; // Specifies how the function + // normalizes the golden template to + // the target image. + int edgeThicknessToIgnore; // Specifies desired thickness of edges to be + // ignored. + float brightThreshold; // Specifies the threshold for areas where the target + // image is brighter than the golden template. + float darkThreshold; // Specifies the threshold for areas where the target + // image is darker than the golden template. + int binary; // Specifies whether the function should return a binary image + // giving the location of defects, or a grayscale image giving + // the intensity of defects. } InspectionOptions; typedef struct CharReport2_struct { - const char* character; //The character value. - PointFloat corner[4]; //An array of four points that describes the rectangle that surrounds the character. - int lowThreshold; //The minimum value of the threshold range used for this character. - int highThreshold; //The maximum value of the threshold range used for this character. - int classificationScore; //The degree to which the assigned character class represents the object better than the other character classes in the character set. - int verificationScore; //The similarity of the character and the reference character for the character class. - int verified; //This element is TRUE if a reference character was found for the character class and FALSE if a reference character was not found. + const char* character; // The character value. + PointFloat corner[4]; // An array of four points that describes the rectangle + // that surrounds the character. + int lowThreshold; // The minimum value of the threshold range used for this + // character. + int highThreshold; // The maximum value of the threshold range used for this + // character. + int classificationScore; // The degree to which the assigned character class + // represents the object better than the other + // character classes in the character set. + int verificationScore; // The similarity of the character and the reference + // character for the character class. + int verified; // This element is TRUE if a reference character was found for + // the character class and FALSE if a reference character was + // not found. } CharReport2; typedef struct CharInfo2_struct { - const char* charValue; //Retrieves the character value of the corresponding character in the character set. - const Image* charImage; //The image you used to train this character. - const Image* internalImage; //The internal representation that NI Vision uses to match objects to this character. - int isReferenceChar; //This element is TRUE if the character is the reference character for the character class. + const char* charValue; // Retrieves the character value of the corresponding + // character in the character set. + const Image* charImage; // The image you used to train this character. + const Image* internalImage; // The internal representation that NI Vision + // uses to match objects to this character. + int isReferenceChar; // This element is TRUE if the character is the + // reference character for the character class. } CharInfo2; typedef struct ReadTextReport2_struct { - const char* readString; //The read string. - CharReport2* characterReport; //An array of reports describing the properties of each identified character. - int numCharacterReports; //The number of identified characters. + const char* readString; // The read string. + CharReport2* characterReport; // An array of reports describing the + // properties of each identified character. + int numCharacterReports; // The number of identified characters. } ReadTextReport2; typedef struct EllipseFeature_struct { - PointFloat position; //The location of the center of the ellipse. - double rotation; //The orientation of the semi-major axis of the ellipse with respect to the horizontal. - double minorRadius; //The length of the semi-minor axis of the ellipse. - double majorRadius; //The length of the semi-major axis of the ellipse. + PointFloat position; // The location of the center of the ellipse. + double rotation; // The orientation of the semi-major axis of the ellipse + // with respect to the horizontal. + double minorRadius; // The length of the semi-minor axis of the ellipse. + double majorRadius; // The length of the semi-major axis of the ellipse. } EllipseFeature; typedef struct CircleFeature_struct { - PointFloat position; //The location of the center of the circle. - double radius; //The radius of the circle. + PointFloat position; // The location of the center of the circle. + double radius; // The radius of the circle. } CircleFeature; typedef struct ConstCurveFeature_struct { - PointFloat position; //The center of the circle that this constant curve lies upon. - double radius; //The radius of the circle that this constant curve lies upon. - double startAngle; //When traveling along the constant curve from one endpoint to the next in a counterclockwise manner, this is the angular component of the vector originating at the center of the constant curve and pointing towards the first endpoint of the constant curve. - double endAngle; //When traveling along the constant curve from one endpoint to the next in a counterclockwise manner, this is the angular component of the vector originating at the center of the constant curve and pointing towards the second endpoint of the constant curve. + PointFloat + position; // The center of the circle that this constant curve lies upon. + double radius; // The radius of the circle that this constant curve lies + // upon. + double startAngle; // When traveling along the constant curve from one + // endpoint to the next in a counterclockwise manner, this + // is the angular component of the vector originating at + // the center of the constant curve and pointing towards + // the first endpoint of the constant curve. + double endAngle; // When traveling along the constant curve from one endpoint + // to the next in a counterclockwise manner, this is the + // angular component of the vector originating at the center + // of the constant curve and pointing towards the second + // endpoint of the constant curve. } ConstCurveFeature; typedef struct RectangleFeature_struct { - PointFloat position; //The center of the rectangle. - PointFloat corner[4]; //The four corners of the rectangle. - double rotation; //The orientation of the rectangle with respect to the horizontal. - double width; //The width of the rectangle. - double height; //The height of the rectangle. + PointFloat position; // The center of the rectangle. + PointFloat corner[4]; // The four corners of the rectangle. + double rotation; // The orientation of the rectangle with respect to the + // horizontal. + double width; // The width of the rectangle. + double height; // The height of the rectangle. } RectangleFeature; typedef struct LegFeature_struct { - PointFloat position; //The location of the leg feature. - PointFloat corner[4]; //The four corners of the leg feature. - double rotation; //The orientation of the leg with respect to the horizontal. - double width; //The width of the leg. - double height; //The height of the leg. + PointFloat position; // The location of the leg feature. + PointFloat corner[4]; // The four corners of the leg feature. + double rotation; // The orientation of the leg with respect to the + // horizontal. + double width; // The width of the leg. + double height; // The height of the leg. } LegFeature; typedef struct CornerFeature_struct { - PointFloat position; //The location of the corner feature. - double rotation; //The angular component of the vector bisecting the corner from position. - double enclosedAngle; //The measure of the enclosed angle of the corner. - int isVirtual; + PointFloat position; // The location of the corner feature. + double rotation; // The angular component of the vector bisecting the corner + // from position. + double enclosedAngle; // The measure of the enclosed angle of the corner. + int isVirtual; } CornerFeature; typedef struct LineFeature_struct { - PointFloat startPoint; //The starting point of the line. - PointFloat endPoint; //The ending point of the line. - double length; //The length of the line measured in pixels from the start point to the end point. - double rotation; //The orientation of the line with respect to the horizontal. + PointFloat startPoint; // The starting point of the line. + PointFloat endPoint; // The ending point of the line. + double length; // The length of the line measured in pixels from the start + // point to the end point. + double + rotation; // The orientation of the line with respect to the horizontal. } LineFeature; typedef struct ParallelLinePairFeature_struct { - PointFloat firstStartPoint; //The starting point of the first line of the pair. - PointFloat firstEndPoint; //The ending point of the first line of the pair. - PointFloat secondStartPoint; //The starting point of the second line of the pair. - PointFloat secondEndPoint; //The ending point of the second line of the pair. - double rotation; //The orientation of the feature with respect to the horizontal. - double distance; //The distance from the first line to the second line. + PointFloat + firstStartPoint; // The starting point of the first line of the pair. + PointFloat firstEndPoint; // The ending point of the first line of the pair. + PointFloat + secondStartPoint; // The starting point of the second line of the pair. + PointFloat secondEndPoint; // The ending point of the second line of the + // pair. + double rotation; // The orientation of the feature with respect to the + // horizontal. + double distance; // The distance from the first line to the second line. } ParallelLinePairFeature; typedef struct PairOfParallelLinePairsFeature_struct { - ParallelLinePairFeature firstParallelLinePair; //The first parallel line pair. - ParallelLinePairFeature secondParallelLinePair; //The second parallel line pair. - double rotation; //The orientation of the feature with respect to the horizontal. - double distance; //The distance from the midline of the first parallel line pair to the midline of the second parallel line pair. + ParallelLinePairFeature + firstParallelLinePair; // The first parallel line pair. + ParallelLinePairFeature + secondParallelLinePair; // The second parallel line pair. + double rotation; // The orientation of the feature with respect to the + // horizontal. + double distance; // The distance from the midline of the first parallel line + // pair to the midline of the second parallel line pair. } PairOfParallelLinePairsFeature; typedef union GeometricFeature_union { - CircleFeature* circle; //A pointer to a CircleFeature. - EllipseFeature* ellipse; //A pointer to an EllipseFeature. - ConstCurveFeature* constCurve; //A pointer to a ConstCurveFeature. - RectangleFeature* rectangle; //A pointer to a RectangleFeature. - LegFeature* leg; //A pointer to a LegFeature. - CornerFeature* corner; //A pointer to a CornerFeature. - ParallelLinePairFeature* parallelLinePair; //A pointer to a ParallelLinePairFeature. - PairOfParallelLinePairsFeature* pairOfParallelLinePairs; //A pointer to a PairOfParallelLinePairsFeature. - LineFeature* line; //A pointer to a LineFeature. - ClosedCurveFeature* closedCurve; //A pointer to a ClosedCurveFeature. + CircleFeature* circle; // A pointer to a CircleFeature. + EllipseFeature* ellipse; // A pointer to an EllipseFeature. + ConstCurveFeature* constCurve; // A pointer to a ConstCurveFeature. + RectangleFeature* rectangle; // A pointer to a RectangleFeature. + LegFeature* leg; // A pointer to a LegFeature. + CornerFeature* corner; // A pointer to a CornerFeature. + ParallelLinePairFeature* + parallelLinePair; // A pointer to a ParallelLinePairFeature. + PairOfParallelLinePairsFeature* + pairOfParallelLinePairs; // A pointer to a + // PairOfParallelLinePairsFeature. + LineFeature* line; // A pointer to a LineFeature. + ClosedCurveFeature* closedCurve; // A pointer to a ClosedCurveFeature. } GeometricFeature; typedef struct FeatureData_struct { - FeatureType type; //An enumeration representing the type of the feature. - PointFloat* contourPoints; //A set of points describing the contour of the feature. - int numContourPoints; //The number of points in the contourPoints array. - GeometricFeature feature; //The feature data specific to this type of feature. + FeatureType type; // An enumeration representing the type of the feature. + PointFloat* + contourPoints; // A set of points describing the contour of the feature. + int numContourPoints; // The number of points in the contourPoints array. + GeometricFeature + feature; // The feature data specific to this type of feature. } FeatureData; typedef struct GeometricPatternMatch2_struct { - PointFloat position; //The location of the origin of the template in the match. - float rotation; //The rotation of the match relative to the template image, in degrees. - float scale; //The size of the match relative to the size of the template image, expressed as a percentage. - float score; //The accuracy of the match. - PointFloat corner[4]; //An array of four points describing the rectangle surrounding the template image. - int inverse; //This element is TRUE if the match is an inverse of the template image. - float occlusion; //The percentage of the match that is occluded. - float templateMatchCurveScore; //The accuracy of the match obtained by comparing the template curves to the curves in the match region. - float matchTemplateCurveScore; //The accuracy of the match obtained by comparing the curves in the match region to the template curves. - float correlationScore; //The accuracy of the match obtained by comparing the template image to the match region using a correlation metric that compares the two regions as a function of their pixel values. - String255 label; //The label corresponding to this match when the match is returned by imaqMatchMultipleGeometricPatterns(). - FeatureData* featureData; //The features used in this match. - int numFeatureData; //The size of the featureData array. - PointFloat calibratedPosition; //The location of the origin of the template in the match. - float calibratedRotation; //The rotation of the match relative to the template image, in degrees. - PointFloat calibratedCorner[4]; //An array of four points describing the rectangle surrounding the template image. + PointFloat + position; // The location of the origin of the template in the match. + float rotation; // The rotation of the match relative to the template image, + // in degrees. + float scale; // The size of the match relative to the size of the template + // image, expressed as a percentage. + float score; // The accuracy of the match. + PointFloat corner[4]; // An array of four points describing the rectangle + // surrounding the template image. + int inverse; // This element is TRUE if the match is an inverse of the + // template image. + float occlusion; // The percentage of the match that is occluded. + float templateMatchCurveScore; // The accuracy of the match obtained by + // comparing the template curves to the curves + // in the match region. + float matchTemplateCurveScore; // The accuracy of the match obtained by + // comparing the curves in the match region to + // the template curves. + float correlationScore; // The accuracy of the match obtained by comparing + // the template image to the match region using a + // correlation metric that compares the two regions + // as a function of their pixel values. + String255 label; // The label corresponding to this match when the match is + // returned by imaqMatchMultipleGeometricPatterns(). + FeatureData* featureData; // The features used in this match. + int numFeatureData; // The size of the featureData array. + PointFloat calibratedPosition; // The location of the origin of the template + // in the match. + float calibratedRotation; // The rotation of the match relative to the + // template image, in degrees. + PointFloat calibratedCorner[4]; // An array of four points describing the + // rectangle surrounding the template image. } GeometricPatternMatch2; typedef struct ClosedCurveFeature_struct { - PointFloat position; //The center of the closed curve feature. - double arcLength; //The arc length of the closed curve feature. + PointFloat position; // The center of the closed curve feature. + double arcLength; // The arc length of the closed curve feature. } ClosedCurveFeature; typedef struct LineMatch_struct { - PointFloat startPoint; //The starting point of the matched line. - PointFloat endPoint; //The ending point of the matched line. - double length; //The length of the line measured in pixels from the start point to the end point. - double rotation; //The orientation of the matched line. - double score; //The score of the matched line. + PointFloat startPoint; // The starting point of the matched line. + PointFloat endPoint; // The ending point of the matched line. + double length; // The length of the line measured in pixels from the start + // point to the end point. + double rotation; // The orientation of the matched line. + double score; // The score of the matched line. } LineMatch; typedef struct LineDescriptor_struct { - double minLength; //Specifies the minimum length of a line the function will return. - double maxLength; //Specifies the maximum length of a line the function will return. + double minLength; // Specifies the minimum length of a line the function will + // return. + double maxLength; // Specifies the maximum length of a line the function will + // return. } LineDescriptor; typedef struct RectangleDescriptor_struct { - double minWidth; //Specifies the minimum width of a rectangle the algorithm will return. - double maxWidth; //Specifies the maximum width of a rectangle the algorithm will return. - double minHeight; //Specifies the minimum height of a rectangle the algorithm will return. - double maxHeight; //Specifies the maximum height of a rectangle the algorithm will return. + double minWidth; // Specifies the minimum width of a rectangle the algorithm + // will return. + double maxWidth; // Specifies the maximum width of a rectangle the algorithm + // will return. + double minHeight; // Specifies the minimum height of a rectangle the + // algorithm will return. + double maxHeight; // Specifies the maximum height of a rectangle the + // algorithm will return. } RectangleDescriptor; typedef struct RectangleMatch_struct { - PointFloat corner[4]; //The corners of the matched rectangle. - double rotation; //The orientation of the matched rectangle. - double width; //The width of the matched rectangle. - double height; //The height of the matched rectangle. - double score; //The score of the matched rectangle. + PointFloat corner[4]; // The corners of the matched rectangle. + double rotation; // The orientation of the matched rectangle. + double width; // The width of the matched rectangle. + double height; // The height of the matched rectangle. + double score; // The score of the matched rectangle. } RectangleMatch; typedef struct EllipseDescriptor_struct { - double minMajorRadius; //Specifies the minimum length of the semi-major axis of an ellipse the function will return. - double maxMajorRadius; //Specifies the maximum length of the semi-major axis of an ellipse the function will return. - double minMinorRadius; //Specifies the minimum length of the semi-minor axis of an ellipse the function will return. - double maxMinorRadius; //Specifies the maximum length of the semi-minor axis of an ellipse the function will return. + double minMajorRadius; // Specifies the minimum length of the semi-major axis + // of an ellipse the function will return. + double maxMajorRadius; // Specifies the maximum length of the semi-major axis + // of an ellipse the function will return. + double minMinorRadius; // Specifies the minimum length of the semi-minor axis + // of an ellipse the function will return. + double maxMinorRadius; // Specifies the maximum length of the semi-minor axis + // of an ellipse the function will return. } EllipseDescriptor; typedef struct EllipseMatch_struct { - PointFloat position; //The location of the center of the matched ellipse. - double rotation; //The orientation of the matched ellipse. - double majorRadius; //The length of the semi-major axis of the matched ellipse. - double minorRadius; //The length of the semi-minor axis of the matched ellipse. - double score; //The score of the matched ellipse. + PointFloat position; // The location of the center of the matched ellipse. + double rotation; // The orientation of the matched ellipse. + double + majorRadius; // The length of the semi-major axis of the matched ellipse. + double + minorRadius; // The length of the semi-minor axis of the matched ellipse. + double score; // The score of the matched ellipse. } EllipseMatch; typedef struct CircleMatch_struct { - PointFloat position; //The location of the center of the matched circle. - double radius; //The radius of the matched circle. - double score; //The score of the matched circle. + PointFloat position; // The location of the center of the matched circle. + double radius; // The radius of the matched circle. + double score; // The score of the matched circle. } CircleMatch; typedef struct CircleDescriptor_struct { - double minRadius; //Specifies the minimum radius of a circle the function will return. - double maxRadius; //Specifies the maximum radius of a circle the function will return. + double minRadius; // Specifies the minimum radius of a circle the function + // will return. + double maxRadius; // Specifies the maximum radius of a circle the function + // will return. } CircleDescriptor; typedef struct ShapeDetectionOptions_struct { - unsigned int mode; //Specifies the method used when looking for the shape in the image. - RangeFloat* angleRanges; //An array of angle ranges, in degrees, where each range specifies how much you expect the shape to be rotated in the image. - int numAngleRanges; //The size of the orientationRanges array. - RangeFloat scaleRange; //A range that specifies the sizes of the shapes you expect to be in the image, expressed as a ratio percentage representing the size of the pattern in the image divided by size of the original pattern multiplied by 100. - double minMatchScore; + unsigned int mode; // Specifies the method used when looking for the shape in + // the image. + RangeFloat* angleRanges; // An array of angle ranges, in degrees, where each + // range specifies how much you expect the shape to + // be rotated in the image. + int numAngleRanges; // The size of the orientationRanges array. + RangeFloat scaleRange; // A range that specifies the sizes of the shapes you + // expect to be in the image, expressed as a ratio + // percentage representing the size of the pattern in + // the image divided by size of the original pattern + // multiplied by 100. + double minMatchScore; } ShapeDetectionOptions; typedef struct Curve_struct { - PointFloat* points; //The points on the curve. - unsigned int numPoints; //The number of points in the curve. - int closed; //This element is TRUE if the curve is closed and FALSE if the curve is open. - double curveLength; //The length of the curve. - double minEdgeStrength; //The lowest edge strength detected on the curve. - double maxEdgeStrength; //The highest edge strength detected on the curve. - double averageEdgeStrength; //The average of all edge strengths detected on the curve. + PointFloat* points; // The points on the curve. + unsigned int numPoints; // The number of points in the curve. + int closed; // This element is TRUE if the curve is closed and FALSE if the + // curve is open. + double curveLength; // The length of the curve. + double minEdgeStrength; // The lowest edge strength detected on the curve. + double maxEdgeStrength; // The highest edge strength detected on the curve. + double averageEdgeStrength; // The average of all edge strengths detected on + // the curve. } Curve; typedef struct CurveOptions_struct { - ExtractionMode extractionMode; //Specifies the method the function uses to identify curves in the image. - int threshold; //Specifies the minimum contrast a seed point must have in order to begin a curve. - EdgeFilterSize filterSize; //Specifies the width of the edge filter the function uses to identify curves in the image. - int minLength; //Specifies the length, in pixels, of the smallest curve the function will extract. - int rowStepSize; //Specifies the distance, in the y direction, between lines the function inspects for curve seed points. - int columnStepSize; //Specifies the distance, in the x direction, between columns the function inspects for curve seed points. - int maxEndPointGap; //Specifies the maximum gap, in pixels, between the endpoints of a curve that the function identifies as a closed curve. - int onlyClosed; //Set this element to TRUE to specify that the function should only identify closed curves in the image. - int subpixelAccuracy; //Set this element to TRUE to specify that the function identifies the location of curves with subpixel accuracy by interpolating between points to find the crossing of threshold. + ExtractionMode extractionMode; // Specifies the method the function uses to + // identify curves in the image. + int threshold; // Specifies the minimum contrast a seed point must have in + // order to begin a curve. + EdgeFilterSize filterSize; // Specifies the width of the edge filter the + // function uses to identify curves in the image. + int minLength; // Specifies the length, in pixels, of the smallest curve the + // function will extract. + int rowStepSize; // Specifies the distance, in the y direction, between lines + // the function inspects for curve seed points. + int columnStepSize; // Specifies the distance, in the x direction, between + // columns the function inspects for curve seed points. + int maxEndPointGap; // Specifies the maximum gap, in pixels, between the + // endpoints of a curve that the function identifies as a + // closed curve. + int onlyClosed; // Set this element to TRUE to specify that the function + // should only identify closed curves in the image. + int subpixelAccuracy; // Set this element to TRUE to specify that the + // function identifies the location of curves with + // subpixel accuracy by interpolating between points to + // find the crossing of threshold. } CurveOptions; typedef struct Barcode2DInfo_struct { - Barcode2DType type; //The type of the 2D barcode. - int binary; //This element is TRUE if the 2D barcode contains binary data and FALSE if the 2D barcode contains text data. - unsigned char* data; //The data encoded in the 2D barcode. - unsigned int dataLength; //The length of the data array. - PointFloat boundingBox[4]; //An array of four points describing the rectangle surrounding the 2D barcode. - unsigned int numErrorsCorrected; //The number of errors the function corrected when decoding the 2D barcode. - unsigned int numErasuresCorrected; //The number of erasures the function corrected when decoding the 2D barcode. - unsigned int rows; //The number of rows in the 2D barcode. - unsigned int columns; //The number of columns in the 2D barcode. + Barcode2DType type; // The type of the 2D barcode. + int binary; // This element is TRUE if the 2D barcode contains binary data + // and FALSE if the 2D barcode contains text data. + unsigned char* data; // The data encoded in the 2D barcode. + unsigned int dataLength; // The length of the data array. + PointFloat boundingBox[4]; // An array of four points describing the + // rectangle surrounding the 2D barcode. + unsigned int numErrorsCorrected; // The number of errors the function + // corrected when decoding the 2D barcode. + unsigned int numErasuresCorrected; // The number of erasures the function + // corrected when decoding the 2D barcode. + unsigned int rows; // The number of rows in the 2D barcode. + unsigned int columns; // The number of columns in the 2D barcode. } Barcode2DInfo; typedef struct DataMatrixOptions_struct { - Barcode2DSearchMode searchMode; //Specifies the mode the function uses to search for barcodes. - Barcode2DContrast contrast; //Specifies the contrast of the barcodes that the function searches for. - Barcode2DCellShape cellShape; //Specifies the shape of the barcode data cells, which affects how the function decodes the barcode. - Barcode2DShape barcodeShape; //Specifies the shape of the barcodes that the function searches for. - DataMatrixSubtype subtype; //Specifies the Data Matrix subtypes of the barcodes that the function searches for. + Barcode2DSearchMode searchMode; // Specifies the mode the function uses to + // search for barcodes. + Barcode2DContrast contrast; // Specifies the contrast of the barcodes that + // the function searches for. + Barcode2DCellShape cellShape; // Specifies the shape of the barcode data + // cells, which affects how the function + // decodes the barcode. + Barcode2DShape barcodeShape; // Specifies the shape of the barcodes that the + // function searches for. + DataMatrixSubtype subtype; // Specifies the Data Matrix subtypes of the + // barcodes that the function searches for. } DataMatrixOptions; typedef struct ClassifierAccuracyReport_struct { - int size; //The size of the arrays in this structure. - float accuracy; //The overall accuracy of the classifier, from 0 to 1000. - char** classNames; //The names of the classes of this classifier. - double* classAccuracy; //An array of size elements that contains accuracy information for each class. - double* classPredictiveValue; //An array containing size elements that contains the predictive values of each class. - int** classificationDistribution; //A two-dimensional array containing information about how the classifier classifies its samples. + int size; // The size of the arrays in this structure. + float accuracy; // The overall accuracy of the classifier, from 0 to 1000. + char** classNames; // The names of the classes of this classifier. + double* classAccuracy; // An array of size elements that contains accuracy + // information for each class. + double* classPredictiveValue; // An array containing size elements that + // contains the predictive values of each + // class. + int** classificationDistribution; // A two-dimensional array containing + // information about how the classifier + // classifies its samples. } ClassifierAccuracyReport; typedef struct NearestNeighborClassResult_struct { - char* className; //The name of the class. - float standardDeviation; //The standard deviation of the members of this class. - int count; //The number of samples in this class. + char* className; // The name of the class. + float standardDeviation; // The standard deviation of the members of this + // class. + int count; // The number of samples in this class. } NearestNeighborClassResult; typedef struct NearestNeighborTrainingReport_struct { - float** classDistancesTable; //The confidence in the training. - NearestNeighborClassResult* allScores; //All classes and their scores. - int allScoresSize; //The number of entries in allScores. + float** classDistancesTable; // The confidence in the training. + NearestNeighborClassResult* allScores; // All classes and their scores. + int allScoresSize; // The number of entries in allScores. } NearestNeighborTrainingReport; typedef struct ParticleClassifierPreprocessingOptions_struct { - int manualThreshold; //Set this element to TRUE to specify the threshold range manually. - RangeFloat manualThresholdRange; //If a manual threshold is being done, the range of pixels to keep. - ThresholdMethod autoThresholdMethod; //If an automatic threshold is being done, the method used to calculate the threshold range. - RangeFloat limits; //The limits on the automatic threshold range. - ParticleType particleType; //Specifies what kind of particles to look for. - int rejectBorder; //Set this element to TRUE to reject border particles. - int numErosions; //The number of erosions to perform. + int manualThreshold; // Set this element to TRUE to specify the threshold + // range manually. + RangeFloat manualThresholdRange; // If a manual threshold is being done, the + // range of pixels to keep. + ThresholdMethod autoThresholdMethod; // If an automatic threshold is being + // done, the method used to calculate + // the threshold range. + RangeFloat limits; // The limits on the automatic threshold range. + ParticleType particleType; // Specifies what kind of particles to look for. + int rejectBorder; // Set this element to TRUE to reject border particles. + int numErosions; // The number of erosions to perform. } ParticleClassifierPreprocessingOptions; typedef struct ClassifierSampleInfo_struct { - char* className; //The name of the class this sample is in. - double* featureVector; //The feature vector of this sample, or NULL if this is not a custom classifier session. - int featureVectorSize; //The number of elements in the feature vector. - Image* thumbnail; //A thumbnail image of this sample, or NULL if no image was specified. + char* className; // The name of the class this sample is in. + double* featureVector; // The feature vector of this sample, or NULL if this + // is not a custom classifier session. + int featureVectorSize; // The number of elements in the feature vector. + Image* thumbnail; // A thumbnail image of this sample, or NULL if no image + // was specified. } ClassifierSampleInfo; typedef struct ClassScore_struct { - char* className; //The name of the class. - float distance; //The distance from the item to this class. + char* className; // The name of the class. + float distance; // The distance from the item to this class. } ClassScore; typedef struct ClassifierReport_struct { - char* bestClassName; //The name of the best class for the sample. - float classificationScore; //The similarity of the sample and the two closest classes in the classifier. - float identificationScore; //The similarity of the sample and the assigned class. - ClassScore* allScores; //All classes and their scores. - int allScoresSize; //The number of entries in allScores. + char* bestClassName; // The name of the best class for the sample. + float classificationScore; // The similarity of the sample and the two + // closest classes in the classifier. + float identificationScore; // The similarity of the sample and the assigned + // class. + ClassScore* allScores; // All classes and their scores. + int allScoresSize; // The number of entries in allScores. } ClassifierReport; typedef struct NearestNeighborOptions_struct { - NearestNeighborMethod method; //The method to use. - NearestNeighborMetric metric; //The metric to use. - int k; //The value of k, if the IMAQ_K_NEAREST_NEIGHBOR method is used. + NearestNeighborMethod method; // The method to use. + NearestNeighborMetric metric; // The metric to use. + int k; // The value of k, if the IMAQ_K_NEAREST_NEIGHBOR method is used. } NearestNeighborOptions; typedef struct ParticleClassifierOptions_struct { - float scaleDependence; //The relative importance of scale when classifying particles. - float mirrorDependence; //The relative importance of mirror symmetry when classifying particles. + float scaleDependence; // The relative importance of scale when classifying + // particles. + float mirrorDependence; // The relative importance of mirror symmetry when + // classifying particles. } ParticleClassifierOptions; typedef struct RGBU64Value_struct { - unsigned short B; //The blue value of the color. - unsigned short G; //The green value of the color. - unsigned short R; //The red value of the color. - unsigned short alpha; //The alpha value of the color, which represents extra information about a color image, such as gamma correction. + unsigned short B; // The blue value of the color. + unsigned short G; // The green value of the color. + unsigned short R; // The red value of the color. + unsigned short alpha; // The alpha value of the color, which represents extra + // information about a color image, such as gamma + // correction. } RGBU64Value; typedef struct GeometricPatternMatch_struct { - PointFloat position; //The location of the origin of the template in the match. - float rotation; //The rotation of the match relative to the template image, in degrees. - float scale; //The size of the match relative to the size of the template image, expressed as a percentage. - float score; //The accuracy of the match. - PointFloat corner[4]; //An array of four points describing the rectangle surrounding the template image. - int inverse; //This element is TRUE if the match is an inverse of the template image. - float occlusion; //The percentage of the match that is occluded. - float templateMatchCurveScore; //The accuracy of the match obtained by comparing the template curves to the curves in the match region. - float matchTemplateCurveScore; //The accuracy of the match obtained by comparing the curves in the match region to the template curves. - float correlationScore; //The accuracy of the match obtained by comparing the template image to the match region using a correlation metric that compares the two regions as a function of their pixel values. + PointFloat + position; // The location of the origin of the template in the match. + float rotation; // The rotation of the match relative to the template image, + // in degrees. + float scale; // The size of the match relative to the size of the template + // image, expressed as a percentage. + float score; // The accuracy of the match. + PointFloat corner[4]; // An array of four points describing the rectangle + // surrounding the template image. + int inverse; // This element is TRUE if the match is an inverse of the + // template image. + float occlusion; // The percentage of the match that is occluded. + float templateMatchCurveScore; // The accuracy of the match obtained by + // comparing the template curves to the curves + // in the match region. + float matchTemplateCurveScore; // The accuracy of the match obtained by + // comparing the curves in the match region to + // the template curves. + float correlationScore; // The accuracy of the match obtained by comparing + // the template image to the match region using a + // correlation metric that compares the two regions + // as a function of their pixel values. } GeometricPatternMatch; typedef struct MatchGeometricPatternAdvancedOptions_struct { - int minFeaturesUsed; //Specifies the minimum number of features the function uses when matching. - int maxFeaturesUsed; //Specifies the maximum number of features the function uses when matching. - int subpixelIterations; //Specifies the maximum number of incremental improvements used to refine matches with subpixel information. - double subpixelTolerance; //Specifies the maximum amount of change, in pixels, between consecutive incremental improvements in the match position before the function stops refining the match position. - int initialMatchListLength; //Specifies the maximum size of the match list. - int matchTemplateCurveScore; //Set this element to TRUE to specify that the function should calculate the match curve to template curve score and return it for each match result. - int correlationScore; //Set this element to TRUE to specify that the function should calculate the correlation score and return it for each match result. - double minMatchSeparationDistance; //Specifies the minimum separation distance, in pixels, between the origins of two matches that have unique positions. - double minMatchSeparationAngle; //Specifies the minimum angular difference, in degrees, between two matches that have unique angles. - double minMatchSeparationScale; //Specifies the minimum difference in scale, expressed as a percentage, between two matches that have unique scales. - double maxMatchOverlap; //Specifies the maximum amount of overlap, expressed as a percentage, allowed between the bounding rectangles of two unique matches. - int coarseResult; //Specifies whether you want the function to spend less time accurately estimating the location of a match. + int minFeaturesUsed; // Specifies the minimum number of features the function + // uses when matching. + int maxFeaturesUsed; // Specifies the maximum number of features the function + // uses when matching. + int subpixelIterations; // Specifies the maximum number of incremental + // improvements used to refine matches with subpixel + // information. + double subpixelTolerance; // Specifies the maximum amount of change, in + // pixels, between consecutive incremental + // improvements in the match position before the + // function stops refining the match position. + int initialMatchListLength; // Specifies the maximum size of the match list. + int matchTemplateCurveScore; // Set this element to TRUE to specify that the + // function should calculate the match curve to + // template curve score and return it for each + // match result. + int correlationScore; // Set this element to TRUE to specify that the + // function should calculate the correlation score and + // return it for each match result. + double minMatchSeparationDistance; // Specifies the minimum separation + // distance, in pixels, between the + // origins of two matches that have unique + // positions. + double minMatchSeparationAngle; // Specifies the minimum angular difference, + // in degrees, between two matches that have + // unique angles. + double minMatchSeparationScale; // Specifies the minimum difference in scale, + // expressed as a percentage, between two + // matches that have unique scales. + double maxMatchOverlap; // Specifies the maximum amount of overlap, expressed + // as a percentage, allowed between the bounding + // rectangles of two unique matches. + int coarseResult; // Specifies whether you want the function to spend less + // time accurately estimating the location of a match. } MatchGeometricPatternAdvancedOptions; typedef struct MatchGeometricPatternOptions_struct { - unsigned int mode; //Specifies the method imaqMatchGeometricPattern() uses when looking for the pattern in the image. - int subpixelAccuracy; //Set this element to TRUE to specify that the function should calculate match locations with subpixel accuracy. - RangeFloat* angleRanges; //An array of angle ranges, in degrees, where each range specifies how much you expect the template to be rotated in the image. - int numAngleRanges; //Number of angle ranges in the angleRanges array. - RangeFloat scaleRange; //A range that specifies the sizes of the pattern you expect to be in the image, expressed as a ratio percentage representing the size of the pattern in the image divided by size of the original pattern multiplied by 100. - RangeFloat occlusionRange; //A range that specifies the percentage of the pattern you expect to be occluded in the image. - int numMatchesRequested; //Number of valid matches expected. - float minMatchScore; //The minimum score a match can have for the function to consider the match valid. + unsigned int mode; // Specifies the method imaqMatchGeometricPattern() uses + // when looking for the pattern in the image. + int subpixelAccuracy; // Set this element to TRUE to specify that the + // function should calculate match locations with + // subpixel accuracy. + RangeFloat* angleRanges; // An array of angle ranges, in degrees, where each + // range specifies how much you expect the template + // to be rotated in the image. + int numAngleRanges; // Number of angle ranges in the angleRanges array. + RangeFloat scaleRange; // A range that specifies the sizes of the pattern you + // expect to be in the image, expressed as a ratio + // percentage representing the size of the pattern in + // the image divided by size of the original pattern + // multiplied by 100. + RangeFloat occlusionRange; // A range that specifies the percentage of the + // pattern you expect to be occluded in the image. + int numMatchesRequested; // Number of valid matches expected. + float minMatchScore; // The minimum score a match can have for the function + // to consider the match valid. } MatchGeometricPatternOptions; typedef struct LearnGeometricPatternAdvancedOptions_struct { - int minRectLength; //Specifies the minimum length for each side of a rectangular feature. - double minRectAspectRatio; //Specifies the minimum aspect ratio of a rectangular feature. - int minRadius; //Specifies the minimum radius for a circular feature. - int minLineLength; //Specifies the minimum length for a linear feature. - double minFeatureStrength; //Specifies the minimum strength for a feature. - int maxFeaturesUsed; //Specifies the maximum number of features the function uses when learning. - int maxPixelDistanceFromLine; //Specifies the maximum number of pixels between an edge pixel and a linear feature for the function to consider that edge pixel as part of the linear feature. + int minRectLength; // Specifies the minimum length for each side of a + // rectangular feature. + double minRectAspectRatio; // Specifies the minimum aspect ratio of a + // rectangular feature. + int minRadius; // Specifies the minimum radius for a circular feature. + int minLineLength; // Specifies the minimum length for a linear feature. + double minFeatureStrength; // Specifies the minimum strength for a feature. + int maxFeaturesUsed; // Specifies the maximum number of features the function + // uses when learning. + int maxPixelDistanceFromLine; // Specifies the maximum number of pixels + // between an edge pixel and a linear feature + // for the function to consider that edge pixel + // as part of the linear feature. } LearnGeometricPatternAdvancedOptions; typedef struct FitEllipseOptions_struct { - int rejectOutliers; //Whether to use every given point or only a subset of the points to fit the ellipse. - double minScore; //Specifies the required quality of the fitted ellipse. - double pixelRadius; //The acceptable distance, in pixels, that a point determined to belong to the ellipse can be from the circumference of the ellipse. - int maxIterations; //Specifies the number of refinement iterations you allow the function to perform on the initial subset of points. + int rejectOutliers; // Whether to use every given point or only a subset of + // the points to fit the ellipse. + double minScore; // Specifies the required quality of the fitted ellipse. + double pixelRadius; // The acceptable distance, in pixels, that a point + // determined to belong to the ellipse can be from the + // circumference of the ellipse. + int maxIterations; // Specifies the number of refinement iterations you allow + // the function to perform on the initial subset of + // points. } FitEllipseOptions; typedef struct FitCircleOptions_struct { - int rejectOutliers; //Whether to use every given point or only a subset of the points to fit the circle. - double minScore; //Specifies the required quality of the fitted circle. - double pixelRadius; //The acceptable distance, in pixels, that a point determined to belong to the circle can be from the circumference of the circle. - int maxIterations; //Specifies the number of refinement iterations you allow the function to perform on the initial subset of points. + int rejectOutliers; // Whether to use every given point or only a subset of + // the points to fit the circle. + double minScore; // Specifies the required quality of the fitted circle. + double pixelRadius; // The acceptable distance, in pixels, that a point + // determined to belong to the circle can be from the + // circumference of the circle. + int maxIterations; // Specifies the number of refinement iterations you allow + // the function to perform on the initial subset of + // points. } FitCircleOptions; typedef struct ConstructROIOptions2_struct { - int windowNumber; //The window number of the image window. - const char* windowTitle; //Specifies the message string that the function displays in the title bar of the window. - PaletteType type; //The palette type to use. - RGBValue* palette; //If type is IMAQ_PALETTE_USER, this array is the palette of colors to use with the window. - int numColors; //If type is IMAQ_PALETTE_USER, this element is the number of colors in the palette array. - unsigned int maxContours; //The maximum number of contours the user will be able to select. + int windowNumber; // The window number of the image window. + const char* windowTitle; // Specifies the message string that the function + // displays in the title bar of the window. + PaletteType type; // The palette type to use. + RGBValue* palette; // If type is IMAQ_PALETTE_USER, this array is the palette + // of colors to use with the window. + int numColors; // If type is IMAQ_PALETTE_USER, this element is the number of + // colors in the palette array. + unsigned int maxContours; // The maximum number of contours the user will be + // able to select. } ConstructROIOptions2; typedef struct HSLValue_struct { - unsigned char L; //The color luminance. - unsigned char S; //The color saturation. - unsigned char H; //The color hue. - unsigned char alpha; //The alpha value of the color, which represents extra information about a color image, such as gamma correction. + unsigned char L; // The color luminance. + unsigned char S; // The color saturation. + unsigned char H; // The color hue. + unsigned char alpha; // The alpha value of the color, which represents extra + // information about a color image, such as gamma + // correction. } HSLValue; typedef struct HSVValue_struct { - unsigned char V; //The color value. - unsigned char S; //The color saturation. - unsigned char H; //The color hue. - unsigned char alpha; //The alpha value of the color, which represents extra information about a color image, such as gamma correction. + unsigned char V; // The color value. + unsigned char S; // The color saturation. + unsigned char H; // The color hue. + unsigned char alpha; // The alpha value of the color, which represents extra + // information about a color image, such as gamma + // correction. } HSVValue; typedef struct HSIValue_struct { - unsigned char I; //The color intensity. - unsigned char S; //The color saturation. - unsigned char H; //The color hue. - unsigned char alpha; //The alpha value of the color, which represents extra information about a color image, such as gamma correction. + unsigned char I; // The color intensity. + unsigned char S; // The color saturation. + unsigned char H; // The color hue. + unsigned char alpha; // The alpha value of the color, which represents extra + // information about a color image, such as gamma + // correction. } HSIValue; typedef struct CIELabValue_struct { - double b; //The yellow/blue information of the color. - double a; //The red/green information of the color. - double L; //The color lightness. - unsigned char alpha; //The alpha value of the color, which represents extra information about a color image, such as gamma correction. + double b; // The yellow/blue information of the color. + double a; // The red/green information of the color. + double L; // The color lightness. + unsigned char alpha; // The alpha value of the color, which represents extra + // information about a color image, such as gamma + // correction. } CIELabValue; typedef struct CIEXYZValue_struct { - double Z; //The Z color information. - double Y; //The color luminance. - double X; //The X color information. - unsigned char alpha; //The alpha value of the color, which represents extra information about a color image, such as gamma correction. + double Z; // The Z color information. + double Y; // The color luminance. + double X; // The X color information. + unsigned char alpha; // The alpha value of the color, which represents extra + // information about a color image, such as gamma + // correction. } CIEXYZValue; typedef union Color2_union { - RGBValue rgb; //The information needed to describe a color in the RGB (Red, Green, and Blue) color space. - HSLValue hsl; //The information needed to describe a color in the HSL (Hue, Saturation, and Luminance) color space. - HSVValue hsv; //The information needed to describe a color in the HSI (Hue, Saturation, and Value) color space. - HSIValue hsi; //The information needed to describe a color in the HSI (Hue, Saturation, and Intensity) color space. - CIELabValue cieLab; //The information needed to describe a color in the CIE L*a*b* (L, a, b) color space. - CIEXYZValue cieXYZ; //The information needed to describe a color in the CIE XYZ (X, Y, Z) color space. - int rawValue; //The integer value for the data in the color union. + RGBValue rgb; // The information needed to describe a color in the RGB (Red, + // Green, and Blue) color space. + HSLValue hsl; // The information needed to describe a color in the HSL (Hue, + // Saturation, and Luminance) color space. + HSVValue hsv; // The information needed to describe a color in the HSI (Hue, + // Saturation, and Value) color space. + HSIValue hsi; // The information needed to describe a color in the HSI (Hue, + // Saturation, and Intensity) color space. + CIELabValue cieLab; // The information needed to describe a color in the CIE + // L*a*b* (L, a, b) color space. + CIEXYZValue cieXYZ; // The information needed to describe a color in the CIE + // XYZ (X, Y, Z) color space. + int rawValue; // The integer value for the data in the color union. } Color2; typedef struct BestEllipse2_struct { - PointFloat center; //The coordinate location of the center of the ellipse. - PointFloat majorAxisStart; //The coordinate location of the start of the major axis of the ellipse. - PointFloat majorAxisEnd; //The coordinate location of the end of the major axis of the ellipse. - PointFloat minorAxisStart; //The coordinate location of the start of the minor axis of the ellipse. - PointFloat minorAxisEnd; //The coordinate location of the end of the minor axis of the ellipse. - double area; //The area of the ellipse. - double perimeter; //The length of the perimeter of the ellipse. - double error; //Represents the least square error of the fitted ellipse to the entire set of points. - int valid; //This element is TRUE if the function achieved the minimum score within the number of allowed refinement iterations and FALSE if the function did not achieve the minimum score. - int* pointsUsed; //An array of the indexes for the points array indicating which points the function used to fit the ellipse. - int numPointsUsed; //The number of points the function used to fit the ellipse. + PointFloat center; // The coordinate location of the center of the ellipse. + PointFloat majorAxisStart; // The coordinate location of the start of the + // major axis of the ellipse. + PointFloat majorAxisEnd; // The coordinate location of the end of the major + // axis of the ellipse. + PointFloat minorAxisStart; // The coordinate location of the start of the + // minor axis of the ellipse. + PointFloat minorAxisEnd; // The coordinate location of the end of the minor + // axis of the ellipse. + double area; // The area of the ellipse. + double perimeter; // The length of the perimeter of the ellipse. + double error; // Represents the least square error of the fitted ellipse to + // the entire set of points. + int valid; // This element is TRUE if the function achieved the minimum score + // within the number of allowed refinement iterations and FALSE if + // the function did not achieve the minimum score. + int* pointsUsed; // An array of the indexes for the points array indicating + // which points the function used to fit the ellipse. + int numPointsUsed; // The number of points the function used to fit the + // ellipse. } BestEllipse2; typedef struct LearnPatternAdvancedOptions_struct { - LearnPatternAdvancedShiftOptions* shiftOptions; //Use this element to control the behavior of imaqLearnPattern2() during the shift-invariant learning phase. - LearnPatternAdvancedRotationOptions* rotationOptions; //Use this element to control the behavior of imaqLearnPattern2()during the rotation-invariant learning phase. + LearnPatternAdvancedShiftOptions* shiftOptions; // Use this element to + // control the behavior of + // imaqLearnPattern2() during + // the shift-invariant + // learning phase. + LearnPatternAdvancedRotationOptions* + rotationOptions; // Use this element to control the behavior of + // imaqLearnPattern2()during the rotation-invariant + // learning phase. } LearnPatternAdvancedOptions; typedef struct AVIInfo_struct { - unsigned int width; //The width of each frame. - unsigned int height; //The height of each frame. - ImageType imageType; //The type of images this AVI contains. - unsigned int numFrames; //The number of frames in the AVI. - unsigned int framesPerSecond; //The number of frames per second this AVI should be shown at. - char* filterName; //The name of the compression filter used to create this AVI. - int hasData; //Specifies whether this AVI has data attached to each frame or not. - unsigned int maxDataSize; //If this AVI has data, the maximum size of the data in each frame. + unsigned int width; // The width of each frame. + unsigned int height; // The height of each frame. + ImageType imageType; // The type of images this AVI contains. + unsigned int numFrames; // The number of frames in the AVI. + unsigned int framesPerSecond; // The number of frames per second this AVI + // should be shown at. + char* filterName; // The name of the compression filter used to create this + // AVI. + int hasData; // Specifies whether this AVI has data attached to each frame or + // not. + unsigned int maxDataSize; // If this AVI has data, the maximum size of the + // data in each frame. } AVIInfo; typedef struct LearnPatternAdvancedShiftOptions_struct { - int initialStepSize; //The largest number of image pixels to shift the sample across the inspection image during the initial phase of shift-invariant matching. - int initialSampleSize; //Specifies the number of template pixels that you want to include in a sample for the initial phase of shift-invariant matching. - double initialSampleSizeFactor; //Specifies the size of the sample for the initial phase of shift-invariant matching as a percent of the template size, in pixels. - int finalSampleSize; //Specifies the number of template pixels you want to add to initialSampleSize for the final phase of shift-invariant matching. - double finalSampleSizeFactor; //Specifies the size of the sample for the final phase of shift-invariant matching as a percent of the edge points in the template, in pixels. - int subpixelSampleSize; //Specifies the number of template pixels that you want to include in a sample for the subpixel phase of shift-invariant matching. - double subpixelSampleSizeFactor; //Specifies the size of the sample for the subpixel phase of shift-invariant matching as a percent of the template size, in pixels. + int initialStepSize; // The largest number of image pixels to shift the + // sample across the inspection image during the initial + // phase of shift-invariant matching. + int initialSampleSize; // Specifies the number of template pixels that you + // want to include in a sample for the initial phase + // of shift-invariant matching. + double initialSampleSizeFactor; // Specifies the size of the sample for the + // initial phase of shift-invariant matching + // as a percent of the template size, in + // pixels. + int finalSampleSize; // Specifies the number of template pixels you want to + // add to initialSampleSize for the final phase of + // shift-invariant matching. + double finalSampleSizeFactor; // Specifies the size of the sample for the + // final phase of shift-invariant matching as a + // percent of the edge points in the template, + // in pixels. + int subpixelSampleSize; // Specifies the number of template pixels that you + // want to include in a sample for the subpixel phase + // of shift-invariant matching. + double subpixelSampleSizeFactor; // Specifies the size of the sample for the + // subpixel phase of shift-invariant + // matching as a percent of the template + // size, in pixels. } LearnPatternAdvancedShiftOptions; typedef struct LearnPatternAdvancedRotationOptions_struct { - SearchStrategy searchStrategySupport; //Specifies the aggressiveness of the rotation search strategy available during the matching phase. - int initialStepSize; //The largest number of image pixels to shift the sample across the inspection image during the initial phase of matching. - int initialSampleSize; //Specifies the number of template pixels that you want to include in a sample for the initial phase of rotation-invariant matching. - double initialSampleSizeFactor; //Specifies the size of the sample for the initial phase of rotation-invariant matching as a percent of the template size, in pixels. - int initialAngularAccuracy; //Sets the angle accuracy, in degrees, to use during the initial phase of rotation-invariant matching. - int finalSampleSize; //Specifies the number of template pixels you want to add to initialSampleSize for the final phase of rotation-invariant matching. - double finalSampleSizeFactor; //Specifies the size of the sample for the final phase of rotation-invariant matching as a percent of the edge points in the template, in pixels. - int finalAngularAccuracy; //Sets the angle accuracy, in degrees, to use during the final phase of the rotation-invariant matching. - int subpixelSampleSize; //Specifies the number of template pixels that you want to include in a sample for the subpixel phase of rotation-invariant matching. - double subpixelSampleSizeFactor; //Specifies the size of the sample for the subpixel phase of rotation-invariant matching as a percent of the template size, in pixels. + SearchStrategy searchStrategySupport; // Specifies the aggressiveness of the + // rotation search strategy available + // during the matching phase. + int initialStepSize; // The largest number of image pixels to shift the + // sample across the inspection image during the initial + // phase of matching. + int initialSampleSize; // Specifies the number of template pixels that you + // want to include in a sample for the initial phase + // of rotation-invariant matching. + double initialSampleSizeFactor; // Specifies the size of the sample for the + // initial phase of rotation-invariant + // matching as a percent of the template + // size, in pixels. + int initialAngularAccuracy; // Sets the angle accuracy, in degrees, to use + // during the initial phase of rotation-invariant + // matching. + int finalSampleSize; // Specifies the number of template pixels you want to + // add to initialSampleSize for the final phase of + // rotation-invariant matching. + double finalSampleSizeFactor; // Specifies the size of the sample for the + // final phase of rotation-invariant matching + // as a percent of the edge points in the + // template, in pixels. + int finalAngularAccuracy; // Sets the angle accuracy, in degrees, to use + // during the final phase of the rotation-invariant + // matching. + int subpixelSampleSize; // Specifies the number of template pixels that you + // want to include in a sample for the subpixel phase + // of rotation-invariant matching. + double subpixelSampleSizeFactor; // Specifies the size of the sample for the + // subpixel phase of rotation-invariant + // matching as a percent of the template + // size, in pixels. } LearnPatternAdvancedRotationOptions; typedef struct MatchPatternAdvancedOptions_struct { - int subpixelIterations; //Defines the maximum number of incremental improvements used to refine matching using subpixel information. - double subpixelTolerance; //Defines the maximum amount of change, in pixels, between consecutive incremental improvements in the match position that you want to trigger the end of the refinement process. - int initialMatchListLength; //Specifies the maximum size of the match list. - int matchListReductionFactor; //Specifies the reduction of the match list as matches are refined. - int initialStepSize; //Specifies the number of pixels to shift the sample across the inspection image during the initial phase of shift-invariant matching. - SearchStrategy searchStrategy; //Specifies the aggressiveness of the rotation search strategy. - int intermediateAngularAccuracy; //Specifies the accuracy to use during the intermediate phase of rotation-invariant matching. + int subpixelIterations; // Defines the maximum number of incremental + // improvements used to refine matching using + // subpixel information. + double subpixelTolerance; // Defines the maximum amount of change, in pixels, + // between consecutive incremental improvements in + // the match position that you want to trigger the + // end of the refinement process. + int initialMatchListLength; // Specifies the maximum size of the match list. + int matchListReductionFactor; // Specifies the reduction of the match list as + // matches are refined. + int initialStepSize; // Specifies the number of pixels to shift the sample + // across the inspection image during the initial phase + // of shift-invariant matching. + SearchStrategy searchStrategy; // Specifies the aggressiveness of the + // rotation search strategy. + int intermediateAngularAccuracy; // Specifies the accuracy to use during the + // intermediate phase of rotation-invariant + // matching. } MatchPatternAdvancedOptions; typedef struct ParticleFilterCriteria2_struct { - MeasurementType parameter; //The morphological measurement that the function uses for filtering. - float lower; //The lower bound of the criteria range. - float upper; //The upper bound of the criteria range. - int calibrated; //Set this element to TRUE to take calibrated measurements. - int exclude; //Set this element to TRUE to indicate that a match occurs when the measurement is outside the criteria range. + MeasurementType parameter; // The morphological measurement that the function + // uses for filtering. + float lower; // The lower bound of the criteria range. + float upper; // The upper bound of the criteria range. + int calibrated; // Set this element to TRUE to take calibrated measurements. + int exclude; // Set this element to TRUE to indicate that a match occurs when + // the measurement is outside the criteria range. } ParticleFilterCriteria2; typedef struct BestCircle2_struct { - PointFloat center; //The coordinate location of the center of the circle. - double radius; //The radius of the circle. - double area; //The area of the circle. - double perimeter; //The length of the perimeter of the circle. - double error; //Represents the least square error of the fitted circle to the entire set of points. - int valid; //This element is TRUE if the function achieved the minimum score within the number of allowed refinement iterations and FALSE if the function did not achieve the minimum score. - int* pointsUsed; //An array of the indexes for the points array indicating which points the function used to fit the circle. - int numPointsUsed; //The number of points the function used to fit the circle. + PointFloat center; // The coordinate location of the center of the circle. + double radius; // The radius of the circle. + double area; // The area of the circle. + double perimeter; // The length of the perimeter of the circle. + double error; // Represents the least square error of the fitted circle to + // the entire set of points. + int valid; // This element is TRUE if the function achieved the minimum score + // within the number of allowed refinement iterations and FALSE if + // the function did not achieve the minimum score. + int* pointsUsed; // An array of the indexes for the points array indicating + // which points the function used to fit the circle. + int numPointsUsed; // The number of points the function used to fit the + // circle. } BestCircle2; typedef struct OCRSpacingOptions_struct { - int minCharSpacing; //The minimum number of pixels that must be between two characters for NI Vision to train or read the characters separately. - int minCharSize; //The minimum number of pixels required for an object to be a potentially identifiable character. - int maxCharSize; //The maximum number of pixels required for an object to be a potentially identifiable character. - int maxHorizontalElementSpacing; //The maximum horizontal spacing, in pixels, allowed between character elements to train or read the character elements as a single character. - int maxVerticalElementSpacing; //The maximum vertical element spacing in pixels. - int minBoundingRectWidth; //The minimum possible width, in pixels, for a character bounding rectangle. - int maxBoundingRectWidth; //The maximum possible width, in pixels, for a character bounding rectangle. - int minBoundingRectHeight; //The minimum possible height, in pixels, for a character bounding rectangle. - int maxBoundingRectHeight; //The maximum possible height, in pixels, for a character bounding rectangle. - int autoSplit; //Set this element to TRUE to automatically adjust the location of the character bounding rectangle when characters overlap vertically. + int minCharSpacing; // The minimum number of pixels that must be between two + // characters for NI Vision to train or read the + // characters separately. + int minCharSize; // The minimum number of pixels required for an object to be + // a potentially identifiable character. + int maxCharSize; // The maximum number of pixels required for an object to be + // a potentially identifiable character. + int maxHorizontalElementSpacing; // The maximum horizontal spacing, in + // pixels, allowed between character + // elements to train or read the character + // elements as a single character. + int maxVerticalElementSpacing; // The maximum vertical element spacing in + // pixels. + int minBoundingRectWidth; // The minimum possible width, in pixels, for a + // character bounding rectangle. + int maxBoundingRectWidth; // The maximum possible width, in pixels, for a + // character bounding rectangle. + int minBoundingRectHeight; // The minimum possible height, in pixels, for a + // character bounding rectangle. + int maxBoundingRectHeight; // The maximum possible height, in pixels, for a + // character bounding rectangle. + int autoSplit; // Set this element to TRUE to automatically adjust the + // location of the character bounding rectangle when + // characters overlap vertically. } OCRSpacingOptions; typedef struct OCRProcessingOptions_struct { - ThresholdMode mode; //The thresholding mode. - int lowThreshold; //The low threshold value when you set mode to IMAQ_FIXED_RANGE. - int highThreshold; //The high threshold value when you set mode to IMAQ_FIXED_RANGE. - int blockCount; //The number of blocks for threshold calculation algorithms that require blocks. - int fastThreshold; //Set this element to TRUE to use a faster, less accurate threshold calculation algorithm. - int biModalCalculation; //Set this element to TRUE to calculate both the low and high threshold values when using the fast thresholding method. - int darkCharacters; //Set this element to TRUE to read or train dark characters on a light background. - int removeParticlesTouchingROI; //Set this element to TRUE to remove the particles touching the ROI. - int erosionCount; //The number of erosions to perform. + ThresholdMode mode; // The thresholding mode. + int lowThreshold; // The low threshold value when you set mode to + // IMAQ_FIXED_RANGE. + int highThreshold; // The high threshold value when you set mode to + // IMAQ_FIXED_RANGE. + int blockCount; // The number of blocks for threshold calculation algorithms + // that require blocks. + int fastThreshold; // Set this element to TRUE to use a faster, less accurate + // threshold calculation algorithm. + int biModalCalculation; // Set this element to TRUE to calculate both the low + // and high threshold values when using the fast + // thresholding method. + int darkCharacters; // Set this element to TRUE to read or train dark + // characters on a light background. + int removeParticlesTouchingROI; // Set this element to TRUE to remove the + // particles touching the ROI. + int erosionCount; // The number of erosions to perform. } OCRProcessingOptions; typedef struct ReadTextOptions_struct { - String255 validChars[255]; //An array of strings that specifies the valid characters. - int numValidChars; //The number of strings in the validChars array that you have initialized. - char substitutionChar; //The character to substitute for objects that the function cannot match with any of the trained characters. - ReadStrategy readStrategy; //The read strategy, which determines how closely the function analyzes images in the reading process to match objects with trained characters. - int acceptanceLevel; //The minimum acceptance level at which an object is considered a trained character. - int aspectRatio; //The maximum aspect ratio variance percentage for valid characters. - ReadResolution readResolution; //The read resolution, which determines how much of the trained character data the function uses to match objects to trained characters. + String255 validChars[255]; // An array of strings that specifies the valid + // characters. + int numValidChars; // The number of strings in the validChars array that you + // have initialized. + char substitutionChar; // The character to substitute for objects that the + // function cannot match with any of the trained + // characters. + ReadStrategy readStrategy; // The read strategy, which determines how closely + // the function analyzes images in the reading + // process to match objects with trained + // characters. + int acceptanceLevel; // The minimum acceptance level at which an object is + // considered a trained character. + int aspectRatio; // The maximum aspect ratio variance percentage for valid + // characters. + ReadResolution readResolution; // The read resolution, which determines how + // much of the trained character data the + // function uses to match objects to trained + // characters. } ReadTextOptions; typedef struct CharInfo_struct { - const char* charValue; //Retrieves the character value of the corresponding character in the character set. - const Image* charImage; //The image you used to train this character. - const Image* internalImage; //The internal representation that NI Vision uses to match objects to this character. + const char* charValue; // Retrieves the character value of the corresponding + // character in the character set. + const Image* charImage; // The image you used to train this character. + const Image* internalImage; // The internal representation that NI Vision + // uses to match objects to this character. } CharInfo; #if !defined(USERINT_HEADER) && !defined(_CVI_RECT_DEFINED) typedef struct Rect_struct { - int top; //Location of the top edge of the rectangle. - int left; //Location of the left edge of the rectangle. - int height; //Height of the rectangle. - int width; //Width of the rectangle. + int top; // Location of the top edge of the rectangle. + int left; // Location of the left edge of the rectangle. + int height; // Height of the rectangle. + int width; // Width of the rectangle. } Rect; #define _CVI_RECT_DEFINED #endif typedef struct CharReport_struct { - const char* character; //The character value. - PointFloat corner[4]; //An array of four points that describes the rectangle that surrounds the character. - int reserved; //This element is reserved. - int lowThreshold; //The minimum value of the threshold range used for this character. - int highThreshold; //The maximum value of the threshold range used for this character. + const char* character; // The character value. + PointFloat corner[4]; // An array of four points that describes the rectangle + // that surrounds the character. + int reserved; // This element is reserved. + int lowThreshold; // The minimum value of the threshold range used for this + // character. + int highThreshold; // The maximum value of the threshold range used for this + // character. } CharReport; typedef struct ReadTextReport_struct { - const char* readString; //The read string. - const CharReport* characterReport; //An array of reports describing the properties of each identified character. - int numCharacterReports; //The number of identified characters. + const char* readString; // The read string. + const CharReport* characterReport; // An array of reports describing the + // properties of each identified + // character. + int numCharacterReports; // The number of identified characters. } ReadTextReport; #if !defined(USERINT_HEADER) && !defined(_CVI_POINT_DEFINED) typedef struct Point_struct { - int x; //The x-coordinate of the point. - int y; //The y-coordinate of the point. + int x; // The x-coordinate of the point. + int y; // The y-coordinate of the point. } Point; #define _CVI_POINT_DEFINED #endif typedef struct Annulus_struct { - Point center; //The coordinate location of the center of the annulus. - int innerRadius; //The internal radius of the annulus. - int outerRadius; //The external radius of the annulus. - double startAngle; //The start angle, in degrees, of the annulus. - double endAngle; //The end angle, in degrees, of the annulus. + Point center; // The coordinate location of the center of the annulus. + int innerRadius; // The internal radius of the annulus. + int outerRadius; // The external radius of the annulus. + double startAngle; // The start angle, in degrees, of the annulus. + double endAngle; // The end angle, in degrees, of the annulus. } Annulus; typedef struct EdgeLocationReport_struct { - PointFloat* edges; //The coordinate location of all edges detected by the search line. - int numEdges; //The number of points in the edges array. + PointFloat* edges; // The coordinate location of all edges detected by the + // search line. + int numEdges; // The number of points in the edges array. } EdgeLocationReport; typedef struct EdgeOptions_struct { - unsigned threshold; //Specifies the threshold value for the contrast of the edge. - unsigned width; //The number of pixels that the function averages to find the contrast at either side of the edge. - unsigned steepness; //The span, in pixels, of the slope of the edge projected along the path specified by the input points. - InterpolationMethod subpixelType; //The method for interpolating. - unsigned subpixelDivisions; //The number of samples the function obtains from a pixel. + unsigned + threshold; // Specifies the threshold value for the contrast of the edge. + unsigned width; // The number of pixels that the function averages to find + // the contrast at either side of the edge. + unsigned steepness; // The span, in pixels, of the slope of the edge + // projected along the path specified by the input + // points. + InterpolationMethod subpixelType; // The method for interpolating. + unsigned subpixelDivisions; // The number of samples the function obtains + // from a pixel. } EdgeOptions; typedef struct EdgeReport_struct { - float location; //The location of the edge from the first point in the points array. - float contrast; //The contrast at the edge. - PolarityType polarity; //The polarity of the edge. - float reserved; //This element is reserved. - PointFloat coordinate; //The coordinates of the edge. + float location; // The location of the edge from the first point in the + // points array. + float contrast; // The contrast at the edge. + PolarityType polarity; // The polarity of the edge. + float reserved; // This element is reserved. + PointFloat coordinate; // The coordinates of the edge. } EdgeReport; typedef struct ExtremeReport_struct { - double location; //The locations of the extreme. - double amplitude; //The amplitude of the extreme. - double secondDerivative; //The second derivative of the extreme. + double location; // The locations of the extreme. + double amplitude; // The amplitude of the extreme. + double secondDerivative; // The second derivative of the extreme. } ExtremeReport; typedef struct FitLineOptions_struct { - float minScore; //Specifies the required quality of the fitted line. - float pixelRadius; //Specifies the neighborhood pixel relationship for the initial subset of points being used. - int numRefinements; //Specifies the number of refinement iterations you allow the function to perform on the initial subset of points. + float minScore; // Specifies the required quality of the fitted line. + float pixelRadius; // Specifies the neighborhood pixel relationship for the + // initial subset of points being used. + int numRefinements; // Specifies the number of refinement iterations you + // allow the function to perform on the initial subset of + // points. } FitLineOptions; typedef struct DisplayMapping_struct { - MappingMethod method; //Describes the method for converting 16-bit pixels to 8-bit pixels. - int minimumValue; //When method is IMAQ_RANGE, minimumValue represents the value that is mapped to 0. - int maximumValue; //When method is IMAQ_RANGE, maximumValue represents the value that is mapped to 255. - int shiftCount; //When method is IMAQ_DOWNSHIFT, shiftCount represents the number of bits the function right-shifts the 16-bit pixel values. + MappingMethod method; // Describes the method for converting 16-bit pixels to + // 8-bit pixels. + int minimumValue; // When method is IMAQ_RANGE, minimumValue represents the + // value that is mapped to 0. + int maximumValue; // When method is IMAQ_RANGE, maximumValue represents the + // value that is mapped to 255. + int shiftCount; // When method is IMAQ_DOWNSHIFT, shiftCount represents the + // number of bits the function right-shifts the 16-bit pixel + // values. } DisplayMapping; typedef struct DetectExtremesOptions_struct { - double threshold; //Defines which extremes are too small. - int width; //Specifies the number of consecutive data points the function uses in the quadratic least-squares fit. + double threshold; // Defines which extremes are too small. + int width; // Specifies the number of consecutive data points the function + // uses in the quadratic least-squares fit. } DetectExtremesOptions; typedef struct ImageInfo_struct { - CalibrationUnit imageUnit; //If you set calibration information with imaqSetSimpleCalibrationInfo(), imageUnit is the calibration unit. - float stepX; //If you set calibration information with imaqSetCalibrationInfo(), stepX is the distance in the calibration unit between two pixels in the x direction. - float stepY; //If you set calibration information with imaqSetCalibrationInfo(), stepY is the distance in the calibration unit between two pixels in the y direction. - ImageType imageType; //The type of the image. - int xRes; //The number of columns in the image. - int yRes; //The number of rows in the image. - int xOffset; //If you set mask offset information with imaqSetMaskOffset(), xOffset is the offset of the mask origin in the x direction. - int yOffset; //If you set mask offset information with imaqSetMaskOffset(), yOffset is the offset of the mask origin in the y direction. - int border; //The number of border pixels around the image. - int pixelsPerLine; //The number of pixels stored for each line of the image. - void* reserved0; //This element is reserved. - void* reserved1; //This element is reserved. - void* imageStart; //A pointer to pixel (0,0). + CalibrationUnit imageUnit; // If you set calibration information with + // imaqSetSimpleCalibrationInfo(), imageUnit is + // the calibration unit. + float stepX; // If you set calibration information with + // imaqSetCalibrationInfo(), stepX is the distance in the + // calibration unit between two pixels in the x direction. + float stepY; // If you set calibration information with + // imaqSetCalibrationInfo(), stepY is the distance in the + // calibration unit between two pixels in the y direction. + ImageType imageType; // The type of the image. + int xRes; // The number of columns in the image. + int yRes; // The number of rows in the image. + int xOffset; // If you set mask offset information with imaqSetMaskOffset(), + // xOffset is the offset of the mask origin in the x direction. + int yOffset; // If you set mask offset information with imaqSetMaskOffset(), + // yOffset is the offset of the mask origin in the y direction. + int border; // The number of border pixels around the image. + int pixelsPerLine; // The number of pixels stored for each line of the image. + void* reserved0; // This element is reserved. + void* reserved1; // This element is reserved. + void* imageStart; // A pointer to pixel (0,0). } ImageInfo; typedef struct LCDOptions_struct { - int litSegments; //Set this parameter to TRUE if the segments are brighter than the background. - float threshold; //Determines whether a segment is ON or OFF. - int sign; //Indicates whether the function must read the sign of the indicator. - int decimalPoint; //Determines whether to look for a decimal separator after each digit. + int litSegments; // Set this parameter to TRUE if the segments are brighter + // than the background. + float threshold; // Determines whether a segment is ON or OFF. + int sign; // Indicates whether the function must read the sign of the + // indicator. + int decimalPoint; // Determines whether to look for a decimal separator after + // each digit. } LCDOptions; typedef struct LCDReport_struct { - const char* text; //A string of the characters of the LCD. - LCDSegments* segmentInfo; //An array of LCDSegment structures describing which segments of each digit are on. - int numCharacters; //The number of characters that the function reads. - int reserved; //This element is reserved. + const char* text; // A string of the characters of the LCD. + LCDSegments* segmentInfo; // An array of LCDSegment structures describing + // which segments of each digit are on. + int numCharacters; // The number of characters that the function reads. + int reserved; // This element is reserved. } LCDReport; typedef struct LCDSegments_struct { - unsigned a:1; //True if the a segment is on. - unsigned b:1; //True if the b segment is on. - unsigned c:1; //True if the c segment is on. - unsigned d:1; //True if the d segment is on. - unsigned e:1; //True if the e segment is on. - unsigned f:1; //True if the f segment is on. - unsigned g:1; //True if the g segment is on. - unsigned reserved:25; //This element is reserved. + unsigned a : 1; // True if the a segment is on. + unsigned b : 1; // True if the b segment is on. + unsigned c : 1; // True if the c segment is on. + unsigned d : 1; // True if the d segment is on. + unsigned e : 1; // True if the e segment is on. + unsigned f : 1; // True if the f segment is on. + unsigned g : 1; // True if the g segment is on. + unsigned reserved : 25; // This element is reserved. } LCDSegments; typedef struct LearnCalibrationOptions_struct { - CalibrationMode mode; //Specifies the type of algorithm you want to use to reduce distortion in your image. - ScalingMethod method; //Defines the scaling method correction functions use to correct the image. - CalibrationROI roi; //Specifies the ROI correction functions use when correcting an image. - int learnMap; //Set this element to TRUE if you want the function to calculate and store an error map during the learning process. - int learnTable; //Set this element to TRUE if you want the function to calculate and store the correction table. + CalibrationMode mode; // Specifies the type of algorithm you want to use to + // reduce distortion in your image. + ScalingMethod method; // Defines the scaling method correction functions use + // to correct the image. + CalibrationROI roi; // Specifies the ROI correction functions use when + // correcting an image. + int learnMap; // Set this element to TRUE if you want the function to + // calculate and store an error map during the learning + // process. + int learnTable; // Set this element to TRUE if you want the function to + // calculate and store the correction table. } LearnCalibrationOptions; typedef struct LearnColorPatternOptions_struct { - LearningMode learnMode; //Specifies the invariance mode the function uses when learning the pattern. - ImageFeatureMode featureMode; //Specifies the features the function uses when learning the color pattern. - int threshold; //Specifies the saturation threshold the function uses to distinguish between two colors that have the same hue values. - ColorIgnoreMode ignoreMode; //Specifies whether the function excludes certain colors from the color features of the template image. - ColorInformation* colorsToIgnore; //An array of ColorInformation structures providing a set of colors to exclude from the color features of the template image. - int numColorsToIgnore; //The number of ColorInformation structures in the colorsToIgnore array. + LearningMode learnMode; // Specifies the invariance mode the function uses + // when learning the pattern. + ImageFeatureMode featureMode; // Specifies the features the function uses + // when learning the color pattern. + int threshold; // Specifies the saturation threshold the function uses to + // distinguish between two colors that have the same hue + // values. + ColorIgnoreMode ignoreMode; // Specifies whether the function excludes + // certain colors from the color features of the + // template image. + ColorInformation* colorsToIgnore; // An array of ColorInformation structures + // providing a set of colors to exclude + // from the color features of the template + // image. + int numColorsToIgnore; // The number of ColorInformation structures in the + // colorsToIgnore array. } LearnColorPatternOptions; typedef struct Line_struct { - Point start; //The coordinate location of the start of the line. - Point end; //The coordinate location of the end of the line. + Point start; // The coordinate location of the start of the line. + Point end; // The coordinate location of the end of the line. } Line; typedef struct LinearAverages_struct { - float* columnAverages; //An array containing the mean pixel value of each column. - int columnCount; //The number of elements in the columnAverages array. - float* rowAverages; //An array containing the mean pixel value of each row. - int rowCount; //The number of elements in the rowAverages array. - float* risingDiagAverages; //An array containing the mean pixel value of each diagonal running from the lower left to the upper right of the inspected area of the image. - int risingDiagCount; //The number of elements in the risingDiagAverages array. - float* fallingDiagAverages; //An array containing the mean pixel value of each diagonal running from the upper left to the lower right of the inspected area of the image. - int fallingDiagCount; //The number of elements in the fallingDiagAverages array. + float* columnAverages; // An array containing the mean pixel value of each + // column. + int columnCount; // The number of elements in the columnAverages array. + float* rowAverages; // An array containing the mean pixel value of each row. + int rowCount; // The number of elements in the rowAverages array. + float* risingDiagAverages; // An array containing the mean pixel value of + // each diagonal running from the lower left to + // the upper right of the inspected area of the + // image. + int risingDiagCount; // The number of elements in the risingDiagAverages + // array. + float* fallingDiagAverages; // An array containing the mean pixel value of + // each diagonal running from the upper left to + // the lower right of the inspected area of the + // image. + int fallingDiagCount; // The number of elements in the fallingDiagAverages + // array. } LinearAverages; typedef struct LineProfile_struct { - float* profileData; //An array containing the value of each pixel in the line. - Rect boundingBox; //The bounding rectangle of the line. - float min; //The smallest pixel value in the line profile. - float max; //The largest pixel value in the line profile. - float mean; //The mean value of the pixels in the line profile. - float stdDev; //The standard deviation of the line profile. - int dataCount; //The size of the profileData array. + float* + profileData; // An array containing the value of each pixel in the line. + Rect boundingBox; // The bounding rectangle of the line. + float min; // The smallest pixel value in the line profile. + float max; // The largest pixel value in the line profile. + float mean; // The mean value of the pixels in the line profile. + float stdDev; // The standard deviation of the line profile. + int dataCount; // The size of the profileData array. } LineProfile; typedef struct MatchColorPatternOptions_struct { - MatchingMode matchMode; //Specifies the method to use when looking for the color pattern in the image. - ImageFeatureMode featureMode; //Specifies the features to use when looking for the color pattern in the image. - int minContrast; //Specifies the minimum contrast expected in the image. - int subpixelAccuracy; //Set this parameter to TRUE to return areas in the image that match the pattern area with subpixel accuracy. - RotationAngleRange* angleRanges; //An array of angle ranges, in degrees, where each range specifies how much you expect the pattern to be rotated in the image. - int numRanges; //Number of angle ranges in the angleRanges array. - double colorWeight; //Determines the percent contribution of the color score to the final color pattern matching score. - ColorSensitivity sensitivity; //Specifies the sensitivity of the color information in the image. - SearchStrategy strategy; //Specifies how the color features of the image are used during the search phase. - int numMatchesRequested; //Number of valid matches expected. - float minMatchScore; //The minimum score a match can have for the function to consider the match valid. + MatchingMode matchMode; // Specifies the method to use when looking for the + // color pattern in the image. + ImageFeatureMode featureMode; // Specifies the features to use when looking + // for the color pattern in the image. + int minContrast; // Specifies the minimum contrast expected in the image. + int subpixelAccuracy; // Set this parameter to TRUE to return areas in the + // image that match the pattern area with subpixel + // accuracy. + RotationAngleRange* angleRanges; // An array of angle ranges, in degrees, + // where each range specifies how much you + // expect the pattern to be rotated in the + // image. + int numRanges; // Number of angle ranges in the angleRanges array. + double colorWeight; // Determines the percent contribution of the color score + // to the final color pattern matching score. + ColorSensitivity sensitivity; // Specifies the sensitivity of the color + // information in the image. + SearchStrategy strategy; // Specifies how the color features of the image are + // used during the search phase. + int numMatchesRequested; // Number of valid matches expected. + float minMatchScore; // The minimum score a match can have for the function + // to consider the match valid. } MatchColorPatternOptions; typedef struct HistogramReport_struct { - int* histogram; //An array describing the number of pixels that fell into each class. - int histogramCount; //The number of elements in the histogram array. - float min; //The smallest pixel value that the function classified. - float max; //The largest pixel value that the function classified. - float start; //The smallest pixel value that fell into the first class. - float width; //The size of each class. - float mean; //The mean value of the pixels that the function classified. - float stdDev; //The standard deviation of the pixels that the function classified. - int numPixels; //The number of pixels that the function classified. + int* histogram; // An array describing the number of pixels that fell into + // each class. + int histogramCount; // The number of elements in the histogram array. + float min; // The smallest pixel value that the function classified. + float max; // The largest pixel value that the function classified. + float start; // The smallest pixel value that fell into the first class. + float width; // The size of each class. + float mean; // The mean value of the pixels that the function classified. + float stdDev; // The standard deviation of the pixels that the function + // classified. + int numPixels; // The number of pixels that the function classified. } HistogramReport; typedef struct ArcInfo_struct { - Rect boundingBox; //The coordinate location of the bounding box of the arc. - double startAngle; //The counterclockwise angle from the x-axis in degrees to the start of the arc. - double endAngle; //The counterclockwise angle from the x-axis in degrees to the end of the arc. + Rect boundingBox; // The coordinate location of the bounding box of the arc. + double startAngle; // The counterclockwise angle from the x-axis in degrees + // to the start of the arc. + double endAngle; // The counterclockwise angle from the x-axis in degrees to + // the end of the arc. } ArcInfo; typedef struct AxisReport_struct { - PointFloat origin; //The origin of the coordinate system, which is the intersection of the two axes of the coordinate system. - PointFloat mainAxisEnd; //The end of the main axis, which is the result of the computation of the intersection of the main axis with the rectangular search area. - PointFloat secondaryAxisEnd; //The end of the secondary axis, which is the result of the computation of the intersection of the secondary axis with the rectangular search area. + PointFloat origin; // The origin of the coordinate system, which is the + // intersection of the two axes of the coordinate system. + PointFloat mainAxisEnd; // The end of the main axis, which is the result of + // the computation of the intersection of the main + // axis with the rectangular search area. + PointFloat secondaryAxisEnd; // The end of the secondary axis, which is the + // result of the computation of the intersection + // of the secondary axis with the rectangular + // search area. } AxisReport; typedef struct BarcodeInfo_struct { - const char* outputString; //A string containing the decoded barcode data. - int size; //The size of the output string. - char outputChar1; //The contents of this character depend on the barcode type. - char outputChar2; //The contents of this character depend on the barcode type. - double confidenceLevel; //A quality measure of the decoded barcode ranging from 0 to 100, with 100 being the best. - BarcodeType type; //The type of barcode. + const char* outputString; // A string containing the decoded barcode data. + int size; // The size of the output string. + char outputChar1; // The contents of this character depend on the barcode + // type. + char outputChar2; // The contents of this character depend on the barcode + // type. + double confidenceLevel; // A quality measure of the decoded barcode ranging + // from 0 to 100, with 100 being the best. + BarcodeType type; // The type of barcode. } BarcodeInfo; typedef struct BCGOptions_struct { - float brightness; //Adjusts the brightness of the image. - float contrast; //Adjusts the contrast of the image. - float gamma; //Performs gamma correction. + float brightness; // Adjusts the brightness of the image. + float contrast; // Adjusts the contrast of the image. + float gamma; // Performs gamma correction. } BCGOptions; typedef struct BestCircle_struct { - PointFloat center; //The coordinate location of the center of the circle. - double radius; //The radius of the circle. - double area; //The area of the circle. - double perimeter; //The length of the perimeter of the circle. - double error; //Represents the least square error of the fitted circle to the entire set of points. + PointFloat center; // The coordinate location of the center of the circle. + double radius; // The radius of the circle. + double area; // The area of the circle. + double perimeter; // The length of the perimeter of the circle. + double error; // Represents the least square error of the fitted circle to + // the entire set of points. } BestCircle; typedef struct BestEllipse_struct { - PointFloat center; //The coordinate location of the center of the ellipse. - PointFloat majorAxisStart; //The coordinate location of the start of the major axis of the ellipse. - PointFloat majorAxisEnd; //The coordinate location of the end of the major axis of the ellipse. - PointFloat minorAxisStart; //The coordinate location of the start of the minor axis of the ellipse. - PointFloat minorAxisEnd; //The coordinate location of the end of the minor axis of the ellipse. - double area; //The area of the ellipse. - double perimeter; //The length of the perimeter of the ellipse. + PointFloat center; // The coordinate location of the center of the ellipse. + PointFloat majorAxisStart; // The coordinate location of the start of the + // major axis of the ellipse. + PointFloat majorAxisEnd; // The coordinate location of the end of the major + // axis of the ellipse. + PointFloat minorAxisStart; // The coordinate location of the start of the + // minor axis of the ellipse. + PointFloat minorAxisEnd; // The coordinate location of the end of the minor + // axis of the ellipse. + double area; // The area of the ellipse. + double perimeter; // The length of the perimeter of the ellipse. } BestEllipse; typedef struct BestLine_struct { - PointFloat start; //The coordinate location of the start of the line. - PointFloat end; //The coordinate location of the end of the line. - LineEquation equation; //Defines the three coefficients of the equation of the best fit line. - int valid; //This element is TRUE if the function achieved the minimum score within the number of allowed refinement iterations and FALSE if the function did not achieve the minimum score. - double error; //Represents the least square error of the fitted line to the entire set of points. - int* pointsUsed; //An array of the indexes for the points array indicating which points the function used to fit the line. - int numPointsUsed; //The number of points the function used to fit the line. + PointFloat start; // The coordinate location of the start of the line. + PointFloat end; // The coordinate location of the end of the line. + LineEquation equation; // Defines the three coefficients of the equation of + // the best fit line. + int valid; // This element is TRUE if the function achieved the minimum score + // within the number of allowed refinement iterations and FALSE if + // the function did not achieve the minimum score. + double error; // Represents the least square error of the fitted line to the + // entire set of points. + int* pointsUsed; // An array of the indexes for the points array indicating + // which points the function used to fit the line. + int numPointsUsed; // The number of points the function used to fit the line. } BestLine; typedef struct BrowserOptions_struct { - int width; //The width to make the browser. - int height; //The height to make the browser image. - int imagesPerLine; //The number of images to place on a single line. - RGBValue backgroundColor; //The background color of the browser. - int frameSize; //Specifies the number of pixels with which to border each thumbnail. - BrowserFrameStyle style; //The style for the frame around each thumbnail. - float ratio; //Specifies the width to height ratio of each thumbnail. - RGBValue focusColor; //The color to use to display focused cells. + int width; // The width to make the browser. + int height; // The height to make the browser image. + int imagesPerLine; // The number of images to place on a single line. + RGBValue backgroundColor; // The background color of the browser. + int frameSize; // Specifies the number of pixels with which to border each + // thumbnail. + BrowserFrameStyle style; // The style for the frame around each thumbnail. + float ratio; // Specifies the width to height ratio of each thumbnail. + RGBValue focusColor; // The color to use to display focused cells. } BrowserOptions; typedef struct CoordinateSystem_struct { - PointFloat origin; //The origin of the coordinate system. - float angle; //The angle, in degrees, of the x-axis of the coordinate system relative to the image x-axis. - AxisOrientation axisOrientation; //The direction of the y-axis of the coordinate reference system. + PointFloat origin; // The origin of the coordinate system. + float angle; // The angle, in degrees, of the x-axis of the coordinate system + // relative to the image x-axis. + AxisOrientation axisOrientation; // The direction of the y-axis of the + // coordinate reference system. } CoordinateSystem; typedef struct CalibrationInfo_struct { - float* errorMap; //The error map for the calibration. - int mapColumns; //The number of columns in the error map. - int mapRows; //The number of rows in the error map. - ROI* userRoi; //Specifies the ROI the user provided when learning the calibration. - ROI* calibrationRoi; //Specifies the ROI that corresponds to the region of the image where the calibration information is accurate. - LearnCalibrationOptions options; //Specifies the calibration options the user provided when learning the calibration. - GridDescriptor grid; //Specifies the scaling constants for the image. - CoordinateSystem system; //Specifies the coordinate system for the real world coordinates. - RangeFloat range; //The range of the grayscale the function used to represent the circles in the grid image. - float quality; //The quality score of the learning process, which is a value between 0-1000. + float* errorMap; // The error map for the calibration. + int mapColumns; // The number of columns in the error map. + int mapRows; // The number of rows in the error map. + ROI* userRoi; // Specifies the ROI the user provided when learning the + // calibration. + ROI* calibrationRoi; // Specifies the ROI that corresponds to the region of + // the image where the calibration information is + // accurate. + LearnCalibrationOptions options; // Specifies the calibration options the + // user provided when learning the + // calibration. + GridDescriptor grid; // Specifies the scaling constants for the image. + CoordinateSystem system; // Specifies the coordinate system for the real + // world coordinates. + RangeFloat range; // The range of the grayscale the function used to + // represent the circles in the grid image. + float quality; // The quality score of the learning process, which is a value + // between 0-1000. } CalibrationInfo; typedef struct CalibrationPoints_struct { - PointFloat* pixelCoordinates; //The array of pixel coordinates. - PointFloat* realWorldCoordinates; //The array of corresponding real-world coordinates. - int numCoordinates; //The number of coordinates in both of the arrays. + PointFloat* pixelCoordinates; // The array of pixel coordinates. + PointFloat* realWorldCoordinates; // The array of corresponding real-world + // coordinates. + int numCoordinates; // The number of coordinates in both of the arrays. } CalibrationPoints; typedef struct CaliperOptions_struct { - TwoEdgePolarityType polarity; //Specifies the edge polarity of the edge pairs. - float separation; //The distance between edge pairs. - float separationDeviation; //Sets the range around the separation value. + TwoEdgePolarityType + polarity; // Specifies the edge polarity of the edge pairs. + float separation; // The distance between edge pairs. + float separationDeviation; // Sets the range around the separation value. } CaliperOptions; typedef struct CaliperReport_struct { - float edge1Contrast; //The contrast of the first edge. - PointFloat edge1Coord; //The coordinates of the first edge. - float edge2Contrast; //The contrast of the second edge. - PointFloat edge2Coord; //The coordinates of the second edge. - float separation; //The distance between the two edges. - float reserved; //This element is reserved. + float edge1Contrast; // The contrast of the first edge. + PointFloat edge1Coord; // The coordinates of the first edge. + float edge2Contrast; // The contrast of the second edge. + PointFloat edge2Coord; // The coordinates of the second edge. + float separation; // The distance between the two edges. + float reserved; // This element is reserved. } CaliperReport; typedef struct DrawTextOptions_struct { - char fontName[32]; //The font name to use. - int fontSize; //The size of the font. - int bold; //Set this parameter to TRUE to bold text. - int italic; //Set this parameter to TRUE to italicize text. - int underline; //Set this parameter to TRUE to underline text. - int strikeout; //Set this parameter to TRUE to strikeout text. - TextAlignment textAlignment; //Sets the alignment of text. - FontColor fontColor; //Sets the font color. + char fontName[32]; // The font name to use. + int fontSize; // The size of the font. + int bold; // Set this parameter to TRUE to bold text. + int italic; // Set this parameter to TRUE to italicize text. + int underline; // Set this parameter to TRUE to underline text. + int strikeout; // Set this parameter to TRUE to strikeout text. + TextAlignment textAlignment; // Sets the alignment of text. + FontColor fontColor; // Sets the font color. } DrawTextOptions; typedef struct CircleReport_struct { - Point center; //The coordinate point of the center of the circle. - int radius; //The radius of the circle, in pixels. - int area; //The area of the circle, in pixels. + Point center; // The coordinate point of the center of the circle. + int radius; // The radius of the circle, in pixels. + int area; // The area of the circle, in pixels. } CircleReport; typedef struct ClosedContour_struct { - Point* points; //The points that make up the closed contour. - int numPoints; //The number of points in the array. + Point* points; // The points that make up the closed contour. + int numPoints; // The number of points in the array. } ClosedContour; typedef struct ColorHistogramReport_struct { - HistogramReport plane1; //The histogram report of the first color plane. - HistogramReport plane2; //The histogram report of the second plane. - HistogramReport plane3; //The histogram report of the third plane. + HistogramReport plane1; // The histogram report of the first color plane. + HistogramReport plane2; // The histogram report of the second plane. + HistogramReport plane3; // The histogram report of the third plane. } ColorHistogramReport; typedef struct ColorInformation_struct { - int infoCount; //The size of the info array. - int saturation; //The saturation level the function uses to learn the color information. - double* info; //An array of color information that represents the color spectrum analysis of a region of an image in a compact form. + int infoCount; // The size of the info array. + int saturation; // The saturation level the function uses to learn the color + // information. + double* info; // An array of color information that represents the color + // spectrum analysis of a region of an image in a compact form. } ColorInformation; typedef struct Complex_struct { - float r; //The real part of the value. - float i; //The imaginary part of the value. + float r; // The real part of the value. + float i; // The imaginary part of the value. } Complex; typedef struct ConcentricRakeReport_struct { - ArcInfo* rakeArcs; //An array containing the location of each concentric arc line used for edge detection. - int numArcs; //The number of arc lines in the rakeArcs array. - PointFloat* firstEdges; //The coordinate location of all edges detected as first edges. - int numFirstEdges; //The number of points in the first edges array. - PointFloat* lastEdges; //The coordinate location of all edges detected as last edges. - int numLastEdges; //The number of points in the last edges array. - EdgeLocationReport* allEdges; //An array of reports describing the location of the edges located by each concentric rake arc line. - int* linesWithEdges; //An array of indices into the rakeArcs array indicating the concentric rake arc lines on which the function detected at least one edge. - int numLinesWithEdges; //The number of concentric rake arc lines along which the function detected edges. + ArcInfo* rakeArcs; // An array containing the location of each concentric arc + // line used for edge detection. + int numArcs; // The number of arc lines in the rakeArcs array. + PointFloat* firstEdges; // The coordinate location of all edges detected as + // first edges. + int numFirstEdges; // The number of points in the first edges array. + PointFloat* lastEdges; // The coordinate location of all edges detected as + // last edges. + int numLastEdges; // The number of points in the last edges array. + EdgeLocationReport* allEdges; // An array of reports describing the location + // of the edges located by each concentric rake + // arc line. + int* linesWithEdges; // An array of indices into the rakeArcs array + // indicating the concentric rake arc lines on which the + // function detected at least one edge. + int numLinesWithEdges; // The number of concentric rake arc lines along which + // the function detected edges. } ConcentricRakeReport; typedef struct ConstructROIOptions_struct { - int windowNumber; //The window number of the image window. - const char* windowTitle; //Specifies the message string that the function displays in the title bar of the window. - PaletteType type; //The palette type to use. - RGBValue* palette; //If type is IMAQ_PALETTE_USER, this array is the palette of colors to use with the window. - int numColors; //If type is IMAQ_PALETTE_USER, this element is the number of colors in the palette array. + int windowNumber; // The window number of the image window. + const char* windowTitle; // Specifies the message string that the function + // displays in the title bar of the window. + PaletteType type; // The palette type to use. + RGBValue* palette; // If type is IMAQ_PALETTE_USER, this array is the palette + // of colors to use with the window. + int numColors; // If type is IMAQ_PALETTE_USER, this element is the number of + // colors in the palette array. } ConstructROIOptions; typedef struct ContourInfo_struct { - ContourType type; //The contour type. - unsigned numPoints; //The number of points that make up the contour. - Point* points; //The points describing the contour. - RGBValue contourColor; //The contour color. + ContourType type; // The contour type. + unsigned numPoints; // The number of points that make up the contour. + Point* points; // The points describing the contour. + RGBValue contourColor; // The contour color. } ContourInfo; typedef union ContourUnion_union { - Point* point; //Use this member when the contour is of type IMAQ_POINT. - Line* line; //Use this member when the contour is of type IMAQ_LINE. - Rect* rect; //Use this member when the contour is of type IMAQ_RECT. - Rect* ovalBoundingBox; //Use this member when the contour is of type IMAQ_OVAL. - ClosedContour* closedContour; //Use this member when the contour is of type IMAQ_CLOSED_CONTOUR. - OpenContour* openContour; //Use this member when the contour is of type IMAQ_OPEN_CONTOUR. - Annulus* annulus; //Use this member when the contour is of type IMAQ_ANNULUS. - RotatedRect* rotatedRect; //Use this member when the contour is of type IMAQ_ROTATED_RECT. + Point* point; // Use this member when the contour is of type IMAQ_POINT. + Line* line; // Use this member when the contour is of type IMAQ_LINE. + Rect* rect; // Use this member when the contour is of type IMAQ_RECT. + Rect* ovalBoundingBox; // Use this member when the contour is of type + // IMAQ_OVAL. + ClosedContour* closedContour; // Use this member when the contour is of type + // IMAQ_CLOSED_CONTOUR. + OpenContour* openContour; // Use this member when the contour is of type + // IMAQ_OPEN_CONTOUR. + Annulus* annulus; // Use this member when the contour is of type + // IMAQ_ANNULUS. + RotatedRect* rotatedRect; // Use this member when the contour is of type + // IMAQ_ROTATED_RECT. } ContourUnion; typedef struct ContourInfo2_struct { - ContourType type; //The contour type. - RGBValue color; //The contour color. - ContourUnion structure; //The information necessary to describe the contour in coordinate space. + ContourType type; // The contour type. + RGBValue color; // The contour color. + ContourUnion structure; // The information necessary to describe the contour + // in coordinate space. } ContourInfo2; typedef struct ContourPoint_struct { - double x; //The x-coordinate value in the image. - double y; //The y-coordinate value in the image. - double curvature; //The change in slope at this edge point of the segment. - double xDisplacement; //The x displacement of the current edge pixel from a cubic spline fit of the current edge segment. - double yDisplacement; //The y displacement of the current edge pixel from a cubic spline fit of the current edge segment. + double x; // The x-coordinate value in the image. + double y; // The y-coordinate value in the image. + double curvature; // The change in slope at this edge point of the segment. + double xDisplacement; // The x displacement of the current edge pixel from a + // cubic spline fit of the current edge segment. + double yDisplacement; // The y displacement of the current edge pixel from a + // cubic spline fit of the current edge segment. } ContourPoint; typedef struct CoordinateTransform_struct { - Point initialOrigin; //The origin of the initial coordinate system. - float initialAngle; //The angle, in degrees, of the x-axis of the initial coordinate system relative to the image x-axis. - Point finalOrigin; //The origin of the final coordinate system. - float finalAngle; //The angle, in degrees, of the x-axis of the final coordinate system relative to the image x-axis. + Point initialOrigin; // The origin of the initial coordinate system. + float initialAngle; // The angle, in degrees, of the x-axis of the initial + // coordinate system relative to the image x-axis. + Point finalOrigin; // The origin of the final coordinate system. + float finalAngle; // The angle, in degrees, of the x-axis of the final + // coordinate system relative to the image x-axis. } CoordinateTransform; typedef struct CoordinateTransform2_struct { - CoordinateSystem referenceSystem; //Defines the coordinate system for input coordinates. - CoordinateSystem measurementSystem; //Defines the coordinate system in which the function should perform measurements. + CoordinateSystem + referenceSystem; // Defines the coordinate system for input coordinates. + CoordinateSystem measurementSystem; // Defines the coordinate system in which + // the function should perform + // measurements. } CoordinateTransform2; typedef struct CannyOptions_struct { - float sigma; //The sigma of the Gaussian smoothing filter that the function applies to the image before edge detection. - float upperThreshold; //The upper fraction of pixel values in the image from which the function chooses a seed or starting point of an edge segment. - float lowerThreshold; //The function multiplies this value by upperThreshold to determine the lower threshold for all the pixels in an edge segment. - int windowSize; //The window size of the Gaussian filter that the function applies to the image. + float sigma; // The sigma of the Gaussian smoothing filter that the function + // applies to the image before edge detection. + float upperThreshold; // The upper fraction of pixel values in the image from + // which the function chooses a seed or starting point + // of an edge segment. + float lowerThreshold; // The function multiplies this value by upperThreshold + // to determine the lower threshold for all the pixels + // in an edge segment. + int windowSize; // The window size of the Gaussian filter that the function + // applies to the image. } CannyOptions; typedef struct Range_struct { - int minValue; //The minimum value of the range. - int maxValue; //The maximum value of the range. + int minValue; // The minimum value of the range. + int maxValue; // The maximum value of the range. } Range; typedef struct UserPointSymbol_struct { - int cols; //Number of columns in the symbol. - int rows; //Number of rows in the symbol. - int* pixels; //The pixels of the symbol. + int cols; // Number of columns in the symbol. + int rows; // Number of rows in the symbol. + int* pixels; // The pixels of the symbol. } UserPointSymbol; typedef struct View3DOptions_struct { - int sizeReduction; //A divisor the function uses when determining the final height and width of the 3D image. - int maxHeight; //Defines the maximum height of a pixel from the image source drawn in 3D. - Direction3D direction; //Defines the 3D orientation. - float alpha; //Determines the angle between the horizontal and the baseline. - float beta; //Determines the angle between the horizontal and the second baseline. - int border; //Defines the border size. - int background; //Defines the background color. - Plane3D plane; //Indicates the view a function uses to show complex images. + int sizeReduction; // A divisor the function uses when determining the final + // height and width of the 3D image. + int maxHeight; // Defines the maximum height of a pixel from the image source + // drawn in 3D. + Direction3D direction; // Defines the 3D orientation. + float alpha; // Determines the angle between the horizontal and the baseline. + float beta; // Determines the angle between the horizontal and the second + // baseline. + int border; // Defines the border size. + int background; // Defines the background color. + Plane3D plane; // Indicates the view a function uses to show complex images. } View3DOptions; typedef struct MatchPatternOptions_struct { - MatchingMode mode; //Specifies the method to use when looking for the pattern in the image. - int minContrast; //Specifies the minimum contrast expected in the image. - int subpixelAccuracy; //Set this element to TRUE to return areas in the image that match the pattern area with subpixel accuracy. - RotationAngleRange* angleRanges; //An array of angle ranges, in degrees, where each range specifies how much you expect the pattern to be rotated in the image. - int numRanges; //Number of angle ranges in the angleRanges array. - int numMatchesRequested; //Number of valid matches expected. - int matchFactor; //Controls the number of potential matches that the function examines. - float minMatchScore; //The minimum score a match can have for the function to consider the match valid. + MatchingMode mode; // Specifies the method to use when looking for the + // pattern in the image. + int minContrast; // Specifies the minimum contrast expected in the image. + int subpixelAccuracy; // Set this element to TRUE to return areas in the + // image that match the pattern area with subpixel + // accuracy. + RotationAngleRange* angleRanges; // An array of angle ranges, in degrees, + // where each range specifies how much you + // expect the pattern to be rotated in the + // image. + int numRanges; // Number of angle ranges in the angleRanges array. + int numMatchesRequested; // Number of valid matches expected. + int matchFactor; // Controls the number of potential matches that the + // function examines. + float minMatchScore; // The minimum score a match can have for the function + // to consider the match valid. } MatchPatternOptions; typedef struct TIFFFileOptions_struct { - int rowsPerStrip; //Indicates the number of rows that the function writes per strip. - PhotometricMode photoInterp; //Designates which photometric interpretation to use. - TIFFCompressionType compressionType; //Indicates the type of compression to use on the TIFF file. + int rowsPerStrip; // Indicates the number of rows that the function writes + // per strip. + PhotometricMode + photoInterp; // Designates which photometric interpretation to use. + TIFFCompressionType compressionType; // Indicates the type of compression to + // use on the TIFF file. } TIFFFileOptions; typedef union Color_union { - RGBValue rgb; //The information needed to describe a color in the RGB (Red, Green, and Blue) color space. - HSLValue hsl; //The information needed to describe a color in the HSL (Hue, Saturation, and Luminance) color space. - HSVValue hsv; //The information needed to describe a color in the HSI (Hue, Saturation, and Value) color space. - HSIValue hsi; //The information needed to describe a color in the HSI (Hue, Saturation, and Intensity) color space. - int rawValue; //The integer value for the data in the color union. + RGBValue rgb; // The information needed to describe a color in the RGB (Red, + // Green, and Blue) color space. + HSLValue hsl; // The information needed to describe a color in the HSL (Hue, + // Saturation, and Luminance) color space. + HSVValue hsv; // The information needed to describe a color in the HSI (Hue, + // Saturation, and Value) color space. + HSIValue hsi; // The information needed to describe a color in the HSI (Hue, + // Saturation, and Intensity) color space. + int rawValue; // The integer value for the data in the color union. } Color; typedef union PixelValue_union { - float grayscale; //A grayscale pixel value. - RGBValue rgb; //A RGB pixel value. - HSLValue hsl; //A HSL pixel value. - Complex complex; //A complex pixel value. - RGBU64Value rgbu64; //An unsigned 64-bit RGB pixel value. + float grayscale; // A grayscale pixel value. + RGBValue rgb; // A RGB pixel value. + HSLValue hsl; // A HSL pixel value. + Complex complex; // A complex pixel value. + RGBU64Value rgbu64; // An unsigned 64-bit RGB pixel value. } PixelValue; typedef struct OpenContour_struct { - Point* points; //The points that make up the open contour. - int numPoints; //The number of points in the array. + Point* points; // The points that make up the open contour. + int numPoints; // The number of points in the array. } OpenContour; typedef struct OverlayTextOptions_struct { - const char* fontName; //The name of the font to use. - int fontSize; //The size of the font. - int bold; //Set this element to TRUE to bold the text. - int italic; //Set this element to TRUE to italicize the text. - int underline; //Set this element to TRUE to underline the text. - int strikeout; //Set this element to TRUE to strikeout the text. - TextAlignment horizontalTextAlignment; //Sets the alignment of the text. - VerticalTextAlignment verticalTextAlignment; //Sets the vertical alignment for the text. - RGBValue backgroundColor; //Sets the color for the text background pixels. - double angle; //The counterclockwise angle, in degrees, of the text relative to the x-axis. + const char* fontName; // The name of the font to use. + int fontSize; // The size of the font. + int bold; // Set this element to TRUE to bold the text. + int italic; // Set this element to TRUE to italicize the text. + int underline; // Set this element to TRUE to underline the text. + int strikeout; // Set this element to TRUE to strikeout the text. + TextAlignment horizontalTextAlignment; // Sets the alignment of the text. + VerticalTextAlignment + verticalTextAlignment; // Sets the vertical alignment for the text. + RGBValue backgroundColor; // Sets the color for the text background pixels. + double angle; // The counterclockwise angle, in degrees, of the text relative + // to the x-axis. } OverlayTextOptions; typedef struct ParticleFilterCriteria_struct { - MeasurementValue parameter; //The morphological measurement that the function uses for filtering. - float lower; //The lower bound of the criteria range. - float upper; //The upper bound of the criteria range. - int exclude; //Set this element to TRUE to indicate that a match occurs when the value is outside the criteria range. + MeasurementValue parameter; // The morphological measurement that the + // function uses for filtering. + float lower; // The lower bound of the criteria range. + float upper; // The upper bound of the criteria range. + int exclude; // Set this element to TRUE to indicate that a match occurs when + // the value is outside the criteria range. } ParticleFilterCriteria; typedef struct ParticleReport_struct { - int area; //The number of pixels in the particle. - float calibratedArea; //The size of the particle, calibrated to the calibration information of the image. - float perimeter; //The length of the perimeter, calibrated to the calibration information of the image. - int numHoles; //The number of holes in the particle. - int areaOfHoles; //The total surface area, in pixels, of all the holes in a particle. - float perimeterOfHoles; //The length of the perimeter of all the holes in the particle calibrated to the calibration information of the image. - Rect boundingBox; //The smallest rectangle that encloses the particle. - float sigmaX; //The sum of the particle pixels on the x-axis. - float sigmaY; //The sum of the particle pixels on the y-axis. - float sigmaXX; //The sum of the particle pixels on the x-axis, squared. - float sigmaYY; //The sum of the particle pixels on the y-axis, squared. - float sigmaXY; //The sum of the particle pixels on the x-axis and y-axis. - int longestLength; //The length of the longest horizontal line segment. - Point longestPoint; //The location of the leftmost pixel of the longest segment in the particle. - int projectionX; //The length of the particle when projected onto the x-axis. - int projectionY; //The length of the particle when projected onto the y-axis. - int connect8; //This element is TRUE if the function used connectivity-8 to determine if particles are touching. + int area; // The number of pixels in the particle. + float calibratedArea; // The size of the particle, calibrated to the + // calibration information of the image. + float perimeter; // The length of the perimeter, calibrated to the + // calibration information of the image. + int numHoles; // The number of holes in the particle. + int areaOfHoles; // The total surface area, in pixels, of all the holes in a + // particle. + float perimeterOfHoles; // The length of the perimeter of all the holes in + // the particle calibrated to the calibration + // information of the image. + Rect boundingBox; // The smallest rectangle that encloses the particle. + float sigmaX; // The sum of the particle pixels on the x-axis. + float sigmaY; // The sum of the particle pixels on the y-axis. + float sigmaXX; // The sum of the particle pixels on the x-axis, squared. + float sigmaYY; // The sum of the particle pixels on the y-axis, squared. + float sigmaXY; // The sum of the particle pixels on the x-axis and y-axis. + int longestLength; // The length of the longest horizontal line segment. + Point longestPoint; // The location of the leftmost pixel of the longest + // segment in the particle. + int projectionX; // The length of the particle when projected onto the + // x-axis. + int projectionY; // The length of the particle when projected onto the + // y-axis. + int connect8; // This element is TRUE if the function used connectivity-8 to + // determine if particles are touching. } ParticleReport; typedef struct PatternMatch_struct { - PointFloat position; //The location of the center of the match. - float rotation; //The rotation of the match relative to the template image, in degrees. - float scale; //The size of the match relative to the size of the template image, expressed as a percentage. - float score; //The accuracy of the match. - PointFloat corner[4]; //An array of four points describing the rectangle surrounding the template image. + PointFloat position; // The location of the center of the match. + float rotation; // The rotation of the match relative to the template image, + // in degrees. + float scale; // The size of the match relative to the size of the template + // image, expressed as a percentage. + float score; // The accuracy of the match. + PointFloat corner[4]; // An array of four points describing the rectangle + // surrounding the template image. } PatternMatch; typedef struct QuantifyData_struct { - float mean; //The mean value of the pixel values. - float stdDev; //The standard deviation of the pixel values. - float min; //The smallest pixel value. - float max; //The largest pixel value. - float calibratedArea; //The area, calibrated to the calibration information of the image. - int pixelArea; //The area, in number of pixels. - float relativeSize; //The proportion, expressed as a percentage, of the associated region relative to the whole image. + float mean; // The mean value of the pixel values. + float stdDev; // The standard deviation of the pixel values. + float min; // The smallest pixel value. + float max; // The largest pixel value. + float calibratedArea; // The area, calibrated to the calibration information + // of the image. + int pixelArea; // The area, in number of pixels. + float relativeSize; // The proportion, expressed as a percentage, of the + // associated region relative to the whole image. } QuantifyData; typedef struct QuantifyReport_struct { - QuantifyData global; //Statistical data of the whole image. - QuantifyData* regions; //An array of QuantifyData structures containing statistical data of each region of the image. - int regionCount; //The number of regions. + QuantifyData global; // Statistical data of the whole image. + QuantifyData* regions; // An array of QuantifyData structures containing + // statistical data of each region of the image. + int regionCount; // The number of regions. } QuantifyReport; typedef struct RakeOptions_struct { - int threshold; //Specifies the threshold value for the contrast of the edge. - int width; //The number of pixels that the function averages to find the contrast at either side of the edge. - int steepness; //The span, in pixels, of the slope of the edge projected along the path specified by the input points. - int subsamplingRatio; //Specifies the number of pixels that separate two consecutive search lines. - InterpolationMethod subpixelType; //The method for interpolating. - int subpixelDivisions; //The number of samples the function obtains from a pixel. + int threshold; // Specifies the threshold value for the contrast of the edge. + int width; // The number of pixels that the function averages to find the + // contrast at either side of the edge. + int steepness; // The span, in pixels, of the slope of the edge projected + // along the path specified by the input points. + int subsamplingRatio; // Specifies the number of pixels that separate two + // consecutive search lines. + InterpolationMethod subpixelType; // The method for interpolating. + int subpixelDivisions; // The number of samples the function obtains from a + // pixel. } RakeOptions; typedef struct RakeReport_struct { - LineFloat* rakeLines; //The coordinate location of each of the rake lines used by the function. - int numRakeLines; //The number of lines in the rakeLines array. - PointFloat* firstEdges; //The coordinate location of all edges detected as first edges. - unsigned int numFirstEdges; //The number of points in the firstEdges array. - PointFloat* lastEdges; //The coordinate location of all edges detected as last edges. - unsigned int numLastEdges; //The number of points in the lastEdges array. - EdgeLocationReport* allEdges; //An array of reports describing the location of the edges located by each rake line. - int* linesWithEdges; //An array of indices into the rakeLines array indicating the rake lines on which the function detected at least one edge. - int numLinesWithEdges; //The number of rake lines along which the function detected edges. + LineFloat* rakeLines; // The coordinate location of each of the rake lines + // used by the function. + int numRakeLines; // The number of lines in the rakeLines array. + PointFloat* firstEdges; // The coordinate location of all edges detected as + // first edges. + unsigned int numFirstEdges; // The number of points in the firstEdges array. + PointFloat* lastEdges; // The coordinate location of all edges detected as + // last edges. + unsigned int numLastEdges; // The number of points in the lastEdges array. + EdgeLocationReport* allEdges; // An array of reports describing the location + // of the edges located by each rake line. + int* linesWithEdges; // An array of indices into the rakeLines array + // indicating the rake lines on which the function + // detected at least one edge. + int numLinesWithEdges; // The number of rake lines along which the function + // detected edges. } RakeReport; typedef struct TransformReport_struct { - PointFloat* points; //An array of transformed coordinates. - int* validPoints; //An array of values that describe the validity of each of the coordinates according to the region of interest you calibrated using either imaqLearnCalibrationGrid() or imaqLearnCalibrationPoints(). - int numPoints; //The length of both the points array and the validPoints array. + PointFloat* points; // An array of transformed coordinates. + int* validPoints; // An array of values that describe the validity of each of + // the coordinates according to the region of interest you + // calibrated using either imaqLearnCalibrationGrid() or + // imaqLearnCalibrationPoints(). + int numPoints; // The length of both the points array and the validPoints + // array. } TransformReport; typedef struct ShapeReport_struct { - Rect coordinates; //The bounding rectangle of the object. - Point centroid; //The coordinate location of the centroid of the object. - int size; //The size, in pixels, of the object. - double score; //A value ranging between 1 and 1,000 that specifies how similar the object in the image is to the template. + Rect coordinates; // The bounding rectangle of the object. + Point centroid; // The coordinate location of the centroid of the object. + int size; // The size, in pixels, of the object. + double score; // A value ranging between 1 and 1,000 that specifies how + // similar the object in the image is to the template. } ShapeReport; typedef struct MeterArc_struct { - PointFloat needleBase; //The coordinate location of the base of the meter needle. - PointFloat* arcCoordPoints; //An array of points describing the coordinate location of the meter arc. - int numOfArcCoordPoints; //The number of points in the arcCoordPoints array. - int needleColor; //This element is TRUE when the meter has a light-colored needle on a dark background. + PointFloat + needleBase; // The coordinate location of the base of the meter needle. + PointFloat* arcCoordPoints; // An array of points describing the coordinate + // location of the meter arc. + int numOfArcCoordPoints; // The number of points in the arcCoordPoints array. + int needleColor; // This element is TRUE when the meter has a light-colored + // needle on a dark background. } MeterArc; typedef struct ThresholdData_struct { - float rangeMin; //The lower boundary of the range to keep. - float rangeMax; //The upper boundary of the range to keep. - float newValue; //If useNewValue is TRUE, newValue is the replacement value for pixels within the range. - int useNewValue; //If TRUE, the function sets pixel values within [rangeMin, rangeMax] to the value specified in newValue. + float rangeMin; // The lower boundary of the range to keep. + float rangeMax; // The upper boundary of the range to keep. + float newValue; // If useNewValue is TRUE, newValue is the replacement value + // for pixels within the range. + int useNewValue; // If TRUE, the function sets pixel values within [rangeMin, + // rangeMax] to the value specified in newValue. } ThresholdData; typedef struct StructuringElement_struct { - int matrixCols; //Number of columns in the matrix. - int matrixRows; //Number of rows in the matrix. - int hexa; //Set this element to TRUE if you specify a hexagonal structuring element in kernel. - int* kernel; //The values of the structuring element. + int matrixCols; // Number of columns in the matrix. + int matrixRows; // Number of rows in the matrix. + int hexa; // Set this element to TRUE if you specify a hexagonal structuring + // element in kernel. + int* kernel; // The values of the structuring element. } StructuringElement; typedef struct SpokeReport_struct { - LineFloat* spokeLines; //The coordinate location of each of the spoke lines used by the function. - int numSpokeLines; //The number of lines in the spokeLines array. - PointFloat* firstEdges; //The coordinate location of all edges detected as first edges. - int numFirstEdges; //The number of points in the firstEdges array. - PointFloat* lastEdges; //The coordinate location of all edges detected as last edges. - int numLastEdges; //The number of points in the lastEdges array. - EdgeLocationReport* allEdges; //An array of reports describing the location of the edges located by each spoke line. - int* linesWithEdges; //An array of indices into the spokeLines array indicating the rake lines on which the function detected at least one edge. - int numLinesWithEdges; //The number of spoke lines along which the function detects edges. + LineFloat* spokeLines; // The coordinate location of each of the spoke lines + // used by the function. + int numSpokeLines; // The number of lines in the spokeLines array. + PointFloat* firstEdges; // The coordinate location of all edges detected as + // first edges. + int numFirstEdges; // The number of points in the firstEdges array. + PointFloat* lastEdges; // The coordinate location of all edges detected as + // last edges. + int numLastEdges; // The number of points in the lastEdges array. + EdgeLocationReport* allEdges; // An array of reports describing the location + // of the edges located by each spoke line. + int* linesWithEdges; // An array of indices into the spokeLines array + // indicating the rake lines on which the function + // detected at least one edge. + int numLinesWithEdges; // The number of spoke lines along which the function + // detects edges. } SpokeReport; typedef struct SimpleEdgeOptions_struct { - LevelType type; //Determines how the function evaluates the threshold and hysteresis values. - int threshold; //The pixel value at which an edge occurs. - int hysteresis; //A value that helps determine edges in noisy images. - EdgeProcess process; //Determines which edges the function looks for. - int subpixel; //Set this element to TRUE to find edges with subpixel accuracy by interpolating between points to find the crossing of the given threshold. + LevelType type; // Determines how the function evaluates the threshold and + // hysteresis values. + int threshold; // The pixel value at which an edge occurs. + int hysteresis; // A value that helps determine edges in noisy images. + EdgeProcess process; // Determines which edges the function looks for. + int subpixel; // Set this element to TRUE to find edges with subpixel + // accuracy by interpolating between points to find the + // crossing of the given threshold. } SimpleEdgeOptions; typedef struct SelectParticleCriteria_struct { - MeasurementValue parameter; //The morphological measurement that the function uses for filtering. - float lower; //The lower boundary of the criteria range. - float upper; //The upper boundary of the criteria range. + MeasurementValue parameter; // The morphological measurement that the + // function uses for filtering. + float lower; // The lower boundary of the criteria range. + float upper; // The upper boundary of the criteria range. } SelectParticleCriteria; typedef struct SegmentInfo_struct { - int numberOfPoints; //The number of points in the segment. - int isOpen; //If TRUE, the contour is open. - double weight; //The significance of the edge in terms of the gray values that constitute the edge. - ContourPoint* points; //The points of the segment. + int numberOfPoints; // The number of points in the segment. + int isOpen; // If TRUE, the contour is open. + double weight; // The significance of the edge in terms of the gray values + // that constitute the edge. + ContourPoint* points; // The points of the segment. } SegmentInfo; typedef struct RotationAngleRange_struct { - float lower; //The lowest amount of rotation, in degrees, a valid pattern can have. - float upper; //The highest amount of rotation, in degrees, a valid pattern can have. + float lower; // The lowest amount of rotation, in degrees, a valid pattern + // can have. + float upper; // The highest amount of rotation, in degrees, a valid pattern + // can have. } RotationAngleRange; typedef struct RotatedRect_struct { - int top; //Location of the top edge of the rectangle before rotation. - int left; //Location of the left edge of the rectangle before rotation. - int height; //Height of the rectangle. - int width; //Width of the rectangle. - double angle; //The rotation, in degrees, of the rectangle. + int top; // Location of the top edge of the rectangle before rotation. + int left; // Location of the left edge of the rectangle before rotation. + int height; // Height of the rectangle. + int width; // Width of the rectangle. + double angle; // The rotation, in degrees, of the rectangle. } RotatedRect; typedef struct ROIProfile_struct { - LineProfile report; //Quantifying information about the points along the edge of each contour in the ROI. - Point* pixels; //An array of the points along the edge of each contour in the ROI. + LineProfile report; // Quantifying information about the points along the + // edge of each contour in the ROI. + Point* pixels; // An array of the points along the edge of each contour in + // the ROI. } ROIProfile; typedef struct ToolWindowOptions_struct { - int showSelectionTool; //If TRUE, the selection tool becomes visible. - int showZoomTool; //If TRUE, the zoom tool becomes visible. - int showPointTool; //If TRUE, the point tool becomes visible. - int showLineTool; //If TRUE, the line tool becomes visible. - int showRectangleTool; //If TRUE, the rectangle tool becomes visible. - int showOvalTool; //If TRUE, the oval tool becomes visible. - int showPolygonTool; //If TRUE, the polygon tool becomes visible. - int showClosedFreehandTool; //If TRUE, the closed freehand tool becomes visible. - int showPolyLineTool; //If TRUE, the polyline tool becomes visible. - int showFreehandTool; //If TRUE, the freehand tool becomes visible. - int showAnnulusTool; //If TRUE, the annulus becomes visible. - int showRotatedRectangleTool; //If TRUE, the rotated rectangle tool becomes visible. - int showPanTool; //If TRUE, the pan tool becomes visible. - int showZoomOutTool; //If TRUE, the zoom out tool becomes visible. - int reserved2; //This element is reserved and should be set to FALSE. - int reserved3; //This element is reserved and should be set to FALSE. - int reserved4; //This element is reserved and should be set to FALSE. + int showSelectionTool; // If TRUE, the selection tool becomes visible. + int showZoomTool; // If TRUE, the zoom tool becomes visible. + int showPointTool; // If TRUE, the point tool becomes visible. + int showLineTool; // If TRUE, the line tool becomes visible. + int showRectangleTool; // If TRUE, the rectangle tool becomes visible. + int showOvalTool; // If TRUE, the oval tool becomes visible. + int showPolygonTool; // If TRUE, the polygon tool becomes visible. + int showClosedFreehandTool; // If TRUE, the closed freehand tool becomes + // visible. + int showPolyLineTool; // If TRUE, the polyline tool becomes visible. + int showFreehandTool; // If TRUE, the freehand tool becomes visible. + int showAnnulusTool; // If TRUE, the annulus becomes visible. + int showRotatedRectangleTool; // If TRUE, the rotated rectangle tool becomes + // visible. + int showPanTool; // If TRUE, the pan tool becomes visible. + int showZoomOutTool; // If TRUE, the zoom out tool becomes visible. + int reserved2; // This element is reserved and should be set to FALSE. + int reserved3; // This element is reserved and should be set to FALSE. + int reserved4; // This element is reserved and should be set to FALSE. } ToolWindowOptions; typedef struct SpokeOptions_struct { - int threshold; //Specifies the threshold value for the contrast of the edge. - int width; //The number of pixels that the function averages to find the contrast at either side of the edge. - int steepness; //The span, in pixels, of the slope of the edge projected along the path specified by the input points. - double subsamplingRatio; //The angle, in degrees, between each radial search line in the spoke. - InterpolationMethod subpixelType; //The method for interpolating. - int subpixelDivisions; //The number of samples the function obtains from a pixel. + int threshold; // Specifies the threshold value for the contrast of the edge. + int width; // The number of pixels that the function averages to find the + // contrast at either side of the edge. + int steepness; // The span, in pixels, of the slope of the edge projected + // along the path specified by the input points. + double subsamplingRatio; // The angle, in degrees, between each radial search + // line in the spoke. + InterpolationMethod subpixelType; // The method for interpolating. + int subpixelDivisions; // The number of samples the function obtains from a + // pixel. } SpokeOptions; #if !defined __GNUC__ && !defined _M_X64 @@ -4645,7 +7328,9 @@ typedef struct SpokeOptions_struct { // Callback Function Type //============================================================================ #ifndef __GNUC__ -typedef void (IMAQ_CALLBACK* EventCallback)(WindowEventType event, int windowNumber, Tool tool, Rect rect); +typedef void(IMAQ_CALLBACK* EventCallback)(WindowEventType event, + int windowNumber, Tool tool, + Rect rect); #endif //============================================================================ @@ -4654,13 +7339,13 @@ typedef void (IMAQ_CALLBACK* EventCallback)(WindowEventType event, int windowNum #ifndef __GNUC__ #pragma const_seg("IMAQVisionColorConstants") #endif -static const RGBValue IMAQ_RGB_TRANSPARENT = { 0, 0, 0, 1 }; -static const RGBValue IMAQ_RGB_RED = { 0, 0, 255, 0 }; -static const RGBValue IMAQ_RGB_BLUE = { 255, 0, 0, 0 }; -static const RGBValue IMAQ_RGB_GREEN = { 0, 255, 0, 0 }; -static const RGBValue IMAQ_RGB_YELLOW = { 0, 255, 255, 0 }; -static const RGBValue IMAQ_RGB_WHITE = { 255, 255, 255, 0 }; -static const RGBValue IMAQ_RGB_BLACK = { 0, 0, 0, 0 }; +static const RGBValue IMAQ_RGB_TRANSPARENT = {0, 0, 0, 1}; +static const RGBValue IMAQ_RGB_RED = {0, 0, 255, 0}; +static const RGBValue IMAQ_RGB_BLUE = {255, 0, 0, 0}; +static const RGBValue IMAQ_RGB_GREEN = {0, 255, 0, 0}; +static const RGBValue IMAQ_RGB_YELLOW = {0, 255, 255, 0}; +static const RGBValue IMAQ_RGB_WHITE = {255, 255, 255, 0}; +static const RGBValue IMAQ_RGB_BLACK = {0, 0, 0, 0}; #ifndef __GNUC__ #pragma const_seg() #endif @@ -4668,469 +7353,899 @@ static const RGBValue IMAQ_RGB_BLACK = { 0, 0, 0, 0 }; //============================================================================ // Backwards Compatibility //============================================================================ -typedef ColorSensitivity ColorComplexity; -#define IMAQ_COMPLEXITY_LOW IMAQ_SENSITIVITY_LOW -#define IMAQ_COMPLEXITY_MED IMAQ_SENSITIVITY_MED -#define IMAQ_COMPLEXITY_HIGH IMAQ_SENSITIVITY_HIGH -#define ERR_INVALID_COLORCOMPLEXITY ERR_INVALID_COLORSENSITIVITY +typedef ColorSensitivity ColorComplexity; +#define IMAQ_COMPLEXITY_LOW IMAQ_SENSITIVITY_LOW +#define IMAQ_COMPLEXITY_MED IMAQ_SENSITIVITY_MED +#define IMAQ_COMPLEXITY_HIGH IMAQ_SENSITIVITY_HIGH +#define ERR_INVALID_COLORCOMPLEXITY ERR_INVALID_COLORSENSITIVITY //============================================================================ // Logical functions //============================================================================ -IMAQ_FUNC int IMAQ_STDCALL imaqAnd(Image* dest, const Image* sourceA, const Image* sourceB); -IMAQ_FUNC int IMAQ_STDCALL imaqAndConstant(Image* dest, const Image* source, PixelValue value); -IMAQ_FUNC int IMAQ_STDCALL imaqCompare(Image* dest, const Image* source, const Image* compareImage, ComparisonFunction compare); -IMAQ_FUNC int IMAQ_STDCALL imaqCompareConstant(Image* dest, const Image* source, PixelValue value, ComparisonFunction compare); -IMAQ_FUNC int IMAQ_STDCALL imaqLogicalDifference(Image* dest, const Image* sourceA, const Image* sourceB); -IMAQ_FUNC int IMAQ_STDCALL imaqLogicalDifferenceConstant(Image* dest, const Image* source, PixelValue value); -IMAQ_FUNC int IMAQ_STDCALL imaqNand(Image* dest, const Image* sourceA, const Image* sourceB); -IMAQ_FUNC int IMAQ_STDCALL imaqNandConstant(Image* dest, const Image* source, PixelValue value); -IMAQ_FUNC int IMAQ_STDCALL imaqNor(Image* dest, const Image* sourceA, const Image* sourceB); -IMAQ_FUNC int IMAQ_STDCALL imaqNorConstant(Image* dest, const Image* source, PixelValue value); -IMAQ_FUNC int IMAQ_STDCALL imaqOr(Image* dest, const Image* sourceA, const Image* sourceB); -IMAQ_FUNC int IMAQ_STDCALL imaqOrConstant(Image* dest, const Image* source, PixelValue value); -IMAQ_FUNC int IMAQ_STDCALL imaqXnor(Image* dest, const Image* sourceA, const Image* sourceB); -IMAQ_FUNC int IMAQ_STDCALL imaqXnorConstant(Image* dest, const Image* source, PixelValue value); -IMAQ_FUNC int IMAQ_STDCALL imaqXor(Image* dest, const Image* sourceA, const Image* sourceB); -IMAQ_FUNC int IMAQ_STDCALL imaqXorConstant(Image* dest, const Image* source, PixelValue value); +IMAQ_FUNC int IMAQ_STDCALL +imaqAnd(Image* dest, const Image* sourceA, const Image* sourceB); +IMAQ_FUNC int IMAQ_STDCALL +imaqAndConstant(Image* dest, const Image* source, PixelValue value); +IMAQ_FUNC int IMAQ_STDCALL imaqCompare(Image* dest, const Image* source, + const Image* compareImage, + ComparisonFunction compare); +IMAQ_FUNC int IMAQ_STDCALL imaqCompareConstant(Image* dest, const Image* source, + PixelValue value, + ComparisonFunction compare); +IMAQ_FUNC int IMAQ_STDCALL +imaqLogicalDifference(Image* dest, const Image* sourceA, const Image* sourceB); +IMAQ_FUNC int IMAQ_STDCALL imaqLogicalDifferenceConstant(Image* dest, + const Image* source, + PixelValue value); +IMAQ_FUNC int IMAQ_STDCALL +imaqNand(Image* dest, const Image* sourceA, const Image* sourceB); +IMAQ_FUNC int IMAQ_STDCALL +imaqNandConstant(Image* dest, const Image* source, PixelValue value); +IMAQ_FUNC int IMAQ_STDCALL +imaqNor(Image* dest, const Image* sourceA, const Image* sourceB); +IMAQ_FUNC int IMAQ_STDCALL +imaqNorConstant(Image* dest, const Image* source, PixelValue value); +IMAQ_FUNC int IMAQ_STDCALL +imaqOr(Image* dest, const Image* sourceA, const Image* sourceB); +IMAQ_FUNC int IMAQ_STDCALL +imaqOrConstant(Image* dest, const Image* source, PixelValue value); +IMAQ_FUNC int IMAQ_STDCALL +imaqXnor(Image* dest, const Image* sourceA, const Image* sourceB); +IMAQ_FUNC int IMAQ_STDCALL +imaqXnorConstant(Image* dest, const Image* source, PixelValue value); +IMAQ_FUNC int IMAQ_STDCALL +imaqXor(Image* dest, const Image* sourceA, const Image* sourceB); +IMAQ_FUNC int IMAQ_STDCALL +imaqXorConstant(Image* dest, const Image* source, PixelValue value); //============================================================================ // Particle Analysis functions //============================================================================ -IMAQ_FUNC int IMAQ_STDCALL imaqCountParticles(Image* image, int connectivity8, int* numParticles); -IMAQ_FUNC int IMAQ_STDCALL imaqMeasureParticle(Image* image, int particleNumber, int calibrated, MeasurementType measurement, double* value); -IMAQ_FUNC MeasureParticlesReport* IMAQ_STDCALL imaqMeasureParticles(Image* image, MeasureParticlesCalibrationMode calibrationMode, const MeasurementType* measurements, size_t numMeasurements); -IMAQ_FUNC int IMAQ_STDCALL imaqParticleFilter4(Image* dest, Image* source, const ParticleFilterCriteria2* criteria, int criteriaCount, const ParticleFilterOptions2* options, const ROI* roi, int* numParticles); +IMAQ_FUNC int IMAQ_STDCALL +imaqCountParticles(Image* image, int connectivity8, int* numParticles); +IMAQ_FUNC int IMAQ_STDCALL +imaqMeasureParticle(Image* image, int particleNumber, int calibrated, + MeasurementType measurement, double* value); +IMAQ_FUNC MeasureParticlesReport* IMAQ_STDCALL +imaqMeasureParticles(Image* image, + MeasureParticlesCalibrationMode calibrationMode, + const MeasurementType* measurements, + size_t numMeasurements); +IMAQ_FUNC int IMAQ_STDCALL +imaqParticleFilter4(Image* dest, Image* source, + const ParticleFilterCriteria2* criteria, int criteriaCount, + const ParticleFilterOptions2* options, const ROI* roi, + int* numParticles); //============================================================================ // Morphology functions //============================================================================ -IMAQ_FUNC int IMAQ_STDCALL imaqConvexHull(Image* dest, Image* source, int connectivity8); -IMAQ_FUNC int IMAQ_STDCALL imaqDanielssonDistance(Image* dest, Image* source); -IMAQ_FUNC int IMAQ_STDCALL imaqFillHoles(Image* dest, const Image* source, int connectivity8); -IMAQ_FUNC CircleReport* IMAQ_STDCALL imaqFindCircles(Image* dest, Image* source, float minRadius, float maxRadius, int* numCircles); -IMAQ_FUNC int IMAQ_STDCALL imaqLabel2(Image* dest, Image* source, int connectivity8, int* particleCount); -IMAQ_FUNC int IMAQ_STDCALL imaqMorphology(Image* dest, Image* source, MorphologyMethod method, const StructuringElement* structuringElement); -IMAQ_FUNC int IMAQ_STDCALL imaqRejectBorder(Image* dest, Image* source, int connectivity8); -IMAQ_FUNC int IMAQ_STDCALL imaqSegmentation(Image* dest, Image* source); -IMAQ_FUNC int IMAQ_STDCALL imaqSeparation(Image* dest, Image* source, int erosions, const StructuringElement* structuringElement); -IMAQ_FUNC int IMAQ_STDCALL imaqSimpleDistance(Image* dest, Image* source, const StructuringElement* structuringElement); -IMAQ_FUNC int IMAQ_STDCALL imaqSizeFilter(Image* dest, Image* source, int connectivity8, int erosions, SizeType keepSize, const StructuringElement* structuringElement); -IMAQ_FUNC int IMAQ_STDCALL imaqSkeleton(Image* dest, Image* source, SkeletonMethod method); - +IMAQ_FUNC int IMAQ_STDCALL +imaqConvexHull(Image* dest, Image* source, int connectivity8); +IMAQ_FUNC int IMAQ_STDCALL imaqDanielssonDistance(Image* dest, Image* source); +IMAQ_FUNC int IMAQ_STDCALL +imaqFillHoles(Image* dest, const Image* source, int connectivity8); +IMAQ_FUNC CircleReport* IMAQ_STDCALL +imaqFindCircles(Image* dest, Image* source, float minRadius, float maxRadius, + int* numCircles); +IMAQ_FUNC int IMAQ_STDCALL +imaqLabel2(Image* dest, Image* source, int connectivity8, int* particleCount); +IMAQ_FUNC int IMAQ_STDCALL +imaqMorphology(Image* dest, Image* source, MorphologyMethod method, + const StructuringElement* structuringElement); +IMAQ_FUNC int IMAQ_STDCALL +imaqRejectBorder(Image* dest, Image* source, int connectivity8); +IMAQ_FUNC int IMAQ_STDCALL imaqSegmentation(Image* dest, Image* source); +IMAQ_FUNC int IMAQ_STDCALL +imaqSeparation(Image* dest, Image* source, int erosions, + const StructuringElement* structuringElement); +IMAQ_FUNC int IMAQ_STDCALL +imaqSimpleDistance(Image* dest, Image* source, + const StructuringElement* structuringElement); +IMAQ_FUNC int IMAQ_STDCALL +imaqSizeFilter(Image* dest, Image* source, int connectivity8, int erosions, + SizeType keepSize, const StructuringElement* structuringElement); +IMAQ_FUNC int IMAQ_STDCALL +imaqSkeleton(Image* dest, Image* source, SkeletonMethod method); //============================================================================ // Acquisition functions //============================================================================ -IMAQ_FUNC Image* IMAQ_STDCALL imaqCopyFromRing(SESSION_ID sessionID, Image* image, int imageToCopy, int* imageNumber, Rect rect); +IMAQ_FUNC Image* IMAQ_STDCALL imaqCopyFromRing(SESSION_ID sessionID, + Image* image, int imageToCopy, + int* imageNumber, Rect rect); IMAQ_FUNC Image* IMAQ_STDCALL imaqEasyAcquire(const char* interfaceName); -IMAQ_FUNC Image* IMAQ_STDCALL imaqExtractFromRing(SESSION_ID sessionID, int imageToExtract, int* imageNumber); -IMAQ_FUNC Image* IMAQ_STDCALL imaqGrab(SESSION_ID sessionID, Image* image, int immediate); -IMAQ_FUNC int IMAQ_STDCALL imaqReleaseImage(SESSION_ID sessionID); -IMAQ_FUNC int IMAQ_STDCALL imaqSetupGrab(SESSION_ID sessionID, Rect rect); -IMAQ_FUNC int IMAQ_STDCALL imaqSetupRing(SESSION_ID sessionID, Image** images, int numImages, int skipCount, Rect rect); -IMAQ_FUNC int IMAQ_STDCALL imaqSetupSequence(SESSION_ID sessionID, Image** images, int numImages, int skipCount, Rect rect); -IMAQ_FUNC Image* IMAQ_STDCALL imaqSnap(SESSION_ID sessionID, Image* image, Rect rect); -IMAQ_FUNC int IMAQ_STDCALL imaqStartAcquisition(SESSION_ID sessionID); -IMAQ_FUNC int IMAQ_STDCALL imaqStopAcquisition(SESSION_ID sessionID); +IMAQ_FUNC Image* IMAQ_STDCALL +imaqExtractFromRing(SESSION_ID sessionID, int imageToExtract, int* imageNumber); +IMAQ_FUNC Image* IMAQ_STDCALL +imaqGrab(SESSION_ID sessionID, Image* image, int immediate); +IMAQ_FUNC int IMAQ_STDCALL imaqReleaseImage(SESSION_ID sessionID); +IMAQ_FUNC int IMAQ_STDCALL imaqSetupGrab(SESSION_ID sessionID, Rect rect); +IMAQ_FUNC int IMAQ_STDCALL imaqSetupRing(SESSION_ID sessionID, Image** images, + int numImages, int skipCount, + Rect rect); +IMAQ_FUNC int IMAQ_STDCALL imaqSetupSequence(SESSION_ID sessionID, + Image** images, int numImages, + int skipCount, Rect rect); +IMAQ_FUNC Image* IMAQ_STDCALL +imaqSnap(SESSION_ID sessionID, Image* image, Rect rect); +IMAQ_FUNC int IMAQ_STDCALL imaqStartAcquisition(SESSION_ID sessionID); +IMAQ_FUNC int IMAQ_STDCALL imaqStopAcquisition(SESSION_ID sessionID); //============================================================================ // Arithmetic functions //============================================================================ -IMAQ_FUNC int IMAQ_STDCALL imaqAbsoluteDifference(Image* dest, const Image* sourceA, const Image* sourceB); -IMAQ_FUNC int IMAQ_STDCALL imaqAbsoluteDifferenceConstant(Image* dest, const Image* source, PixelValue value); -IMAQ_FUNC int IMAQ_STDCALL imaqAdd(Image* dest, const Image* sourceA, const Image* sourceB); -IMAQ_FUNC int IMAQ_STDCALL imaqAddConstant(Image* dest, const Image* source, PixelValue value); -IMAQ_FUNC int IMAQ_STDCALL imaqAverage(Image* dest, const Image* sourceA, const Image* sourceB); -IMAQ_FUNC int IMAQ_STDCALL imaqAverageConstant(Image* dest, const Image* source, PixelValue value); -IMAQ_FUNC int IMAQ_STDCALL imaqDivide2(Image* dest, const Image* sourceA, const Image* sourceB, RoundingMode roundingMode); -IMAQ_FUNC int IMAQ_STDCALL imaqDivideConstant2(Image* dest, const Image* source, PixelValue value, RoundingMode roundingMode); -IMAQ_FUNC int IMAQ_STDCALL imaqMax(Image* dest, const Image* sourceA, const Image* sourceB); -IMAQ_FUNC int IMAQ_STDCALL imaqMaxConstant(Image* dest, const Image* source, PixelValue value); -IMAQ_FUNC int IMAQ_STDCALL imaqMin(Image* dest, const Image* sourceA, const Image* sourceB); -IMAQ_FUNC int IMAQ_STDCALL imaqMinConstant(Image* dest, const Image* source, PixelValue value); -IMAQ_FUNC int IMAQ_STDCALL imaqModulo(Image* dest, const Image* sourceA, const Image* sourceB); -IMAQ_FUNC int IMAQ_STDCALL imaqModuloConstant(Image* dest, const Image* source, PixelValue value); -IMAQ_FUNC int IMAQ_STDCALL imaqMulDiv(Image* dest, const Image* sourceA, const Image* sourceB, float value); -IMAQ_FUNC int IMAQ_STDCALL imaqMultiply(Image* dest, const Image* sourceA, const Image* sourceB); -IMAQ_FUNC int IMAQ_STDCALL imaqMultiplyConstant(Image* dest, const Image* source, PixelValue value); -IMAQ_FUNC int IMAQ_STDCALL imaqSubtract(Image* dest, const Image* sourceA, const Image* sourceB); -IMAQ_FUNC int IMAQ_STDCALL imaqSubtractConstant(Image* dest, const Image* source, PixelValue value); +IMAQ_FUNC int IMAQ_STDCALL +imaqAbsoluteDifference(Image* dest, const Image* sourceA, const Image* sourceB); +IMAQ_FUNC int IMAQ_STDCALL imaqAbsoluteDifferenceConstant(Image* dest, + const Image* source, + PixelValue value); +IMAQ_FUNC int IMAQ_STDCALL +imaqAdd(Image* dest, const Image* sourceA, const Image* sourceB); +IMAQ_FUNC int IMAQ_STDCALL +imaqAddConstant(Image* dest, const Image* source, PixelValue value); +IMAQ_FUNC int IMAQ_STDCALL +imaqAverage(Image* dest, const Image* sourceA, const Image* sourceB); +IMAQ_FUNC int IMAQ_STDCALL +imaqAverageConstant(Image* dest, const Image* source, PixelValue value); +IMAQ_FUNC int IMAQ_STDCALL imaqDivide2(Image* dest, const Image* sourceA, + const Image* sourceB, + RoundingMode roundingMode); +IMAQ_FUNC int IMAQ_STDCALL imaqDivideConstant2(Image* dest, const Image* source, + PixelValue value, + RoundingMode roundingMode); +IMAQ_FUNC int IMAQ_STDCALL +imaqMax(Image* dest, const Image* sourceA, const Image* sourceB); +IMAQ_FUNC int IMAQ_STDCALL +imaqMaxConstant(Image* dest, const Image* source, PixelValue value); +IMAQ_FUNC int IMAQ_STDCALL +imaqMin(Image* dest, const Image* sourceA, const Image* sourceB); +IMAQ_FUNC int IMAQ_STDCALL +imaqMinConstant(Image* dest, const Image* source, PixelValue value); +IMAQ_FUNC int IMAQ_STDCALL +imaqModulo(Image* dest, const Image* sourceA, const Image* sourceB); +IMAQ_FUNC int IMAQ_STDCALL +imaqModuloConstant(Image* dest, const Image* source, PixelValue value); +IMAQ_FUNC int IMAQ_STDCALL imaqMulDiv(Image* dest, const Image* sourceA, + const Image* sourceB, float value); +IMAQ_FUNC int IMAQ_STDCALL +imaqMultiply(Image* dest, const Image* sourceA, const Image* sourceB); +IMAQ_FUNC int IMAQ_STDCALL +imaqMultiplyConstant(Image* dest, const Image* source, PixelValue value); +IMAQ_FUNC int IMAQ_STDCALL +imaqSubtract(Image* dest, const Image* sourceA, const Image* sourceB); +IMAQ_FUNC int IMAQ_STDCALL +imaqSubtractConstant(Image* dest, const Image* source, PixelValue value); //============================================================================ // Caliper functions //============================================================================ -IMAQ_FUNC CaliperReport* IMAQ_STDCALL imaqCaliperTool(const Image* image, const Point* points, int numPoints, const EdgeOptions* edgeOptions, const CaliperOptions* caliperOptions, int* numEdgePairs); -IMAQ_FUNC ConcentricRakeReport2* IMAQ_STDCALL imaqConcentricRake2(Image* image, ROI* roi, ConcentricRakeDirection direction, EdgeProcess process, int stepSize, EdgeOptions2* edgeOptions); -IMAQ_FUNC ExtremeReport* IMAQ_STDCALL imaqDetectExtremes(const double* pixels, int numPixels, DetectionMode mode, const DetectExtremesOptions* options, int* numExtremes); -IMAQ_FUNC int IMAQ_STDCALL imaqDetectRotation(const Image* referenceImage, const Image* testImage, PointFloat referenceCenter, PointFloat testCenter, int radius, float precision, double* angle); -IMAQ_FUNC EdgeReport2* IMAQ_STDCALL imaqEdgeTool4(Image* image, ROI* roi, EdgeProcess processType, EdgeOptions2* edgeOptions, const unsigned int reverseDirection); -IMAQ_FUNC FindEdgeReport* IMAQ_STDCALL imaqFindEdge2(Image* image, const ROI* roi, const CoordinateSystem* baseSystem, const CoordinateSystem* newSystem, const FindEdgeOptions2* findEdgeOptions, const StraightEdgeOptions* straightEdgeOptions); -IMAQ_FUNC int IMAQ_STDCALL imaqFindTransformRect2(Image* image, const ROI* roi, FindTransformMode mode, CoordinateSystem* baseSystem, CoordinateSystem* newSystem, const FindTransformRectOptions2* findTransformOptions, const StraightEdgeOptions* straightEdgeOptions, AxisReport* axisReport); -IMAQ_FUNC int IMAQ_STDCALL imaqFindTransformRects2(Image* image, const ROI* primaryROI, const ROI* secondaryROI, FindTransformMode mode, CoordinateSystem* baseSystem, CoordinateSystem* newSystem, const FindTransformRectsOptions2* findTransformOptions, const StraightEdgeOptions* primaryStraightEdgeOptions, const StraightEdgeOptions* secondaryStraightEdgeOptions, AxisReport* axisReport); -IMAQ_FUNC int IMAQ_STDCALL imaqLineGaugeTool2(const Image* image, Point start, Point end, LineGaugeMethod method, const EdgeOptions* edgeOptions, const CoordinateTransform2* transform, float* distance); -IMAQ_FUNC RakeReport2* IMAQ_STDCALL imaqRake2(Image* image, ROI* roi, RakeDirection direction, EdgeProcess process, int stepSize, EdgeOptions2* edgeOptions); -IMAQ_FUNC PointFloat* IMAQ_STDCALL imaqSimpleEdge(const Image* image, const Point* points, int numPoints, const SimpleEdgeOptions* options, int* numEdges); -IMAQ_FUNC SpokeReport2* IMAQ_STDCALL imaqSpoke2(Image* image, ROI* roi, SpokeDirection direction, EdgeProcess process, int stepSize, EdgeOptions2* edgeOptions); -IMAQ_FUNC StraightEdgeReport2* IMAQ_STDCALL imaqStraightEdge(const Image* image, const ROI* roi, SearchDirection searchDirection, const EdgeOptions2* edgeOptions, const StraightEdgeOptions* straightEdgeOptions); -IMAQ_FUNC StraightEdgeReport2* IMAQ_STDCALL imaqStraightEdge2(const Image* image, const ROI* roi, SearchDirection searchDirection, const EdgeOptions2* edgeOptions, const StraightEdgeOptions* straightEdgeOptions, unsigned int optimizedMode); +IMAQ_FUNC CaliperReport* IMAQ_STDCALL +imaqCaliperTool(const Image* image, const Point* points, int numPoints, + const EdgeOptions* edgeOptions, + const CaliperOptions* caliperOptions, int* numEdgePairs); +IMAQ_FUNC ConcentricRakeReport2* IMAQ_STDCALL +imaqConcentricRake2(Image* image, ROI* roi, ConcentricRakeDirection direction, + EdgeProcess process, int stepSize, + EdgeOptions2* edgeOptions); +IMAQ_FUNC ExtremeReport* IMAQ_STDCALL +imaqDetectExtremes(const double* pixels, int numPixels, DetectionMode mode, + const DetectExtremesOptions* options, int* numExtremes); +IMAQ_FUNC int IMAQ_STDCALL +imaqDetectRotation(const Image* referenceImage, const Image* testImage, + PointFloat referenceCenter, PointFloat testCenter, + int radius, float precision, double* angle); +IMAQ_FUNC EdgeReport2* IMAQ_STDCALL +imaqEdgeTool4(Image* image, ROI* roi, EdgeProcess processType, + EdgeOptions2* edgeOptions, const unsigned int reverseDirection); +IMAQ_FUNC FindEdgeReport* IMAQ_STDCALL +imaqFindEdge2(Image* image, const ROI* roi, const CoordinateSystem* baseSystem, + const CoordinateSystem* newSystem, + const FindEdgeOptions2* findEdgeOptions, + const StraightEdgeOptions* straightEdgeOptions); +IMAQ_FUNC int IMAQ_STDCALL +imaqFindTransformRect2(Image* image, const ROI* roi, FindTransformMode mode, + CoordinateSystem* baseSystem, + CoordinateSystem* newSystem, + const FindTransformRectOptions2* findTransformOptions, + const StraightEdgeOptions* straightEdgeOptions, + AxisReport* axisReport); +IMAQ_FUNC int IMAQ_STDCALL +imaqFindTransformRects2(Image* image, const ROI* primaryROI, + const ROI* secondaryROI, FindTransformMode mode, + CoordinateSystem* baseSystem, + CoordinateSystem* newSystem, + const FindTransformRectsOptions2* findTransformOptions, + const StraightEdgeOptions* primaryStraightEdgeOptions, + const StraightEdgeOptions* secondaryStraightEdgeOptions, + AxisReport* axisReport); +IMAQ_FUNC int IMAQ_STDCALL +imaqLineGaugeTool2(const Image* image, Point start, Point end, + LineGaugeMethod method, const EdgeOptions* edgeOptions, + const CoordinateTransform2* transform, float* distance); +IMAQ_FUNC RakeReport2* IMAQ_STDCALL +imaqRake2(Image* image, ROI* roi, RakeDirection direction, EdgeProcess process, + int stepSize, EdgeOptions2* edgeOptions); +IMAQ_FUNC PointFloat* IMAQ_STDCALL +imaqSimpleEdge(const Image* image, const Point* points, int numPoints, + const SimpleEdgeOptions* options, int* numEdges); +IMAQ_FUNC SpokeReport2* IMAQ_STDCALL +imaqSpoke2(Image* image, ROI* roi, SpokeDirection direction, + EdgeProcess process, int stepSize, EdgeOptions2* edgeOptions); +IMAQ_FUNC StraightEdgeReport2* IMAQ_STDCALL +imaqStraightEdge(const Image* image, const ROI* roi, + SearchDirection searchDirection, + const EdgeOptions2* edgeOptions, + const StraightEdgeOptions* straightEdgeOptions); +IMAQ_FUNC StraightEdgeReport2* IMAQ_STDCALL +imaqStraightEdge2(const Image* image, const ROI* roi, + SearchDirection searchDirection, + const EdgeOptions2* edgeOptions, + const StraightEdgeOptions* straightEdgeOptions, + unsigned int optimizedMode); //============================================================================ // Spatial Filters functions //============================================================================ -IMAQ_FUNC int IMAQ_STDCALL imaqCannyEdgeFilter(Image* dest, const Image* source, const CannyOptions* options); -IMAQ_FUNC int IMAQ_STDCALL imaqConvolve2(Image* dest, Image* source, float* kernel, int matrixRows, int matrixCols, float normalize, Image* mask, RoundingMode roundingMode); -IMAQ_FUNC int IMAQ_STDCALL imaqCorrelate(Image* dest, Image* source, const Image* templateImage, Rect rect); -IMAQ_FUNC int IMAQ_STDCALL imaqEdgeFilter(Image* dest, Image* source, OutlineMethod method, const Image* mask); -IMAQ_FUNC int IMAQ_STDCALL imaqLowPass(Image* dest, Image* source, int width, int height, float tolerance, const Image* mask); -IMAQ_FUNC int IMAQ_STDCALL imaqMedianFilter(Image* dest, Image* source, int width, int height, const Image* mask); -IMAQ_FUNC int IMAQ_STDCALL imaqNthOrderFilter(Image* dest, Image* source, int width, int height, int n, const Image* mask); +IMAQ_FUNC int IMAQ_STDCALL imaqCannyEdgeFilter(Image* dest, const Image* source, + const CannyOptions* options); +IMAQ_FUNC int IMAQ_STDCALL +imaqConvolve2(Image* dest, Image* source, float* kernel, int matrixRows, + int matrixCols, float normalize, Image* mask, + RoundingMode roundingMode); +IMAQ_FUNC int IMAQ_STDCALL imaqCorrelate(Image* dest, Image* source, + const Image* templateImage, Rect rect); +IMAQ_FUNC int IMAQ_STDCALL imaqEdgeFilter(Image* dest, Image* source, + OutlineMethod method, + const Image* mask); +IMAQ_FUNC int IMAQ_STDCALL imaqLowPass(Image* dest, Image* source, int width, + int height, float tolerance, + const Image* mask); +IMAQ_FUNC int IMAQ_STDCALL imaqMedianFilter(Image* dest, Image* source, + int width, int height, + const Image* mask); +IMAQ_FUNC int IMAQ_STDCALL imaqNthOrderFilter(Image* dest, Image* source, + int width, int height, int n, + const Image* mask); //============================================================================ // Drawing functions //============================================================================ -IMAQ_FUNC int IMAQ_STDCALL imaqDrawLineOnImage(Image* dest, const Image* source, DrawMode mode, Point start, Point end, float newPixelValue); -IMAQ_FUNC int IMAQ_STDCALL imaqDrawShapeOnImage(Image* dest, const Image* source, Rect rect, DrawMode mode, ShapeMode shape, float newPixelValue); -IMAQ_FUNC int IMAQ_STDCALL imaqDrawTextOnImage(Image* dest, const Image* source, Point coord, const char* text, const DrawTextOptions* options, int* fontNameUsed); +IMAQ_FUNC int IMAQ_STDCALL imaqDrawLineOnImage(Image* dest, const Image* source, + DrawMode mode, Point start, + Point end, float newPixelValue); +IMAQ_FUNC int IMAQ_STDCALL +imaqDrawShapeOnImage(Image* dest, const Image* source, Rect rect, DrawMode mode, + ShapeMode shape, float newPixelValue); +IMAQ_FUNC int IMAQ_STDCALL imaqDrawTextOnImage(Image* dest, const Image* source, + Point coord, const char* text, + const DrawTextOptions* options, + int* fontNameUsed); //============================================================================ // Interlacing functions //============================================================================ -IMAQ_FUNC int IMAQ_STDCALL imaqInterlaceCombine(Image* frame, const Image* odd, const Image* even); -IMAQ_FUNC int IMAQ_STDCALL imaqInterlaceSeparate(const Image* frame, Image* odd, Image* even); +IMAQ_FUNC int IMAQ_STDCALL +imaqInterlaceCombine(Image* frame, const Image* odd, const Image* even); +IMAQ_FUNC int IMAQ_STDCALL +imaqInterlaceSeparate(const Image* frame, Image* odd, Image* even); //============================================================================ // Image Information functions //============================================================================ -IMAQ_FUNC char** IMAQ_STDCALL imaqEnumerateCustomKeys(const Image* image, unsigned int* size); -IMAQ_FUNC int IMAQ_STDCALL imaqGetBitDepth(const Image* image, unsigned int* bitDepth); -IMAQ_FUNC int IMAQ_STDCALL imaqGetBytesPerPixel(const Image* image, int* byteCount); -IMAQ_FUNC int IMAQ_STDCALL imaqGetImageInfo(const Image* image, ImageInfo* info); -IMAQ_FUNC int IMAQ_STDCALL imaqGetImageSize(const Image* image, int* width, int* height); -IMAQ_FUNC int IMAQ_STDCALL imaqGetImageType(const Image* image, ImageType* type); -IMAQ_FUNC int IMAQ_STDCALL imaqGetMaskOffset(const Image* image, Point* offset); -IMAQ_FUNC void* IMAQ_STDCALL imaqGetPixelAddress(const Image* image, Point pixel); -IMAQ_FUNC int IMAQ_STDCALL imaqGetVisionInfoTypes(const Image* image, unsigned int* present); -IMAQ_FUNC int IMAQ_STDCALL imaqIsImageEmpty(const Image* image, int* empty); -IMAQ_FUNC void* IMAQ_STDCALL imaqReadCustomData(const Image* image, const char* key, unsigned int* size); -IMAQ_FUNC int IMAQ_STDCALL imaqRemoveCustomData(Image* image, const char* key); -IMAQ_FUNC int IMAQ_STDCALL imaqRemoveVisionInfo2(const Image* image, unsigned int info); -IMAQ_FUNC int IMAQ_STDCALL imaqSetBitDepth(Image* image, unsigned int bitDepth); -IMAQ_FUNC int IMAQ_STDCALL imaqSetImageSize(Image* image, int width, int height); -IMAQ_FUNC int IMAQ_STDCALL imaqSetMaskOffset(Image* image, Point offset); -IMAQ_FUNC int IMAQ_STDCALL imaqWriteCustomData(Image* image, const char* key, const void* data, unsigned int size); +IMAQ_FUNC char** IMAQ_STDCALL +imaqEnumerateCustomKeys(const Image* image, unsigned int* size); +IMAQ_FUNC int IMAQ_STDCALL +imaqGetBitDepth(const Image* image, unsigned int* bitDepth); +IMAQ_FUNC int IMAQ_STDCALL +imaqGetBytesPerPixel(const Image* image, int* byteCount); +IMAQ_FUNC int IMAQ_STDCALL +imaqGetImageInfo(const Image* image, ImageInfo* info); +IMAQ_FUNC int IMAQ_STDCALL +imaqGetImageSize(const Image* image, int* width, int* height); +IMAQ_FUNC int IMAQ_STDCALL +imaqGetImageType(const Image* image, ImageType* type); +IMAQ_FUNC int IMAQ_STDCALL imaqGetMaskOffset(const Image* image, Point* offset); +IMAQ_FUNC void* IMAQ_STDCALL +imaqGetPixelAddress(const Image* image, Point pixel); +IMAQ_FUNC int IMAQ_STDCALL +imaqGetVisionInfoTypes(const Image* image, unsigned int* present); +IMAQ_FUNC int IMAQ_STDCALL imaqIsImageEmpty(const Image* image, int* empty); +IMAQ_FUNC void* IMAQ_STDCALL +imaqReadCustomData(const Image* image, const char* key, unsigned int* size); +IMAQ_FUNC int IMAQ_STDCALL imaqRemoveCustomData(Image* image, const char* key); +IMAQ_FUNC int IMAQ_STDCALL +imaqRemoveVisionInfo2(const Image* image, unsigned int info); +IMAQ_FUNC int IMAQ_STDCALL imaqSetBitDepth(Image* image, unsigned int bitDepth); +IMAQ_FUNC int IMAQ_STDCALL +imaqSetImageSize(Image* image, int width, int height); +IMAQ_FUNC int IMAQ_STDCALL imaqSetMaskOffset(Image* image, Point offset); +IMAQ_FUNC int IMAQ_STDCALL imaqWriteCustomData(Image* image, const char* key, + const void* data, + unsigned int size); //============================================================================ // Display functions //============================================================================ -IMAQ_FUNC int IMAQ_STDCALL imaqAreToolsContextSensitive(int* sensitive); -IMAQ_FUNC int IMAQ_STDCALL imaqCloseWindow(int windowNumber); -IMAQ_FUNC int IMAQ_STDCALL imaqDisplayImage(const Image* image, int windowNumber, int resize); -IMAQ_FUNC int IMAQ_STDCALL imaqGetLastKey(char* keyPressed, int* windowNumber, int* modifiers); +IMAQ_FUNC int IMAQ_STDCALL imaqAreToolsContextSensitive(int* sensitive); +IMAQ_FUNC int IMAQ_STDCALL imaqCloseWindow(int windowNumber); +IMAQ_FUNC int IMAQ_STDCALL +imaqDisplayImage(const Image* image, int windowNumber, int resize); +IMAQ_FUNC int IMAQ_STDCALL +imaqGetLastKey(char* keyPressed, int* windowNumber, int* modifiers); IMAQ_FUNC void* IMAQ_STDCALL imaqGetSystemWindowHandle(int windowNumber); -IMAQ_FUNC int IMAQ_STDCALL imaqGetWindowCenterPos(int windowNumber, Point* centerPosition); -IMAQ_FUNC int IMAQ_STDCALL imaqSetToolContextSensitivity(int sensitive); -IMAQ_FUNC int IMAQ_STDCALL imaqShowWindow(int windowNumber, int visible); +IMAQ_FUNC int IMAQ_STDCALL +imaqGetWindowCenterPos(int windowNumber, Point* centerPosition); +IMAQ_FUNC int IMAQ_STDCALL imaqSetToolContextSensitivity(int sensitive); +IMAQ_FUNC int IMAQ_STDCALL imaqShowWindow(int windowNumber, int visible); //============================================================================ // Image Manipulation functions //============================================================================ -IMAQ_FUNC int IMAQ_STDCALL imaqCast(Image* dest, const Image* source, ImageType type, const float* lookup, int shift); -IMAQ_FUNC int IMAQ_STDCALL imaqCopyRect(Image* dest, const Image* source, Rect rect, Point destLoc); -IMAQ_FUNC int IMAQ_STDCALL imaqDuplicate(Image* dest, const Image* source); -IMAQ_FUNC void* IMAQ_STDCALL imaqFlatten(const Image* image, FlattenType type, CompressionType compression, int quality, unsigned int* size); -IMAQ_FUNC int IMAQ_STDCALL imaqFlip(Image* dest, const Image* source, FlipAxis axis); -IMAQ_FUNC int IMAQ_STDCALL imaqMask(Image* dest, const Image* source, const Image* mask); -IMAQ_FUNC int IMAQ_STDCALL imaqResample(Image* dest, const Image* source, int newWidth, int newHeight, InterpolationMethod method, Rect rect); -IMAQ_FUNC int IMAQ_STDCALL imaqRotate2(Image* dest, const Image* source, float angle, PixelValue fill, InterpolationMethod method, int maintainSize); -IMAQ_FUNC int IMAQ_STDCALL imaqScale(Image* dest, const Image* source, int xScale, int yScale, ScalingMode scaleMode, Rect rect); -IMAQ_FUNC int IMAQ_STDCALL imaqShift(Image* dest, const Image* source, int shiftX, int shiftY, PixelValue fill); -IMAQ_FUNC int IMAQ_STDCALL imaqTranspose(Image* dest, const Image* source); -IMAQ_FUNC int IMAQ_STDCALL imaqUnflatten(Image* image, const void* data, unsigned int size); -IMAQ_FUNC int IMAQ_STDCALL imaqUnwrapImage(Image* dest, const Image* source, Annulus annulus, RectOrientation orientation, InterpolationMethod method); -IMAQ_FUNC int IMAQ_STDCALL imaqView3D(Image* dest, Image* source, const View3DOptions* options); +IMAQ_FUNC int IMAQ_STDCALL imaqCast(Image* dest, const Image* source, + ImageType type, const float* lookup, + int shift); +IMAQ_FUNC int IMAQ_STDCALL +imaqCopyRect(Image* dest, const Image* source, Rect rect, Point destLoc); +IMAQ_FUNC int IMAQ_STDCALL imaqDuplicate(Image* dest, const Image* source); +IMAQ_FUNC void* IMAQ_STDCALL imaqFlatten(const Image* image, FlattenType type, + CompressionType compression, + int quality, unsigned int* size); +IMAQ_FUNC int IMAQ_STDCALL +imaqFlip(Image* dest, const Image* source, FlipAxis axis); +IMAQ_FUNC int IMAQ_STDCALL +imaqMask(Image* dest, const Image* source, const Image* mask); +IMAQ_FUNC int IMAQ_STDCALL imaqResample(Image* dest, const Image* source, + int newWidth, int newHeight, + InterpolationMethod method, Rect rect); +IMAQ_FUNC int IMAQ_STDCALL +imaqRotate2(Image* dest, const Image* source, float angle, PixelValue fill, + InterpolationMethod method, int maintainSize); +IMAQ_FUNC int IMAQ_STDCALL imaqScale(Image* dest, const Image* source, + int xScale, int yScale, + ScalingMode scaleMode, Rect rect); +IMAQ_FUNC int IMAQ_STDCALL imaqShift(Image* dest, const Image* source, + int shiftX, int shiftY, PixelValue fill); +IMAQ_FUNC int IMAQ_STDCALL imaqTranspose(Image* dest, const Image* source); +IMAQ_FUNC int IMAQ_STDCALL +imaqUnflatten(Image* image, const void* data, unsigned int size); +IMAQ_FUNC int IMAQ_STDCALL +imaqUnwrapImage(Image* dest, const Image* source, Annulus annulus, + RectOrientation orientation, InterpolationMethod method); +IMAQ_FUNC int IMAQ_STDCALL +imaqView3D(Image* dest, Image* source, const View3DOptions* options); //============================================================================ // File I/O functions //============================================================================ -IMAQ_FUNC int IMAQ_STDCALL imaqCloseAVI(AVISession session); -IMAQ_FUNC AVISession IMAQ_STDCALL imaqCreateAVI(const char* fileName, const char* compressionFilter, int quality, unsigned int framesPerSecond, unsigned int maxDataSize); -IMAQ_FUNC int IMAQ_STDCALL imaqGetAVIInfo(AVISession session, AVIInfo* info); -IMAQ_FUNC int IMAQ_STDCALL imaqGetFileInfo(const char* fileName, CalibrationUnit* calibrationUnit, float* calibrationX, float* calibrationY, int* width, int* height, ImageType* imageType); +IMAQ_FUNC int IMAQ_STDCALL imaqCloseAVI(AVISession session); +IMAQ_FUNC AVISession IMAQ_STDCALL +imaqCreateAVI(const char* fileName, const char* compressionFilter, int quality, + unsigned int framesPerSecond, unsigned int maxDataSize); +IMAQ_FUNC int IMAQ_STDCALL imaqGetAVIInfo(AVISession session, AVIInfo* info); +IMAQ_FUNC int IMAQ_STDCALL +imaqGetFileInfo(const char* fileName, CalibrationUnit* calibrationUnit, + float* calibrationX, float* calibrationY, int* width, + int* height, ImageType* imageType); IMAQ_FUNC FilterName* IMAQ_STDCALL imaqGetFilterNames(int* numFilters); -IMAQ_FUNC char** IMAQ_STDCALL imaqLoadImagePopup(const char* defaultDirectory, const char* defaultFileSpec, const char* fileTypeList, const char* title, int allowMultiplePaths, ButtonLabel buttonLabel, int restrictDirectory, int restrictExtension, int allowCancel, int allowMakeDirectory, int* cancelled, int* numPaths); -IMAQ_FUNC AVISession IMAQ_STDCALL imaqOpenAVI(const char* fileName); -IMAQ_FUNC int IMAQ_STDCALL imaqReadAVIFrame(Image* image, AVISession session, unsigned int frameNum, void* data, unsigned int* dataSize); -IMAQ_FUNC int IMAQ_STDCALL imaqReadFile(Image* image, const char* fileName, RGBValue* colorTable, int* numColors); -IMAQ_FUNC int IMAQ_STDCALL imaqReadVisionFile(Image* image, const char* fileName, RGBValue* colorTable, int* numColors); -IMAQ_FUNC int IMAQ_STDCALL imaqWriteAVIFrame(Image* image, AVISession session, const void* data, unsigned int dataLength); -IMAQ_FUNC int IMAQ_STDCALL imaqWriteBMPFile(const Image* image, const char* fileName, int compress, const RGBValue* colorTable); -IMAQ_FUNC int IMAQ_STDCALL imaqWriteFile(const Image* image, const char* fileName, const RGBValue* colorTable); -IMAQ_FUNC int IMAQ_STDCALL imaqWriteJPEGFile(const Image* image, const char* fileName, unsigned int quality, void* colorTable); -IMAQ_FUNC int IMAQ_STDCALL imaqWriteJPEG2000File(const Image* image, const char* fileName, int lossless, float compressionRatio, const JPEG2000FileAdvancedOptions* advancedOptions, const RGBValue* colorTable); -IMAQ_FUNC int IMAQ_STDCALL imaqWritePNGFile2(const Image* image, const char* fileName, unsigned int compressionSpeed, const RGBValue* colorTable, int useBitDepth); -IMAQ_FUNC int IMAQ_STDCALL imaqWriteTIFFFile(const Image* image, const char* fileName, const TIFFFileOptions* options, const RGBValue* colorTable); -IMAQ_FUNC int IMAQ_STDCALL imaqWriteVisionFile(const Image* image, const char* fileName, const RGBValue* colorTable); - +IMAQ_FUNC char** IMAQ_STDCALL +imaqLoadImagePopup(const char* defaultDirectory, const char* defaultFileSpec, + const char* fileTypeList, const char* title, + int allowMultiplePaths, ButtonLabel buttonLabel, + int restrictDirectory, int restrictExtension, + int allowCancel, int allowMakeDirectory, int* cancelled, + int* numPaths); +IMAQ_FUNC AVISession IMAQ_STDCALL imaqOpenAVI(const char* fileName); +IMAQ_FUNC int IMAQ_STDCALL imaqReadAVIFrame(Image* image, AVISession session, + unsigned int frameNum, void* data, + unsigned int* dataSize); +IMAQ_FUNC int IMAQ_STDCALL imaqReadFile(Image* image, const char* fileName, + RGBValue* colorTable, int* numColors); +IMAQ_FUNC int IMAQ_STDCALL +imaqReadVisionFile(Image* image, const char* fileName, RGBValue* colorTable, + int* numColors); +IMAQ_FUNC int IMAQ_STDCALL imaqWriteAVIFrame(Image* image, AVISession session, + const void* data, + unsigned int dataLength); +IMAQ_FUNC int IMAQ_STDCALL imaqWriteBMPFile(const Image* image, + const char* fileName, int compress, + const RGBValue* colorTable); +IMAQ_FUNC int IMAQ_STDCALL imaqWriteFile(const Image* image, + const char* fileName, + const RGBValue* colorTable); +IMAQ_FUNC int IMAQ_STDCALL +imaqWriteJPEGFile(const Image* image, const char* fileName, + unsigned int quality, void* colorTable); +IMAQ_FUNC int IMAQ_STDCALL +imaqWriteJPEG2000File(const Image* image, const char* fileName, int lossless, + float compressionRatio, + const JPEG2000FileAdvancedOptions* advancedOptions, + const RGBValue* colorTable); +IMAQ_FUNC int IMAQ_STDCALL +imaqWritePNGFile2(const Image* image, const char* fileName, + unsigned int compressionSpeed, const RGBValue* colorTable, + int useBitDepth); +IMAQ_FUNC int IMAQ_STDCALL +imaqWriteTIFFFile(const Image* image, const char* fileName, + const TIFFFileOptions* options, const RGBValue* colorTable); +IMAQ_FUNC int IMAQ_STDCALL imaqWriteVisionFile(const Image* image, + const char* fileName, + const RGBValue* colorTable); //============================================================================ // Analytic Geometry functions //============================================================================ -IMAQ_FUNC int IMAQ_STDCALL imaqBuildCoordinateSystem(const Point* points, ReferenceMode mode, AxisOrientation orientation, CoordinateSystem* system); -IMAQ_FUNC BestCircle2* IMAQ_STDCALL imaqFitCircle2(const PointFloat* points, int numPoints, const FitCircleOptions* options); -IMAQ_FUNC BestEllipse2* IMAQ_STDCALL imaqFitEllipse2(const PointFloat* points, int numPoints, const FitEllipseOptions* options); -IMAQ_FUNC BestLine* IMAQ_STDCALL imaqFitLine(const PointFloat* points, int numPoints, const FitLineOptions* options); -IMAQ_FUNC int IMAQ_STDCALL imaqGetAngle(PointFloat start1, PointFloat end1, PointFloat start2, PointFloat end2, float* angle); -IMAQ_FUNC int IMAQ_STDCALL imaqGetBisectingLine(PointFloat start1, PointFloat end1, PointFloat start2, PointFloat end2, PointFloat* bisectStart, PointFloat* bisectEnd); -IMAQ_FUNC int IMAQ_STDCALL imaqGetDistance(PointFloat point1, PointFloat point2, float* distance); -IMAQ_FUNC int IMAQ_STDCALL imaqGetIntersection(PointFloat start1, PointFloat end1, PointFloat start2, PointFloat end2, PointFloat* intersection); -IMAQ_FUNC int IMAQ_STDCALL imaqGetMidLine(PointFloat refLineStart, PointFloat refLineEnd, PointFloat point, PointFloat* midLineStart, PointFloat* midLineEnd); -IMAQ_FUNC int IMAQ_STDCALL imaqGetPerpendicularLine(PointFloat refLineStart, PointFloat refLineEnd, PointFloat point, PointFloat* perpLineStart, PointFloat* perpLineEnd, double* distance); -IMAQ_FUNC SegmentInfo* IMAQ_STDCALL imaqGetPointsOnContour(const Image* image, int* numSegments); -IMAQ_FUNC Point* IMAQ_STDCALL imaqGetPointsOnLine(Point start, Point end, int* numPoints); -IMAQ_FUNC int IMAQ_STDCALL imaqGetPolygonArea(const PointFloat* points, int numPoints, float* area); -IMAQ_FUNC float* IMAQ_STDCALL imaqInterpolatePoints(const Image* image, const Point* points, int numPoints, InterpolationMethod method, int subpixel, int* interpCount); +IMAQ_FUNC int IMAQ_STDCALL +imaqBuildCoordinateSystem(const Point* points, ReferenceMode mode, + AxisOrientation orientation, + CoordinateSystem* system); +IMAQ_FUNC BestCircle2* IMAQ_STDCALL +imaqFitCircle2(const PointFloat* points, int numPoints, + const FitCircleOptions* options); +IMAQ_FUNC BestEllipse2* IMAQ_STDCALL +imaqFitEllipse2(const PointFloat* points, int numPoints, + const FitEllipseOptions* options); +IMAQ_FUNC BestLine* IMAQ_STDCALL imaqFitLine(const PointFloat* points, + int numPoints, + const FitLineOptions* options); +IMAQ_FUNC int IMAQ_STDCALL imaqGetAngle(PointFloat start1, PointFloat end1, + PointFloat start2, PointFloat end2, + float* angle); +IMAQ_FUNC int IMAQ_STDCALL +imaqGetBisectingLine(PointFloat start1, PointFloat end1, PointFloat start2, + PointFloat end2, PointFloat* bisectStart, + PointFloat* bisectEnd); +IMAQ_FUNC int IMAQ_STDCALL +imaqGetDistance(PointFloat point1, PointFloat point2, float* distance); +IMAQ_FUNC int IMAQ_STDCALL +imaqGetIntersection(PointFloat start1, PointFloat end1, PointFloat start2, + PointFloat end2, PointFloat* intersection); +IMAQ_FUNC int IMAQ_STDCALL +imaqGetMidLine(PointFloat refLineStart, PointFloat refLineEnd, PointFloat point, + PointFloat* midLineStart, PointFloat* midLineEnd); +IMAQ_FUNC int IMAQ_STDCALL +imaqGetPerpendicularLine(PointFloat refLineStart, PointFloat refLineEnd, + PointFloat point, PointFloat* perpLineStart, + PointFloat* perpLineEnd, double* distance); +IMAQ_FUNC SegmentInfo* IMAQ_STDCALL +imaqGetPointsOnContour(const Image* image, int* numSegments); +IMAQ_FUNC Point* IMAQ_STDCALL +imaqGetPointsOnLine(Point start, Point end, int* numPoints); +IMAQ_FUNC int IMAQ_STDCALL +imaqGetPolygonArea(const PointFloat* points, int numPoints, float* area); +IMAQ_FUNC float* IMAQ_STDCALL +imaqInterpolatePoints(const Image* image, const Point* points, int numPoints, + InterpolationMethod method, int subpixel, + int* interpCount); //============================================================================ // Clipboard functions //============================================================================ IMAQ_FUNC int IMAQ_STDCALL imaqClipboardToImage(Image* dest, RGBValue* palette); -IMAQ_FUNC int IMAQ_STDCALL imaqImageToClipboard(const Image* image, const RGBValue* palette); +IMAQ_FUNC int IMAQ_STDCALL +imaqImageToClipboard(const Image* image, const RGBValue* palette); //============================================================================ // Border functions //============================================================================ IMAQ_FUNC int IMAQ_STDCALL imaqFillBorder(Image* image, BorderMethod method); -IMAQ_FUNC int IMAQ_STDCALL imaqGetBorderSize(const Image* image, int* borderSize); +IMAQ_FUNC int IMAQ_STDCALL +imaqGetBorderSize(const Image* image, int* borderSize); IMAQ_FUNC int IMAQ_STDCALL imaqSetBorderSize(Image* image, int size); //============================================================================ // Image Management functions //============================================================================ -IMAQ_FUNC int IMAQ_STDCALL imaqArrayToImage(Image* image, const void* array, int numCols, int numRows); +IMAQ_FUNC int IMAQ_STDCALL +imaqArrayToImage(Image* image, const void* array, int numCols, int numRows); IMAQ_FUNC Image* IMAQ_STDCALL imaqCreateImage(ImageType type, int borderSize); -IMAQ_FUNC void* IMAQ_STDCALL imaqImageToArray(const Image* image, Rect rect, int* columns, int* rows); +IMAQ_FUNC void* IMAQ_STDCALL +imaqImageToArray(const Image* image, Rect rect, int* columns, int* rows); //============================================================================ // Color Processing functions //============================================================================ -IMAQ_FUNC Color2 IMAQ_STDCALL imaqChangeColorSpace2(const Color2* sourceColor, ColorMode sourceSpace, ColorMode destSpace, double offset, const CIEXYZValue* whiteReference); -IMAQ_FUNC int IMAQ_STDCALL imaqColorBCGTransform(Image* dest, const Image* source, const BCGOptions* redOptions, const BCGOptions* greenOptions, const BCGOptions* blueOptions, const Image* mask); -IMAQ_FUNC int IMAQ_STDCALL imaqColorEqualize(Image* dest, const Image* source, int colorEqualization); -IMAQ_FUNC ColorHistogramReport* IMAQ_STDCALL imaqColorHistogram2(Image* image, int numClasses, ColorMode mode, const CIEXYZValue* whiteReference, Image* mask); -IMAQ_FUNC int IMAQ_STDCALL imaqColorLookup(Image* dest, const Image* source, ColorMode mode, const Image* mask, const short* plane1, const short* plane2, const short* plane3); -IMAQ_FUNC int IMAQ_STDCALL imaqColorThreshold(Image* dest, const Image* source, int replaceValue, ColorMode mode, const Range* plane1Range, const Range* plane2Range, const Range* plane3Range); -IMAQ_FUNC SupervisedColorSegmentationReport* IMAQ_STDCALL imaqSupervisedColorSegmentation(ClassifierSession* session, Image* labelImage, const Image* srcImage, const ROI* roi, const ROILabel* labelIn, unsigned int numLabelIn, int maxDistance, int minIdentificationScore, const ColorSegmenationOptions* segmentOptions); -IMAQ_FUNC int IMAQ_STDCALL imaqGetColorSegmentationMaxDistance(ClassifierSession* session, const ColorSegmenationOptions* segmentOptions, SegmentationDistanceLevel distLevel, int* maxDistance); +IMAQ_FUNC Color2 IMAQ_STDCALL +imaqChangeColorSpace2(const Color2* sourceColor, ColorMode sourceSpace, + ColorMode destSpace, double offset, + const CIEXYZValue* whiteReference); +IMAQ_FUNC int IMAQ_STDCALL +imaqColorBCGTransform(Image* dest, const Image* source, + const BCGOptions* redOptions, + const BCGOptions* greenOptions, + const BCGOptions* blueOptions, const Image* mask); +IMAQ_FUNC int IMAQ_STDCALL +imaqColorEqualize(Image* dest, const Image* source, int colorEqualization); +IMAQ_FUNC ColorHistogramReport* IMAQ_STDCALL +imaqColorHistogram2(Image* image, int numClasses, ColorMode mode, + const CIEXYZValue* whiteReference, Image* mask); +IMAQ_FUNC int IMAQ_STDCALL +imaqColorLookup(Image* dest, const Image* source, ColorMode mode, + const Image* mask, const short* plane1, const short* plane2, + const short* plane3); +IMAQ_FUNC int IMAQ_STDCALL +imaqColorThreshold(Image* dest, const Image* source, int replaceValue, + ColorMode mode, const Range* plane1Range, + const Range* plane2Range, const Range* plane3Range); +IMAQ_FUNC SupervisedColorSegmentationReport* IMAQ_STDCALL +imaqSupervisedColorSegmentation(ClassifierSession* session, Image* labelImage, + const Image* srcImage, const ROI* roi, + const ROILabel* labelIn, + unsigned int numLabelIn, int maxDistance, + int minIdentificationScore, + const ColorSegmenationOptions* segmentOptions); +IMAQ_FUNC int IMAQ_STDCALL imaqGetColorSegmentationMaxDistance( + ClassifierSession* session, const ColorSegmenationOptions* segmentOptions, + SegmentationDistanceLevel distLevel, int* maxDistance); //============================================================================ // Transform functions //============================================================================ -IMAQ_FUNC int IMAQ_STDCALL imaqBCGTransform(Image* dest, const Image* source, const BCGOptions* options, const Image* mask); -IMAQ_FUNC int IMAQ_STDCALL imaqEqualize(Image* dest, const Image* source, float min, float max, const Image* mask); -IMAQ_FUNC int IMAQ_STDCALL imaqInverse(Image* dest, const Image* source, const Image* mask); -IMAQ_FUNC int IMAQ_STDCALL imaqMathTransform(Image* dest, const Image* source, MathTransformMethod method, float rangeMin, float rangeMax, float power, const Image* mask); -IMAQ_FUNC int IMAQ_STDCALL imaqWatershedTransform(Image* dest, const Image* source, int connectivity8, int* zoneCount); -IMAQ_FUNC int IMAQ_STDCALL imaqLookup2(Image* dest, const Image* source, const int* table, const Image* mask); - +IMAQ_FUNC int IMAQ_STDCALL imaqBCGTransform(Image* dest, const Image* source, + const BCGOptions* options, + const Image* mask); +IMAQ_FUNC int IMAQ_STDCALL imaqEqualize(Image* dest, const Image* source, + float min, float max, + const Image* mask); +IMAQ_FUNC int IMAQ_STDCALL +imaqInverse(Image* dest, const Image* source, const Image* mask); +IMAQ_FUNC int IMAQ_STDCALL imaqMathTransform(Image* dest, const Image* source, + MathTransformMethod method, + float rangeMin, float rangeMax, + float power, const Image* mask); +IMAQ_FUNC int IMAQ_STDCALL +imaqWatershedTransform(Image* dest, const Image* source, int connectivity8, + int* zoneCount); +IMAQ_FUNC int IMAQ_STDCALL imaqLookup2(Image* dest, const Image* source, + const int* table, const Image* mask); //============================================================================ // Window Management functions //============================================================================ -IMAQ_FUNC int IMAQ_STDCALL imaqAreScrollbarsVisible(int windowNumber, int* visible); -IMAQ_FUNC int IMAQ_STDCALL imaqBringWindowToTop(int windowNumber); -IMAQ_FUNC int IMAQ_STDCALL imaqGetMousePos(Point* position, int* windowNumber); -IMAQ_FUNC int IMAQ_STDCALL imaqGetWindowBackground(int windowNumber, WindowBackgroundFillStyle* fillStyle, WindowBackgroundHatchStyle* hatchStyle, RGBValue* fillColor, RGBValue* backgroundColor); -IMAQ_FUNC int IMAQ_STDCALL imaqGetWindowDisplayMapping(int windowNum, DisplayMapping* mapping); -IMAQ_FUNC int IMAQ_STDCALL imaqGetWindowGrid(int windowNumber, int* xResolution, int* yResolution); -IMAQ_FUNC int IMAQ_STDCALL imaqGetWindowHandle(int* handle); -IMAQ_FUNC int IMAQ_STDCALL imaqGetWindowPos(int windowNumber, Point* position); -IMAQ_FUNC int IMAQ_STDCALL imaqGetWindowSize(int windowNumber, int* width, int* height); +IMAQ_FUNC int IMAQ_STDCALL +imaqAreScrollbarsVisible(int windowNumber, int* visible); +IMAQ_FUNC int IMAQ_STDCALL imaqBringWindowToTop(int windowNumber); +IMAQ_FUNC int IMAQ_STDCALL imaqGetMousePos(Point* position, int* windowNumber); +IMAQ_FUNC int IMAQ_STDCALL +imaqGetWindowBackground(int windowNumber, WindowBackgroundFillStyle* fillStyle, + WindowBackgroundHatchStyle* hatchStyle, + RGBValue* fillColor, RGBValue* backgroundColor); +IMAQ_FUNC int IMAQ_STDCALL +imaqGetWindowDisplayMapping(int windowNum, DisplayMapping* mapping); +IMAQ_FUNC int IMAQ_STDCALL +imaqGetWindowGrid(int windowNumber, int* xResolution, int* yResolution); +IMAQ_FUNC int IMAQ_STDCALL imaqGetWindowHandle(int* handle); +IMAQ_FUNC int IMAQ_STDCALL imaqGetWindowPos(int windowNumber, Point* position); +IMAQ_FUNC int IMAQ_STDCALL +imaqGetWindowSize(int windowNumber, int* width, int* height); IMAQ_FUNC char* IMAQ_STDCALL imaqGetWindowTitle(int windowNumber); -IMAQ_FUNC int IMAQ_STDCALL imaqGetWindowZoom2(int windowNumber, float* xZoom, float* yZoom); -IMAQ_FUNC int IMAQ_STDCALL imaqIsWindowNonTearing(int windowNumber, int* nonTearing); -IMAQ_FUNC int IMAQ_STDCALL imaqIsWindowVisible(int windowNumber, int* visible); -IMAQ_FUNC int IMAQ_STDCALL imaqMoveWindow(int windowNumber, Point position); -IMAQ_FUNC int IMAQ_STDCALL imaqSetupWindow(int windowNumber, int configuration); -IMAQ_FUNC int IMAQ_STDCALL imaqSetWindowBackground(int windowNumber, WindowBackgroundFillStyle fillStyle, WindowBackgroundHatchStyle hatchStyle, const RGBValue* fillColor, const RGBValue* backgroundColor); -IMAQ_FUNC int IMAQ_STDCALL imaqSetWindowDisplayMapping(int windowNumber, const DisplayMapping* mapping); -IMAQ_FUNC int IMAQ_STDCALL imaqSetWindowGrid(int windowNumber, int xResolution, int yResolution); -IMAQ_FUNC int IMAQ_STDCALL imaqSetWindowMaxContourCount(int windowNumber, unsigned int maxContourCount); -IMAQ_FUNC int IMAQ_STDCALL imaqSetWindowNonTearing(int windowNumber, int nonTearing); -IMAQ_FUNC int IMAQ_STDCALL imaqSetWindowPalette(int windowNumber, PaletteType type, const RGBValue* palette, int numColors); -IMAQ_FUNC int IMAQ_STDCALL imaqSetWindowSize(int windowNumber, int width, int height); -IMAQ_FUNC int IMAQ_STDCALL imaqSetWindowThreadPolicy(WindowThreadPolicy policy); -IMAQ_FUNC int IMAQ_STDCALL imaqSetWindowTitle(int windowNumber, const char* title); -IMAQ_FUNC int IMAQ_STDCALL imaqSetWindowZoomToFit(int windowNumber, int zoomToFit); -IMAQ_FUNC int IMAQ_STDCALL imaqShowScrollbars(int windowNumber, int visible); -IMAQ_FUNC int IMAQ_STDCALL imaqZoomWindow2(int windowNumber, float xZoom, float yZoom, Point center); +IMAQ_FUNC int IMAQ_STDCALL +imaqGetWindowZoom2(int windowNumber, float* xZoom, float* yZoom); +IMAQ_FUNC int IMAQ_STDCALL +imaqIsWindowNonTearing(int windowNumber, int* nonTearing); +IMAQ_FUNC int IMAQ_STDCALL imaqIsWindowVisible(int windowNumber, int* visible); +IMAQ_FUNC int IMAQ_STDCALL imaqMoveWindow(int windowNumber, Point position); +IMAQ_FUNC int IMAQ_STDCALL imaqSetupWindow(int windowNumber, int configuration); +IMAQ_FUNC int IMAQ_STDCALL +imaqSetWindowBackground(int windowNumber, WindowBackgroundFillStyle fillStyle, + WindowBackgroundHatchStyle hatchStyle, + const RGBValue* fillColor, + const RGBValue* backgroundColor); +IMAQ_FUNC int IMAQ_STDCALL +imaqSetWindowDisplayMapping(int windowNumber, const DisplayMapping* mapping); +IMAQ_FUNC int IMAQ_STDCALL +imaqSetWindowGrid(int windowNumber, int xResolution, int yResolution); +IMAQ_FUNC int IMAQ_STDCALL +imaqSetWindowMaxContourCount(int windowNumber, unsigned int maxContourCount); +IMAQ_FUNC int IMAQ_STDCALL +imaqSetWindowNonTearing(int windowNumber, int nonTearing); +IMAQ_FUNC int IMAQ_STDCALL +imaqSetWindowPalette(int windowNumber, PaletteType type, + const RGBValue* palette, int numColors); +IMAQ_FUNC int IMAQ_STDCALL +imaqSetWindowSize(int windowNumber, int width, int height); +IMAQ_FUNC int IMAQ_STDCALL imaqSetWindowThreadPolicy(WindowThreadPolicy policy); +IMAQ_FUNC int IMAQ_STDCALL +imaqSetWindowTitle(int windowNumber, const char* title); +IMAQ_FUNC int IMAQ_STDCALL +imaqSetWindowZoomToFit(int windowNumber, int zoomToFit); +IMAQ_FUNC int IMAQ_STDCALL imaqShowScrollbars(int windowNumber, int visible); +IMAQ_FUNC int IMAQ_STDCALL +imaqZoomWindow2(int windowNumber, float xZoom, float yZoom, Point center); //============================================================================ // Utilities functions //============================================================================ -IMAQ_FUNC const float* IMAQ_STDCALL imaqGetKernel(KernelFamily family, int size, int number); -IMAQ_FUNC Annulus IMAQ_STDCALL imaqMakeAnnulus(Point center, int innerRadius, int outerRadius, double startAngle, double endAngle); -IMAQ_FUNC Point IMAQ_STDCALL imaqMakePoint(int xCoordinate, int yCoordinate); -IMAQ_FUNC PointFloat IMAQ_STDCALL imaqMakePointFloat(float xCoordinate, float yCoordinate); -IMAQ_FUNC Rect IMAQ_STDCALL imaqMakeRect(int top, int left, int height, int width); -IMAQ_FUNC Rect IMAQ_STDCALL imaqMakeRectFromRotatedRect(RotatedRect rotatedRect); -IMAQ_FUNC RotatedRect IMAQ_STDCALL imaqMakeRotatedRect(int top, int left, int height, int width, double angle); -IMAQ_FUNC RotatedRect IMAQ_STDCALL imaqMakeRotatedRectFromRect(Rect rect); -IMAQ_FUNC int IMAQ_STDCALL imaqMulticoreOptions(MulticoreOperation operation, unsigned int* customNumCores); +IMAQ_FUNC const float* IMAQ_STDCALL +imaqGetKernel(KernelFamily family, int size, int number); +IMAQ_FUNC Annulus IMAQ_STDCALL +imaqMakeAnnulus(Point center, int innerRadius, int outerRadius, + double startAngle, double endAngle); +IMAQ_FUNC Point IMAQ_STDCALL imaqMakePoint(int xCoordinate, int yCoordinate); +IMAQ_FUNC PointFloat IMAQ_STDCALL +imaqMakePointFloat(float xCoordinate, float yCoordinate); +IMAQ_FUNC Rect IMAQ_STDCALL +imaqMakeRect(int top, int left, int height, int width); +IMAQ_FUNC Rect IMAQ_STDCALL +imaqMakeRectFromRotatedRect(RotatedRect rotatedRect); +IMAQ_FUNC RotatedRect IMAQ_STDCALL +imaqMakeRotatedRect(int top, int left, int height, int width, double angle); +IMAQ_FUNC RotatedRect IMAQ_STDCALL imaqMakeRotatedRectFromRect(Rect rect); +IMAQ_FUNC int IMAQ_STDCALL imaqMulticoreOptions(MulticoreOperation operation, + unsigned int* customNumCores); //============================================================================ // Tool Window functions //============================================================================ -IMAQ_FUNC int IMAQ_STDCALL imaqCloseToolWindow(void); -IMAQ_FUNC int IMAQ_STDCALL imaqGetCurrentTool(Tool* currentTool); -IMAQ_FUNC int IMAQ_STDCALL imaqGetLastEvent(WindowEventType* type, int* windowNumber, Tool* tool, Rect* rect); +IMAQ_FUNC int IMAQ_STDCALL imaqCloseToolWindow(void); +IMAQ_FUNC int IMAQ_STDCALL imaqGetCurrentTool(Tool* currentTool); +IMAQ_FUNC int IMAQ_STDCALL imaqGetLastEvent(WindowEventType* type, + int* windowNumber, Tool* tool, + Rect* rect); IMAQ_FUNC void* IMAQ_STDCALL imaqGetToolWindowHandle(void); -IMAQ_FUNC int IMAQ_STDCALL imaqGetToolWindowPos(Point* position); -IMAQ_FUNC int IMAQ_STDCALL imaqIsToolWindowVisible(int* visible); -IMAQ_FUNC int IMAQ_STDCALL imaqMoveToolWindow(Point position); -IMAQ_FUNC int IMAQ_STDCALL imaqSetCurrentTool(Tool currentTool); +IMAQ_FUNC int IMAQ_STDCALL imaqGetToolWindowPos(Point* position); +IMAQ_FUNC int IMAQ_STDCALL imaqIsToolWindowVisible(int* visible); +IMAQ_FUNC int IMAQ_STDCALL imaqMoveToolWindow(Point position); +IMAQ_FUNC int IMAQ_STDCALL imaqSetCurrentTool(Tool currentTool); #ifndef __GNUC__ -IMAQ_FUNC int IMAQ_STDCALL imaqSetEventCallback(EventCallback callback, int synchronous); +IMAQ_FUNC int IMAQ_STDCALL +imaqSetEventCallback(EventCallback callback, int synchronous); #endif -IMAQ_FUNC int IMAQ_STDCALL imaqSetToolColor(const RGBValue* color); -IMAQ_FUNC int IMAQ_STDCALL imaqSetupToolWindow(int showCoordinates, int maxIconsPerLine, const ToolWindowOptions* options); -IMAQ_FUNC int IMAQ_STDCALL imaqShowToolWindow(int visible); +IMAQ_FUNC int IMAQ_STDCALL imaqSetToolColor(const RGBValue* color); +IMAQ_FUNC int IMAQ_STDCALL +imaqSetupToolWindow(int showCoordinates, int maxIconsPerLine, + const ToolWindowOptions* options); +IMAQ_FUNC int IMAQ_STDCALL imaqShowToolWindow(int visible); //============================================================================ // Meter functions //============================================================================ -IMAQ_FUNC MeterArc* IMAQ_STDCALL imaqGetMeterArc(int lightNeedle, MeterArcMode mode, const ROI* roi, PointFloat base, PointFloat start, PointFloat end); -IMAQ_FUNC int IMAQ_STDCALL imaqReadMeter(const Image* image, const MeterArc* arcInfo, double* percentage, PointFloat* endOfNeedle); +IMAQ_FUNC MeterArc* IMAQ_STDCALL +imaqGetMeterArc(int lightNeedle, MeterArcMode mode, const ROI* roi, + PointFloat base, PointFloat start, PointFloat end); +IMAQ_FUNC int IMAQ_STDCALL +imaqReadMeter(const Image* image, const MeterArc* arcInfo, double* percentage, + PointFloat* endOfNeedle); //============================================================================ // Calibration functions //============================================================================ -IMAQ_FUNC int IMAQ_STDCALL imaqCopyCalibrationInfo2(Image* dest, Image* source, Point offset); -IMAQ_FUNC int IMAQ_STDCALL imaqCorrectCalibratedImage(Image* dest, const Image* source, PixelValue fill, InterpolationMethod method, const ROI* roi); -IMAQ_FUNC CalibrationInfo* IMAQ_STDCALL imaqGetCalibrationInfo2(const Image* image); -IMAQ_FUNC CalibrationInfo* IMAQ_STDCALL imaqGetCalibrationInfo3(Image* image, unsigned int isGetErrorMap); -IMAQ_FUNC int IMAQ_STDCALL imaqLearnCalibrationGrid(Image* image, const ROI* roi, const LearnCalibrationOptions* options, const GridDescriptor* grid, const CoordinateSystem* system, const RangeFloat* range, float* quality); -IMAQ_FUNC int IMAQ_STDCALL imaqLearnCalibrationPoints(Image* image, const CalibrationPoints* points, const ROI* roi, const LearnCalibrationOptions* options, const GridDescriptor* grid, const CoordinateSystem* system, float* quality); -IMAQ_FUNC int IMAQ_STDCALL imaqSetCoordinateSystem(Image* image, const CoordinateSystem* system); -IMAQ_FUNC int IMAQ_STDCALL imaqSetSimpleCalibration(Image* image, ScalingMethod method, int learnTable, const GridDescriptor* grid, const CoordinateSystem* system); -IMAQ_FUNC TransformReport* IMAQ_STDCALL imaqTransformPixelToRealWorld(const Image* image, const PointFloat* pixelCoordinates, int numCoordinates); -IMAQ_FUNC TransformReport* IMAQ_STDCALL imaqTransformRealWorldToPixel(const Image* image, const PointFloat* realWorldCoordinates, int numCoordinates); -IMAQ_FUNC int IMAQ_STDCALL imaqSetSimpleCalibration2(Image* image, const GridDescriptor* gridDescriptor); -IMAQ_FUNC int IMAQ_STDCALL imaqCalibrationSetAxisInfo(Image* image, CoordinateSystem* axisInfo); -IMAQ_FUNC int IMAQ_STDCALL imaqCalibrationGetThumbnailImage(Image* templateImage, Image* image, CalibrationThumbnailType type, unsigned int index); -IMAQ_FUNC GetCalibrationInfoReport* IMAQ_STDCALL imaqCalibrationGetCalibrationInfo(Image* image, unsigned int isGetErrorMap); -IMAQ_FUNC GetCameraParametersReport* IMAQ_STDCALL imaqCalibrationGetCameraParameters(Image* templateImage); -IMAQ_FUNC int IMAQ_STDCALL imaqCalibrationCompactInformation(Image* image); +IMAQ_FUNC int IMAQ_STDCALL +imaqCopyCalibrationInfo2(Image* dest, Image* source, Point offset); +IMAQ_FUNC int IMAQ_STDCALL +imaqCorrectCalibratedImage(Image* dest, const Image* source, PixelValue fill, + InterpolationMethod method, const ROI* roi); +IMAQ_FUNC CalibrationInfo* IMAQ_STDCALL +imaqGetCalibrationInfo2(const Image* image); +IMAQ_FUNC CalibrationInfo* IMAQ_STDCALL +imaqGetCalibrationInfo3(Image* image, unsigned int isGetErrorMap); +IMAQ_FUNC int IMAQ_STDCALL +imaqLearnCalibrationGrid(Image* image, const ROI* roi, + const LearnCalibrationOptions* options, + const GridDescriptor* grid, + const CoordinateSystem* system, + const RangeFloat* range, float* quality); +IMAQ_FUNC int IMAQ_STDCALL +imaqLearnCalibrationPoints(Image* image, const CalibrationPoints* points, + const ROI* roi, + const LearnCalibrationOptions* options, + const GridDescriptor* grid, + const CoordinateSystem* system, float* quality); +IMAQ_FUNC int IMAQ_STDCALL +imaqSetCoordinateSystem(Image* image, const CoordinateSystem* system); +IMAQ_FUNC int IMAQ_STDCALL +imaqSetSimpleCalibration(Image* image, ScalingMethod method, int learnTable, + const GridDescriptor* grid, + const CoordinateSystem* system); +IMAQ_FUNC TransformReport* IMAQ_STDCALL +imaqTransformPixelToRealWorld(const Image* image, + const PointFloat* pixelCoordinates, + int numCoordinates); +IMAQ_FUNC TransformReport* IMAQ_STDCALL +imaqTransformRealWorldToPixel(const Image* image, + const PointFloat* realWorldCoordinates, + int numCoordinates); +IMAQ_FUNC int IMAQ_STDCALL +imaqSetSimpleCalibration2(Image* image, const GridDescriptor* gridDescriptor); +IMAQ_FUNC int IMAQ_STDCALL +imaqCalibrationSetAxisInfo(Image* image, CoordinateSystem* axisInfo); +IMAQ_FUNC int IMAQ_STDCALL +imaqCalibrationGetThumbnailImage(Image* templateImage, Image* image, + CalibrationThumbnailType type, + unsigned int index); +IMAQ_FUNC GetCalibrationInfoReport* IMAQ_STDCALL +imaqCalibrationGetCalibrationInfo(Image* image, unsigned int isGetErrorMap); +IMAQ_FUNC GetCameraParametersReport* IMAQ_STDCALL +imaqCalibrationGetCameraParameters(Image* templateImage); +IMAQ_FUNC int IMAQ_STDCALL imaqCalibrationCompactInformation(Image* image); //============================================================================ // Pixel Manipulation functions //============================================================================ -IMAQ_FUNC int IMAQ_STDCALL imaqArrayToComplexPlane(Image* dest, const Image* source, const float* newPixels, ComplexPlane plane); -IMAQ_FUNC float* IMAQ_STDCALL imaqComplexPlaneToArray(const Image* image, ComplexPlane plane, Rect rect, int* rows, int* columns); -IMAQ_FUNC int IMAQ_STDCALL imaqExtractColorPlanes(const Image* image, ColorMode mode, Image* plane1, Image* plane2, Image* plane3); -IMAQ_FUNC int IMAQ_STDCALL imaqExtractComplexPlane(Image* dest, const Image* source, ComplexPlane plane); -IMAQ_FUNC int IMAQ_STDCALL imaqFillImage(Image* image, PixelValue value, const Image* mask); -IMAQ_FUNC void* IMAQ_STDCALL imaqGetLine(const Image* image, Point start, Point end, int* numPoints); -IMAQ_FUNC int IMAQ_STDCALL imaqGetPixel(const Image* image, Point pixel, PixelValue* value); -IMAQ_FUNC int IMAQ_STDCALL imaqReplaceColorPlanes(Image* dest, const Image* source, ColorMode mode, const Image* plane1, const Image* plane2, const Image* plane3); -IMAQ_FUNC int IMAQ_STDCALL imaqReplaceComplexPlane(Image* dest, const Image* source, const Image* newValues, ComplexPlane plane); -IMAQ_FUNC int IMAQ_STDCALL imaqSetLine(Image* image, const void* array, int arraySize, Point start, Point end); -IMAQ_FUNC int IMAQ_STDCALL imaqSetPixel(Image* image, Point coord, PixelValue value); +IMAQ_FUNC int IMAQ_STDCALL +imaqArrayToComplexPlane(Image* dest, const Image* source, + const float* newPixels, ComplexPlane plane); +IMAQ_FUNC float* IMAQ_STDCALL +imaqComplexPlaneToArray(const Image* image, ComplexPlane plane, Rect rect, + int* rows, int* columns); +IMAQ_FUNC int IMAQ_STDCALL imaqExtractColorPlanes(const Image* image, + ColorMode mode, Image* plane1, + Image* plane2, Image* plane3); +IMAQ_FUNC int IMAQ_STDCALL +imaqExtractComplexPlane(Image* dest, const Image* source, ComplexPlane plane); +IMAQ_FUNC int IMAQ_STDCALL +imaqFillImage(Image* image, PixelValue value, const Image* mask); +IMAQ_FUNC void* IMAQ_STDCALL +imaqGetLine(const Image* image, Point start, Point end, int* numPoints); +IMAQ_FUNC int IMAQ_STDCALL +imaqGetPixel(const Image* image, Point pixel, PixelValue* value); +IMAQ_FUNC int IMAQ_STDCALL +imaqReplaceColorPlanes(Image* dest, const Image* source, ColorMode mode, + const Image* plane1, const Image* plane2, + const Image* plane3); +IMAQ_FUNC int IMAQ_STDCALL +imaqReplaceComplexPlane(Image* dest, const Image* source, + const Image* newValues, ComplexPlane plane); +IMAQ_FUNC int IMAQ_STDCALL imaqSetLine(Image* image, const void* array, + int arraySize, Point start, Point end); +IMAQ_FUNC int IMAQ_STDCALL +imaqSetPixel(Image* image, Point coord, PixelValue value); //============================================================================ // Color Matching functions //============================================================================ -IMAQ_FUNC ColorInformation* IMAQ_STDCALL imaqLearnColor(const Image* image, const ROI* roi, ColorSensitivity sensitivity, int saturation); -IMAQ_FUNC int* IMAQ_STDCALL imaqMatchColor(const Image* image, const ColorInformation* info, const ROI* roi, int* numScores); +IMAQ_FUNC ColorInformation* IMAQ_STDCALL +imaqLearnColor(const Image* image, const ROI* roi, ColorSensitivity sensitivity, + int saturation); +IMAQ_FUNC int* IMAQ_STDCALL imaqMatchColor(const Image* image, + const ColorInformation* info, + const ROI* roi, int* numScores); //============================================================================ // Frequency Domain Analysis functions //============================================================================ -IMAQ_FUNC int IMAQ_STDCALL imaqAttenuate(Image* dest, const Image* source, AttenuateMode highlow); +IMAQ_FUNC int IMAQ_STDCALL +imaqAttenuate(Image* dest, const Image* source, AttenuateMode highlow); IMAQ_FUNC int IMAQ_STDCALL imaqConjugate(Image* dest, const Image* source); IMAQ_FUNC int IMAQ_STDCALL imaqFFT(Image* dest, const Image* source); -IMAQ_FUNC int IMAQ_STDCALL imaqFlipFrequencies(Image* dest, const Image* source); +IMAQ_FUNC int IMAQ_STDCALL +imaqFlipFrequencies(Image* dest, const Image* source); IMAQ_FUNC int IMAQ_STDCALL imaqInverseFFT(Image* dest, const Image* source); -IMAQ_FUNC int IMAQ_STDCALL imaqTruncate(Image* dest, const Image* source, TruncateMode highlow, float ratioToKeep); +IMAQ_FUNC int IMAQ_STDCALL imaqTruncate(Image* dest, const Image* source, + TruncateMode highlow, + float ratioToKeep); //============================================================================ // Barcode I/O functions //============================================================================ -IMAQ_FUNC int IMAQ_STDCALL imaqGradeDataMatrixBarcodeAIM(const Image* image, AIMGradeReport* report); -IMAQ_FUNC BarcodeInfo* IMAQ_STDCALL imaqReadBarcode(const Image* image, BarcodeType type, const ROI* roi, int validate); -IMAQ_FUNC DataMatrixReport* IMAQ_STDCALL imaqReadDataMatrixBarcode2(Image* image, const ROI* roi, DataMatrixGradingMode prepareForGrading, const DataMatrixDescriptionOptions* descriptionOptions, const DataMatrixSizeOptions* sizeOptions, const DataMatrixSearchOptions* searchOptions); -IMAQ_FUNC Barcode2DInfo* IMAQ_STDCALL imaqReadPDF417Barcode(const Image* image, const ROI* roi, Barcode2DSearchMode searchMode, unsigned int* numBarcodes); -IMAQ_FUNC QRCodeReport* IMAQ_STDCALL imaqReadQRCode(Image* image, const ROI* roi, QRGradingMode reserved, const QRCodeDescriptionOptions* descriptionOptions, const QRCodeSizeOptions* sizeOptions, const QRCodeSearchOptions* searchOptions); +IMAQ_FUNC int IMAQ_STDCALL +imaqGradeDataMatrixBarcodeAIM(const Image* image, AIMGradeReport* report); +IMAQ_FUNC BarcodeInfo* IMAQ_STDCALL +imaqReadBarcode(const Image* image, BarcodeType type, const ROI* roi, + int validate); +IMAQ_FUNC DataMatrixReport* IMAQ_STDCALL imaqReadDataMatrixBarcode2( + Image* image, const ROI* roi, DataMatrixGradingMode prepareForGrading, + const DataMatrixDescriptionOptions* descriptionOptions, + const DataMatrixSizeOptions* sizeOptions, + const DataMatrixSearchOptions* searchOptions); +IMAQ_FUNC Barcode2DInfo* IMAQ_STDCALL +imaqReadPDF417Barcode(const Image* image, const ROI* roi, + Barcode2DSearchMode searchMode, + unsigned int* numBarcodes); +IMAQ_FUNC QRCodeReport* IMAQ_STDCALL +imaqReadQRCode(Image* image, const ROI* roi, QRGradingMode reserved, + const QRCodeDescriptionOptions* descriptionOptions, + const QRCodeSizeOptions* sizeOptions, + const QRCodeSearchOptions* searchOptions); //============================================================================ // LCD functions //============================================================================ -IMAQ_FUNC int IMAQ_STDCALL imaqFindLCDSegments(ROI* roi, const Image* image, const LCDOptions* options); -IMAQ_FUNC LCDReport* IMAQ_STDCALL imaqReadLCD(const Image* image, const ROI* roi, const LCDOptions* options); +IMAQ_FUNC int IMAQ_STDCALL +imaqFindLCDSegments(ROI* roi, const Image* image, const LCDOptions* options); +IMAQ_FUNC LCDReport* IMAQ_STDCALL +imaqReadLCD(const Image* image, const ROI* roi, const LCDOptions* options); //============================================================================ // Shape Matching functions //============================================================================ -IMAQ_FUNC ShapeReport* IMAQ_STDCALL imaqMatchShape(Image* dest, Image* source, const Image* templateImage, int scaleInvariant, int connectivity8, double tolerance, int* numMatches); +IMAQ_FUNC ShapeReport* IMAQ_STDCALL +imaqMatchShape(Image* dest, Image* source, const Image* templateImage, + int scaleInvariant, int connectivity8, double tolerance, + int* numMatches); //============================================================================ // Contours functions //============================================================================ -IMAQ_FUNC ContourID IMAQ_STDCALL imaqAddAnnulusContour(ROI* roi, Annulus annulus); -IMAQ_FUNC ContourID IMAQ_STDCALL imaqAddClosedContour(ROI* roi, const Point* points, int numPoints); -IMAQ_FUNC ContourID IMAQ_STDCALL imaqAddLineContour(ROI* roi, Point start, Point end); -IMAQ_FUNC ContourID IMAQ_STDCALL imaqAddOpenContour(ROI* roi, const Point* points, int numPoints); -IMAQ_FUNC ContourID IMAQ_STDCALL imaqAddOvalContour(ROI* roi, Rect boundingBox); -IMAQ_FUNC ContourID IMAQ_STDCALL imaqAddPointContour(ROI* roi, Point point); -IMAQ_FUNC ContourID IMAQ_STDCALL imaqAddRectContour(ROI* roi, Rect rect); -IMAQ_FUNC ContourID IMAQ_STDCALL imaqAddRotatedRectContour2(ROI* roi, RotatedRect rect); -IMAQ_FUNC ContourID IMAQ_STDCALL imaqCopyContour(ROI* destRoi, const ROI* sourceRoi, ContourID id); -IMAQ_FUNC ContourID IMAQ_STDCALL imaqGetContour(const ROI* roi, unsigned int index); -IMAQ_FUNC int IMAQ_STDCALL imaqGetContourColor(const ROI* roi, ContourID id, RGBValue* contourColor); -IMAQ_FUNC int IMAQ_STDCALL imaqGetContourCount(const ROI* roi); -IMAQ_FUNC ContourInfo2* IMAQ_STDCALL imaqGetContourInfo2(const ROI* roi, ContourID id); -IMAQ_FUNC int IMAQ_STDCALL imaqMoveContour(ROI* roi, ContourID id, int deltaX, int deltaY); -IMAQ_FUNC int IMAQ_STDCALL imaqRemoveContour(ROI* roi, ContourID id); -IMAQ_FUNC int IMAQ_STDCALL imaqSetContourColor(ROI* roi, ContourID id, const RGBValue* color); +IMAQ_FUNC ContourID IMAQ_STDCALL +imaqAddAnnulusContour(ROI* roi, Annulus annulus); +IMAQ_FUNC ContourID IMAQ_STDCALL +imaqAddClosedContour(ROI* roi, const Point* points, int numPoints); +IMAQ_FUNC ContourID IMAQ_STDCALL +imaqAddLineContour(ROI* roi, Point start, Point end); +IMAQ_FUNC ContourID IMAQ_STDCALL +imaqAddOpenContour(ROI* roi, const Point* points, int numPoints); +IMAQ_FUNC ContourID IMAQ_STDCALL imaqAddOvalContour(ROI* roi, Rect boundingBox); +IMAQ_FUNC ContourID IMAQ_STDCALL imaqAddPointContour(ROI* roi, Point point); +IMAQ_FUNC ContourID IMAQ_STDCALL imaqAddRectContour(ROI* roi, Rect rect); +IMAQ_FUNC ContourID IMAQ_STDCALL +imaqAddRotatedRectContour2(ROI* roi, RotatedRect rect); +IMAQ_FUNC ContourID IMAQ_STDCALL +imaqCopyContour(ROI* destRoi, const ROI* sourceRoi, ContourID id); +IMAQ_FUNC ContourID IMAQ_STDCALL +imaqGetContour(const ROI* roi, unsigned int index); +IMAQ_FUNC int IMAQ_STDCALL +imaqGetContourColor(const ROI* roi, ContourID id, RGBValue* contourColor); +IMAQ_FUNC int IMAQ_STDCALL imaqGetContourCount(const ROI* roi); +IMAQ_FUNC ContourInfo2* IMAQ_STDCALL +imaqGetContourInfo2(const ROI* roi, ContourID id); +IMAQ_FUNC int IMAQ_STDCALL +imaqMoveContour(ROI* roi, ContourID id, int deltaX, int deltaY); +IMAQ_FUNC int IMAQ_STDCALL imaqRemoveContour(ROI* roi, ContourID id); +IMAQ_FUNC int IMAQ_STDCALL +imaqSetContourColor(ROI* roi, ContourID id, const RGBValue* color); //============================================================================ // Regions of Interest functions //============================================================================ -IMAQ_FUNC int IMAQ_STDCALL imaqConstructROI2(const Image* image, ROI* roi, Tool initialTool, const ToolWindowOptions* tools, const ConstructROIOptions2* options, int* okay); +IMAQ_FUNC int IMAQ_STDCALL +imaqConstructROI2(const Image* image, ROI* roi, Tool initialTool, + const ToolWindowOptions* tools, + const ConstructROIOptions2* options, int* okay); IMAQ_FUNC ROI* IMAQ_STDCALL imaqCreateROI(void); -IMAQ_FUNC int IMAQ_STDCALL imaqGetROIBoundingBox(const ROI* roi, Rect* boundingBox); -IMAQ_FUNC int IMAQ_STDCALL imaqGetROIColor(const ROI* roi, RGBValue* roiColor); +IMAQ_FUNC int IMAQ_STDCALL +imaqGetROIBoundingBox(const ROI* roi, Rect* boundingBox); +IMAQ_FUNC int IMAQ_STDCALL imaqGetROIColor(const ROI* roi, RGBValue* roiColor); IMAQ_FUNC ROI* IMAQ_STDCALL imaqGetWindowROI(int windowNumber); -IMAQ_FUNC int IMAQ_STDCALL imaqSetROIColor(ROI* roi, const RGBValue* color); -IMAQ_FUNC int IMAQ_STDCALL imaqSetWindowROI(int windowNumber, const ROI* roi); +IMAQ_FUNC int IMAQ_STDCALL imaqSetROIColor(ROI* roi, const RGBValue* color); +IMAQ_FUNC int IMAQ_STDCALL imaqSetWindowROI(int windowNumber, const ROI* roi); //============================================================================ // Image Analysis functions //============================================================================ -IMAQ_FUNC int IMAQ_STDCALL imaqCentroid(const Image* image, PointFloat* centroid, const Image* mask); -IMAQ_FUNC Curve* IMAQ_STDCALL imaqExtractCurves(const Image* image, const ROI* roi, const CurveOptions* curveOptions, unsigned int* numCurves); -IMAQ_FUNC HistogramReport* IMAQ_STDCALL imaqHistogram(const Image* image, int numClasses, float min, float max, const Image* mask); -IMAQ_FUNC LinearAverages* IMAQ_STDCALL imaqLinearAverages2(Image* image, LinearAveragesMode mode, Rect rect); -IMAQ_FUNC LineProfile* IMAQ_STDCALL imaqLineProfile(const Image* image, Point start, Point end); -IMAQ_FUNC QuantifyReport* IMAQ_STDCALL imaqQuantify(const Image* image, const Image* mask); +IMAQ_FUNC int IMAQ_STDCALL +imaqCentroid(const Image* image, PointFloat* centroid, const Image* mask); +IMAQ_FUNC Curve* IMAQ_STDCALL +imaqExtractCurves(const Image* image, const ROI* roi, + const CurveOptions* curveOptions, unsigned int* numCurves); +IMAQ_FUNC HistogramReport* IMAQ_STDCALL +imaqHistogram(const Image* image, int numClasses, float min, float max, + const Image* mask); +IMAQ_FUNC LinearAverages* IMAQ_STDCALL +imaqLinearAverages2(Image* image, LinearAveragesMode mode, Rect rect); +IMAQ_FUNC LineProfile* IMAQ_STDCALL +imaqLineProfile(const Image* image, Point start, Point end); +IMAQ_FUNC QuantifyReport* IMAQ_STDCALL +imaqQuantify(const Image* image, const Image* mask); //============================================================================ // Error Management functions //============================================================================ -IMAQ_FUNC int IMAQ_STDCALL imaqClearError(void); -IMAQ_FUNC char* IMAQ_STDCALL imaqGetErrorText(int errorCode); -IMAQ_FUNC int IMAQ_STDCALL imaqGetLastError(void); +IMAQ_FUNC int IMAQ_STDCALL imaqClearError(void); +IMAQ_FUNC char* IMAQ_STDCALL imaqGetErrorText(int errorCode); +IMAQ_FUNC int IMAQ_STDCALL imaqGetLastError(void); IMAQ_FUNC const char* IMAQ_STDCALL imaqGetLastErrorFunc(void); -IMAQ_FUNC int IMAQ_STDCALL imaqSetError(int errorCode, const char* function); +IMAQ_FUNC int IMAQ_STDCALL imaqSetError(int errorCode, const char* function); //============================================================================ // Threshold functions //============================================================================ -IMAQ_FUNC ThresholdData* IMAQ_STDCALL imaqAutoThreshold2(Image* dest, const Image* source, int numClasses, ThresholdMethod method, const Image* mask); -IMAQ_FUNC int IMAQ_STDCALL imaqLocalThreshold(Image* dest, const Image* source, unsigned int windowWidth, unsigned int windowHeight, LocalThresholdMethod method, double deviationWeight, ObjectType type, float replaceValue); -IMAQ_FUNC int IMAQ_STDCALL imaqMagicWand(Image* dest, const Image* source, Point coord, float tolerance, int connectivity8, float replaceValue); -IMAQ_FUNC int IMAQ_STDCALL imaqMultithreshold(Image* dest, const Image* source, const ThresholdData* ranges, int numRanges); -IMAQ_FUNC int IMAQ_STDCALL imaqThreshold(Image* dest, const Image* source, float rangeMin, float rangeMax, int useNewValue, float newValue); +IMAQ_FUNC ThresholdData* IMAQ_STDCALL +imaqAutoThreshold2(Image* dest, const Image* source, int numClasses, + ThresholdMethod method, const Image* mask); +IMAQ_FUNC int IMAQ_STDCALL +imaqLocalThreshold(Image* dest, const Image* source, unsigned int windowWidth, + unsigned int windowHeight, LocalThresholdMethod method, + double deviationWeight, ObjectType type, float replaceValue); +IMAQ_FUNC int IMAQ_STDCALL imaqMagicWand(Image* dest, const Image* source, + Point coord, float tolerance, + int connectivity8, float replaceValue); +IMAQ_FUNC int IMAQ_STDCALL imaqMultithreshold(Image* dest, const Image* source, + const ThresholdData* ranges, + int numRanges); +IMAQ_FUNC int IMAQ_STDCALL imaqThreshold(Image* dest, const Image* source, + float rangeMin, float rangeMax, + int useNewValue, float newValue); //============================================================================ // Memory Management functions @@ -5140,206 +8255,575 @@ IMAQ_FUNC int IMAQ_STDCALL imaqDispose(void* object); //============================================================================ // Pattern Matching functions //============================================================================ -IMAQ_FUNC CircleMatch* IMAQ_STDCALL imaqDetectCircles(const Image* image, const CircleDescriptor* circleDescriptor, const CurveOptions* curveOptions, const ShapeDetectionOptions* shapeDetectionOptions, const ROI* roi, int* numMatchesReturned); -IMAQ_FUNC EllipseMatch* IMAQ_STDCALL imaqDetectEllipses(const Image* image, const EllipseDescriptor* ellipseDescriptor, const CurveOptions* curveOptions, const ShapeDetectionOptions* shapeDetectionOptions, const ROI* roi, int* numMatchesReturned); -IMAQ_FUNC LineMatch* IMAQ_STDCALL imaqDetectLines(const Image* image, const LineDescriptor* lineDescriptor, const CurveOptions* curveOptions, const ShapeDetectionOptions* shapeDetectionOptions, const ROI* roi, int* numMatchesReturned); -IMAQ_FUNC RectangleMatch* IMAQ_STDCALL imaqDetectRectangles(const Image* image, const RectangleDescriptor* rectangleDescriptor, const CurveOptions* curveOptions, const ShapeDetectionOptions* shapeDetectionOptions, const ROI* roi, int* numMatchesReturned); -IMAQ_FUNC FeatureData* IMAQ_STDCALL imaqGetGeometricFeaturesFromCurves(const Curve* curves, unsigned int numCurves, const FeatureType* featureTypes, unsigned int numFeatureTypes, unsigned int* numFeatures); -IMAQ_FUNC FeatureData* IMAQ_STDCALL imaqGetGeometricTemplateFeatureInfo(const Image* pattern, unsigned int* numFeatures); -IMAQ_FUNC int IMAQ_STDCALL imaqLearnColorPattern(Image* image, const LearnColorPatternOptions* options); -IMAQ_FUNC int IMAQ_STDCALL imaqLearnGeometricPattern(Image* image, PointFloat originOffset, const CurveOptions* curveOptions, const LearnGeometricPatternAdvancedOptions* advancedLearnOptions, const Image* mask); -IMAQ_FUNC MultipleGeometricPattern* IMAQ_STDCALL imaqLearnMultipleGeometricPatterns(const Image** patterns, unsigned int numberOfPatterns, const String255* labels); -IMAQ_FUNC int IMAQ_STDCALL imaqLearnPattern3(Image* image, LearningMode learningMode, LearnPatternAdvancedOptions* advancedOptions, const Image* mask); -IMAQ_FUNC PatternMatch* IMAQ_STDCALL imaqMatchColorPattern(const Image* image, Image* pattern, const MatchColorPatternOptions* options, Rect searchRect, int* numMatches); -IMAQ_FUNC GeometricPatternMatch2* IMAQ_STDCALL imaqMatchGeometricPattern2(const Image* image, const Image* pattern, const CurveOptions* curveOptions, const MatchGeometricPatternOptions* matchOptions, const MatchGeometricPatternAdvancedOptions2* advancedMatchOptions, const ROI* roi, int* numMatches); -IMAQ_FUNC GeometricPatternMatch2* IMAQ_STDCALL imaqMatchMultipleGeometricPatterns(const Image* image, const MultipleGeometricPattern* multiplePattern, const ROI* roi, int* numMatches); -IMAQ_FUNC MultipleGeometricPattern* IMAQ_STDCALL imaqReadMultipleGeometricPatternFile(const char* fileName, String255 description); -IMAQ_FUNC PatternMatch* IMAQ_STDCALL imaqRefineMatches(const Image* image, const Image* pattern, const PatternMatch* candidatesIn, int numCandidatesIn, MatchPatternOptions* options, MatchPatternAdvancedOptions* advancedOptions, int* numCandidatesOut); -IMAQ_FUNC int IMAQ_STDCALL imaqSetMultipleGeometricPatternsOptions(MultipleGeometricPattern* multiplePattern, const char* label, const CurveOptions* curveOptions, const MatchGeometricPatternOptions* matchOptions, const MatchGeometricPatternAdvancedOptions2* advancedMatchOptions); -IMAQ_FUNC int IMAQ_STDCALL imaqWriteMultipleGeometricPatternFile(const MultipleGeometricPattern* multiplePattern, const char* fileName, const char* description); -IMAQ_FUNC GeometricPatternMatch3* IMAQ_STDCALL imaqMatchGeometricPattern3(const Image* image, const Image* pattern, const CurveOptions* curveOptions, const MatchGeometricPatternOptions* matchOptions, const MatchGeometricPatternAdvancedOptions3* advancedMatchOptions, const ROI* roi, size_t* numMatches); -IMAQ_FUNC int IMAQ_STDCALL imaqLearnGeometricPattern2(Image* image, PointFloat originOffset, double angleOffset, const CurveOptions* curveOptions, const LearnGeometricPatternAdvancedOptions2* advancedLearnOptions, const Image* mask); -IMAQ_FUNC PatternMatch* IMAQ_STDCALL imaqMatchPattern3(const Image* image, const Image* pattern, const MatchPatternOptions* options, const MatchPatternAdvancedOptions* advancedOptions, const ROI* roi, int* numMatches); +IMAQ_FUNC CircleMatch* IMAQ_STDCALL +imaqDetectCircles(const Image* image, const CircleDescriptor* circleDescriptor, + const CurveOptions* curveOptions, + const ShapeDetectionOptions* shapeDetectionOptions, + const ROI* roi, int* numMatchesReturned); +IMAQ_FUNC EllipseMatch* IMAQ_STDCALL +imaqDetectEllipses(const Image* image, + const EllipseDescriptor* ellipseDescriptor, + const CurveOptions* curveOptions, + const ShapeDetectionOptions* shapeDetectionOptions, + const ROI* roi, int* numMatchesReturned); +IMAQ_FUNC LineMatch* IMAQ_STDCALL +imaqDetectLines(const Image* image, const LineDescriptor* lineDescriptor, + const CurveOptions* curveOptions, + const ShapeDetectionOptions* shapeDetectionOptions, + const ROI* roi, int* numMatchesReturned); +IMAQ_FUNC RectangleMatch* IMAQ_STDCALL +imaqDetectRectangles(const Image* image, + const RectangleDescriptor* rectangleDescriptor, + const CurveOptions* curveOptions, + const ShapeDetectionOptions* shapeDetectionOptions, + const ROI* roi, int* numMatchesReturned); +IMAQ_FUNC FeatureData* IMAQ_STDCALL +imaqGetGeometricFeaturesFromCurves(const Curve* curves, unsigned int numCurves, + const FeatureType* featureTypes, + unsigned int numFeatureTypes, + unsigned int* numFeatures); +IMAQ_FUNC FeatureData* IMAQ_STDCALL +imaqGetGeometricTemplateFeatureInfo(const Image* pattern, + unsigned int* numFeatures); +IMAQ_FUNC int IMAQ_STDCALL +imaqLearnColorPattern(Image* image, const LearnColorPatternOptions* options); +IMAQ_FUNC int IMAQ_STDCALL imaqLearnGeometricPattern( + Image* image, PointFloat originOffset, const CurveOptions* curveOptions, + const LearnGeometricPatternAdvancedOptions* advancedLearnOptions, + const Image* mask); +IMAQ_FUNC MultipleGeometricPattern* IMAQ_STDCALL +imaqLearnMultipleGeometricPatterns(const Image** patterns, + unsigned int numberOfPatterns, + const String255* labels); +IMAQ_FUNC int IMAQ_STDCALL +imaqLearnPattern3(Image* image, LearningMode learningMode, + LearnPatternAdvancedOptions* advancedOptions, + const Image* mask); +IMAQ_FUNC PatternMatch* IMAQ_STDCALL +imaqMatchColorPattern(const Image* image, Image* pattern, + const MatchColorPatternOptions* options, Rect searchRect, + int* numMatches); +IMAQ_FUNC GeometricPatternMatch2* IMAQ_STDCALL imaqMatchGeometricPattern2( + const Image* image, const Image* pattern, const CurveOptions* curveOptions, + const MatchGeometricPatternOptions* matchOptions, + const MatchGeometricPatternAdvancedOptions2* advancedMatchOptions, + const ROI* roi, int* numMatches); +IMAQ_FUNC GeometricPatternMatch2* IMAQ_STDCALL +imaqMatchMultipleGeometricPatterns( + const Image* image, const MultipleGeometricPattern* multiplePattern, + const ROI* roi, int* numMatches); +IMAQ_FUNC MultipleGeometricPattern* IMAQ_STDCALL +imaqReadMultipleGeometricPatternFile(const char* fileName, + String255 description); +IMAQ_FUNC PatternMatch* IMAQ_STDCALL +imaqRefineMatches(const Image* image, const Image* pattern, + const PatternMatch* candidatesIn, int numCandidatesIn, + MatchPatternOptions* options, + MatchPatternAdvancedOptions* advancedOptions, + int* numCandidatesOut); +IMAQ_FUNC int IMAQ_STDCALL imaqSetMultipleGeometricPatternsOptions( + MultipleGeometricPattern* multiplePattern, const char* label, + const CurveOptions* curveOptions, + const MatchGeometricPatternOptions* matchOptions, + const MatchGeometricPatternAdvancedOptions2* advancedMatchOptions); +IMAQ_FUNC int IMAQ_STDCALL imaqWriteMultipleGeometricPatternFile( + const MultipleGeometricPattern* multiplePattern, const char* fileName, + const char* description); +IMAQ_FUNC GeometricPatternMatch3* IMAQ_STDCALL imaqMatchGeometricPattern3( + const Image* image, const Image* pattern, const CurveOptions* curveOptions, + const MatchGeometricPatternOptions* matchOptions, + const MatchGeometricPatternAdvancedOptions3* advancedMatchOptions, + const ROI* roi, size_t* numMatches); +IMAQ_FUNC int IMAQ_STDCALL imaqLearnGeometricPattern2( + Image* image, PointFloat originOffset, double angleOffset, + const CurveOptions* curveOptions, + const LearnGeometricPatternAdvancedOptions2* advancedLearnOptions, + const Image* mask); +IMAQ_FUNC PatternMatch* IMAQ_STDCALL +imaqMatchPattern3(const Image* image, const Image* pattern, + const MatchPatternOptions* options, + const MatchPatternAdvancedOptions* advancedOptions, + const ROI* roi, int* numMatches); //============================================================================ // Overlay functions //============================================================================ IMAQ_FUNC int IMAQ_STDCALL imaqClearOverlay(Image* image, const char* group); -IMAQ_FUNC int IMAQ_STDCALL imaqCopyOverlay(Image* dest, const Image* source, const char* group); -IMAQ_FUNC int IMAQ_STDCALL imaqGetOverlayProperties(const Image* image, const char* group, TransformBehaviors* transformBehaviors); -IMAQ_FUNC int IMAQ_STDCALL imaqMergeOverlay(Image* dest, const Image* source, const RGBValue* palette, unsigned int numColors, const char* group); -IMAQ_FUNC int IMAQ_STDCALL imaqOverlayArc(Image* image, const ArcInfo* arc, const RGBValue* color, DrawMode drawMode, const char* group); -IMAQ_FUNC int IMAQ_STDCALL imaqOverlayBitmap(Image* image, Point destLoc, const RGBValue* bitmap, unsigned int numCols, unsigned int numRows, const char* group); -IMAQ_FUNC int IMAQ_STDCALL imaqOverlayClosedContour(Image* image, const Point* points, int numPoints, const RGBValue* color, DrawMode drawMode, const char* group); -IMAQ_FUNC int IMAQ_STDCALL imaqOverlayLine(Image* image, Point start, Point end, const RGBValue* color, const char* group); -IMAQ_FUNC int IMAQ_STDCALL imaqOverlayMetafile(Image* image, const void* metafile, Rect rect, const char* group); -IMAQ_FUNC int IMAQ_STDCALL imaqOverlayOpenContour(Image* image, const Point* points, int numPoints, const RGBValue* color, const char* group); -IMAQ_FUNC int IMAQ_STDCALL imaqOverlayOval(Image* image, Rect boundingBox, const RGBValue* color, DrawMode drawMode, char* group); -IMAQ_FUNC int IMAQ_STDCALL imaqOverlayPoints(Image* image, const Point* points, int numPoints, const RGBValue* colors, int numColors, PointSymbol symbol, const UserPointSymbol* userSymbol, const char* group); -IMAQ_FUNC int IMAQ_STDCALL imaqOverlayRect(Image* image, Rect rect, const RGBValue* color, DrawMode drawMode, const char* group); -IMAQ_FUNC int IMAQ_STDCALL imaqOverlayROI(Image* image, const ROI* roi, PointSymbol symbol, const UserPointSymbol* userSymbol, const char* group); -IMAQ_FUNC int IMAQ_STDCALL imaqOverlayText(Image* image, Point origin, const char* text, const RGBValue* color, const OverlayTextOptions* options, const char* group); -IMAQ_FUNC int IMAQ_STDCALL imaqSetOverlayProperties(Image* image, const char* group, TransformBehaviors* transformBehaviors); +IMAQ_FUNC int IMAQ_STDCALL +imaqCopyOverlay(Image* dest, const Image* source, const char* group); +IMAQ_FUNC int IMAQ_STDCALL +imaqGetOverlayProperties(const Image* image, const char* group, + TransformBehaviors* transformBehaviors); +IMAQ_FUNC int IMAQ_STDCALL +imaqMergeOverlay(Image* dest, const Image* source, const RGBValue* palette, + unsigned int numColors, const char* group); +IMAQ_FUNC int IMAQ_STDCALL imaqOverlayArc(Image* image, const ArcInfo* arc, + const RGBValue* color, + DrawMode drawMode, const char* group); +IMAQ_FUNC int IMAQ_STDCALL +imaqOverlayBitmap(Image* image, Point destLoc, const RGBValue* bitmap, + unsigned int numCols, unsigned int numRows, + const char* group); +IMAQ_FUNC int IMAQ_STDCALL +imaqOverlayClosedContour(Image* image, const Point* points, int numPoints, + const RGBValue* color, DrawMode drawMode, + const char* group); +IMAQ_FUNC int IMAQ_STDCALL imaqOverlayLine(Image* image, Point start, Point end, + const RGBValue* color, + const char* group); +IMAQ_FUNC int IMAQ_STDCALL imaqOverlayMetafile(Image* image, + const void* metafile, Rect rect, + const char* group); +IMAQ_FUNC int IMAQ_STDCALL +imaqOverlayOpenContour(Image* image, const Point* points, int numPoints, + const RGBValue* color, const char* group); +IMAQ_FUNC int IMAQ_STDCALL imaqOverlayOval(Image* image, Rect boundingBox, + const RGBValue* color, + DrawMode drawMode, char* group); +IMAQ_FUNC int IMAQ_STDCALL +imaqOverlayPoints(Image* image, const Point* points, int numPoints, + const RGBValue* colors, int numColors, PointSymbol symbol, + const UserPointSymbol* userSymbol, const char* group); +IMAQ_FUNC int IMAQ_STDCALL +imaqOverlayRect(Image* image, Rect rect, const RGBValue* color, + DrawMode drawMode, const char* group); +IMAQ_FUNC int IMAQ_STDCALL +imaqOverlayROI(Image* image, const ROI* roi, PointSymbol symbol, + const UserPointSymbol* userSymbol, const char* group); +IMAQ_FUNC int IMAQ_STDCALL +imaqOverlayText(Image* image, Point origin, const char* text, + const RGBValue* color, const OverlayTextOptions* options, + const char* group); +IMAQ_FUNC int IMAQ_STDCALL +imaqSetOverlayProperties(Image* image, const char* group, + TransformBehaviors* transformBehaviors); //============================================================================ // OCR functions //============================================================================ -IMAQ_FUNC CharSet* IMAQ_STDCALL imaqCreateCharSet(void); -IMAQ_FUNC int IMAQ_STDCALL imaqDeleteChar(CharSet* set, int index); -IMAQ_FUNC int IMAQ_STDCALL imaqGetCharCount(const CharSet* set); -IMAQ_FUNC CharInfo2* IMAQ_STDCALL imaqGetCharInfo2(const CharSet* set, int index); -IMAQ_FUNC int IMAQ_STDCALL imaqReadOCRFile(const char* fileName, CharSet* set, String255 setDescription, ReadTextOptions* readOptions, OCRProcessingOptions* processingOptions, OCRSpacingOptions* spacingOptions); -IMAQ_FUNC ReadTextReport3* IMAQ_STDCALL imaqReadText3(const Image* image, const CharSet* set, const ROI* roi, const ReadTextOptions* readOptions, const OCRProcessingOptions* processingOptions, const OCRSpacingOptions* spacingOptions); -IMAQ_FUNC int IMAQ_STDCALL imaqRenameChar(CharSet* set, int index, const char* newCharValue); -IMAQ_FUNC int IMAQ_STDCALL imaqSetReferenceChar(const CharSet* set, int index, int isReferenceChar); -IMAQ_FUNC int IMAQ_STDCALL imaqTrainChars(const Image* image, CharSet* set, int index, const char* charValue, const ROI* roi, const OCRProcessingOptions* processingOptions, const OCRSpacingOptions* spacingOptions); -IMAQ_FUNC int* IMAQ_STDCALL imaqVerifyPatterns(const Image* image, const CharSet* set, const String255* expectedPatterns, int patternCount, const ROI* roi, int* numScores); -IMAQ_FUNC int* IMAQ_STDCALL imaqVerifyText(const Image* image, const CharSet* set, const char* expectedString, const ROI* roi, int* numScores); -IMAQ_FUNC int IMAQ_STDCALL imaqWriteOCRFile(const char* fileName, const CharSet* set, const char* setDescription, const ReadTextOptions* readOptions, const OCRProcessingOptions* processingOptions, const OCRSpacingOptions* spacingOptions); +IMAQ_FUNC CharSet* IMAQ_STDCALL imaqCreateCharSet(void); +IMAQ_FUNC int IMAQ_STDCALL imaqDeleteChar(CharSet* set, int index); +IMAQ_FUNC int IMAQ_STDCALL imaqGetCharCount(const CharSet* set); +IMAQ_FUNC CharInfo2* IMAQ_STDCALL +imaqGetCharInfo2(const CharSet* set, int index); +IMAQ_FUNC int IMAQ_STDCALL +imaqReadOCRFile(const char* fileName, CharSet* set, String255 setDescription, + ReadTextOptions* readOptions, + OCRProcessingOptions* processingOptions, + OCRSpacingOptions* spacingOptions); +IMAQ_FUNC ReadTextReport3* IMAQ_STDCALL +imaqReadText3(const Image* image, const CharSet* set, const ROI* roi, + const ReadTextOptions* readOptions, + const OCRProcessingOptions* processingOptions, + const OCRSpacingOptions* spacingOptions); +IMAQ_FUNC int IMAQ_STDCALL +imaqRenameChar(CharSet* set, int index, const char* newCharValue); +IMAQ_FUNC int IMAQ_STDCALL +imaqSetReferenceChar(const CharSet* set, int index, int isReferenceChar); +IMAQ_FUNC int IMAQ_STDCALL +imaqTrainChars(const Image* image, CharSet* set, int index, + const char* charValue, const ROI* roi, + const OCRProcessingOptions* processingOptions, + const OCRSpacingOptions* spacingOptions); +IMAQ_FUNC int* IMAQ_STDCALL +imaqVerifyPatterns(const Image* image, const CharSet* set, + const String255* expectedPatterns, int patternCount, + const ROI* roi, int* numScores); +IMAQ_FUNC int* IMAQ_STDCALL +imaqVerifyText(const Image* image, const CharSet* set, + const char* expectedString, const ROI* roi, int* numScores); +IMAQ_FUNC int IMAQ_STDCALL +imaqWriteOCRFile(const char* fileName, const CharSet* set, + const char* setDescription, const ReadTextOptions* readOptions, + const OCRProcessingOptions* processingOptions, + const OCRSpacingOptions* spacingOptions); //============================================================================ // Geometric Matching functions //============================================================================ -IMAQ_FUNC ExtractContourReport* IMAQ_STDCALL imaqExtractContour(Image* image, const ROI* roi, ExtractContourDirection direction, CurveParameters* curveParams, const ConnectionConstraint* connectionConstraintParams, unsigned int numOfConstraints, ExtractContourSelection selection, Image* contourImage); -IMAQ_FUNC int IMAQ_STDCALL imaqContourOverlay(Image* image, const Image* contourImage, const ContourOverlaySettings* pointsSettings, const ContourOverlaySettings* eqnSettings, const char* groupName); -IMAQ_FUNC ContourComputeCurvatureReport* IMAQ_STDCALL imaqContourComputeCurvature(const Image* contourImage, unsigned int kernel); -IMAQ_FUNC CurvatureAnalysisReport* IMAQ_STDCALL imaqContourClassifyCurvature(const Image* contourImage, unsigned int kernel, RangeLabel* curvatureClasses, unsigned int numCurvatureClasses); -IMAQ_FUNC ComputeDistancesReport* IMAQ_STDCALL imaqContourComputeDistances(const Image* targetImage, const Image* templateImage, const SetupMatchPatternData* matchSetupData, unsigned int smoothingKernel); -IMAQ_FUNC ClassifyDistancesReport* IMAQ_STDCALL imaqContourClassifyDistances(const Image* targetImage, const Image* templateImage, const SetupMatchPatternData* matchSetupData, unsigned int smoothingKernel, const RangeLabel* distanceRanges, unsigned int numDistanceRanges); -IMAQ_FUNC ContourInfoReport* IMAQ_STDCALL imaqContourInfo(const Image* contourImage); -IMAQ_FUNC SetupMatchPatternData* IMAQ_STDCALL imaqContourSetupMatchPattern(MatchMode* matchMode, unsigned int enableSubPixelAccuracy, CurveParameters* curveParams, unsigned int useLearnCurveParameters, const RangeSettingDouble* rangeSettings, unsigned int numRangeSettings); -IMAQ_FUNC int IMAQ_STDCALL imaqContourAdvancedSetupMatchPattern(SetupMatchPatternData* matchSetupData, GeometricAdvancedSetupDataOption* geometricOptions, unsigned int numGeometricOptions); -IMAQ_FUNC ContourFitLineReport* IMAQ_STDCALL imaqContourFitLine(Image* image, double pixelRadius); -IMAQ_FUNC PartialCircle* IMAQ_STDCALL imaqContourFitCircle(Image* image, double pixelRadius, int rejectOutliers); -IMAQ_FUNC PartialEllipse* IMAQ_STDCALL imaqContourFitEllipse(Image* image, double pixelRadius, int rejectOutliers); -IMAQ_FUNC ContourFitSplineReport* IMAQ_STDCALL imaqContourFitSpline(Image* image, int degree, int numberOfControlPoints); -IMAQ_FUNC ContourFitPolynomialReport* IMAQ_STDCALL imaqContourFitPolynomial(Image* image, int order); +IMAQ_FUNC ExtractContourReport* IMAQ_STDCALL +imaqExtractContour(Image* image, const ROI* roi, + ExtractContourDirection direction, + CurveParameters* curveParams, + const ConnectionConstraint* connectionConstraintParams, + unsigned int numOfConstraints, + ExtractContourSelection selection, Image* contourImage); +IMAQ_FUNC int IMAQ_STDCALL +imaqContourOverlay(Image* image, const Image* contourImage, + const ContourOverlaySettings* pointsSettings, + const ContourOverlaySettings* eqnSettings, + const char* groupName); +IMAQ_FUNC ContourComputeCurvatureReport* IMAQ_STDCALL +imaqContourComputeCurvature(const Image* contourImage, unsigned int kernel); +IMAQ_FUNC CurvatureAnalysisReport* IMAQ_STDCALL +imaqContourClassifyCurvature(const Image* contourImage, unsigned int kernel, + RangeLabel* curvatureClasses, + unsigned int numCurvatureClasses); +IMAQ_FUNC ComputeDistancesReport* IMAQ_STDCALL +imaqContourComputeDistances(const Image* targetImage, + const Image* templateImage, + const SetupMatchPatternData* matchSetupData, + unsigned int smoothingKernel); +IMAQ_FUNC ClassifyDistancesReport* IMAQ_STDCALL imaqContourClassifyDistances( + const Image* targetImage, const Image* templateImage, + const SetupMatchPatternData* matchSetupData, unsigned int smoothingKernel, + const RangeLabel* distanceRanges, unsigned int numDistanceRanges); +IMAQ_FUNC ContourInfoReport* IMAQ_STDCALL +imaqContourInfo(const Image* contourImage); +IMAQ_FUNC SetupMatchPatternData* IMAQ_STDCALL imaqContourSetupMatchPattern( + MatchMode* matchMode, unsigned int enableSubPixelAccuracy, + CurveParameters* curveParams, unsigned int useLearnCurveParameters, + const RangeSettingDouble* rangeSettings, unsigned int numRangeSettings); +IMAQ_FUNC int IMAQ_STDCALL imaqContourAdvancedSetupMatchPattern( + SetupMatchPatternData* matchSetupData, + GeometricAdvancedSetupDataOption* geometricOptions, + unsigned int numGeometricOptions); +IMAQ_FUNC ContourFitLineReport* IMAQ_STDCALL +imaqContourFitLine(Image* image, double pixelRadius); +IMAQ_FUNC PartialCircle* IMAQ_STDCALL +imaqContourFitCircle(Image* image, double pixelRadius, int rejectOutliers); +IMAQ_FUNC PartialEllipse* IMAQ_STDCALL +imaqContourFitEllipse(Image* image, double pixelRadius, int rejectOutliers); +IMAQ_FUNC ContourFitSplineReport* IMAQ_STDCALL +imaqContourFitSpline(Image* image, int degree, int numberOfControlPoints); +IMAQ_FUNC ContourFitPolynomialReport* IMAQ_STDCALL +imaqContourFitPolynomial(Image* image, int order); //============================================================================ // Edge Detection functions //============================================================================ -IMAQ_FUNC FindCircularEdgeReport* IMAQ_STDCALL imaqFindCircularEdge2(Image* image, const ROI* roi, const CoordinateSystem* baseSystem, const CoordinateSystem* newSystem, const FindCircularEdgeOptions* edgeOptions, const CircleFitOptions* circleFitOptions); -IMAQ_FUNC FindConcentricEdgeReport* IMAQ_STDCALL imaqFindConcentricEdge2(Image* image, const ROI* roi, const CoordinateSystem* baseSystem, const CoordinateSystem* newSystem, const FindConcentricEdgeOptions* edgeOptions, const ConcentricEdgeFitOptions* concentricEdgeFitOptions); +IMAQ_FUNC FindCircularEdgeReport* IMAQ_STDCALL +imaqFindCircularEdge2(Image* image, const ROI* roi, + const CoordinateSystem* baseSystem, + const CoordinateSystem* newSystem, + const FindCircularEdgeOptions* edgeOptions, + const CircleFitOptions* circleFitOptions); +IMAQ_FUNC FindConcentricEdgeReport* IMAQ_STDCALL imaqFindConcentricEdge2( + Image* image, const ROI* roi, const CoordinateSystem* baseSystem, + const CoordinateSystem* newSystem, + const FindConcentricEdgeOptions* edgeOptions, + const ConcentricEdgeFitOptions* concentricEdgeFitOptions); //============================================================================ // Morphology Reconstruction functions //============================================================================ -IMAQ_FUNC int IMAQ_STDCALL imaqGrayMorphologyReconstruct(Image* dstImage, Image* srcImage, const Image* markerImage, PointFloat* points, int numOfPoints, MorphologyReconstructOperation operation, const StructuringElement* structuringElement, const ROI* roi); -IMAQ_FUNC int IMAQ_STDCALL imaqMorphologyReconstruct(Image* dstImage, Image* srcImage, const Image* markerImage, PointFloat* points, int numOfPoints, MorphologyReconstructOperation operation, Connectivity connectivity, const ROI* roi); +IMAQ_FUNC int IMAQ_STDCALL +imaqGrayMorphologyReconstruct(Image* dstImage, Image* srcImage, + const Image* markerImage, PointFloat* points, + int numOfPoints, + MorphologyReconstructOperation operation, + const StructuringElement* structuringElement, + const ROI* roi); +IMAQ_FUNC int IMAQ_STDCALL +imaqMorphologyReconstruct(Image* dstImage, Image* srcImage, + const Image* markerImage, PointFloat* points, + int numOfPoints, + MorphologyReconstructOperation operation, + Connectivity connectivity, const ROI* roi); //============================================================================ // Texture functions //============================================================================ -IMAQ_FUNC int IMAQ_STDCALL imaqDetectTextureDefect(ClassifierSession* session, Image* destImage, const Image* srcImage, const ROI* roi, int initialStepSize, int finalStepSize, unsigned char defectPixelValue, double minClassificationScore); -IMAQ_FUNC int IMAQ_STDCALL imaqClassificationTextureDefectOptions(ClassifierSession* session, WindowSize* windowOptions, WaveletOptions* waveletOptions, void** bandsUsed, int* numBandsUsed, CooccurrenceOptions* cooccurrenceOptions, unsigned char setOperation); -IMAQ_FUNC int IMAQ_STDCALL imaqCooccurrenceMatrix(const Image* srcImage, const ROI* roi, int levelPixel, const DisplacementVector* displacementVec, void* featureOptionArray, unsigned int featureOptionArraySize, void** cooccurrenceMatrixArray, int* coocurrenceMatrixRows, int* coocurrenceMatrixCols, void** featureVectorArray, int* featureVectorArraySize); -IMAQ_FUNC ExtractTextureFeaturesReport* IMAQ_STDCALL imaqExtractTextureFeatures(const Image* srcImage, const ROI* roi, const WindowSize* windowOptions, const WaveletOptions* waveletOptions, void* waveletBands, unsigned int numWaveletBands, const CooccurrenceOptions* cooccurrenceOptions, unsigned char useWindow); -IMAQ_FUNC WaveletBandsReport* IMAQ_STDCALL imaqExtractWaveletBands(const Image* srcImage, const WaveletOptions* waveletOptions, void* waveletBands, unsigned int numWaveletBands); +IMAQ_FUNC int IMAQ_STDCALL +imaqDetectTextureDefect(ClassifierSession* session, Image* destImage, + const Image* srcImage, const ROI* roi, + int initialStepSize, int finalStepSize, + unsigned char defectPixelValue, + double minClassificationScore); +IMAQ_FUNC int IMAQ_STDCALL imaqClassificationTextureDefectOptions( + ClassifierSession* session, WindowSize* windowOptions, + WaveletOptions* waveletOptions, void** bandsUsed, int* numBandsUsed, + CooccurrenceOptions* cooccurrenceOptions, unsigned char setOperation); +IMAQ_FUNC int IMAQ_STDCALL +imaqCooccurrenceMatrix(const Image* srcImage, const ROI* roi, int levelPixel, + const DisplacementVector* displacementVec, + void* featureOptionArray, + unsigned int featureOptionArraySize, + void** cooccurrenceMatrixArray, + int* coocurrenceMatrixRows, int* coocurrenceMatrixCols, + void** featureVectorArray, int* featureVectorArraySize); +IMAQ_FUNC ExtractTextureFeaturesReport* IMAQ_STDCALL +imaqExtractTextureFeatures(const Image* srcImage, const ROI* roi, + const WindowSize* windowOptions, + const WaveletOptions* waveletOptions, + void* waveletBands, unsigned int numWaveletBands, + const CooccurrenceOptions* cooccurrenceOptions, + unsigned char useWindow); +IMAQ_FUNC WaveletBandsReport* IMAQ_STDCALL +imaqExtractWaveletBands(const Image* srcImage, + const WaveletOptions* waveletOptions, + void* waveletBands, unsigned int numWaveletBands); //============================================================================ // Regions of Interest Manipulation functions //============================================================================ -IMAQ_FUNC ROI* IMAQ_STDCALL imaqMaskToROI(const Image* mask, int* withinLimit); -IMAQ_FUNC ROIProfile* IMAQ_STDCALL imaqROIProfile(const Image* image, const ROI* roi); -IMAQ_FUNC int IMAQ_STDCALL imaqROIToMask(Image* mask, const ROI* roi, int fillValue, const Image* imageModel, int* inSpace); -IMAQ_FUNC int IMAQ_STDCALL imaqTransformROI2(ROI* roi, const CoordinateSystem* baseSystem, const CoordinateSystem* newSystem); -IMAQ_FUNC LabelToROIReport* IMAQ_STDCALL imaqLabelToROI(const Image* image, const unsigned int* labelsIn, unsigned int numLabelsIn, int maxNumVectors, int isExternelEdges); +IMAQ_FUNC ROI* IMAQ_STDCALL imaqMaskToROI(const Image* mask, int* withinLimit); +IMAQ_FUNC ROIProfile* IMAQ_STDCALL +imaqROIProfile(const Image* image, const ROI* roi); +IMAQ_FUNC int IMAQ_STDCALL imaqROIToMask(Image* mask, const ROI* roi, + int fillValue, const Image* imageModel, + int* inSpace); +IMAQ_FUNC int IMAQ_STDCALL imaqTransformROI2(ROI* roi, + const CoordinateSystem* baseSystem, + const CoordinateSystem* newSystem); +IMAQ_FUNC LabelToROIReport* IMAQ_STDCALL +imaqLabelToROI(const Image* image, const unsigned int* labelsIn, + unsigned int numLabelsIn, int maxNumVectors, + int isExternelEdges); //============================================================================ // Morphology functions //============================================================================ -IMAQ_FUNC int IMAQ_STDCALL imaqGrayMorphology(Image* dest, Image* source, MorphologyMethod method, const StructuringElement* structuringElement); +IMAQ_FUNC int IMAQ_STDCALL +imaqGrayMorphology(Image* dest, Image* source, MorphologyMethod method, + const StructuringElement* structuringElement); //============================================================================ // Classification functions //============================================================================ -IMAQ_FUNC int IMAQ_STDCALL imaqAddClassifierSample(Image* image, ClassifierSession* session, const ROI* roi, const char* sampleClass, double* featureVector, unsigned int vectorSize); -IMAQ_FUNC ClassifierReportAdvanced* IMAQ_STDCALL imaqAdvanceClassify(Image* image, const ClassifierSession* session, const ROI* roi, double* featureVector, unsigned int vectorSize); -IMAQ_FUNC ClassifierReport* IMAQ_STDCALL imaqClassify(Image* image, const ClassifierSession* session, const ROI* roi, double* featureVector, unsigned int vectorSize); -IMAQ_FUNC ClassifierSession* IMAQ_STDCALL imaqCreateClassifier(ClassifierType type); -IMAQ_FUNC int IMAQ_STDCALL imaqDeleteClassifierSample(ClassifierSession* session, int index); -IMAQ_FUNC ClassifierAccuracyReport* IMAQ_STDCALL imaqGetClassifierAccuracy(const ClassifierSession* session); -IMAQ_FUNC ClassifierSampleInfo* IMAQ_STDCALL imaqGetClassifierSampleInfo(const ClassifierSession* session, int index, int* numSamples); -IMAQ_FUNC int IMAQ_STDCALL imaqGetColorClassifierOptions(const ClassifierSession* session, ColorOptions* options); -IMAQ_FUNC int IMAQ_STDCALL imaqGetNearestNeighborOptions(const ClassifierSession* session, NearestNeighborOptions* options); -IMAQ_FUNC int IMAQ_STDCALL imaqGetParticleClassifierOptions2(const ClassifierSession* session, ParticleClassifierPreprocessingOptions2* preprocessingOptions, ParticleClassifierOptions* options); -IMAQ_FUNC ClassifierSession* IMAQ_STDCALL imaqReadClassifierFile(ClassifierSession* session, const char* fileName, ReadClassifierFileMode mode, ClassifierType* type, ClassifierEngineType* engine, String255 description); -IMAQ_FUNC int IMAQ_STDCALL imaqRelabelClassifierSample(ClassifierSession* session, int index, const char* newClass); -IMAQ_FUNC int IMAQ_STDCALL imaqSetParticleClassifierOptions2(ClassifierSession* session, const ParticleClassifierPreprocessingOptions2* preprocessingOptions, const ParticleClassifierOptions* options); -IMAQ_FUNC int IMAQ_STDCALL imaqSetColorClassifierOptions(ClassifierSession* session, const ColorOptions* options); -IMAQ_FUNC NearestNeighborTrainingReport* IMAQ_STDCALL imaqTrainNearestNeighborClassifier(ClassifierSession* session, const NearestNeighborOptions* options); -IMAQ_FUNC int IMAQ_STDCALL imaqWriteClassifierFile(const ClassifierSession* session, const char* fileName, WriteClassifierFileMode mode, const String255 description); +IMAQ_FUNC int IMAQ_STDCALL +imaqAddClassifierSample(Image* image, ClassifierSession* session, + const ROI* roi, const char* sampleClass, + double* featureVector, unsigned int vectorSize); +IMAQ_FUNC ClassifierReportAdvanced* IMAQ_STDCALL +imaqAdvanceClassify(Image* image, const ClassifierSession* session, + const ROI* roi, double* featureVector, + unsigned int vectorSize); +IMAQ_FUNC ClassifierReport* IMAQ_STDCALL +imaqClassify(Image* image, const ClassifierSession* session, const ROI* roi, + double* featureVector, unsigned int vectorSize); +IMAQ_FUNC ClassifierSession* IMAQ_STDCALL +imaqCreateClassifier(ClassifierType type); +IMAQ_FUNC int IMAQ_STDCALL +imaqDeleteClassifierSample(ClassifierSession* session, int index); +IMAQ_FUNC ClassifierAccuracyReport* IMAQ_STDCALL +imaqGetClassifierAccuracy(const ClassifierSession* session); +IMAQ_FUNC ClassifierSampleInfo* IMAQ_STDCALL +imaqGetClassifierSampleInfo(const ClassifierSession* session, int index, + int* numSamples); +IMAQ_FUNC int IMAQ_STDCALL +imaqGetColorClassifierOptions(const ClassifierSession* session, + ColorOptions* options); +IMAQ_FUNC int IMAQ_STDCALL +imaqGetNearestNeighborOptions(const ClassifierSession* session, + NearestNeighborOptions* options); +IMAQ_FUNC int IMAQ_STDCALL imaqGetParticleClassifierOptions2( + const ClassifierSession* session, + ParticleClassifierPreprocessingOptions2* preprocessingOptions, + ParticleClassifierOptions* options); +IMAQ_FUNC ClassifierSession* IMAQ_STDCALL +imaqReadClassifierFile(ClassifierSession* session, const char* fileName, + ReadClassifierFileMode mode, ClassifierType* type, + ClassifierEngineType* engine, String255 description); +IMAQ_FUNC int IMAQ_STDCALL +imaqRelabelClassifierSample(ClassifierSession* session, int index, + const char* newClass); +IMAQ_FUNC int IMAQ_STDCALL imaqSetParticleClassifierOptions2( + ClassifierSession* session, + const ParticleClassifierPreprocessingOptions2* preprocessingOptions, + const ParticleClassifierOptions* options); +IMAQ_FUNC int IMAQ_STDCALL +imaqSetColorClassifierOptions(ClassifierSession* session, + const ColorOptions* options); +IMAQ_FUNC NearestNeighborTrainingReport* IMAQ_STDCALL +imaqTrainNearestNeighborClassifier(ClassifierSession* session, + const NearestNeighborOptions* options); +IMAQ_FUNC int IMAQ_STDCALL +imaqWriteClassifierFile(const ClassifierSession* session, const char* fileName, + WriteClassifierFileMode mode, + const String255 description); //============================================================================ // Measure Distances functions //============================================================================ -IMAQ_FUNC ClampMax2Report* IMAQ_STDCALL imaqClampMax2(Image* image, const ROI* roi, const CoordinateSystem* baseSystem, const CoordinateSystem* newSystem, const CurveOptions* curveSettings, const ClampSettings* clampSettings, const ClampOverlaySettings* clampOverlaySettings); +IMAQ_FUNC ClampMax2Report* IMAQ_STDCALL +imaqClampMax2(Image* image, const ROI* roi, const CoordinateSystem* baseSystem, + const CoordinateSystem* newSystem, + const CurveOptions* curveSettings, + const ClampSettings* clampSettings, + const ClampOverlaySettings* clampOverlaySettings); //============================================================================ // Inspection functions //============================================================================ -IMAQ_FUNC int IMAQ_STDCALL imaqCompareGoldenTemplate(const Image* image, const Image* goldenTemplate, Image* brightDefects, Image* darkDefects, const InspectionAlignment* alignment, const InspectionOptions* options); -IMAQ_FUNC int IMAQ_STDCALL imaqLearnGoldenTemplate(Image* goldenTemplate, PointFloat originOffset, const Image* mask); +IMAQ_FUNC int IMAQ_STDCALL +imaqCompareGoldenTemplate(const Image* image, const Image* goldenTemplate, + Image* brightDefects, Image* darkDefects, + const InspectionAlignment* alignment, + const InspectionOptions* options); +IMAQ_FUNC int IMAQ_STDCALL imaqLearnGoldenTemplate(Image* goldenTemplate, + PointFloat originOffset, + const Image* mask); //============================================================================ // Obsolete functions //============================================================================ -IMAQ_FUNC int IMAQ_STDCALL imaqRotate(Image* dest, const Image* source, float angle, PixelValue fill, InterpolationMethod method); -IMAQ_FUNC int IMAQ_STDCALL imaqWritePNGFile(const Image* image, const char* fileName, unsigned int compressionSpeed, const RGBValue* colorTable); -IMAQ_FUNC ParticleReport* IMAQ_STDCALL imaqSelectParticles(const Image* image, const ParticleReport* reports, int reportCount, int rejectBorder, const SelectParticleCriteria* criteria, int criteriaCount, int* selectedCount); -IMAQ_FUNC int IMAQ_STDCALL imaqParticleFilter(Image* dest, Image* source, const ParticleFilterCriteria* criteria, int criteriaCount, int rejectMatches, int connectivity8); -IMAQ_FUNC ParticleReport* IMAQ_STDCALL imaqGetParticleInfo(Image* image, int connectivity8, ParticleInfoMode mode, int* reportCount); -IMAQ_FUNC int IMAQ_STDCALL imaqCalcCoeff(const Image* image, const ParticleReport* report, MeasurementValue parameter, float* coefficient); -IMAQ_FUNC EdgeReport* IMAQ_STDCALL imaqEdgeTool(const Image* image, const Point* points, int numPoints, const EdgeOptions* options, int* numEdges); -IMAQ_FUNC CircleReport* IMAQ_STDCALL imaqCircles(Image* dest, const Image* source, float minRadius, float maxRadius, int* numCircles); -IMAQ_FUNC int IMAQ_STDCALL imaqLabel(Image* dest, Image* source, int connectivity8, int* particleCount); -IMAQ_FUNC int IMAQ_STDCALL imaqFitEllipse(const PointFloat* points, int numPoints, BestEllipse* ellipse); -IMAQ_FUNC int IMAQ_STDCALL imaqFitCircle(const PointFloat* points, int numPoints, BestCircle* circle); -IMAQ_FUNC Color IMAQ_STDCALL imaqChangeColorSpace(const Color* sourceColor, ColorMode sourceSpace, ColorMode destSpace); -IMAQ_FUNC PatternMatch* IMAQ_STDCALL imaqMatchPattern(const Image* image, Image* pattern, const MatchPatternOptions* options, Rect searchRect, int* numMatches); -IMAQ_FUNC int IMAQ_STDCALL imaqConvex(Image* dest, const Image* source); -IMAQ_FUNC int IMAQ_STDCALL imaqIsVisionInfoPresent(const Image* image, VisionInfoType type, int* present); -IMAQ_FUNC int IMAQ_STDCALL imaqLineGaugeTool(const Image* image, Point start, Point end, LineGaugeMethod method, const EdgeOptions* edgeOptions, const CoordinateTransform* reference, float* distance); -IMAQ_FUNC int IMAQ_STDCALL imaqBestCircle(const PointFloat* points, int numPoints, PointFloat* center, double* radius); -IMAQ_FUNC int IMAQ_STDCALL imaqSavePattern(const Image* pattern, const char* fileName); -IMAQ_FUNC int IMAQ_STDCALL imaqLoadPattern(Image* pattern, const char* fileName); -IMAQ_FUNC int IMAQ_STDCALL imaqTransformROI(ROI* roi, Point originStart, float angleStart, Point originFinal, float angleFinal); -IMAQ_FUNC int IMAQ_STDCALL imaqCoordinateReference(const Point* points, ReferenceMode mode, Point* origin, float* angle); -IMAQ_FUNC ContourInfo* IMAQ_STDCALL imaqGetContourInfo(const ROI* roi, ContourID id); -IMAQ_FUNC int IMAQ_STDCALL imaqSetWindowOverlay(int windowNumber, const Overlay* overlay); -IMAQ_FUNC Overlay* IMAQ_STDCALL imaqCreateOverlayFromROI(const ROI* roi); -IMAQ_FUNC Overlay* IMAQ_STDCALL imaqCreateOverlayFromMetafile(const void* metafile); -IMAQ_FUNC int IMAQ_STDCALL imaqSetCalibrationInfo(Image* image, CalibrationUnit unit, float xDistance, float yDistance); -IMAQ_FUNC int IMAQ_STDCALL imaqGetCalibrationInfo(const Image* image, CalibrationUnit* unit, float* xDistance, float* yDistance); -IMAQ_FUNC int IMAQ_STDCALL imaqConstructROI(const Image* image, ROI* roi, Tool initialTool, const ToolWindowOptions* tools, const ConstructROIOptions* options, int* okay); -IMAQ_FUNC int IMAQ_STDCALL imaqGetParticleClassifierOptions(const ClassifierSession* session, ParticleClassifierPreprocessingOptions* preprocessingOptions, ParticleClassifierOptions* options); -IMAQ_FUNC int IMAQ_STDCALL imaqZoomWindow(int windowNumber, int xZoom, int yZoom, Point center); -IMAQ_FUNC int IMAQ_STDCALL imaqGetWindowZoom(int windowNumber, int* xZoom, int* yZoom); -IMAQ_FUNC int IMAQ_STDCALL imaqParticleFilter3(Image* dest, Image* source, const ParticleFilterCriteria2* criteria, int criteriaCount, const ParticleFilterOptions* options, const ROI* roi, int* numParticles); -IMAQ_FUNC ReadTextReport2* IMAQ_STDCALL imaqReadText2(const Image* image, const CharSet* set, const ROI* roi, const ReadTextOptions* readOptions, const OCRProcessingOptions* processingOptions, const OCRSpacingOptions* spacingOptions); -IMAQ_FUNC int IMAQ_STDCALL imaqLearnPattern2(Image* image, LearningMode learningMode, LearnPatternAdvancedOptions* advancedOptions); -IMAQ_FUNC int IMAQ_STDCALL imaqConvolve(Image* dest, Image* source, const float* kernel, int matrixRows, int matrixCols, float normalize, const Image* mask); -IMAQ_FUNC int IMAQ_STDCALL imaqDivideConstant(Image* dest, const Image* source, PixelValue value); -IMAQ_FUNC int IMAQ_STDCALL imaqDivide(Image* dest, const Image* sourceA, const Image* sourceB); -IMAQ_FUNC EdgeReport2* IMAQ_STDCALL imaqEdgeTool3(const Image* image, const ROI* roi, EdgeProcess processType, const EdgeOptions2* edgeOptions); -IMAQ_FUNC ConcentricRakeReport* IMAQ_STDCALL imaqConcentricRake(const Image* image, const ROI* roi, ConcentricRakeDirection direction, EdgeProcess process, const RakeOptions* options); -IMAQ_FUNC SpokeReport* IMAQ_STDCALL imaqSpoke(const Image* image, const ROI* roi, SpokeDirection direction, EdgeProcess process, const SpokeOptions* options); -IMAQ_FUNC int IMAQ_STDCALL imaqLearnPattern(Image* image, LearningMode learningMode); -IMAQ_FUNC int IMAQ_STDCALL imaqLookup(Image* dest, const Image* source, const short* table, const Image* mask); -IMAQ_FUNC PatternMatch* IMAQ_STDCALL imaqMatchPattern2(const Image* image, const Image* pattern, const MatchPatternOptions* options, const MatchPatternAdvancedOptions* advancedOptions, Rect searchRect, int* numMatches); -IMAQ_FUNC int IMAQ_STDCALL imaqSetParticleClassifierOptions(ClassifierSession* session, const ParticleClassifierPreprocessingOptions* preprocessingOptions, const ParticleClassifierOptions* options); -IMAQ_FUNC int IMAQ_STDCALL imaqCopyCalibrationInfo(Image* dest, const Image* source); -IMAQ_FUNC int IMAQ_STDCALL imaqParticleFilter2(Image* dest, Image* source, const ParticleFilterCriteria2* criteria, int criteriaCount, int rejectMatches, int connectivity8, int* numParticles); -IMAQ_FUNC EdgeReport* IMAQ_STDCALL imaqEdgeTool2(const Image* image, const Point* points, int numPoints, EdgeProcess process, const EdgeOptions* options, int* numEdges); -IMAQ_FUNC ContourID IMAQ_STDCALL imaqAddRotatedRectContour(ROI* roi, RotatedRect rect); -IMAQ_FUNC Barcode2DInfo* IMAQ_STDCALL imaqReadDataMatrixBarcode(const Image* image, const ROI* roi, const DataMatrixOptions* options, unsigned int* numBarcodes); -IMAQ_FUNC LinearAverages* IMAQ_STDCALL imaqLinearAverages(const Image* image, Rect rect); -IMAQ_FUNC GeometricPatternMatch* IMAQ_STDCALL imaqMatchGeometricPattern(const Image* image, const Image* pattern, const CurveOptions* curveOptions, const MatchGeometricPatternOptions* matchOptions, const MatchGeometricPatternAdvancedOptions* advancedMatchOptions, const ROI* roi, int* numMatches); -IMAQ_FUNC CharInfo* IMAQ_STDCALL imaqGetCharInfo(const CharSet* set, int index); -IMAQ_FUNC ReadTextReport* IMAQ_STDCALL imaqReadText(const Image* image, const CharSet* set, const ROI* roi, const ReadTextOptions* readOptions, const OCRProcessingOptions* processingOptions, const OCRSpacingOptions* spacingOptions); -IMAQ_FUNC ThresholdData* IMAQ_STDCALL imaqAutoThreshold(Image* dest, Image* source, int numClasses, ThresholdMethod method); -IMAQ_FUNC ColorHistogramReport* IMAQ_STDCALL imaqColorHistogram(Image* image, int numClasses, ColorMode mode, const Image* mask); -IMAQ_FUNC RakeReport* IMAQ_STDCALL imaqRake(const Image* image, const ROI* roi, RakeDirection direction, EdgeProcess process, const RakeOptions* options); +IMAQ_FUNC int IMAQ_STDCALL imaqRotate(Image* dest, const Image* source, + float angle, PixelValue fill, + InterpolationMethod method); +IMAQ_FUNC int IMAQ_STDCALL +imaqWritePNGFile(const Image* image, const char* fileName, + unsigned int compressionSpeed, const RGBValue* colorTable); +IMAQ_FUNC ParticleReport* IMAQ_STDCALL +imaqSelectParticles(const Image* image, const ParticleReport* reports, + int reportCount, int rejectBorder, + const SelectParticleCriteria* criteria, int criteriaCount, + int* selectedCount); +IMAQ_FUNC int IMAQ_STDCALL +imaqParticleFilter(Image* dest, Image* source, + const ParticleFilterCriteria* criteria, int criteriaCount, + int rejectMatches, int connectivity8); +IMAQ_FUNC ParticleReport* IMAQ_STDCALL +imaqGetParticleInfo(Image* image, int connectivity8, ParticleInfoMode mode, + int* reportCount); +IMAQ_FUNC int IMAQ_STDCALL +imaqCalcCoeff(const Image* image, const ParticleReport* report, + MeasurementValue parameter, float* coefficient); +IMAQ_FUNC EdgeReport* IMAQ_STDCALL +imaqEdgeTool(const Image* image, const Point* points, int numPoints, + const EdgeOptions* options, int* numEdges); +IMAQ_FUNC CircleReport* IMAQ_STDCALL +imaqCircles(Image* dest, const Image* source, float minRadius, float maxRadius, + int* numCircles); +IMAQ_FUNC int IMAQ_STDCALL +imaqLabel(Image* dest, Image* source, int connectivity8, int* particleCount); +IMAQ_FUNC int IMAQ_STDCALL +imaqFitEllipse(const PointFloat* points, int numPoints, BestEllipse* ellipse); +IMAQ_FUNC int IMAQ_STDCALL +imaqFitCircle(const PointFloat* points, int numPoints, BestCircle* circle); +IMAQ_FUNC Color IMAQ_STDCALL imaqChangeColorSpace(const Color* sourceColor, + ColorMode sourceSpace, + ColorMode destSpace); +IMAQ_FUNC PatternMatch* IMAQ_STDCALL +imaqMatchPattern(const Image* image, Image* pattern, + const MatchPatternOptions* options, Rect searchRect, + int* numMatches); +IMAQ_FUNC int IMAQ_STDCALL imaqConvex(Image* dest, const Image* source); +IMAQ_FUNC int IMAQ_STDCALL +imaqIsVisionInfoPresent(const Image* image, VisionInfoType type, int* present); +IMAQ_FUNC int IMAQ_STDCALL +imaqLineGaugeTool(const Image* image, Point start, Point end, + LineGaugeMethod method, const EdgeOptions* edgeOptions, + const CoordinateTransform* reference, float* distance); +IMAQ_FUNC int IMAQ_STDCALL imaqBestCircle(const PointFloat* points, + int numPoints, PointFloat* center, + double* radius); +IMAQ_FUNC int IMAQ_STDCALL +imaqSavePattern(const Image* pattern, const char* fileName); +IMAQ_FUNC int IMAQ_STDCALL +imaqLoadPattern(Image* pattern, const char* fileName); +IMAQ_FUNC int IMAQ_STDCALL imaqTransformROI(ROI* roi, Point originStart, + float angleStart, Point originFinal, + float angleFinal); +IMAQ_FUNC int IMAQ_STDCALL imaqCoordinateReference(const Point* points, + ReferenceMode mode, + Point* origin, float* angle); +IMAQ_FUNC ContourInfo* IMAQ_STDCALL +imaqGetContourInfo(const ROI* roi, ContourID id); +IMAQ_FUNC int IMAQ_STDCALL +imaqSetWindowOverlay(int windowNumber, const Overlay* overlay); +IMAQ_FUNC Overlay* IMAQ_STDCALL imaqCreateOverlayFromROI(const ROI* roi); +IMAQ_FUNC Overlay* IMAQ_STDCALL +imaqCreateOverlayFromMetafile(const void* metafile); +IMAQ_FUNC int IMAQ_STDCALL +imaqSetCalibrationInfo(Image* image, CalibrationUnit unit, float xDistance, + float yDistance); +IMAQ_FUNC int IMAQ_STDCALL +imaqGetCalibrationInfo(const Image* image, CalibrationUnit* unit, + float* xDistance, float* yDistance); +IMAQ_FUNC int IMAQ_STDCALL +imaqConstructROI(const Image* image, ROI* roi, Tool initialTool, + const ToolWindowOptions* tools, + const ConstructROIOptions* options, int* okay); +IMAQ_FUNC int IMAQ_STDCALL imaqGetParticleClassifierOptions( + const ClassifierSession* session, + ParticleClassifierPreprocessingOptions* preprocessingOptions, + ParticleClassifierOptions* options); +IMAQ_FUNC int IMAQ_STDCALL +imaqZoomWindow(int windowNumber, int xZoom, int yZoom, Point center); +IMAQ_FUNC int IMAQ_STDCALL +imaqGetWindowZoom(int windowNumber, int* xZoom, int* yZoom); +IMAQ_FUNC int IMAQ_STDCALL +imaqParticleFilter3(Image* dest, Image* source, + const ParticleFilterCriteria2* criteria, int criteriaCount, + const ParticleFilterOptions* options, const ROI* roi, + int* numParticles); +IMAQ_FUNC ReadTextReport2* IMAQ_STDCALL +imaqReadText2(const Image* image, const CharSet* set, const ROI* roi, + const ReadTextOptions* readOptions, + const OCRProcessingOptions* processingOptions, + const OCRSpacingOptions* spacingOptions); +IMAQ_FUNC int IMAQ_STDCALL +imaqLearnPattern2(Image* image, LearningMode learningMode, + LearnPatternAdvancedOptions* advancedOptions); +IMAQ_FUNC int IMAQ_STDCALL +imaqConvolve(Image* dest, Image* source, const float* kernel, int matrixRows, + int matrixCols, float normalize, const Image* mask); +IMAQ_FUNC int IMAQ_STDCALL +imaqDivideConstant(Image* dest, const Image* source, PixelValue value); +IMAQ_FUNC int IMAQ_STDCALL +imaqDivide(Image* dest, const Image* sourceA, const Image* sourceB); +IMAQ_FUNC EdgeReport2* IMAQ_STDCALL +imaqEdgeTool3(const Image* image, const ROI* roi, EdgeProcess processType, + const EdgeOptions2* edgeOptions); +IMAQ_FUNC ConcentricRakeReport* IMAQ_STDCALL +imaqConcentricRake(const Image* image, const ROI* roi, + ConcentricRakeDirection direction, EdgeProcess process, + const RakeOptions* options); +IMAQ_FUNC SpokeReport* IMAQ_STDCALL +imaqSpoke(const Image* image, const ROI* roi, SpokeDirection direction, + EdgeProcess process, const SpokeOptions* options); +IMAQ_FUNC int IMAQ_STDCALL +imaqLearnPattern(Image* image, LearningMode learningMode); +IMAQ_FUNC int IMAQ_STDCALL imaqLookup(Image* dest, const Image* source, + const short* table, const Image* mask); +IMAQ_FUNC PatternMatch* IMAQ_STDCALL +imaqMatchPattern2(const Image* image, const Image* pattern, + const MatchPatternOptions* options, + const MatchPatternAdvancedOptions* advancedOptions, + Rect searchRect, int* numMatches); +IMAQ_FUNC int IMAQ_STDCALL imaqSetParticleClassifierOptions( + ClassifierSession* session, + const ParticleClassifierPreprocessingOptions* preprocessingOptions, + const ParticleClassifierOptions* options); +IMAQ_FUNC int IMAQ_STDCALL +imaqCopyCalibrationInfo(Image* dest, const Image* source); +IMAQ_FUNC int IMAQ_STDCALL +imaqParticleFilter2(Image* dest, Image* source, + const ParticleFilterCriteria2* criteria, int criteriaCount, + int rejectMatches, int connectivity8, int* numParticles); +IMAQ_FUNC EdgeReport* IMAQ_STDCALL +imaqEdgeTool2(const Image* image, const Point* points, int numPoints, + EdgeProcess process, const EdgeOptions* options, int* numEdges); +IMAQ_FUNC ContourID IMAQ_STDCALL +imaqAddRotatedRectContour(ROI* roi, RotatedRect rect); +IMAQ_FUNC Barcode2DInfo* IMAQ_STDCALL +imaqReadDataMatrixBarcode(const Image* image, const ROI* roi, + const DataMatrixOptions* options, + unsigned int* numBarcodes); +IMAQ_FUNC LinearAverages* IMAQ_STDCALL +imaqLinearAverages(const Image* image, Rect rect); +IMAQ_FUNC GeometricPatternMatch* IMAQ_STDCALL imaqMatchGeometricPattern( + const Image* image, const Image* pattern, const CurveOptions* curveOptions, + const MatchGeometricPatternOptions* matchOptions, + const MatchGeometricPatternAdvancedOptions* advancedMatchOptions, + const ROI* roi, int* numMatches); +IMAQ_FUNC CharInfo* IMAQ_STDCALL imaqGetCharInfo(const CharSet* set, int index); +IMAQ_FUNC ReadTextReport* IMAQ_STDCALL +imaqReadText(const Image* image, const CharSet* set, const ROI* roi, + const ReadTextOptions* readOptions, + const OCRProcessingOptions* processingOptions, + const OCRSpacingOptions* spacingOptions); +IMAQ_FUNC ThresholdData* IMAQ_STDCALL +imaqAutoThreshold(Image* dest, Image* source, int numClasses, + ThresholdMethod method); +IMAQ_FUNC ColorHistogramReport* IMAQ_STDCALL +imaqColorHistogram(Image* image, int numClasses, ColorMode mode, + const Image* mask); +IMAQ_FUNC RakeReport* IMAQ_STDCALL +imaqRake(const Image* image, const ROI* roi, RakeDirection direction, + EdgeProcess process, const RakeOptions* options); -IMAQ_FUNC int IMAQ_STDCALL Priv_ReadJPEGString_C(Image* image, const unsigned char* string, unsigned int stringLength); +IMAQ_FUNC int IMAQ_STDCALL Priv_ReadJPEGString_C(Image* image, + const unsigned char* string, + unsigned int stringLength); #endif - diff --git a/wpilibc/wpilibC++Devices/include/pcre.h b/wpilibc/wpilibC++Devices/include/pcre.h index f8ddcbf101..0605461c51 100644 --- a/wpilibc/wpilibC++Devices/include/pcre.h +++ b/wpilibc/wpilibC++Devices/include/pcre.h @@ -41,10 +41,10 @@ POSSIBILITY OF SUCH DAMAGE. /* The current PCRE version information. */ -#define PCRE_MAJOR 7 -#define PCRE_MINOR 8 -#define PCRE_PRERELEASE -#define PCRE_DATE 2008-09-05 +#define PCRE_MAJOR 7 +#define PCRE_MINOR 8 +#define PCRE_PRERELEASE +#define PCRE_DATE 2008 - 09 - 05 /* When an application links to a PCRE DLL in Windows, the symbols that are imported have to be identified as such. When building PCRE, the appropriate @@ -63,36 +63,36 @@ don't change existing definitions of PCRE_EXP_DECL and PCRECPP_EXP_DECL. */ #define PCRE_STATIC #if defined(_WIN32) && !defined(PCRE_STATIC) -# ifndef PCRE_EXP_DECL -# define PCRE_EXP_DECL extern __declspec(dllimport) -# endif -# ifdef __cplusplus -# ifndef PCRECPP_EXP_DECL -# define PCRECPP_EXP_DECL extern __declspec(dllimport) -# endif -# ifndef PCRECPP_EXP_DEFN -# define PCRECPP_EXP_DEFN __declspec(dllimport) -# endif -# endif +#ifndef PCRE_EXP_DECL +#define PCRE_EXP_DECL extern __declspec(dllimport) +#endif +#ifdef __cplusplus +#ifndef PCRECPP_EXP_DECL +#define PCRECPP_EXP_DECL extern __declspec(dllimport) +#endif +#ifndef PCRECPP_EXP_DEFN +#define PCRECPP_EXP_DEFN __declspec(dllimport) +#endif +#endif #endif /* By default, we use the standard "extern" declarations. */ #ifndef PCRE_EXP_DECL -# ifdef __cplusplus -# define PCRE_EXP_DECL extern "C" -# else -# define PCRE_EXP_DECL extern -# endif +#ifdef __cplusplus +#define PCRE_EXP_DECL extern "C" +#else +#define PCRE_EXP_DECL extern +#endif #endif #ifdef __cplusplus -# ifndef PCRECPP_EXP_DECL -# define PCRECPP_EXP_DECL extern -# endif -# ifndef PCRECPP_EXP_DEFN -# define PCRECPP_EXP_DEFN -# endif +#ifndef PCRECPP_EXP_DECL +#define PCRECPP_EXP_DECL extern +#endif +#ifndef PCRECPP_EXP_DEFN +#define PCRECPP_EXP_DEFN +#endif #endif /** @@ -109,13 +109,13 @@ don't change existing definitions of PCRE_EXP_DECL and PCRECPP_EXP_DECL. */ * Adam Kemp 12/15/2008 */ #ifndef PCRE_CALL_CONVENTION -# if defined(_WIN32) /* 32-bit and 64-bit */ -# define PCRE_CALL_CONVENTION __cdecl -# else -# define PCRE_CALL_CONVENTION -# endif +#if defined(_WIN32) /* 32-bit and 64-bit */ +#define PCRE_CALL_CONVENTION __cdecl #else -# define PCRE_CALL_CONVENTION +#define PCRE_CALL_CONVENTION +#endif +#else +#define PCRE_CALL_CONVENTION #endif /* Have to include stdlib.h in order to ensure that size_t is defined; @@ -131,106 +131,106 @@ extern "C" { /* Options */ -#define PCRE_CASELESS 0x00000001 -#define PCRE_MULTILINE 0x00000002 -#define PCRE_DOTALL 0x00000004 -#define PCRE_EXTENDED 0x00000008 -#define PCRE_ANCHORED 0x00000010 -#define PCRE_DOLLAR_ENDONLY 0x00000020 -#define PCRE_EXTRA 0x00000040 -#define PCRE_NOTBOL 0x00000080 -#define PCRE_NOTEOL 0x00000100 -#define PCRE_UNGREEDY 0x00000200 -#define PCRE_NOTEMPTY 0x00000400 -#define PCRE_UTF8 0x00000800 -#define PCRE_NO_AUTO_CAPTURE 0x00001000 -#define PCRE_NO_UTF8_CHECK 0x00002000 -#define PCRE_AUTO_CALLOUT 0x00004000 -#define PCRE_PARTIAL 0x00008000 -#define PCRE_DFA_SHORTEST 0x00010000 -#define PCRE_DFA_RESTART 0x00020000 -#define PCRE_FIRSTLINE 0x00040000 -#define PCRE_DUPNAMES 0x00080000 -#define PCRE_NEWLINE_CR 0x00100000 -#define PCRE_NEWLINE_LF 0x00200000 -#define PCRE_NEWLINE_CRLF 0x00300000 -#define PCRE_NEWLINE_ANY 0x00400000 -#define PCRE_NEWLINE_ANYCRLF 0x00500000 -#define PCRE_BSR_ANYCRLF 0x00800000 -#define PCRE_BSR_UNICODE 0x01000000 -#define PCRE_JAVASCRIPT_COMPAT 0x02000000 +#define PCRE_CASELESS 0x00000001 +#define PCRE_MULTILINE 0x00000002 +#define PCRE_DOTALL 0x00000004 +#define PCRE_EXTENDED 0x00000008 +#define PCRE_ANCHORED 0x00000010 +#define PCRE_DOLLAR_ENDONLY 0x00000020 +#define PCRE_EXTRA 0x00000040 +#define PCRE_NOTBOL 0x00000080 +#define PCRE_NOTEOL 0x00000100 +#define PCRE_UNGREEDY 0x00000200 +#define PCRE_NOTEMPTY 0x00000400 +#define PCRE_UTF8 0x00000800 +#define PCRE_NO_AUTO_CAPTURE 0x00001000 +#define PCRE_NO_UTF8_CHECK 0x00002000 +#define PCRE_AUTO_CALLOUT 0x00004000 +#define PCRE_PARTIAL 0x00008000 +#define PCRE_DFA_SHORTEST 0x00010000 +#define PCRE_DFA_RESTART 0x00020000 +#define PCRE_FIRSTLINE 0x00040000 +#define PCRE_DUPNAMES 0x00080000 +#define PCRE_NEWLINE_CR 0x00100000 +#define PCRE_NEWLINE_LF 0x00200000 +#define PCRE_NEWLINE_CRLF 0x00300000 +#define PCRE_NEWLINE_ANY 0x00400000 +#define PCRE_NEWLINE_ANYCRLF 0x00500000 +#define PCRE_BSR_ANYCRLF 0x00800000 +#define PCRE_BSR_UNICODE 0x01000000 +#define PCRE_JAVASCRIPT_COMPAT 0x02000000 /* Exec-time and get/set-time error codes */ -#define PCRE_ERROR_NOMATCH (-1) -#define PCRE_ERROR_NULL (-2) -#define PCRE_ERROR_BADOPTION (-3) -#define PCRE_ERROR_BADMAGIC (-4) -#define PCRE_ERROR_UNKNOWN_OPCODE (-5) -#define PCRE_ERROR_UNKNOWN_NODE (-5) /* For backward compatibility */ -#define PCRE_ERROR_NOMEMORY (-6) -#define PCRE_ERROR_NOSUBSTRING (-7) -#define PCRE_ERROR_MATCHLIMIT (-8) -#define PCRE_ERROR_CALLOUT (-9) /* Never used by PCRE itself */ -#define PCRE_ERROR_BADUTF8 (-10) +#define PCRE_ERROR_NOMATCH (-1) +#define PCRE_ERROR_NULL (-2) +#define PCRE_ERROR_BADOPTION (-3) +#define PCRE_ERROR_BADMAGIC (-4) +#define PCRE_ERROR_UNKNOWN_OPCODE (-5) +#define PCRE_ERROR_UNKNOWN_NODE (-5) /* For backward compatibility */ +#define PCRE_ERROR_NOMEMORY (-6) +#define PCRE_ERROR_NOSUBSTRING (-7) +#define PCRE_ERROR_MATCHLIMIT (-8) +#define PCRE_ERROR_CALLOUT (-9) /* Never used by PCRE itself */ +#define PCRE_ERROR_BADUTF8 (-10) #define PCRE_ERROR_BADUTF8_OFFSET (-11) -#define PCRE_ERROR_PARTIAL (-12) -#define PCRE_ERROR_BADPARTIAL (-13) -#define PCRE_ERROR_INTERNAL (-14) -#define PCRE_ERROR_BADCOUNT (-15) -#define PCRE_ERROR_DFA_UITEM (-16) -#define PCRE_ERROR_DFA_UCOND (-17) -#define PCRE_ERROR_DFA_UMLIMIT (-18) -#define PCRE_ERROR_DFA_WSSIZE (-19) -#define PCRE_ERROR_DFA_RECURSE (-20) +#define PCRE_ERROR_PARTIAL (-12) +#define PCRE_ERROR_BADPARTIAL (-13) +#define PCRE_ERROR_INTERNAL (-14) +#define PCRE_ERROR_BADCOUNT (-15) +#define PCRE_ERROR_DFA_UITEM (-16) +#define PCRE_ERROR_DFA_UCOND (-17) +#define PCRE_ERROR_DFA_UMLIMIT (-18) +#define PCRE_ERROR_DFA_WSSIZE (-19) +#define PCRE_ERROR_DFA_RECURSE (-20) #define PCRE_ERROR_RECURSIONLIMIT (-21) -#define PCRE_ERROR_NULLWSLIMIT (-22) /* No longer actually used */ -#define PCRE_ERROR_BADNEWLINE (-23) +#define PCRE_ERROR_NULLWSLIMIT (-22) /* No longer actually used */ +#define PCRE_ERROR_BADNEWLINE (-23) /* Request types for pcre_fullinfo() */ -#define PCRE_INFO_OPTIONS 0 -#define PCRE_INFO_SIZE 1 -#define PCRE_INFO_CAPTURECOUNT 2 -#define PCRE_INFO_BACKREFMAX 3 -#define PCRE_INFO_FIRSTBYTE 4 -#define PCRE_INFO_FIRSTCHAR 4 /* For backwards compatibility */ -#define PCRE_INFO_FIRSTTABLE 5 -#define PCRE_INFO_LASTLITERAL 6 -#define PCRE_INFO_NAMEENTRYSIZE 7 -#define PCRE_INFO_NAMECOUNT 8 -#define PCRE_INFO_NAMETABLE 9 -#define PCRE_INFO_STUDYSIZE 10 -#define PCRE_INFO_DEFAULT_TABLES 11 -#define PCRE_INFO_OKPARTIAL 12 -#define PCRE_INFO_JCHANGED 13 -#define PCRE_INFO_HASCRORLF 14 +#define PCRE_INFO_OPTIONS 0 +#define PCRE_INFO_SIZE 1 +#define PCRE_INFO_CAPTURECOUNT 2 +#define PCRE_INFO_BACKREFMAX 3 +#define PCRE_INFO_FIRSTBYTE 4 +#define PCRE_INFO_FIRSTCHAR 4 /* For backwards compatibility */ +#define PCRE_INFO_FIRSTTABLE 5 +#define PCRE_INFO_LASTLITERAL 6 +#define PCRE_INFO_NAMEENTRYSIZE 7 +#define PCRE_INFO_NAMECOUNT 8 +#define PCRE_INFO_NAMETABLE 9 +#define PCRE_INFO_STUDYSIZE 10 +#define PCRE_INFO_DEFAULT_TABLES 11 +#define PCRE_INFO_OKPARTIAL 12 +#define PCRE_INFO_JCHANGED 13 +#define PCRE_INFO_HASCRORLF 14 /* Request types for pcre_config(). Do not re-arrange, in order to remain compatible. */ -#define PCRE_CONFIG_UTF8 0 -#define PCRE_CONFIG_NEWLINE 1 -#define PCRE_CONFIG_LINK_SIZE 2 -#define PCRE_CONFIG_POSIX_MALLOC_THRESHOLD 3 -#define PCRE_CONFIG_MATCH_LIMIT 4 -#define PCRE_CONFIG_STACKRECURSE 5 -#define PCRE_CONFIG_UNICODE_PROPERTIES 6 -#define PCRE_CONFIG_MATCH_LIMIT_RECURSION 7 -#define PCRE_CONFIG_BSR 8 +#define PCRE_CONFIG_UTF8 0 +#define PCRE_CONFIG_NEWLINE 1 +#define PCRE_CONFIG_LINK_SIZE 2 +#define PCRE_CONFIG_POSIX_MALLOC_THRESHOLD 3 +#define PCRE_CONFIG_MATCH_LIMIT 4 +#define PCRE_CONFIG_STACKRECURSE 5 +#define PCRE_CONFIG_UNICODE_PROPERTIES 6 +#define PCRE_CONFIG_MATCH_LIMIT_RECURSION 7 +#define PCRE_CONFIG_BSR 8 /* Bit flags for the pcre_extra structure. Do not re-arrange or redefine these bits, just add new ones on the end, in order to remain compatible. */ -#define PCRE_EXTRA_STUDY_DATA 0x0001 -#define PCRE_EXTRA_MATCH_LIMIT 0x0002 -#define PCRE_EXTRA_CALLOUT_DATA 0x0004 -#define PCRE_EXTRA_TABLES 0x0008 -#define PCRE_EXTRA_MATCH_LIMIT_RECURSION 0x0010 +#define PCRE_EXTRA_STUDY_DATA 0x0001 +#define PCRE_EXTRA_MATCH_LIMIT 0x0002 +#define PCRE_EXTRA_CALLOUT_DATA 0x0004 +#define PCRE_EXTRA_TABLES 0x0008 +#define PCRE_EXTRA_MATCH_LIMIT_RECURSION 0x0010 /* Types */ -struct real_pcre; /* declaration; the definition is private */ +struct real_pcre; /* declaration; the definition is private */ typedef struct real_pcre pcre; /* When PCRE is compiled as a C++ library, the subject pointer type can be @@ -246,11 +246,11 @@ such as way as to be extensible. Always add new fields at the end, in order to remain compatible. */ typedef struct pcre_extra { - unsigned long int flags; /* Bits for which fields are set */ - void *study_data; /* Opaque data from pcre_study() */ - unsigned long int match_limit; /* Maximum number of calls to match() */ - void *callout_data; /* Data passed back in callouts */ - const unsigned char *tables; /* Pointer to character tables */ + unsigned long int flags; /* Bits for which fields are set */ + void *study_data; /* Opaque data from pcre_study() */ + unsigned long int match_limit; /* Maximum number of calls to match() */ + void *callout_data; /* Data passed back in callouts */ + const unsigned char *tables; /* Pointer to character tables */ unsigned long int match_limit_recursion; /* Max recursive calls to match() */ } pcre_extra; @@ -260,20 +260,20 @@ without changing the API of the function, thereby allowing old clients to work without modification. */ typedef struct pcre_callout_block { - int version; /* Identifies version of block */ + int version; /* Identifies version of block */ /* ------------------------ Version 0 ------------------------------- */ - int callout_number; /* Number compiled into pattern */ - int *offset_vector; /* The offset vector */ - PCRE_SPTR subject; /* The subject being matched */ - int subject_length; /* The length of the subject */ - int start_match; /* Offset to start of this match attempt */ - int current_position; /* Where we currently are in the subject */ - int capture_top; /* Max current capture */ - int capture_last; /* Most recently closed capture */ - void *callout_data; /* Data passed in with the call */ + int callout_number; /* Number compiled into pattern */ + int *offset_vector; /* The offset vector */ + PCRE_SPTR subject; /* The subject being matched */ + int subject_length; /* The length of the subject */ + int start_match; /* Offset to start of this match attempt */ + int current_position; /* Where we currently are in the subject */ + int capture_top; /* Max current capture */ + int capture_last; /* Most recently closed capture */ + void *callout_data; /* Data passed in with the call */ /* ------------------- Added for Version 1 -------------------------- */ - int pattern_position; /* Offset to next item in the pattern */ - int next_item_length; /* Length of next item in the pattern */ + int pattern_position; /* Offset to next item in the pattern */ + int next_item_length; /* Length of next item in the pattern */ /* ------------------------------------------------------------------ */ } pcre_callout_block; @@ -284,55 +284,62 @@ that is triggered by the (?) regex item. For Virtual Pascal, these definitions have to take another form. */ #ifndef VPCOMPAT -PCRE_EXP_DECL void* (PCRE_CALL_CONVENTION *pcre_malloc)(size_t); -PCRE_EXP_DECL void (PCRE_CALL_CONVENTION *pcre_free)(void *); -PCRE_EXP_DECL void* (PCRE_CALL_CONVENTION *pcre_stack_malloc)(size_t); -PCRE_EXP_DECL void (PCRE_CALL_CONVENTION *pcre_stack_free)(void *); -PCRE_EXP_DECL int (PCRE_CALL_CONVENTION *pcre_callout)(pcre_callout_block *); -#else /* VPCOMPAT */ -PCRE_EXP_DECL void* PCRE_CALL_CONVENTION pcre_malloc(size_t); -PCRE_EXP_DECL void PCRE_CALL_CONVENTION pcre_free(void *); -PCRE_EXP_DECL void* PCRE_CALL_CONVENTION pcre_stack_malloc(size_t); -PCRE_EXP_DECL void PCRE_CALL_CONVENTION pcre_stack_free(void *); -PCRE_EXP_DECL int PCRE_CALL_CONVENTION pcre_callout(pcre_callout_block *); -#endif /* VPCOMPAT */ +PCRE_EXP_DECL void *(PCRE_CALL_CONVENTION *pcre_malloc)(size_t); +PCRE_EXP_DECL void(PCRE_CALL_CONVENTION *pcre_free)(void *); +PCRE_EXP_DECL void *(PCRE_CALL_CONVENTION *pcre_stack_malloc)(size_t); +PCRE_EXP_DECL void(PCRE_CALL_CONVENTION *pcre_stack_free)(void *); +PCRE_EXP_DECL int(PCRE_CALL_CONVENTION *pcre_callout)(pcre_callout_block *); +#else /* VPCOMPAT */ +PCRE_EXP_DECL void *PCRE_CALL_CONVENTION pcre_malloc(size_t); +PCRE_EXP_DECL void PCRE_CALL_CONVENTION pcre_free(void *); +PCRE_EXP_DECL void *PCRE_CALL_CONVENTION pcre_stack_malloc(size_t); +PCRE_EXP_DECL void PCRE_CALL_CONVENTION pcre_stack_free(void *); +PCRE_EXP_DECL int PCRE_CALL_CONVENTION pcre_callout(pcre_callout_block *); +#endif /* VPCOMPAT */ /* Exported PCRE functions */ -PCRE_EXP_DECL pcre* PCRE_CALL_CONVENTION pcre_compile(const char *, int, const char **, int *, - const unsigned char *); -PCRE_EXP_DECL pcre* PCRE_CALL_CONVENTION pcre_compile2(const char *, int, int *, const char **, - int *, const unsigned char *); -PCRE_EXP_DECL int PCRE_CALL_CONVENTION pcre_config(int, void *); -PCRE_EXP_DECL int PCRE_CALL_CONVENTION pcre_copy_named_substring(const pcre *, const char *, - int *, int, const char *, char *, int); -PCRE_EXP_DECL int PCRE_CALL_CONVENTION pcre_copy_substring(const char *, int *, int, int, char *, - int); -PCRE_EXP_DECL int PCRE_CALL_CONVENTION pcre_dfa_exec(const pcre *, const pcre_extra *, - const char *, int, int, int, int *, int , int *, int); -PCRE_EXP_DECL int PCRE_CALL_CONVENTION pcre_exec(const pcre *, const pcre_extra *, PCRE_SPTR, - int, int, int, int *, int); +PCRE_EXP_DECL pcre *PCRE_CALL_CONVENTION +pcre_compile(const char *, int, const char **, int *, const unsigned char *); +PCRE_EXP_DECL pcre *PCRE_CALL_CONVENTION pcre_compile2(const char *, int, int *, + const char **, int *, + const unsigned char *); +PCRE_EXP_DECL int PCRE_CALL_CONVENTION pcre_config(int, void *); +PCRE_EXP_DECL int PCRE_CALL_CONVENTION +pcre_copy_named_substring(const pcre *, const char *, int *, int, const char *, + char *, int); +PCRE_EXP_DECL int PCRE_CALL_CONVENTION +pcre_copy_substring(const char *, int *, int, int, char *, int); +PCRE_EXP_DECL int PCRE_CALL_CONVENTION +pcre_dfa_exec(const pcre *, const pcre_extra *, const char *, int, int, int, + int *, int, int *, int); +PCRE_EXP_DECL int PCRE_CALL_CONVENTION pcre_exec(const pcre *, + const pcre_extra *, PCRE_SPTR, + int, int, int, int *, int); PCRE_EXP_DECL void PCRE_CALL_CONVENTION pcre_free_substring(const char *); PCRE_EXP_DECL void PCRE_CALL_CONVENTION pcre_free_substring_list(const char **); -PCRE_EXP_DECL int PCRE_CALL_CONVENTION pcre_fullinfo(const pcre *, const pcre_extra *, int, - void *); -PCRE_EXP_DECL int PCRE_CALL_CONVENTION pcre_get_named_substring(const pcre *, const char *, - int *, int, const char *, const char **); -PCRE_EXP_DECL int PCRE_CALL_CONVENTION pcre_get_stringnumber(const pcre *, const char *); -PCRE_EXP_DECL int PCRE_CALL_CONVENTION pcre_get_stringtable_entries(const pcre *, const char *, - char **, char **); -PCRE_EXP_DECL int PCRE_CALL_CONVENTION pcre_get_substring(const char *, int *, int, int, - const char **); -PCRE_EXP_DECL int PCRE_CALL_CONVENTION pcre_get_substring_list(const char *, int *, int, - const char ***); -PCRE_EXP_DECL int PCRE_CALL_CONVENTION pcre_info(const pcre *, int *, int *); -PCRE_EXP_DECL const unsigned char* PCRE_CALL_CONVENTION pcre_maketables(void); -PCRE_EXP_DECL int PCRE_CALL_CONVENTION pcre_refcount(pcre *, int); -PCRE_EXP_DECL pcre_extra* PCRE_CALL_CONVENTION pcre_study(const pcre *, int, const char **); -PCRE_EXP_DECL const char* PCRE_CALL_CONVENTION pcre_version(void); +PCRE_EXP_DECL int PCRE_CALL_CONVENTION +pcre_fullinfo(const pcre *, const pcre_extra *, int, void *); +PCRE_EXP_DECL int PCRE_CALL_CONVENTION +pcre_get_named_substring(const pcre *, const char *, int *, int, const char *, + const char **); +PCRE_EXP_DECL int PCRE_CALL_CONVENTION +pcre_get_stringnumber(const pcre *, const char *); +PCRE_EXP_DECL int PCRE_CALL_CONVENTION +pcre_get_stringtable_entries(const pcre *, const char *, char **, char **); +PCRE_EXP_DECL int PCRE_CALL_CONVENTION +pcre_get_substring(const char *, int *, int, int, const char **); +PCRE_EXP_DECL int PCRE_CALL_CONVENTION +pcre_get_substring_list(const char *, int *, int, const char ***); +PCRE_EXP_DECL int PCRE_CALL_CONVENTION pcre_info(const pcre *, int *, int *); +PCRE_EXP_DECL const unsigned char *PCRE_CALL_CONVENTION pcre_maketables(void); +PCRE_EXP_DECL int PCRE_CALL_CONVENTION pcre_refcount(pcre *, int); +PCRE_EXP_DECL pcre_extra *PCRE_CALL_CONVENTION +pcre_study(const pcre *, int, const char **); +PCRE_EXP_DECL const char *PCRE_CALL_CONVENTION pcre_version(void); #ifdef __cplusplus -} /* extern "C" */ +} /* extern "C" */ #endif #endif /* End of pcre.h */ diff --git a/wpilibc/wpilibC++Devices/src/ADXL345_I2C.cpp b/wpilibc/wpilibC++Devices/src/ADXL345_I2C.cpp index 785da79511..4943c93fad 100644 --- a/wpilibc/wpilibC++Devices/src/ADXL345_I2C.cpp +++ b/wpilibc/wpilibC++Devices/src/ADXL345_I2C.cpp @@ -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. */ /*----------------------------------------------------------------------------*/ @@ -21,52 +22,40 @@ constexpr double ADXL345_I2C::kGsPerLSB; * @param port The I2C port the accelerometer is attached to * @param range The range (+ or -) that the accelerometer will measure. */ -ADXL345_I2C::ADXL345_I2C(Port port, Range range): - I2C(port, kAddress) -{ - //m_i2c = new I2C((I2C::Port)port, kAddress); +ADXL345_I2C::ADXL345_I2C(Port port, Range range) : I2C(port, kAddress) { + // m_i2c = new I2C((I2C::Port)port, kAddress); - // Turn on the measurements - Write(kPowerCtlRegister, kPowerCtl_Measure); - // Specify the data format to read - SetRange(range); + // Turn on the measurements + Write(kPowerCtlRegister, kPowerCtl_Measure); + // Specify the data format to read + SetRange(range); - HALReport(HALUsageReporting::kResourceType_ADXL345, HALUsageReporting::kADXL345_I2C, 0); - LiveWindow::GetInstance()->AddSensor("ADXL345_I2C", port, this); + HALReport(HALUsageReporting::kResourceType_ADXL345, + HALUsageReporting::kADXL345_I2C, 0); + LiveWindow::GetInstance()->AddSensor("ADXL345_I2C", port, this); } /** * Destructor. */ -ADXL345_I2C::~ADXL345_I2C() -{ - //delete m_i2c; - //m_i2c = NULL; +ADXL345_I2C::~ADXL345_I2C() { + // delete m_i2c; + // m_i2c = NULL; } /** {@inheritdoc} */ -void ADXL345_I2C::SetRange(Range range) -{ - Write(kDataFormatRegister, kDataFormat_FullRes | (uint8_t)range); +void ADXL345_I2C::SetRange(Range range) { + Write(kDataFormatRegister, kDataFormat_FullRes | (uint8_t)range); } /** {@inheritdoc} */ -double ADXL345_I2C::GetX() -{ - return GetAcceleration(kAxis_X); -} +double ADXL345_I2C::GetX() { return GetAcceleration(kAxis_X); } /** {@inheritdoc} */ -double ADXL345_I2C::GetY() -{ - return GetAcceleration(kAxis_Y); -} +double ADXL345_I2C::GetY() { return GetAcceleration(kAxis_Y); } /** {@inheritdoc} */ -double ADXL345_I2C::GetZ() -{ - return GetAcceleration(kAxis_Z); -} +double ADXL345_I2C::GetZ() { return GetAcceleration(kAxis_Z); } /** * Get the acceleration of one axis in Gs. @@ -74,53 +63,50 @@ double ADXL345_I2C::GetZ() * @param axis The axis to read from. * @return Acceleration of the ADXL345 in Gs. */ -double ADXL345_I2C::GetAcceleration(ADXL345_I2C::Axes axis) -{ - int16_t rawAccel = 0; - //if(m_i2c) - //{ - Read(kDataRegister + (uint8_t)axis, sizeof(rawAccel), (uint8_t *)&rawAccel); - //} - return rawAccel * kGsPerLSB; +double ADXL345_I2C::GetAcceleration(ADXL345_I2C::Axes axis) { + int16_t rawAccel = 0; + // if(m_i2c) + //{ + Read(kDataRegister + (uint8_t)axis, sizeof(rawAccel), (uint8_t *)&rawAccel); + //} + return rawAccel * kGsPerLSB; } /** * Get the acceleration of all axes in Gs. * - * @return An object containing the acceleration measured on each axis of the ADXL345 in Gs. + * @return An object containing the acceleration measured on each axis of the + * ADXL345 in Gs. */ -ADXL345_I2C::AllAxes ADXL345_I2C::GetAccelerations() -{ - AllAxes data = AllAxes(); - int16_t rawData[3]; - //if (m_i2c) - //{ - Read(kDataRegister, sizeof(rawData), (uint8_t*)rawData); +ADXL345_I2C::AllAxes ADXL345_I2C::GetAccelerations() { + AllAxes data = AllAxes(); + int16_t rawData[3]; + // if (m_i2c) + //{ + Read(kDataRegister, sizeof(rawData), (uint8_t *)rawData); - data.XAxis = rawData[0] * kGsPerLSB; - data.YAxis = rawData[1] * kGsPerLSB; - data.ZAxis = rawData[2] * kGsPerLSB; - //} - return data; + data.XAxis = rawData[0] * kGsPerLSB; + data.YAxis = rawData[1] * kGsPerLSB; + data.ZAxis = rawData[2] * kGsPerLSB; + //} + return data; } std::string ADXL345_I2C::GetSmartDashboardType() const { - return "3AxisAccelerometer"; + return "3AxisAccelerometer"; } void ADXL345_I2C::InitTable(ITable *subtable) { - m_table = subtable; - UpdateTable(); + m_table = subtable; + UpdateTable(); } void ADXL345_I2C::UpdateTable() { - if (m_table != NULL) { - m_table->PutNumber("X", GetX()); - m_table->PutNumber("Y", GetY()); - m_table->PutNumber("Z", GetZ()); - } + if (m_table != NULL) { + m_table->PutNumber("X", GetX()); + m_table->PutNumber("Y", GetY()); + m_table->PutNumber("Z", GetZ()); + } } -ITable* ADXL345_I2C::GetTable() const { - return m_table; -} +ITable *ADXL345_I2C::GetTable() const { return m_table; } diff --git a/wpilibc/wpilibC++Devices/src/ADXL345_SPI.cpp b/wpilibc/wpilibC++Devices/src/ADXL345_SPI.cpp index 86e4ec9ee1..1f000b8d1b 100644 --- a/wpilibc/wpilibC++Devices/src/ADXL345_SPI.cpp +++ b/wpilibc/wpilibC++Devices/src/ADXL345_SPI.cpp @@ -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,80 +16,67 @@ const uint8_t ADXL345_SPI::kDataFormatRegister; const uint8_t ADXL345_SPI::kDataRegister; constexpr double ADXL345_SPI::kGsPerLSB; - /** * Constructor. * * @param port The SPI port the accelerometer is attached to * @param range The range (+ or -) that the accelerometer will measure. */ -ADXL345_SPI::ADXL345_SPI(SPI::Port port, ADXL345_SPI::Range range) -{ - m_port = port; - Init(range); - LiveWindow::GetInstance()->AddSensor("ADXL345_SPI", port, this); +ADXL345_SPI::ADXL345_SPI(SPI::Port port, ADXL345_SPI::Range range) { + m_port = port; + Init(range); + LiveWindow::GetInstance()->AddSensor("ADXL345_SPI", port, this); } /** * Internal common init function. */ -void ADXL345_SPI::Init(Range range) -{ - m_spi = new SPI(m_port); - m_spi->SetClockRate(500000); - m_spi->SetMSBFirst(); - m_spi->SetSampleDataOnFalling(); - m_spi->SetClockActiveLow(); - m_spi->SetChipSelectActiveHigh(); +void ADXL345_SPI::Init(Range range) { + m_spi = new SPI(m_port); + m_spi->SetClockRate(500000); + m_spi->SetMSBFirst(); + m_spi->SetSampleDataOnFalling(); + m_spi->SetClockActiveLow(); + m_spi->SetChipSelectActiveHigh(); - uint8_t commands[2]; - // Turn on the measurements - commands[0] = kPowerCtlRegister; - commands[1] = kPowerCtl_Measure; - m_spi->Transaction(commands, commands, 2); + uint8_t commands[2]; + // Turn on the measurements + commands[0] = kPowerCtlRegister; + commands[1] = kPowerCtl_Measure; + m_spi->Transaction(commands, commands, 2); - SetRange(range); + SetRange(range); - HALReport(HALUsageReporting::kResourceType_ADXL345, HALUsageReporting::kADXL345_SPI); + HALReport(HALUsageReporting::kResourceType_ADXL345, + HALUsageReporting::kADXL345_SPI); } /** * Destructor. */ -ADXL345_SPI::~ADXL345_SPI() -{ - delete m_spi; - m_spi = NULL; +ADXL345_SPI::~ADXL345_SPI() { + delete m_spi; + m_spi = NULL; } /** {@inheritdoc} */ -void ADXL345_SPI::SetRange(Range range) -{ - uint8_t commands[2]; - - // Specify the data format to read - commands[0] = kDataFormatRegister; - commands[1] = kDataFormat_FullRes| (uint8_t)(range & 0x03); - m_spi->Transaction(commands, commands, 2); +void ADXL345_SPI::SetRange(Range range) { + uint8_t commands[2]; + + // Specify the data format to read + commands[0] = kDataFormatRegister; + commands[1] = kDataFormat_FullRes | (uint8_t)(range & 0x03); + m_spi->Transaction(commands, commands, 2); } /** {@inheritdoc} */ -double ADXL345_SPI::GetX() -{ - return GetAcceleration(kAxis_X); -} +double ADXL345_SPI::GetX() { return GetAcceleration(kAxis_X); } /** {@inheritdoc} */ -double ADXL345_SPI::GetY() -{ - return GetAcceleration(kAxis_Y); -} +double ADXL345_SPI::GetY() { return GetAcceleration(kAxis_Y); } /** {@inheritdoc} */ -double ADXL345_SPI::GetZ() -{ - return GetAcceleration(kAxis_Z); -} +double ADXL345_SPI::GetZ() { return GetAcceleration(kAxis_Z); } /** * Get the acceleration of one axis in Gs. @@ -96,68 +84,63 @@ double ADXL345_SPI::GetZ() * @param axis The axis to read from. * @return Acceleration of the ADXL345 in Gs. */ -double ADXL345_SPI::GetAcceleration(ADXL345_SPI::Axes axis) -{ - int16_t rawAccel = 0; - if(m_spi) - { - uint8_t buffer[3]; - uint8_t command[3] = {0,0,0}; - command[0] = (kAddress_Read | kAddress_MultiByte | kDataRegister) + (uint8_t)axis; - m_spi->Transaction(command, buffer, 3); +double ADXL345_SPI::GetAcceleration(ADXL345_SPI::Axes axis) { + int16_t rawAccel = 0; + if (m_spi) { + uint8_t buffer[3]; + uint8_t command[3] = {0, 0, 0}; + command[0] = + (kAddress_Read | kAddress_MultiByte | kDataRegister) + (uint8_t)axis; + m_spi->Transaction(command, buffer, 3); - // Sensor is little endian... swap bytes - rawAccel = buffer[2]<<8 | buffer[1]; - } - return rawAccel * kGsPerLSB; + // Sensor is little endian... swap bytes + rawAccel = buffer[2] << 8 | buffer[1]; + } + return rawAccel * kGsPerLSB; } /** * Get the acceleration of all axes in Gs. * - * @return An object containing the acceleration measured on each axis of the ADXL345 in Gs. + * @return An object containing the acceleration measured on each axis of the + * ADXL345 in Gs. */ -ADXL345_SPI::AllAxes ADXL345_SPI::GetAccelerations() -{ - AllAxes data = AllAxes(); - uint8_t dataBuffer[7] = {0,0,0,0,0,0,0}; - int16_t rawData[3]; - if (m_spi) - { - // Select the data address. - dataBuffer[0] = (kAddress_Read | kAddress_MultiByte | kDataRegister); - m_spi->Transaction(dataBuffer, dataBuffer, 7); +ADXL345_SPI::AllAxes ADXL345_SPI::GetAccelerations() { + AllAxes data = AllAxes(); + uint8_t dataBuffer[7] = {0, 0, 0, 0, 0, 0, 0}; + int16_t rawData[3]; + if (m_spi) { + // Select the data address. + dataBuffer[0] = (kAddress_Read | kAddress_MultiByte | kDataRegister); + m_spi->Transaction(dataBuffer, dataBuffer, 7); - for (int32_t i=0; i<3; i++) - { - // Sensor is little endian... swap bytes - rawData[i] = dataBuffer[i*2+2] << 8 | dataBuffer[i*2+1]; - } + for (int32_t i = 0; i < 3; i++) { + // Sensor is little endian... swap bytes + rawData[i] = dataBuffer[i * 2 + 2] << 8 | dataBuffer[i * 2 + 1]; + } - data.XAxis = rawData[0] * kGsPerLSB; - data.YAxis = rawData[1] * kGsPerLSB; - data.ZAxis = rawData[2] * kGsPerLSB; - } - return data; + data.XAxis = rawData[0] * kGsPerLSB; + data.YAxis = rawData[1] * kGsPerLSB; + data.ZAxis = rawData[2] * kGsPerLSB; + } + return data; } std::string ADXL345_SPI::GetSmartDashboardType() const { - return "3AxisAccelerometer"; + return "3AxisAccelerometer"; } -void ADXL345_SPI::InitTable(ITable *subtable) { - m_table = subtable; - UpdateTable(); +void ADXL345_SPI::InitTable(ITable* subtable) { + m_table = subtable; + UpdateTable(); } void ADXL345_SPI::UpdateTable() { - if (m_table != NULL) { - m_table->PutNumber("X", GetX()); - m_table->PutNumber("Y", GetY()); - m_table->PutNumber("Z", GetZ()); - } + if (m_table != NULL) { + m_table->PutNumber("X", GetX()); + m_table->PutNumber("Y", GetY()); + m_table->PutNumber("Z", GetZ()); + } } -ITable* ADXL345_SPI::GetTable() const { - return m_table; -} +ITable* ADXL345_SPI::GetTable() const { return m_table; } diff --git a/wpilibc/wpilibC++Devices/src/AnalogAccelerometer.cpp b/wpilibc/wpilibC++Devices/src/AnalogAccelerometer.cpp index e2c17184df..9e685b1045 100644 --- a/wpilibc/wpilibC++Devices/src/AnalogAccelerometer.cpp +++ b/wpilibc/wpilibC++Devices/src/AnalogAccelerometer.cpp @@ -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,57 +13,55 @@ /** * Common function for initializing the accelerometer. */ -void AnalogAccelerometer::InitAccelerometer() -{ - m_table = NULL; - m_voltsPerG = 1.0; - m_zeroGVoltage = 2.5; - HALReport(HALUsageReporting::kResourceType_Accelerometer, m_AnalogInput->GetChannel()); - LiveWindow::GetInstance()->AddSensor("Accelerometer", m_AnalogInput->GetChannel(), this); +void AnalogAccelerometer::InitAccelerometer() { + m_table = NULL; + m_voltsPerG = 1.0; + m_zeroGVoltage = 2.5; + HALReport(HALUsageReporting::kResourceType_Accelerometer, + m_AnalogInput->GetChannel()); + LiveWindow::GetInstance()->AddSensor("Accelerometer", + m_AnalogInput->GetChannel(), this); } /** * Create a new instance of an accelerometer. * The constructor allocates desired analog input. - * @param channel The channel number for the analog input the accelerometer is connected to + * @param channel The channel number for the analog input the accelerometer is + * connected to */ -AnalogAccelerometer::AnalogAccelerometer(int32_t channel) -{ - m_AnalogInput = new AnalogInput(channel); - m_allocatedChannel = true; - InitAccelerometer(); +AnalogAccelerometer::AnalogAccelerometer(int32_t channel) { + m_AnalogInput = new AnalogInput(channel); + m_allocatedChannel = true; + InitAccelerometer(); } /** * Create a new instance of Accelerometer from an existing AnalogInput. - * Make a new instance of accelerometer given an AnalogInput. This is particularly - * useful if the port is going to be read as an analog channel as well as through + * Make a new instance of accelerometer given an AnalogInput. This is + * particularly + * useful if the port is going to be read as an analog channel as well as + * through * the Accelerometer class. - * @param channel The existing AnalogInput object for the analog input the accelerometer is connected to + * @param channel The existing AnalogInput object for the analog input the + * accelerometer is connected to */ -AnalogAccelerometer::AnalogAccelerometer(AnalogInput *channel) -{ - if (channel == NULL) - { - wpi_setWPIError(NullParameter); - } - else - { - m_AnalogInput = channel; - InitAccelerometer(); - } - m_allocatedChannel = false; +AnalogAccelerometer::AnalogAccelerometer(AnalogInput *channel) { + if (channel == NULL) { + wpi_setWPIError(NullParameter); + } else { + m_AnalogInput = channel; + InitAccelerometer(); + } + m_allocatedChannel = false; } /** * Delete the analog components used for the accelerometer. */ -AnalogAccelerometer::~AnalogAccelerometer() -{ - if (m_allocatedChannel) - { - delete m_AnalogInput; - } +AnalogAccelerometer::~AnalogAccelerometer() { + if (m_allocatedChannel) { + delete m_AnalogInput; + } } /** @@ -72,67 +71,58 @@ AnalogAccelerometer::~AnalogAccelerometer() * * @return The current acceleration of the sensor in Gs. */ -float AnalogAccelerometer::GetAcceleration() const -{ - return (m_AnalogInput->GetAverageVoltage() - m_zeroGVoltage) / m_voltsPerG; +float AnalogAccelerometer::GetAcceleration() const { + return (m_AnalogInput->GetAverageVoltage() - m_zeroGVoltage) / m_voltsPerG; } /** * Set the accelerometer sensitivity. * - * This sets the sensitivity of the accelerometer used for calculating the acceleration. - * The sensitivity varies by accelerometer model. There are constants defined for various models. + * This sets the sensitivity of the accelerometer used for calculating the + * acceleration. + * The sensitivity varies by accelerometer model. There are constants defined + * for various models. * * @param sensitivity The sensitivity of accelerometer in Volts per G. */ -void AnalogAccelerometer::SetSensitivity(float sensitivity) -{ - m_voltsPerG = sensitivity; +void AnalogAccelerometer::SetSensitivity(float sensitivity) { + m_voltsPerG = sensitivity; } /** * Set the voltage that corresponds to 0 G. * - * The zero G voltage varies by accelerometer model. There are constants defined for various models. + * The zero G voltage varies by accelerometer model. There are constants defined + * for various models. * * @param zero The zero G voltage. */ -void AnalogAccelerometer::SetZero(float zero) -{ - m_zeroGVoltage = zero; -} +void AnalogAccelerometer::SetZero(float zero) { m_zeroGVoltage = zero; } /** * Get the Acceleration for the PID Source parent. * * @return The current acceleration in Gs. */ -double AnalogAccelerometer::PIDGet() const -{ - return GetAcceleration(); -} +double AnalogAccelerometer::PIDGet() const { return GetAcceleration(); } void AnalogAccelerometer::UpdateTable() { - if (m_table != NULL) { - m_table->PutNumber("Value", GetAcceleration()); - } + if (m_table != NULL) { + m_table->PutNumber("Value", GetAcceleration()); + } } -void AnalogAccelerometer::StartLiveWindowMode() { -} +void AnalogAccelerometer::StartLiveWindowMode() {} -void AnalogAccelerometer::StopLiveWindowMode() { -} +void AnalogAccelerometer::StopLiveWindowMode() {} std::string AnalogAccelerometer::GetSmartDashboardType() const { - return "Accelerometer"; + return "Accelerometer"; } void AnalogAccelerometer::InitTable(ITable *subTable) { - m_table = subTable; - UpdateTable(); + m_table = subTable; + UpdateTable(); } -ITable * AnalogAccelerometer::GetTable() const { - return m_table; -} +ITable *AnalogAccelerometer::GetTable() const { return m_table; } diff --git a/wpilibc/wpilibC++Devices/src/AnalogInput.cpp b/wpilibc/wpilibC++Devices/src/AnalogInput.cpp index 99855899a9..0ccb60d91b 100644 --- a/wpilibc/wpilibC++Devices/src/AnalogInput.cpp +++ b/wpilibc/wpilibC++Devices/src/AnalogInput.cpp @@ -20,116 +20,115 @@ const uint32_t AnalogInput::kAccumulatorChannels[] = {0, 1}; /** * Common initialization. */ -void AnalogInput::InitAnalogInput(uint32_t channel) -{ - m_table = NULL; - char buf[64]; - Resource::CreateResourceObject(&inputs, kAnalogInputs); +void AnalogInput::InitAnalogInput(uint32_t channel) { + m_table = NULL; + char buf[64]; + Resource::CreateResourceObject(&inputs, kAnalogInputs); - if (!checkAnalogInputChannel(channel)) - { - snprintf(buf, 64, "analog input %d", channel); - wpi_setWPIErrorWithContext(ChannelIndexOutOfRange, buf); - return; - } + if (!checkAnalogInputChannel(channel)) { + snprintf(buf, 64, "analog input %d", channel); + wpi_setWPIErrorWithContext(ChannelIndexOutOfRange, buf); + return; + } - snprintf(buf, 64, "Analog Input %d", channel); - if (inputs->Allocate(channel, buf) == ~0ul) - { - CloneError(inputs); - return; - } + snprintf(buf, 64, "Analog Input %d", channel); + if (inputs->Allocate(channel, buf) == ~0ul) { + CloneError(inputs); + return; + } - m_channel = channel; + m_channel = channel; - void* port = getPort(channel); - int32_t status = 0; - m_port = initializeAnalogInputPort(port, &status); - wpi_setErrorWithContext(status, getHALErrorMessage(status)); + void *port = getPort(channel); + int32_t status = 0; + m_port = initializeAnalogInputPort(port, &status); + wpi_setErrorWithContext(status, getHALErrorMessage(status)); - LiveWindow::GetInstance()->AddSensor("AnalogInput", channel, this); - HALReport(HALUsageReporting::kResourceType_AnalogChannel, channel); + LiveWindow::GetInstance()->AddSensor("AnalogInput", channel, this); + HALReport(HALUsageReporting::kResourceType_AnalogChannel, channel); } /** * Construct an analog input. * - * @param channel The channel number on the roboRIO to represent. 0-3 are on-board 4-7 are on the MXP port. + * @param channel The channel number on the roboRIO to represent. 0-3 are + * on-board 4-7 are on the MXP port. */ -AnalogInput::AnalogInput(uint32_t channel) -{ - InitAnalogInput(channel); -} +AnalogInput::AnalogInput(uint32_t channel) { InitAnalogInput(channel); } /** * Channel destructor. */ -AnalogInput::~AnalogInput() -{ - inputs->Free(m_channel); -} +AnalogInput::~AnalogInput() { inputs->Free(m_channel); } /** * Get a sample straight from this channel. - * The sample is a 12-bit value representing the 0V to 5V range of the A/D converter in the module. - * The units are in A/D converter codes. Use GetVoltage() to get the analog value in calibrated units. + * The sample is a 12-bit value representing the 0V to 5V range of the A/D + * converter in the module. + * The units are in A/D converter codes. Use GetVoltage() to get the analog + * value in calibrated units. * @return A sample straight from this channel. */ -int16_t AnalogInput::GetValue() const -{ - if (StatusIsFatal()) return 0; - int32_t status = 0; - int16_t value = getAnalogValue(m_port, &status); - wpi_setErrorWithContext(status, getHALErrorMessage(status)); - return value; +int16_t AnalogInput::GetValue() const { + if (StatusIsFatal()) return 0; + int32_t status = 0; + int16_t value = getAnalogValue(m_port, &status); + wpi_setErrorWithContext(status, getHALErrorMessage(status)); + return value; } /** - * Get a sample from the output of the oversample and average engine for this channel. + * Get a sample from the output of the oversample and average engine for this + * channel. * The sample is 12-bit + the bits configured in SetOversampleBits(). - * The value configured in SetAverageBits() will cause this value to be averaged 2**bits number of samples. - * This is not a sliding window. The sample will not change until 2**(OversampleBits + AverageBits) samples + * The value configured in SetAverageBits() will cause this value to be averaged + * 2**bits number of samples. + * This is not a sliding window. The sample will not change until + * 2**(OversampleBits + AverageBits) samples * have been acquired from the module on this channel. * Use GetAverageVoltage() to get the analog value in calibrated units. * @return A sample from the oversample and average engine for this channel. */ -int32_t AnalogInput::GetAverageValue() const -{ - if (StatusIsFatal()) return 0; - int32_t status = 0; - int32_t value = getAnalogAverageValue(m_port, &status); - wpi_setErrorWithContext(status, getHALErrorMessage(status)); - return value; +int32_t AnalogInput::GetAverageValue() const { + if (StatusIsFatal()) return 0; + int32_t status = 0; + int32_t value = getAnalogAverageValue(m_port, &status); + wpi_setErrorWithContext(status, getHALErrorMessage(status)); + return value; } /** * Get a scaled sample straight from this channel. - * The value is scaled to units of Volts using the calibrated scaling data from GetLSBWeight() and GetOffset(). + * The value is scaled to units of Volts using the calibrated scaling data from + * GetLSBWeight() and GetOffset(). * @return A scaled sample straight from this channel. */ -float AnalogInput::GetVoltage() const -{ - if (StatusIsFatal()) return 0.0f; - int32_t status = 0; - float voltage = getAnalogVoltage(m_port, &status); - wpi_setErrorWithContext(status, getHALErrorMessage(status)); - return voltage; +float AnalogInput::GetVoltage() const { + if (StatusIsFatal()) return 0.0f; + int32_t status = 0; + float voltage = getAnalogVoltage(m_port, &status); + wpi_setErrorWithContext(status, getHALErrorMessage(status)); + return voltage; } /** - * Get a scaled sample from the output of the oversample and average engine for this channel. - * The value is scaled to units of Volts using the calibrated scaling data from GetLSBWeight() and GetOffset(). - * Using oversampling will cause this value to be higher resolution, but it will update more slowly. - * Using averaging will cause this value to be more stable, but it will update more slowly. - * @return A scaled sample from the output of the oversample and average engine for this channel. + * Get a scaled sample from the output of the oversample and average engine for + * this channel. + * The value is scaled to units of Volts using the calibrated scaling data from + * GetLSBWeight() and GetOffset(). + * Using oversampling will cause this value to be higher resolution, but it will + * update more slowly. + * Using averaging will cause this value to be more stable, but it will update + * more slowly. + * @return A scaled sample from the output of the oversample and average engine + * for this channel. */ -float AnalogInput::GetAverageVoltage() const -{ - if (StatusIsFatal()) return 0.0f; - int32_t status = 0; - float voltage = getAnalogAverageVoltage(m_port, &status); - wpi_setErrorWithContext(status, getHALErrorMessage(status)); - return voltage; +float AnalogInput::GetAverageVoltage() const { + if (StatusIsFatal()) return 0.0f; + int32_t status = 0; + float voltage = getAnalogAverageVoltage(m_port, &status); + wpi_setErrorWithContext(status, getHALErrorMessage(status)); + return voltage; } /** @@ -139,13 +138,12 @@ float AnalogInput::GetAverageVoltage() const * * @return Least significant bit weight. */ -uint32_t AnalogInput::GetLSBWeight() const -{ - if (StatusIsFatal()) return 0; - int32_t status = 0; - int32_t lsbWeight = getAnalogLSBWeight(m_port, &status); - wpi_setErrorWithContext(status, getHALErrorMessage(status)); - return lsbWeight; +uint32_t AnalogInput::GetLSBWeight() const { + if (StatusIsFatal()) return 0; + int32_t status = 0; + int32_t lsbWeight = getAnalogLSBWeight(m_port, &status); + wpi_setErrorWithContext(status, getHALErrorMessage(status)); + return lsbWeight; } /** @@ -155,86 +153,86 @@ uint32_t AnalogInput::GetLSBWeight() const * * @return Offset constant. */ -int32_t AnalogInput::GetOffset() const -{ - if (StatusIsFatal()) return 0; - int32_t status = 0; - int32_t offset = getAnalogOffset(m_port, &status); - wpi_setErrorWithContext(status, getHALErrorMessage(status)); - return offset; +int32_t AnalogInput::GetOffset() const { + if (StatusIsFatal()) return 0; + int32_t status = 0; + int32_t offset = getAnalogOffset(m_port, &status); + wpi_setErrorWithContext(status, getHALErrorMessage(status)); + return offset; } /** * Get the channel number. * @return The channel number. */ -uint32_t AnalogInput::GetChannel() const -{ - if (StatusIsFatal()) return 0; - return m_channel; +uint32_t AnalogInput::GetChannel() const { + if (StatusIsFatal()) return 0; + return m_channel; } /** * Set the number of averaging bits. - * This sets the number of averaging bits. The actual number of averaged samples is 2^bits. - * Use averaging to improve the stability of your measurement at the expense of sampling rate. + * This sets the number of averaging bits. The actual number of averaged samples + * is 2^bits. + * Use averaging to improve the stability of your measurement at the expense of + * sampling rate. * The averaging is done automatically in the FPGA. * * @param bits Number of bits of averaging. */ -void AnalogInput::SetAverageBits(uint32_t bits) -{ - if (StatusIsFatal()) return; - int32_t status = 0; - setAnalogAverageBits(m_port, bits, &status); - wpi_setErrorWithContext(status, getHALErrorMessage(status)); +void AnalogInput::SetAverageBits(uint32_t bits) { + if (StatusIsFatal()) return; + int32_t status = 0; + setAnalogAverageBits(m_port, bits, &status); + wpi_setErrorWithContext(status, getHALErrorMessage(status)); } /** * Get the number of averaging bits previously configured. - * This gets the number of averaging bits from the FPGA. The actual number of averaged samples is 2^bits. + * This gets the number of averaging bits from the FPGA. The actual number of + * averaged samples is 2^bits. * The averaging is done automatically in the FPGA. * * @return Number of bits of averaging previously configured. */ -uint32_t AnalogInput::GetAverageBits() const -{ - int32_t status = 0; - int32_t averageBits = getAnalogAverageBits(m_port, &status); - wpi_setErrorWithContext(status, getHALErrorMessage(status)); - return averageBits; +uint32_t AnalogInput::GetAverageBits() const { + int32_t status = 0; + int32_t averageBits = getAnalogAverageBits(m_port, &status); + wpi_setErrorWithContext(status, getHALErrorMessage(status)); + return averageBits; } /** * Set the number of oversample bits. - * This sets the number of oversample bits. The actual number of oversampled values is 2^bits. - * Use oversampling to improve the resolution of your measurements at the expense of sampling rate. + * This sets the number of oversample bits. The actual number of oversampled + * values is 2^bits. + * Use oversampling to improve the resolution of your measurements at the + * expense of sampling rate. * The oversampling is done automatically in the FPGA. * * @param bits Number of bits of oversampling. */ -void AnalogInput::SetOversampleBits(uint32_t bits) -{ - if (StatusIsFatal()) return; - int32_t status = 0; - setAnalogOversampleBits(m_port, bits, &status); - wpi_setErrorWithContext(status, getHALErrorMessage(status)); +void AnalogInput::SetOversampleBits(uint32_t bits) { + if (StatusIsFatal()) return; + int32_t status = 0; + setAnalogOversampleBits(m_port, bits, &status); + wpi_setErrorWithContext(status, getHALErrorMessage(status)); } /** * Get the number of oversample bits previously configured. - * This gets the number of oversample bits from the FPGA. The actual number of oversampled values is + * This gets the number of oversample bits from the FPGA. The actual number of + * oversampled values is * 2^bits. The oversampling is done automatically in the FPGA. * * @return Number of bits of oversampling previously configured. */ -uint32_t AnalogInput::GetOversampleBits() const -{ - if (StatusIsFatal()) return 0; - int32_t status = 0; - int32_t oversampleBits = getAnalogOversampleBits(m_port, &status); - wpi_setErrorWithContext(status, getHALErrorMessage(status)); - return oversampleBits; +uint32_t AnalogInput::GetOversampleBits() const { + if (StatusIsFatal()) return 0; + int32_t status = 0; + int32_t oversampleBits = getAnalogOversampleBits(m_port, &status); + wpi_setErrorWithContext(status, getHALErrorMessage(status)); + return oversampleBits; } /** @@ -242,89 +240,85 @@ uint32_t AnalogInput::GetOversampleBits() const * * @return The analog input is attached to an accumulator. */ -bool AnalogInput::IsAccumulatorChannel() const -{ - if (StatusIsFatal()) return false; - int32_t status = 0; - bool isAccum = isAccumulatorChannel(m_port, &status); - wpi_setErrorWithContext(status, getHALErrorMessage(status)); - return isAccum; +bool AnalogInput::IsAccumulatorChannel() const { + if (StatusIsFatal()) return false; + int32_t status = 0; + bool isAccum = isAccumulatorChannel(m_port, &status); + wpi_setErrorWithContext(status, getHALErrorMessage(status)); + return isAccum; } /** * Initialize the accumulator. */ -void AnalogInput::InitAccumulator() -{ - if (StatusIsFatal()) return; - m_accumulatorOffset = 0; - int32_t status = 0; - initAccumulator(m_port, &status); - wpi_setErrorWithContext(status, getHALErrorMessage(status)); +void AnalogInput::InitAccumulator() { + if (StatusIsFatal()) return; + m_accumulatorOffset = 0; + int32_t status = 0; + initAccumulator(m_port, &status); + wpi_setErrorWithContext(status, getHALErrorMessage(status)); } - /** * Set an initial value for the accumulator. * * This will be added to all values returned to the user. - * @param initialValue The value that the accumulator should start from when reset. + * @param initialValue The value that the accumulator should start from when + * reset. */ -void AnalogInput::SetAccumulatorInitialValue(int64_t initialValue) -{ - if (StatusIsFatal()) return; - m_accumulatorOffset = initialValue; +void AnalogInput::SetAccumulatorInitialValue(int64_t initialValue) { + if (StatusIsFatal()) return; + m_accumulatorOffset = initialValue; } /** * Resets the accumulator to the initial value. */ -void AnalogInput::ResetAccumulator() -{ - if (StatusIsFatal()) return; - int32_t status = 0; - resetAccumulator(m_port, &status); - wpi_setErrorWithContext(status, getHALErrorMessage(status)); +void AnalogInput::ResetAccumulator() { + if (StatusIsFatal()) return; + int32_t status = 0; + resetAccumulator(m_port, &status); + wpi_setErrorWithContext(status, getHALErrorMessage(status)); - if(!StatusIsFatal()) - { - // Wait until the next sample, so the next call to GetAccumulator*() - // won't have old values. - const float sampleTime = 1.0f / GetSampleRate(); - const float overSamples = 1 << GetOversampleBits(); - const float averageSamples = 1 << GetAverageBits(); - Wait(sampleTime * overSamples * averageSamples); - } + if (!StatusIsFatal()) { + // Wait until the next sample, so the next call to GetAccumulator*() + // won't have old values. + const float sampleTime = 1.0f / GetSampleRate(); + const float overSamples = 1 << GetOversampleBits(); + const float averageSamples = 1 << GetAverageBits(); + Wait(sampleTime * overSamples * averageSamples); + } } /** * Set the center value of the accumulator. * - * The center value is subtracted from each A/D value before it is added to the accumulator. This - * is used for the center value of devices like gyros and accelerometers to + * The center value is subtracted from each A/D value before it is added to the + * accumulator. This + * is used for the center value of devices like gyros and accelerometers to * take the device offset into account when integrating. * - * This center value is based on the output of the oversampled and averaged source from the accumulator - * channel. Because of this, any non-zero oversample bits will affect the size of the value for this field. + * This center value is based on the output of the oversampled and averaged + * source from the accumulator + * channel. Because of this, any non-zero oversample bits will affect the size + * of the value for this field. */ -void AnalogInput::SetAccumulatorCenter(int32_t center) -{ - if (StatusIsFatal()) return; - int32_t status = 0; - setAccumulatorCenter(m_port, center, &status); - wpi_setErrorWithContext(status, getHALErrorMessage(status)); +void AnalogInput::SetAccumulatorCenter(int32_t center) { + if (StatusIsFatal()) return; + int32_t status = 0; + setAccumulatorCenter(m_port, center, &status); + wpi_setErrorWithContext(status, getHALErrorMessage(status)); } /** * Set the accumulator's deadband. - * @param + * @param */ -void AnalogInput::SetAccumulatorDeadband(int32_t deadband) -{ - if (StatusIsFatal()) return; - int32_t status = 0; - setAccumulatorDeadband(m_port, deadband, &status); - wpi_setErrorWithContext(status, getHALErrorMessage(status)); +void AnalogInput::SetAccumulatorDeadband(int32_t deadband) { + if (StatusIsFatal()) return; + int32_t status = 0; + setAccumulatorDeadband(m_port, deadband, &status); + wpi_setErrorWithContext(status, getHALErrorMessage(status)); } /** @@ -335,32 +329,30 @@ void AnalogInput::SetAccumulatorDeadband(int32_t deadband) * * @return The 64-bit value accumulated since the last Reset(). */ -int64_t AnalogInput::GetAccumulatorValue() const -{ - if (StatusIsFatal()) return 0; - int32_t status = 0; - int64_t value = getAccumulatorValue(m_port, &status); - wpi_setErrorWithContext(status, getHALErrorMessage(status)); - return value + m_accumulatorOffset; +int64_t AnalogInput::GetAccumulatorValue() const { + if (StatusIsFatal()) return 0; + int32_t status = 0; + int64_t value = getAccumulatorValue(m_port, &status); + wpi_setErrorWithContext(status, getHALErrorMessage(status)); + return value + m_accumulatorOffset; } /** * Read the number of accumulated values. * - * Read the count of the accumulated values since the accumulator was last Reset(). + * Read the count of the accumulated values since the accumulator was last + * Reset(). * * @return The number of times samples from the channel were accumulated. */ -uint32_t AnalogInput::GetAccumulatorCount() const -{ - if (StatusIsFatal()) return 0; - int32_t status = 0; - uint32_t count = getAccumulatorCount(m_port, &status); - wpi_setErrorWithContext(status, getHALErrorMessage(status)); - return count; +uint32_t AnalogInput::GetAccumulatorCount() const { + if (StatusIsFatal()) return 0; + int32_t status = 0; + uint32_t count = getAccumulatorCount(m_port, &status); + wpi_setErrorWithContext(status, getHALErrorMessage(status)); + return count; } - /** * Read the accumulated value and the number of accumulated values atomically. * @@ -370,13 +362,12 @@ uint32_t AnalogInput::GetAccumulatorCount() const * @param value Pointer to the 64-bit accumulated output. * @param count Pointer to the number of accumulation cycles. */ -void AnalogInput::GetAccumulatorOutput(int64_t *value, uint32_t *count) const -{ - if (StatusIsFatal()) return; - int32_t status = 0; - getAccumulatorOutput(m_port, value, count, &status); - wpi_setErrorWithContext(status, getHALErrorMessage(status)); - *value += m_accumulatorOffset; +void AnalogInput::GetAccumulatorOutput(int64_t *value, uint32_t *count) const { + if (StatusIsFatal()) return; + int32_t status = 0; + getAccumulatorOutput(m_port, value, count, &status); + wpi_setErrorWithContext(status, getHALErrorMessage(status)); + *value += m_accumulatorOffset; } /** @@ -385,11 +376,10 @@ void AnalogInput::GetAccumulatorOutput(int64_t *value, uint32_t *count) const * This is 62500 samples/s per channel. * @param samplesPerSecond The number of samples per second. */ -void AnalogInput::SetSampleRate(float samplesPerSecond) -{ - int32_t status = 0; - setAnalogSampleRate(samplesPerSecond, &status); - wpi_setGlobalErrorWithContext(status, getHALErrorMessage(status)); +void AnalogInput::SetSampleRate(float samplesPerSecond) { + int32_t status = 0; + setAnalogSampleRate(samplesPerSecond, &status); + wpi_setGlobalErrorWithContext(status, getHALErrorMessage(status)); } /** @@ -397,12 +387,11 @@ void AnalogInput::SetSampleRate(float samplesPerSecond) * * @return Sample rate. */ -float AnalogInput::GetSampleRate() -{ - int32_t status = 0; - float sampleRate = getAnalogSampleRate(&status); - wpi_setGlobalErrorWithContext(status, getHALErrorMessage(status)); - return sampleRate; +float AnalogInput::GetSampleRate() { + int32_t status = 0; + float sampleRate = getAnalogSampleRate(&status); + wpi_setGlobalErrorWithContext(status, getHALErrorMessage(status)); + return sampleRate; } /** @@ -410,35 +399,28 @@ float AnalogInput::GetSampleRate() * * @return The average voltage. */ -double AnalogInput::PIDGet() const -{ - if (StatusIsFatal()) return 0.0; - return GetAverageVoltage(); +double AnalogInput::PIDGet() const { + if (StatusIsFatal()) return 0.0; + return GetAverageVoltage(); } void AnalogInput::UpdateTable() { - if (m_table != NULL) { - m_table->PutNumber("Value", GetAverageVoltage()); - } + if (m_table != NULL) { + m_table->PutNumber("Value", GetAverageVoltage()); + } } -void AnalogInput::StartLiveWindowMode() { +void AnalogInput::StartLiveWindowMode() {} -} - -void AnalogInput::StopLiveWindowMode() { - -} +void AnalogInput::StopLiveWindowMode() {} std::string AnalogInput::GetSmartDashboardType() const { - return "Analog Input"; + return "Analog Input"; } void AnalogInput::InitTable(ITable *subTable) { - m_table = subTable; - UpdateTable(); + m_table = subTable; + UpdateTable(); } -ITable * AnalogInput::GetTable() const { - return m_table; -} +ITable *AnalogInput::GetTable() const { return m_table; } diff --git a/wpilibc/wpilibC++Devices/src/AnalogOutput.cpp b/wpilibc/wpilibC++Devices/src/AnalogOutput.cpp index b769fc0558..a468b1cb3c 100644 --- a/wpilibc/wpilibC++Devices/src/AnalogOutput.cpp +++ b/wpilibc/wpilibC++Devices/src/AnalogOutput.cpp @@ -13,34 +13,32 @@ static Resource *outputs = NULL; void AnalogOutput::InitAnalogOutput(uint32_t channel) { - m_table = NULL; + m_table = NULL; - Resource::CreateResourceObject(&outputs, kAnalogOutputs); + Resource::CreateResourceObject(&outputs, kAnalogOutputs); - char buf[64]; + char buf[64]; - if(!checkAnalogOutputChannel(channel)) - { - snprintf(buf, 64, "analog input %d", channel); - wpi_setWPIErrorWithContext(ChannelIndexOutOfRange, buf); - return; - } + if (!checkAnalogOutputChannel(channel)) { + snprintf(buf, 64, "analog input %d", channel); + wpi_setWPIErrorWithContext(ChannelIndexOutOfRange, buf); + return; + } - if(outputs->Allocate(channel, buf) == ~0ul) - { - CloneError(outputs); - return; - } + if (outputs->Allocate(channel, buf) == ~0ul) { + CloneError(outputs); + return; + } - m_channel = channel; + m_channel = channel; - void* port = getPort(m_channel); - int32_t status = 0; - m_port = initializeAnalogOutputPort(port, &status); - wpi_setErrorWithContext(status, getHALErrorMessage(status)); + void *port = getPort(m_channel); + int32_t status = 0; + m_port = initializeAnalogOutputPort(port, &status); + wpi_setErrorWithContext(status, getHALErrorMessage(status)); - LiveWindow::GetInstance()->AddActuator("AnalogOutput", m_channel, this); - HALReport(HALUsageReporting::kResourceType_AnalogOutput, m_channel); + LiveWindow::GetInstance()->AddActuator("AnalogOutput", m_channel, this); + HALReport(HALUsageReporting::kResourceType_AnalogOutput, m_channel); } /** @@ -48,16 +46,12 @@ void AnalogOutput::InitAnalogOutput(uint32_t channel) { * All analog outputs are located on the MXP port. * @param The channel number on the roboRIO to represent. */ -AnalogOutput::AnalogOutput(uint32_t channel) { - InitAnalogOutput(channel); -} +AnalogOutput::AnalogOutput(uint32_t channel) { InitAnalogOutput(channel); } /** * Destructor. Frees analog output resource */ -AnalogOutput::~AnalogOutput() { - outputs->Free(m_channel); -} +AnalogOutput::~AnalogOutput() { outputs->Free(m_channel); } /** * Set the value of the analog output @@ -65,10 +59,10 @@ AnalogOutput::~AnalogOutput() { * @param voltage The output value in Volts, from 0.0 to +5.0 */ void AnalogOutput::SetVoltage(float voltage) { - int32_t status = 0; - setAnalogOutput(m_port, voltage, &status); + int32_t status = 0; + setAnalogOutput(m_port, voltage, &status); - wpi_setErrorWithContext(status, getHALErrorMessage(status)); + wpi_setErrorWithContext(status, getHALErrorMessage(status)); } /** @@ -77,35 +71,31 @@ void AnalogOutput::SetVoltage(float voltage) { * @return The value in Volts, from 0.0 to +5.0 */ float AnalogOutput::GetVoltage() const { - int32_t status = 0; - float voltage = getAnalogOutput(m_port, &status); + int32_t status = 0; + float voltage = getAnalogOutput(m_port, &status); - wpi_setErrorWithContext(status, getHALErrorMessage(status)); + wpi_setErrorWithContext(status, getHALErrorMessage(status)); - return voltage; + return voltage; } void AnalogOutput::UpdateTable() { - if (m_table != NULL) { - m_table->PutNumber("Value", GetVoltage()); - } + if (m_table != NULL) { + m_table->PutNumber("Value", GetVoltage()); + } } -void AnalogOutput::StartLiveWindowMode() { -} +void AnalogOutput::StartLiveWindowMode() {} -void AnalogOutput::StopLiveWindowMode() { -} +void AnalogOutput::StopLiveWindowMode() {} std::string AnalogOutput::GetSmartDashboardType() const { - return "Analog Output"; + return "Analog Output"; } void AnalogOutput::InitTable(ITable *subTable) { - m_table = subTable; - UpdateTable(); + m_table = subTable; + UpdateTable(); } -ITable *AnalogOutput::GetTable() const { - return m_table; -} +ITable *AnalogOutput::GetTable() const { return m_table; } diff --git a/wpilibc/wpilibC++Devices/src/AnalogPotentiometer.cpp b/wpilibc/wpilibC++Devices/src/AnalogPotentiometer.cpp index 5aa7a14e80..05c9ce07d9 100644 --- a/wpilibc/wpilibC++Devices/src/AnalogPotentiometer.cpp +++ b/wpilibc/wpilibC++Devices/src/AnalogPotentiometer.cpp @@ -5,50 +5,64 @@ /** * Common initialization code called by all constructors. */ -void AnalogPotentiometer::initPot(AnalogInput *input, double fullRange, double offset) { - m_fullRange = fullRange; - m_offset = offset; - m_analog_input = input; +void AnalogPotentiometer::initPot(AnalogInput *input, double fullRange, + double offset) { + m_fullRange = fullRange; + m_offset = offset; + m_analog_input = input; } /** * Construct an Analog Potentiometer object from a channel number. - * @param channel The channel number on the roboRIO to represent. 0-3 are on-board 4-7 are on the MXP port. - * @param fullRange The angular value (in desired units) representing the full 0-5V range of the input. - * @param offset The angular value (in desired units) representing the angular output at 0V. + * @param channel The channel number on the roboRIO to represent. 0-3 are + * on-board 4-7 are on the MXP port. + * @param fullRange The angular value (in desired units) representing the full + * 0-5V range of the input. + * @param offset The angular value (in desired units) representing the angular + * output at 0V. */ -AnalogPotentiometer::AnalogPotentiometer(int channel, double fullRange, double offset) { - m_init_analog_input = true; - initPot(new AnalogInput(channel), fullRange, offset); +AnalogPotentiometer::AnalogPotentiometer(int channel, double fullRange, + double offset) { + m_init_analog_input = true; + initPot(new AnalogInput(channel), fullRange, offset); } /** - * Construct an Analog Potentiometer object from an existing Analog Input pointer. - * @param channel The existing Analog Input pointer - * @param fullRange The angular value (in desired units) representing the full 0-5V range of the input. - * @param offset The angular value (in desired units) representing the angular output at 0V. + * Construct an Analog Potentiometer object from an existing Analog Input + * pointer. + * @param channel The existing Analog Input pointer + * @param fullRange The angular value (in desired units) representing the full + * 0-5V range of the input. + * @param offset The angular value (in desired units) representing the angular + * output at 0V. */ -AnalogPotentiometer::AnalogPotentiometer(AnalogInput *input, double fullRange, double offset) { - m_init_analog_input = false; - initPot(input, fullRange, offset); +AnalogPotentiometer::AnalogPotentiometer(AnalogInput *input, double fullRange, + double offset) { + m_init_analog_input = false; + initPot(input, fullRange, offset); } /** - * Construct an Analog Potentiometer object from an existing Analog Input reference. - * @param channel The existing Analog Input reference - * @param fullRange The angular value (in desired units) representing the full 0-5V range of the input. - * @param offset The angular value (in desired units) representing the angular output at 0V. + * Construct an Analog Potentiometer object from an existing Analog Input + * reference. + * @param channel The existing Analog Input reference + * @param fullRange The angular value (in desired units) representing the full + * 0-5V range of the input. + * @param offset The angular value (in desired units) representing the angular + * output at 0V. */ -AnalogPotentiometer::AnalogPotentiometer(AnalogInput &input, double fullRange, double offset) { - m_init_analog_input = false; - initPot(&input, fullRange, offset); +AnalogPotentiometer::AnalogPotentiometer(AnalogInput &input, double fullRange, + double offset) { + m_init_analog_input = false; + initPot(&input, fullRange, offset); } /** - * Destructor. Releases the Analog Input resource if it was allocated by this object + * Destructor. Releases the Analog Input resource if it was allocated by this + * object */ AnalogPotentiometer::~AnalogPotentiometer() { - if(m_init_analog_input){ + if (m_init_analog_input) { delete m_analog_input; m_init_analog_input = false; } @@ -57,10 +71,13 @@ AnalogPotentiometer::~AnalogPotentiometer() { /** * Get the current reading of the potentiometer. * - * @return The current position of the potentiometer (in the units used for fullRaneg and offset). + * @return The current position of the potentiometer (in the units used for + * fullRaneg and offset). */ double AnalogPotentiometer::Get() const { - return (m_analog_input->GetVoltage() / ControllerPower::GetVoltage5V()) * m_fullRange + m_offset; + return (m_analog_input->GetVoltage() / ControllerPower::GetVoltage5V()) * + m_fullRange + + m_offset; } /** @@ -68,32 +85,27 @@ double AnalogPotentiometer::Get() const { * * @return The current reading. */ -double AnalogPotentiometer::PIDGet() const { - return Get(); -} - +double AnalogPotentiometer::PIDGet() const { return Get(); } /** * @return the Smart Dashboard Type */ std::string AnalogPotentiometer::GetSmartDashboardType() const { - return "Analog Input"; + return "Analog Input"; } /** * Live Window code, only does anything if live window is activated. */ void AnalogPotentiometer::InitTable(ITable *subtable) { - m_table = subtable; - UpdateTable(); + m_table = subtable; + UpdateTable(); } void AnalogPotentiometer::UpdateTable() { - if (m_table != NULL) { - m_table->PutNumber("Value", Get()); - } + if (m_table != NULL) { + m_table->PutNumber("Value", Get()); + } } -ITable* AnalogPotentiometer::GetTable() const { - return m_table; -} +ITable *AnalogPotentiometer::GetTable() const { return m_table; } diff --git a/wpilibc/wpilibC++Devices/src/AnalogTrigger.cpp b/wpilibc/wpilibC++Devices/src/AnalogTrigger.cpp index 61cd0148c0..f5ffe64651 100644 --- a/wpilibc/wpilibC++Devices/src/AnalogTrigger.cpp +++ b/wpilibc/wpilibC++Devices/src/AnalogTrigger.cpp @@ -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. */ /*----------------------------------------------------------------------------*/ @@ -14,27 +15,24 @@ /** * Initialize an analog trigger from a channel. */ -void AnalogTrigger::InitTrigger(uint32_t channel) -{ - void* port = getPort(channel); - int32_t status = 0; - uint32_t index = 0; - m_trigger = initializeAnalogTrigger(port, &index, &status); - wpi_setErrorWithContext(status, getHALErrorMessage(status)); - m_index = index; +void AnalogTrigger::InitTrigger(uint32_t channel) { + void *port = getPort(channel); + int32_t status = 0; + uint32_t index = 0; + m_trigger = initializeAnalogTrigger(port, &index, &status); + wpi_setErrorWithContext(status, getHALErrorMessage(status)); + m_index = index; - HALReport(HALUsageReporting::kResourceType_AnalogTrigger, channel); + HALReport(HALUsageReporting::kResourceType_AnalogTrigger, channel); } /** * Constructor for an analog trigger given a channel number. * - * @param channel The channel number on the roboRIO to represent. 0-3 are on-board 4-7 are on the MXP port. + * @param channel The channel number on the roboRIO to represent. 0-3 are + * on-board 4-7 are on the MXP port. */ -AnalogTrigger::AnalogTrigger(int32_t channel) -{ - InitTrigger(channel); -} +AnalogTrigger::AnalogTrigger(int32_t channel) { InitTrigger(channel); } /** * Construct an analog trigger given an analog input. @@ -42,31 +40,29 @@ AnalogTrigger::AnalogTrigger(int32_t channel) * trigger and an analog input object. * @param channel The pointer to the existing AnalogInput object */ -AnalogTrigger::AnalogTrigger(AnalogInput *input) -{ - InitTrigger(input->GetChannel()); +AnalogTrigger::AnalogTrigger(AnalogInput *input) { + InitTrigger(input->GetChannel()); } -AnalogTrigger::~AnalogTrigger() -{ - int32_t status = 0; - cleanAnalogTrigger(m_trigger, &status); - wpi_setErrorWithContext(status, getHALErrorMessage(status)); +AnalogTrigger::~AnalogTrigger() { + int32_t status = 0; + cleanAnalogTrigger(m_trigger, &status); + wpi_setErrorWithContext(status, getHALErrorMessage(status)); } /** * Set the upper and lower limits of the analog trigger. - * The limits are given in ADC codes. If oversampling is used, the units must be scaled + * The limits are given in ADC codes. If oversampling is used, the units must + * be scaled * appropriately. * @param lower The lower limit of the trigger in ADC codes (12-bit values). * @param upper The upper limit of the trigger in ADC codes (12-bit values). */ -void AnalogTrigger::SetLimitsRaw(int32_t lower, int32_t upper) -{ - if (StatusIsFatal()) return; - int32_t status = 0; - setAnalogTriggerLimitsRaw(m_trigger, lower, upper, &status); - wpi_setErrorWithContext(status, getHALErrorMessage(status)); +void AnalogTrigger::SetLimitsRaw(int32_t lower, int32_t upper) { + if (StatusIsFatal()) return; + int32_t status = 0; + setAnalogTriggerLimitsRaw(m_trigger, lower, upper, &status); + wpi_setErrorWithContext(status, getHALErrorMessage(status)); } /** @@ -75,40 +71,42 @@ void AnalogTrigger::SetLimitsRaw(int32_t lower, int32_t upper) * @param lower The lower limit of the trigger in Volts. * @param upper The upper limit of the trigger in Volts. */ -void AnalogTrigger::SetLimitsVoltage(float lower, float upper) -{ - if (StatusIsFatal()) return; - int32_t status = 0; - setAnalogTriggerLimitsVoltage(m_trigger, lower, upper, &status); - wpi_setErrorWithContext(status, getHALErrorMessage(status)); +void AnalogTrigger::SetLimitsVoltage(float lower, float upper) { + if (StatusIsFatal()) return; + int32_t status = 0; + setAnalogTriggerLimitsVoltage(m_trigger, lower, upper, &status); + wpi_setErrorWithContext(status, getHALErrorMessage(status)); } /** * Configure the analog trigger to use the averaged vs. raw values. - * If the value is true, then the averaged value is selected for the analog trigger, otherwise + * If the value is true, then the averaged value is selected for the analog + * trigger, otherwise * the immediate value is used. - * @param useAveragedValue If true, use the Averaged value, otherwise use the instantaneous reading + * @param useAveragedValue If true, use the Averaged value, otherwise use the + * instantaneous reading */ -void AnalogTrigger::SetAveraged(bool useAveragedValue) -{ - if (StatusIsFatal()) return; - int32_t status = 0; - setAnalogTriggerAveraged(m_trigger, useAveragedValue, &status); - wpi_setErrorWithContext(status, getHALErrorMessage(status)); +void AnalogTrigger::SetAveraged(bool useAveragedValue) { + if (StatusIsFatal()) return; + int32_t status = 0; + setAnalogTriggerAveraged(m_trigger, useAveragedValue, &status); + wpi_setErrorWithContext(status, getHALErrorMessage(status)); } /** * Configure the analog trigger to use a filtered value. - * The analog trigger will operate with a 3 point average rejection filter. This is designed to - * help with 360 degree pot applications for the period where the pot crosses through zero. - * @param useFilteredValue If true, use the 3 point rejection filter, otherwise use the unfiltered value + * The analog trigger will operate with a 3 point average rejection filter. This + * is designed to + * help with 360 degree pot applications for the period where the pot crosses + * through zero. + * @param useFilteredValue If true, use the 3 point rejection filter, otherwise + * use the unfiltered value */ -void AnalogTrigger::SetFiltered(bool useFilteredValue) -{ - if (StatusIsFatal()) return; - int32_t status = 0; - setAnalogTriggerFiltered(m_trigger, useFilteredValue, &status); - wpi_setErrorWithContext(status, getHALErrorMessage(status)); +void AnalogTrigger::SetFiltered(bool useFilteredValue) { + if (StatusIsFatal()) return; + int32_t status = 0; + setAnalogTriggerFiltered(m_trigger, useFilteredValue, &status); + wpi_setErrorWithContext(status, getHALErrorMessage(status)); } /** @@ -116,10 +114,9 @@ void AnalogTrigger::SetFiltered(bool useFilteredValue) * This is the FPGA index of this analog trigger instance. * @return The index of the analog trigger. */ -uint32_t AnalogTrigger::GetIndex() -{ - if (StatusIsFatal()) return ~0ul; - return m_index; +uint32_t AnalogTrigger::GetIndex() { + if (StatusIsFatal()) return ~0ul; + return m_index; } /** @@ -127,13 +124,12 @@ uint32_t AnalogTrigger::GetIndex() * True if the analog input is between the upper and lower limits. * @return True if the analog input is between the upper and lower limits. */ -bool AnalogTrigger::GetInWindow() -{ - if (StatusIsFatal()) return false; - int32_t status = 0; - bool result = getAnalogTriggerInWindow(m_trigger, &status); - wpi_setErrorWithContext(status, getHALErrorMessage(status)); - return result; +bool AnalogTrigger::GetInWindow() { + if (StatusIsFatal()) return false; + int32_t status = 0; + bool result = getAnalogTriggerInWindow(m_trigger, &status); + wpi_setErrorWithContext(status, getHALErrorMessage(status)); + return result; } /** @@ -141,15 +137,15 @@ bool AnalogTrigger::GetInWindow() * True if above upper limit. * False if below lower limit. * If in Hysteresis, maintain previous state. - * @return True if above upper limit. False if below lower limit. If in Hysteresis, maintain previous state. + * @return True if above upper limit. False if below lower limit. If in + * Hysteresis, maintain previous state. */ -bool AnalogTrigger::GetTriggerState() -{ - if (StatusIsFatal()) return false; - int32_t status = 0; - bool result = getAnalogTriggerTriggerState(m_trigger, &status); - wpi_setErrorWithContext(status, getHALErrorMessage(status)); - return result; +bool AnalogTrigger::GetTriggerState() { + if (StatusIsFatal()) return false; + int32_t status = 0; + bool result = getAnalogTriggerTriggerState(m_trigger, &status); + wpi_setErrorWithContext(status, getHALErrorMessage(status)); + return result; } /** @@ -159,8 +155,7 @@ bool AnalogTrigger::GetTriggerState() * @param type An enum of the type of output object to create. * @return A pointer to a new AnalogTriggerOutput object. */ -AnalogTriggerOutput *AnalogTrigger::CreateOutput(AnalogTriggerType type) -{ - if (StatusIsFatal()) return NULL; - return new AnalogTriggerOutput(this, type); +AnalogTriggerOutput *AnalogTrigger::CreateOutput(AnalogTriggerType type) { + if (StatusIsFatal()) return NULL; + return new AnalogTriggerOutput(this, type); } diff --git a/wpilibc/wpilibC++Devices/src/AnalogTriggerOutput.cpp b/wpilibc/wpilibC++Devices/src/AnalogTriggerOutput.cpp index 07e92c6037..87f75c20bc 100644 --- a/wpilibc/wpilibC++Devices/src/AnalogTriggerOutput.cpp +++ b/wpilibc/wpilibC++Devices/src/AnalogTriggerOutput.cpp @@ -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,41 +11,42 @@ #include "WPIErrors.h" /** - * Create an object that represents one of the four outputs from an analog trigger. + * Create an object that represents one of the four outputs from an analog + * trigger. * - * Because this class derives from DigitalSource, it can be passed into routing functions + * Because this class derives from DigitalSource, it can be passed into routing + * functions * for Counter, Encoder, etc. * * @param trigger A pointer to the trigger for which this is an output. - * @param outputType An enum that specifies the output on the trigger to represent. + * @param outputType An enum that specifies the output on the trigger to + * represent. */ -AnalogTriggerOutput::AnalogTriggerOutput(AnalogTrigger *trigger, AnalogTriggerType outputType) - : m_trigger (trigger) - , m_outputType (outputType) -{ - HALReport(HALUsageReporting::kResourceType_AnalogTriggerOutput, trigger->GetIndex(), outputType); +AnalogTriggerOutput::AnalogTriggerOutput(AnalogTrigger *trigger, + AnalogTriggerType outputType) + : m_trigger(trigger), m_outputType(outputType) { + HALReport(HALUsageReporting::kResourceType_AnalogTriggerOutput, + trigger->GetIndex(), outputType); } -AnalogTriggerOutput::~AnalogTriggerOutput() -{ - if (m_interrupt != NULL) - { - int32_t status = 0; - cleanInterrupts(m_interrupt, &status); - wpi_setErrorWithContext(status, getHALErrorMessage(status)); - m_interrupt = NULL; - m_interrupts->Free(m_interruptIndex); - } +AnalogTriggerOutput::~AnalogTriggerOutput() { + if (m_interrupt != NULL) { + int32_t status = 0; + cleanInterrupts(m_interrupt, &status); + wpi_setErrorWithContext(status, getHALErrorMessage(status)); + m_interrupt = NULL; + m_interrupts->Free(m_interruptIndex); + } } /** * Get the state of the analog trigger output. * @return The state of the analog trigger output. */ -bool AnalogTriggerOutput::Get() const -{ +bool AnalogTriggerOutput::Get() const { int32_t status = 0; - bool result = getAnalogTriggerOutput(m_trigger->m_trigger, m_outputType, &status); + bool result = + getAnalogTriggerOutput(m_trigger->m_trigger, m_outputType, &status); wpi_setErrorWithContext(status, getHALErrorMessage(status)); return result; } @@ -52,23 +54,16 @@ bool AnalogTriggerOutput::Get() const /** * @return The value to be written to the channel field of a routing mux. */ -uint32_t AnalogTriggerOutput::GetChannelForRouting() const -{ - return (m_trigger->m_index << 2) + m_outputType; +uint32_t AnalogTriggerOutput::GetChannelForRouting() const { + return (m_trigger->m_index << 2) + m_outputType; } /** * @return The value to be written to the module field of a routing mux. */ -uint32_t AnalogTriggerOutput::GetModuleForRouting() const -{ - return 0; -} +uint32_t AnalogTriggerOutput::GetModuleForRouting() const { return 0; } /** * @return The value to be written to the module field of a routing mux. */ -bool AnalogTriggerOutput::GetAnalogTriggerForRouting() const -{ - return true; -} +bool AnalogTriggerOutput::GetAnalogTriggerForRouting() const { return true; } diff --git a/wpilibc/wpilibC++Devices/src/BuiltInAccelerometer.cpp b/wpilibc/wpilibC++Devices/src/BuiltInAccelerometer.cpp index c36c17f6f0..4b2a7f5745 100644 --- a/wpilibc/wpilibC++Devices/src/BuiltInAccelerometer.cpp +++ b/wpilibc/wpilibC++Devices/src/BuiltInAccelerometer.cpp @@ -13,73 +13,58 @@ * Constructor. * @param range The range the accelerometer will measure */ -BuiltInAccelerometer::BuiltInAccelerometer(Range range) - : m_table(0) -{ - SetRange(range); +BuiltInAccelerometer::BuiltInAccelerometer(Range range) : m_table(0) { + SetRange(range); - HALReport(HALUsageReporting::kResourceType_Accelerometer, 0, 0, "Built-in accelerometer"); - LiveWindow::GetInstance()->AddSensor((std::string)"BuiltInAccel",0, this); + HALReport(HALUsageReporting::kResourceType_Accelerometer, 0, 0, + "Built-in accelerometer"); + LiveWindow::GetInstance()->AddSensor((std::string) "BuiltInAccel", 0, this); } -BuiltInAccelerometer::~BuiltInAccelerometer() -{ -} +BuiltInAccelerometer::~BuiltInAccelerometer() {} /** {@inheritdoc} */ -void BuiltInAccelerometer::SetRange(Range range) -{ - if(range == kRange_16G) - { - wpi_setWPIErrorWithContext(ParameterOutOfRange, "16G range not supported (use k2G, k4G, or k8G)"); - } +void BuiltInAccelerometer::SetRange(Range range) { + if (range == kRange_16G) { + wpi_setWPIErrorWithContext( + ParameterOutOfRange, "16G range not supported (use k2G, k4G, or k8G)"); + } - setAccelerometerActive(false); - setAccelerometerRange((AccelerometerRange)range); - setAccelerometerActive(true); + setAccelerometerActive(false); + setAccelerometerRange((AccelerometerRange)range); + setAccelerometerActive(true); } /** * @return The acceleration of the RoboRIO along the X axis in g-forces */ -double BuiltInAccelerometer::GetX() -{ - return getAccelerometerX(); -} +double BuiltInAccelerometer::GetX() { return getAccelerometerX(); } /** * @return The acceleration of the RoboRIO along the Y axis in g-forces */ -double BuiltInAccelerometer::GetY() -{ - return getAccelerometerY(); -} +double BuiltInAccelerometer::GetY() { return getAccelerometerY(); } /** * @return The acceleration of the RoboRIO along the Z axis in g-forces */ -double BuiltInAccelerometer::GetZ() -{ - return getAccelerometerZ(); -} +double BuiltInAccelerometer::GetZ() { return getAccelerometerZ(); } std::string BuiltInAccelerometer::GetSmartDashboardType() const { - return "3AxisAccelerometer"; + return "3AxisAccelerometer"; } -void BuiltInAccelerometer::InitTable(ITable *subtable) { - m_table = subtable; - UpdateTable(); +void BuiltInAccelerometer::InitTable(ITable* subtable) { + m_table = subtable; + UpdateTable(); } void BuiltInAccelerometer::UpdateTable() { - if (m_table != NULL) { - m_table->PutNumber("X", GetX()); - m_table->PutNumber("Y", GetY()); - m_table->PutNumber("Z", GetZ()); - } + if (m_table != NULL) { + m_table->PutNumber("X", GetX()); + m_table->PutNumber("Y", GetY()); + m_table->PutNumber("Z", GetZ()); + } } -ITable* BuiltInAccelerometer::GetTable() const { - return m_table; -} +ITable* BuiltInAccelerometer::GetTable() const { return m_table; } diff --git a/wpilibc/wpilibC++Devices/src/CANJaguar.cpp b/wpilibc/wpilibC++Devices/src/CANJaguar.cpp index 6f7d3fbe37..25782df8c8 100644 --- a/wpilibc/wpilibC++Devices/src/CANJaguar.cpp +++ b/wpilibc/wpilibC++Devices/src/CANJaguar.cpp @@ -16,203 +16,199 @@ #include "LiveWindow/LiveWindow.h" /* we are on ARM-LE now, not Freescale so no need to swap */ -#define swap16(x) (x) -#define swap32(x) (x) +#define swap16(x) (x) +#define swap32(x) (x) /* Compare floats for equality as fixed point numbers */ -#define FXP8_EQ(a,b) ((int16_t)((a)*256.0)==(int16_t)((b)*256.0)) -#define FXP16_EQ(a,b) ((int32_t)((a)*65536.0)==(int32_t)((b)*65536.0)) +#define FXP8_EQ(a, b) ((int16_t)((a)*256.0) == (int16_t)((b)*256.0)) +#define FXP16_EQ(a, b) ((int32_t)((a)*65536.0) == (int32_t)((b)*65536.0)) const int32_t CANJaguar::kControllerRate; constexpr double CANJaguar::kApproxBusVoltage; static const int32_t kSendMessagePeriod = 20; -static const uint32_t kFullMessageIDMask = (CAN_MSGID_API_M | CAN_MSGID_MFR_M | CAN_MSGID_DTYPE_M); +static const uint32_t kFullMessageIDMask = + (CAN_MSGID_API_M | CAN_MSGID_MFR_M | CAN_MSGID_DTYPE_M); static const int32_t kReceiveStatusAttempts = 50; static Resource *allocated = NULL; -static int32_t sendMessageHelper(uint32_t messageID, const uint8_t *data, uint8_t dataSize, int32_t period) -{ - static const uint32_t kTrustedMessages[] = { - LM_API_VOLT_T_EN, LM_API_VOLT_T_SET, LM_API_SPD_T_EN, LM_API_SPD_T_SET, - LM_API_VCOMP_T_EN, LM_API_VCOMP_T_SET, LM_API_POS_T_EN, LM_API_POS_T_SET, - LM_API_ICTRL_T_EN, LM_API_ICTRL_T_SET}; +static int32_t sendMessageHelper(uint32_t messageID, const uint8_t *data, + uint8_t dataSize, int32_t period) { + static const uint32_t kTrustedMessages[] = { + LM_API_VOLT_T_EN, LM_API_VOLT_T_SET, LM_API_SPD_T_EN, LM_API_SPD_T_SET, + LM_API_VCOMP_T_EN, LM_API_VCOMP_T_SET, LM_API_POS_T_EN, LM_API_POS_T_SET, + LM_API_ICTRL_T_EN, LM_API_ICTRL_T_SET}; - int32_t status=0; + int32_t status = 0; - for (uint8_t i=0; i<(sizeof(kTrustedMessages)/sizeof(kTrustedMessages[0])); i++) - { - if ((kFullMessageIDMask & messageID) == kTrustedMessages[i]) - { - uint8_t dataBuffer[8]; - dataBuffer[0] = 0; - dataBuffer[1] = 0; + for (uint8_t i = 0; + i < (sizeof(kTrustedMessages) / sizeof(kTrustedMessages[0])); i++) { + if ((kFullMessageIDMask & messageID) == kTrustedMessages[i]) { + uint8_t dataBuffer[8]; + dataBuffer[0] = 0; + dataBuffer[1] = 0; - // Make sure the data will still fit after adjusting for the token. - assert(dataSize <= 6); + // Make sure the data will still fit after adjusting for the token. + assert(dataSize <= 6); - for (uint8_t j=0; j < dataSize; j++) - { - dataBuffer[j + 2] = data[j]; - } + for (uint8_t j = 0; j < dataSize; j++) { + dataBuffer[j + 2] = data[j]; + } - FRC_NetworkCommunication_CANSessionMux_sendMessage(messageID, dataBuffer, dataSize + 2, period, &status); + FRC_NetworkCommunication_CANSessionMux_sendMessage( + messageID, dataBuffer, dataSize + 2, period, &status); - return status; - } - } + return status; + } + } - FRC_NetworkCommunication_CANSessionMux_sendMessage(messageID, data, dataSize, period, &status); + FRC_NetworkCommunication_CANSessionMux_sendMessage(messageID, data, dataSize, + period, &status); - return status; + return status; } /** * Common initialization code called by all constructors. */ -void CANJaguar::InitCANJaguar() -{ - m_table = NULL; - m_safetyHelper = new MotorSafetyHelper(this); +void CANJaguar::InitCANJaguar() { + m_table = NULL; + m_safetyHelper = new MotorSafetyHelper(this); - m_value = 0.0f; - m_speedReference = LM_REF_NONE; - m_positionReference = LM_REF_NONE; - m_p = 0.0; - m_i = 0.0; - m_d = 0.0; - m_busVoltage = 0.0f; - m_outputVoltage = 0.0f; - m_outputCurrent = 0.0f; - m_temperature = 0.0f; - m_position = 0.0; - m_speed = 0.0; - m_limits = 0x00; - m_faults = 0x0000; - m_firmwareVersion = 0; - m_hardwareVersion = 0; - m_neutralMode = kNeutralMode_Jumper; - m_encoderCodesPerRev = 0; - m_potentiometerTurns = 0; - m_limitMode = kLimitMode_SwitchInputsOnly; - m_forwardLimit = 0.0; - m_reverseLimit = 0.0; - m_maxOutputVoltage = 30.0; - m_voltageRampRate = 0.0; - m_faultTime = 0.0f; + m_value = 0.0f; + m_speedReference = LM_REF_NONE; + m_positionReference = LM_REF_NONE; + m_p = 0.0; + m_i = 0.0; + m_d = 0.0; + m_busVoltage = 0.0f; + m_outputVoltage = 0.0f; + m_outputCurrent = 0.0f; + m_temperature = 0.0f; + m_position = 0.0; + m_speed = 0.0; + m_limits = 0x00; + m_faults = 0x0000; + m_firmwareVersion = 0; + m_hardwareVersion = 0; + m_neutralMode = kNeutralMode_Jumper; + m_encoderCodesPerRev = 0; + m_potentiometerTurns = 0; + m_limitMode = kLimitMode_SwitchInputsOnly; + m_forwardLimit = 0.0; + m_reverseLimit = 0.0; + m_maxOutputVoltage = 30.0; + m_voltageRampRate = 0.0; + m_faultTime = 0.0f; - // Parameters only need to be verified if they are set - m_controlModeVerified = false; // Needs to be verified because it's set in the constructor - m_speedRefVerified = true; - m_posRefVerified = true; - m_pVerified = true; - m_iVerified = true; - m_dVerified = true; - m_neutralModeVerified = true; - m_encoderCodesPerRevVerified = true; - m_potentiometerTurnsVerified = true; - m_limitModeVerified = true; - m_forwardLimitVerified = true; - m_reverseLimitVerified = true; - m_maxOutputVoltageVerified = true; - m_voltageRampRateVerified = true; - m_faultTimeVerified = true; + // Parameters only need to be verified if they are set + m_controlModeVerified = + false; // Needs to be verified because it's set in the constructor + m_speedRefVerified = true; + m_posRefVerified = true; + m_pVerified = true; + m_iVerified = true; + m_dVerified = true; + m_neutralModeVerified = true; + m_encoderCodesPerRevVerified = true; + m_potentiometerTurnsVerified = true; + m_limitModeVerified = true; + m_forwardLimitVerified = true; + m_reverseLimitVerified = true; + m_maxOutputVoltageVerified = true; + m_voltageRampRateVerified = true; + m_faultTimeVerified = true; - m_receivedStatusMessage0 = false; - m_receivedStatusMessage1 = false; - m_receivedStatusMessage2 = false; + m_receivedStatusMessage0 = false; + m_receivedStatusMessage1 = false; + m_receivedStatusMessage2 = false; - bool receivedFirmwareVersion = false; - uint8_t dataBuffer[8]; - uint8_t dataSize; + bool receivedFirmwareVersion = false; + uint8_t dataBuffer[8]; + uint8_t dataSize; - // Request firmware and hardware version only once - requestMessage(CAN_IS_FRAME_REMOTE | CAN_MSGID_API_FIRMVER); - requestMessage(LM_API_HWVER); + // Request firmware and hardware version only once + requestMessage(CAN_IS_FRAME_REMOTE | CAN_MSGID_API_FIRMVER); + requestMessage(LM_API_HWVER); - // Wait until we've gotten all of the status data at least once. - for(int i = 0; i < kReceiveStatusAttempts; i++) - { - Wait(0.001); + // Wait until we've gotten all of the status data at least once. + for (int i = 0; i < kReceiveStatusAttempts; i++) { + Wait(0.001); - setupPeriodicStatus(); - updatePeriodicStatus(); + setupPeriodicStatus(); + updatePeriodicStatus(); - if(!receivedFirmwareVersion && - getMessage(CAN_MSGID_API_FIRMVER, CAN_MSGID_FULL_M, dataBuffer, &dataSize)) - { - m_firmwareVersion = unpackint32_t(dataBuffer); - receivedFirmwareVersion = true; - } + if (!receivedFirmwareVersion && + getMessage(CAN_MSGID_API_FIRMVER, CAN_MSGID_FULL_M, dataBuffer, + &dataSize)) { + m_firmwareVersion = unpackint32_t(dataBuffer); + receivedFirmwareVersion = true; + } - if(m_receivedStatusMessage0 && - m_receivedStatusMessage1 && - m_receivedStatusMessage2 && - receivedFirmwareVersion) - { - break; - } - } + if (m_receivedStatusMessage0 && m_receivedStatusMessage1 && + m_receivedStatusMessage2 && receivedFirmwareVersion) { + break; + } + } - if(!m_receivedStatusMessage0 || - !m_receivedStatusMessage1 || - !m_receivedStatusMessage2 || - !receivedFirmwareVersion) - { - wpi_setWPIErrorWithContext(JaguarMessageNotFound, "Status data not found"); - } + if (!m_receivedStatusMessage0 || !m_receivedStatusMessage1 || + !m_receivedStatusMessage2 || !receivedFirmwareVersion) { + wpi_setWPIErrorWithContext(JaguarMessageNotFound, "Status data not found"); + } - if(getMessage(LM_API_HWVER, CAN_MSGID_FULL_M, dataBuffer, &dataSize)) - m_hardwareVersion = dataBuffer[0]; + if (getMessage(LM_API_HWVER, CAN_MSGID_FULL_M, dataBuffer, &dataSize)) + m_hardwareVersion = dataBuffer[0]; - if (m_deviceNumber < 1 || m_deviceNumber > 63) - { - char buf[256]; - snprintf(buf, 256, "device number \"%d\" must be between 1 and 63", m_deviceNumber); - wpi_setWPIErrorWithContext(ParameterOutOfRange, buf); - return; - } + if (m_deviceNumber < 1 || m_deviceNumber > 63) { + char buf[256]; + snprintf(buf, 256, "device number \"%d\" must be between 1 and 63", + m_deviceNumber); + wpi_setWPIErrorWithContext(ParameterOutOfRange, buf); + return; + } - if (StatusIsFatal()) - return; + if (StatusIsFatal()) return; - // 3330 was the first shipping RDK firmware version for the Jaguar - if (m_firmwareVersion >= 3330 || m_firmwareVersion < 108) - { - char buf[256]; - if (m_firmwareVersion < 3330) - { - snprintf(buf, 256, "Jag #%d firmware (%d) is too old (must be at least version 108 of the FIRST approved firmware)", m_deviceNumber, m_firmwareVersion); - } - else - { - snprintf(buf, 256, "Jag #%d firmware (%d) is not FIRST approved (must be at least version 108 of the FIRST approved firmware)", m_deviceNumber, m_firmwareVersion); - } - wpi_setWPIErrorWithContext(JaguarVersionError, buf); - return; - } + // 3330 was the first shipping RDK firmware version for the Jaguar + if (m_firmwareVersion >= 3330 || m_firmwareVersion < 108) { + char buf[256]; + if (m_firmwareVersion < 3330) { + snprintf(buf, 256, + "Jag #%d firmware (%d) is too old (must be at least version 108 " + "of the FIRST approved firmware)", + m_deviceNumber, m_firmwareVersion); + } else { + snprintf(buf, 256, + "Jag #%d firmware (%d) is not FIRST approved (must be at least " + "version 108 of the FIRST approved firmware)", + m_deviceNumber, m_firmwareVersion); + } + wpi_setWPIErrorWithContext(JaguarVersionError, buf); + return; + } - switch (m_controlMode) - { - case kPercentVbus: - case kVoltage: - // No additional configuration required... start enabled. - EnableControl(); - break; - default: - break; - } - m_isInverted = false; - HALReport(HALUsageReporting::kResourceType_CANJaguar, m_deviceNumber, m_controlMode); - LiveWindow::GetInstance()->AddActuator("CANJaguar", m_deviceNumber, this); + switch (m_controlMode) { + case kPercentVbus: + case kVoltage: + // No additional configuration required... start enabled. + EnableControl(); + break; + default: + break; + } + m_isInverted = false; + HALReport(HALUsageReporting::kResourceType_CANJaguar, m_deviceNumber, + m_controlMode); + LiveWindow::GetInstance()->AddActuator("CANJaguar", m_deviceNumber, this); } /** * Constructor for the CANJaguar device.
* By default the device is configured in Percent mode. - * The control mode can be changed by calling one of the control modes listed below. + * The control mode can be changed by calling one of the control modes listed + * below. * * @param deviceNumber The address of the Jaguar on the CAN bus. * @see CANJaguar#SetCurrentMode(double, double, double) @@ -233,140 +229,138 @@ void CANJaguar::InitCANJaguar() * @see CANJaguar#SetVoltageMode(QuadEncoderTag, int) */ CANJaguar::CANJaguar(uint8_t deviceNumber) - : m_deviceNumber (deviceNumber) - , m_maxOutputVoltage (kApproxBusVoltage) - , m_safetyHelper (NULL) -{ - char buf[64]; - snprintf(buf, 64, "CANJaguar device number %d", m_deviceNumber); - Resource::CreateResourceObject(&allocated, 63); + : m_deviceNumber(deviceNumber), + m_maxOutputVoltage(kApproxBusVoltage), + m_safetyHelper(NULL) { + char buf[64]; + snprintf(buf, 64, "CANJaguar device number %d", m_deviceNumber); + Resource::CreateResourceObject(&allocated, 63); - if (allocated->Allocate(m_deviceNumber-1, buf) == ~0ul) - { - CloneError(allocated); - return; - } + if (allocated->Allocate(m_deviceNumber - 1, buf) == ~0ul) { + CloneError(allocated); + return; + } - SetPercentMode(); - InitCANJaguar(); - ConfigMaxOutputVoltage(kApproxBusVoltage); + SetPercentMode(); + InitCANJaguar(); + ConfigMaxOutputVoltage(kApproxBusVoltage); } -CANJaguar::~CANJaguar() -{ - allocated->Free(m_deviceNumber-1); +CANJaguar::~CANJaguar() { + allocated->Free(m_deviceNumber - 1); - int32_t status; + int32_t status; - // Disable periodic setpoints - if(m_controlMode == kPercentVbus) - FRC_NetworkCommunication_CANSessionMux_sendMessage(m_deviceNumber | LM_API_VOLT_T_SET, NULL, 0, CAN_SEND_PERIOD_STOP_REPEATING, &status); - else if(m_controlMode == kSpeed) - FRC_NetworkCommunication_CANSessionMux_sendMessage(m_deviceNumber | LM_API_SPD_T_SET, NULL, 0, CAN_SEND_PERIOD_STOP_REPEATING, &status); - else if(m_controlMode == kPosition) - FRC_NetworkCommunication_CANSessionMux_sendMessage(m_deviceNumber | LM_API_POS_T_SET, NULL, 0, CAN_SEND_PERIOD_STOP_REPEATING, &status); - else if(m_controlMode == kCurrent) - FRC_NetworkCommunication_CANSessionMux_sendMessage(m_deviceNumber | LM_API_ICTRL_T_SET, NULL, 0, CAN_SEND_PERIOD_STOP_REPEATING, &status); - else if(m_controlMode == kVoltage) - FRC_NetworkCommunication_CANSessionMux_sendMessage(m_deviceNumber | LM_API_VCOMP_T_SET, NULL, 0, CAN_SEND_PERIOD_STOP_REPEATING, &status); + // Disable periodic setpoints + if (m_controlMode == kPercentVbus) + FRC_NetworkCommunication_CANSessionMux_sendMessage( + m_deviceNumber | LM_API_VOLT_T_SET, NULL, 0, + CAN_SEND_PERIOD_STOP_REPEATING, &status); + else if (m_controlMode == kSpeed) + FRC_NetworkCommunication_CANSessionMux_sendMessage( + m_deviceNumber | LM_API_SPD_T_SET, NULL, 0, + CAN_SEND_PERIOD_STOP_REPEATING, &status); + else if (m_controlMode == kPosition) + FRC_NetworkCommunication_CANSessionMux_sendMessage( + m_deviceNumber | LM_API_POS_T_SET, NULL, 0, + CAN_SEND_PERIOD_STOP_REPEATING, &status); + else if (m_controlMode == kCurrent) + FRC_NetworkCommunication_CANSessionMux_sendMessage( + m_deviceNumber | LM_API_ICTRL_T_SET, NULL, 0, + CAN_SEND_PERIOD_STOP_REPEATING, &status); + else if (m_controlMode == kVoltage) + FRC_NetworkCommunication_CANSessionMux_sendMessage( + m_deviceNumber | LM_API_VCOMP_T_SET, NULL, 0, + CAN_SEND_PERIOD_STOP_REPEATING, &status); - delete m_safetyHelper; - m_safetyHelper = NULL; + delete m_safetyHelper; + m_safetyHelper = NULL; } /** * @return The CAN ID passed in the constructor */ -uint8_t CANJaguar::getDeviceNumber() const -{ - return m_deviceNumber; -} +uint8_t CANJaguar::getDeviceNumber() const { return m_deviceNumber; } /** * Sets the output set-point value. * * The scale and the units depend on the mode the Jaguar is in.
- * In percentVbus Mode, the outputValue is from -1.0 to 1.0 (same as PWM Jaguar).
+ * In percentVbus Mode, the outputValue is from -1.0 to 1.0 (same as PWM + * Jaguar).
* In voltage Mode, the outputValue is in volts.
* In current Mode, the outputValue is in amps.
* In speed Mode, the outputValue is in rotations/minute.
* In position Mode, the outputValue is in rotations. * * @param outputValue The set-point to sent to the motor controller. - * @param syncGroup The update group to add this Set() to, pending UpdateSyncGroup(). If 0, update immediately. + * @param syncGroup The update group to add this Set() to, pending + * UpdateSyncGroup(). If 0, update immediately. */ -void CANJaguar::Set(float outputValue, uint8_t syncGroup) -{ - uint32_t messageID; - uint8_t dataBuffer[8]; - uint8_t dataSize; +void CANJaguar::Set(float outputValue, uint8_t syncGroup) { + uint32_t messageID; + uint8_t dataBuffer[8]; + uint8_t dataSize; - if(m_safetyHelper && !m_safetyHelper->IsAlive() && m_controlEnabled) - { - EnableControl(); - } + if (m_safetyHelper && !m_safetyHelper->IsAlive() && m_controlEnabled) { + EnableControl(); + } - if(m_controlEnabled) - { - switch(m_controlMode) - { - case kPercentVbus: - { - messageID = LM_API_VOLT_T_SET; - if (outputValue > 1.0) outputValue = 1.0; - if (outputValue < -1.0) outputValue = -1.0; - dataSize = packPercentage(dataBuffer, (m_isInverted ? -outputValue : outputValue)); - } - break; - case kSpeed: - { - messageID = LM_API_SPD_T_SET; - dataSize = packFXP16_16(dataBuffer, (m_isInverted ? -outputValue : outputValue)); - } - break; - case kPosition: - { - messageID = LM_API_POS_T_SET; - dataSize = packFXP16_16(dataBuffer, outputValue); - } - break; - case kCurrent: - { - messageID = LM_API_ICTRL_T_SET; - dataSize = packFXP8_8(dataBuffer, outputValue); - } - break; - case kVoltage: - { - messageID = LM_API_VCOMP_T_SET; - dataSize = packFXP8_8(dataBuffer, (m_isInverted ? -outputValue : outputValue)); - } - break; - default: - wpi_setWPIErrorWithContext(IncompatibleMode, "The Jaguar only supports Current, Voltage, Position, Speed, and Percent (Throttle) modes."); - return; - } - if (syncGroup != 0) - { - dataBuffer[dataSize] = syncGroup; - dataSize++; - } + if (m_controlEnabled) { + switch (m_controlMode) { + case kPercentVbus: { + messageID = LM_API_VOLT_T_SET; + if (outputValue > 1.0) outputValue = 1.0; + if (outputValue < -1.0) outputValue = -1.0; + dataSize = packPercentage(dataBuffer, + (m_isInverted ? -outputValue : outputValue)); + } break; + case kSpeed: { + messageID = LM_API_SPD_T_SET; + dataSize = packFXP16_16(dataBuffer, + (m_isInverted ? -outputValue : outputValue)); + } break; + case kPosition: { + messageID = LM_API_POS_T_SET; + dataSize = packFXP16_16(dataBuffer, outputValue); + } break; + case kCurrent: { + messageID = LM_API_ICTRL_T_SET; + dataSize = packFXP8_8(dataBuffer, outputValue); + } break; + case kVoltage: { + messageID = LM_API_VCOMP_T_SET; + dataSize = + packFXP8_8(dataBuffer, (m_isInverted ? -outputValue : outputValue)); + } break; + default: + wpi_setWPIErrorWithContext(IncompatibleMode, + "The Jaguar only supports Current, Voltage, " + "Position, Speed, and Percent (Throttle) " + "modes."); + return; + } + if (syncGroup != 0) { + dataBuffer[dataSize] = syncGroup; + dataSize++; + } - sendMessage(messageID, dataBuffer, dataSize, kSendMessagePeriod); + sendMessage(messageID, dataBuffer, dataSize, kSendMessagePeriod); - if (m_safetyHelper) m_safetyHelper->Feed(); - } + if (m_safetyHelper) m_safetyHelper->Feed(); + } - m_value = outputValue; + m_value = outputValue; - verify(); + verify(); } /** * Get the recently set outputValue setpoint. * * The scale and the units depend on the mode the Jaguar is in.
- * In percentVbus Mode, the outputValue is from -1.0 to 1.0 (same as PWM Jaguar).
+ * In percentVbus Mode, the outputValue is from -1.0 to 1.0 (same as PWM + * Jaguar).
* In voltage Mode, the outputValue is in volts.
* In current Mode, the outputValue is in amps.
* In speed Mode, the outputValue is in rotations/minute.
@@ -374,123 +368,106 @@ void CANJaguar::Set(float outputValue, uint8_t syncGroup) * * @return The most recently set outputValue setpoint. */ -float CANJaguar::Get() const -{ - return m_value; -} +float CANJaguar::Get() const { return m_value; } /** * Common interface for disabling a motor. * * @deprecated Call {@link #DisableControl()} instead. */ -void CANJaguar::Disable() -{ - DisableControl(); -} +void CANJaguar::Disable() { DisableControl(); } /** * Write out the PID value as seen in the PIDOutput base object. * * @deprecated Call Set instead. * - * @param output Write out the PercentVbus value as was computed by the PIDController + * @param output Write out the PercentVbus value as was computed by the + * PIDController */ -void CANJaguar::PIDWrite(float output) -{ - if (m_controlMode == kPercentVbus) - { - Set(output); - } - else - { - wpi_setWPIErrorWithContext(IncompatibleMode, "PID only supported in PercentVbus mode"); - } +void CANJaguar::PIDWrite(float output) { + if (m_controlMode == kPercentVbus) { + Set(output); + } else { + wpi_setWPIErrorWithContext(IncompatibleMode, + "PID only supported in PercentVbus mode"); + } } -uint8_t CANJaguar::packPercentage(uint8_t *buffer, double value) -{ - int16_t intValue = (int16_t)(value * 32767.0); - *((int16_t*)buffer) = swap16(intValue); - return sizeof(int16_t); +uint8_t CANJaguar::packPercentage(uint8_t *buffer, double value) { + int16_t intValue = (int16_t)(value * 32767.0); + *((int16_t *)buffer) = swap16(intValue); + return sizeof(int16_t); } -uint8_t CANJaguar::packFXP8_8(uint8_t *buffer, double value) -{ - int16_t intValue = (int16_t)(value * 256.0); - *((int16_t*)buffer) = swap16(intValue); - return sizeof(int16_t); +uint8_t CANJaguar::packFXP8_8(uint8_t *buffer, double value) { + int16_t intValue = (int16_t)(value * 256.0); + *((int16_t *)buffer) = swap16(intValue); + return sizeof(int16_t); } -uint8_t CANJaguar::packFXP16_16(uint8_t *buffer, double value) -{ - int32_t intValue = (int32_t)(value * 65536.0); - *((int32_t*)buffer) = swap32(intValue); - return sizeof(int32_t); +uint8_t CANJaguar::packFXP16_16(uint8_t *buffer, double value) { + int32_t intValue = (int32_t)(value * 65536.0); + *((int32_t *)buffer) = swap32(intValue); + return sizeof(int32_t); } -uint8_t CANJaguar::packint16_t(uint8_t *buffer, int16_t value) -{ - *((int16_t*)buffer) = swap16(value); - return sizeof(int16_t); +uint8_t CANJaguar::packint16_t(uint8_t *buffer, int16_t value) { + *((int16_t *)buffer) = swap16(value); + return sizeof(int16_t); } -uint8_t CANJaguar::packint32_t(uint8_t *buffer, int32_t value) -{ - *((int32_t*)buffer) = swap32(value); - return sizeof(int32_t); +uint8_t CANJaguar::packint32_t(uint8_t *buffer, int32_t value) { + *((int32_t *)buffer) = swap32(value); + return sizeof(int32_t); } -double CANJaguar::unpackPercentage(uint8_t *buffer) const -{ - int16_t value = *((int16_t*)buffer); - value = swap16(value); - return value / 32767.0; +double CANJaguar::unpackPercentage(uint8_t *buffer) const { + int16_t value = *((int16_t *)buffer); + value = swap16(value); + return value / 32767.0; } -double CANJaguar::unpackFXP8_8(uint8_t *buffer) const -{ - int16_t value = *((int16_t*)buffer); - value = swap16(value); - return value / 256.0; +double CANJaguar::unpackFXP8_8(uint8_t *buffer) const { + int16_t value = *((int16_t *)buffer); + value = swap16(value); + return value / 256.0; } -double CANJaguar::unpackFXP16_16(uint8_t *buffer) const -{ - int32_t value = *((int32_t*)buffer); - value = swap32(value); - return value / 65536.0; +double CANJaguar::unpackFXP16_16(uint8_t *buffer) const { + int32_t value = *((int32_t *)buffer); + value = swap32(value); + return value / 65536.0; } -int16_t CANJaguar::unpackint16_t(uint8_t *buffer) const -{ - int16_t value = *((int16_t*)buffer); - return swap16(value); +int16_t CANJaguar::unpackint16_t(uint8_t *buffer) const { + int16_t value = *((int16_t *)buffer); + return swap16(value); } -int32_t CANJaguar::unpackint32_t(uint8_t *buffer) const -{ - int32_t value = *((int32_t*)buffer); - return swap32(value); +int32_t CANJaguar::unpackint32_t(uint8_t *buffer) const { + int32_t value = *((int32_t *)buffer); + return swap32(value); } /** * Send a message to the Jaguar. * - * @param messageID The messageID to be used on the CAN bus (device number is added internally) + * @param messageID The messageID to be used on the CAN bus (device number is + * added internally) * @param data The up to 8 bytes of data to be sent with the message * @param dataSize Specify how much of the data in "data" to send * @param periodic If positive, tell Network Communications to send the message * every "period" milliseconds. */ -void CANJaguar::sendMessage(uint32_t messageID, const uint8_t *data, uint8_t dataSize, int32_t period) -{ - int32_t localStatus = sendMessageHelper(messageID | m_deviceNumber, data, dataSize, period); +void CANJaguar::sendMessage(uint32_t messageID, const uint8_t *data, + uint8_t dataSize, int32_t period) { + int32_t localStatus = + sendMessageHelper(messageID | m_deviceNumber, data, dataSize, period); - if(localStatus < 0) - { - wpi_setErrorWithContext(localStatus, "sendMessage"); - } + if (localStatus < 0) { + wpi_setErrorWithContext(localStatus, "sendMessage"); + } } /** @@ -500,9 +477,8 @@ void CANJaguar::sendMessage(uint32_t messageID, const uint8_t *data, uint8_t dat * @param periodic If positive, tell Network Communications to send the message * every "period" milliseconds. */ -void CANJaguar::requestMessage(uint32_t messageID, int32_t period) -{ - sendMessageHelper(messageID | m_deviceNumber, NULL, 0, period); +void CANJaguar::requestMessage(uint32_t messageID, int32_t period) { + sendMessageHelper(messageID | m_deviceNumber, NULL, 0, period); } /** @@ -510,112 +486,110 @@ void CANJaguar::requestMessage(uint32_t messageID, int32_t period) * * Jaguar always generates a message with the same message ID when replying. * - * @param messageID The messageID to read from the CAN bus (device number is added internally) + * @param messageID The messageID to read from the CAN bus (device number is + * added internally) * @param data The up to 8 bytes of data that was received with the message * @param dataSize Indicates how much data was received * - * @return true if the message was found. Otherwise, no new message is available. + * @return true if the message was found. Otherwise, no new message is + * available. */ -bool CANJaguar::getMessage(uint32_t messageID, uint32_t messageMask, uint8_t *data, uint8_t *dataSize) const -{ - uint32_t targetedMessageID = messageID | m_deviceNumber; - int32_t status = 0; - uint32_t timeStamp; +bool CANJaguar::getMessage(uint32_t messageID, uint32_t messageMask, + uint8_t *data, uint8_t *dataSize) const { + uint32_t targetedMessageID = messageID | m_deviceNumber; + int32_t status = 0; + uint32_t timeStamp; - // Caller may have set bit31 for remote frame transmission so clear invalid bits[31-29] - targetedMessageID &= CAN_MSGID_FULL_M; + // Caller may have set bit31 for remote frame transmission so clear invalid + // bits[31-29] + targetedMessageID &= CAN_MSGID_FULL_M; - // Get the data. - FRC_NetworkCommunication_CANSessionMux_receiveMessage(&targetedMessageID, messageMask, data, dataSize, &timeStamp, &status); + // Get the data. + FRC_NetworkCommunication_CANSessionMux_receiveMessage( + &targetedMessageID, messageMask, data, dataSize, &timeStamp, &status); - // Do we already have the most recent value? - if(status == ERR_CANSessionMux_MessageNotFound) - return false; - else - wpi_setErrorWithContext(status, "receiveMessage"); + // Do we already have the most recent value? + if (status == ERR_CANSessionMux_MessageNotFound) + return false; + else + wpi_setErrorWithContext(status, "receiveMessage"); - return true; + return true; } /** * Enables periodic status updates from the Jaguar. */ void CANJaguar::setupPeriodicStatus() { - uint8_t data[8]; - uint8_t dataSize; + uint8_t data[8]; + uint8_t dataSize; - // Message 0 returns bus voltage, output voltage, output current, and - // temperature. - static const uint8_t kMessage0Data[] = { - LM_PSTAT_VOLTBUS_B0, LM_PSTAT_VOLTBUS_B1, - LM_PSTAT_VOLTOUT_B0, LM_PSTAT_VOLTOUT_B1, - LM_PSTAT_CURRENT_B0, LM_PSTAT_CURRENT_B1, - LM_PSTAT_TEMP_B0, LM_PSTAT_TEMP_B1 - }; + // Message 0 returns bus voltage, output voltage, output current, and + // temperature. + static const uint8_t kMessage0Data[] = { + LM_PSTAT_VOLTBUS_B0, LM_PSTAT_VOLTBUS_B1, LM_PSTAT_VOLTOUT_B0, + LM_PSTAT_VOLTOUT_B1, LM_PSTAT_CURRENT_B0, LM_PSTAT_CURRENT_B1, + LM_PSTAT_TEMP_B0, LM_PSTAT_TEMP_B1}; - // Message 1 returns position and speed - static const uint8_t kMessage1Data[] = { - LM_PSTAT_POS_B0, LM_PSTAT_POS_B1, LM_PSTAT_POS_B2, LM_PSTAT_POS_B3, - LM_PSTAT_SPD_B0, LM_PSTAT_SPD_B1, LM_PSTAT_SPD_B2, LM_PSTAT_SPD_B3 - }; + // Message 1 returns position and speed + static const uint8_t kMessage1Data[] = { + LM_PSTAT_POS_B0, LM_PSTAT_POS_B1, LM_PSTAT_POS_B2, LM_PSTAT_POS_B3, + LM_PSTAT_SPD_B0, LM_PSTAT_SPD_B1, LM_PSTAT_SPD_B2, LM_PSTAT_SPD_B3}; - // Message 2 returns limits and faults - static const uint8_t kMessage2Data[] = { - LM_PSTAT_LIMIT_CLR, - LM_PSTAT_FAULT, - LM_PSTAT_END - }; + // Message 2 returns limits and faults + static const uint8_t kMessage2Data[] = {LM_PSTAT_LIMIT_CLR, LM_PSTAT_FAULT, + LM_PSTAT_END}; - dataSize = packint16_t(data, kSendMessagePeriod); - sendMessage(LM_API_PSTAT_PER_EN_S0, data, dataSize); - sendMessage(LM_API_PSTAT_PER_EN_S1, data, dataSize); - sendMessage(LM_API_PSTAT_PER_EN_S2, data, dataSize); + dataSize = packint16_t(data, kSendMessagePeriod); + sendMessage(LM_API_PSTAT_PER_EN_S0, data, dataSize); + sendMessage(LM_API_PSTAT_PER_EN_S1, data, dataSize); + sendMessage(LM_API_PSTAT_PER_EN_S2, data, dataSize); - dataSize = 8; - sendMessage(LM_API_PSTAT_CFG_S0, kMessage0Data, dataSize); - sendMessage(LM_API_PSTAT_CFG_S1, kMessage1Data, dataSize); - sendMessage(LM_API_PSTAT_CFG_S2, kMessage2Data, dataSize); + dataSize = 8; + sendMessage(LM_API_PSTAT_CFG_S0, kMessage0Data, dataSize); + sendMessage(LM_API_PSTAT_CFG_S1, kMessage1Data, dataSize); + sendMessage(LM_API_PSTAT_CFG_S2, kMessage2Data, dataSize); } /** * Check for new periodic status updates and unpack them into local variables */ void CANJaguar::updatePeriodicStatus() const { - uint8_t data[8]; - uint8_t dataSize; + uint8_t data[8]; + uint8_t dataSize; - // Check if a new bus voltage/output voltage/current/temperature message - // has arrived and unpack the values into the cached member variables - if(getMessage(LM_API_PSTAT_DATA_S0, CAN_MSGID_FULL_M, data, &dataSize)) { - m_mutex.lock(); - m_busVoltage = unpackFXP8_8(data); - m_outputVoltage = unpackPercentage(data + 2) * m_busVoltage; - m_outputCurrent = unpackFXP8_8(data + 4); - m_temperature = unpackFXP8_8(data + 6); - m_mutex.unlock(); + // Check if a new bus voltage/output voltage/current/temperature message + // has arrived and unpack the values into the cached member variables + if (getMessage(LM_API_PSTAT_DATA_S0, CAN_MSGID_FULL_M, data, &dataSize)) { + m_mutex.lock(); + m_busVoltage = unpackFXP8_8(data); + m_outputVoltage = unpackPercentage(data + 2) * m_busVoltage; + m_outputCurrent = unpackFXP8_8(data + 4); + m_temperature = unpackFXP8_8(data + 6); + m_mutex.unlock(); - m_receivedStatusMessage0 = true; - } + m_receivedStatusMessage0 = true; + } - // Check if a new position/speed message has arrived and do the same - if(getMessage(LM_API_PSTAT_DATA_S1, CAN_MSGID_FULL_M, data, &dataSize)) { - m_mutex.lock(); - m_position = unpackFXP16_16(data); - m_speed = unpackFXP16_16(data + 4); - m_mutex.unlock(); + // Check if a new position/speed message has arrived and do the same + if (getMessage(LM_API_PSTAT_DATA_S1, CAN_MSGID_FULL_M, data, &dataSize)) { + m_mutex.lock(); + m_position = unpackFXP16_16(data); + m_speed = unpackFXP16_16(data + 4); + m_mutex.unlock(); - m_receivedStatusMessage1 = true; - } + m_receivedStatusMessage1 = true; + } - // Check if a new limits/faults message has arrived and do the same - if(getMessage(LM_API_PSTAT_DATA_S2, CAN_MSGID_FULL_M, data, &dataSize)) { - m_mutex.lock(); - m_limits = data[0]; - m_faults = data[1]; - m_mutex.unlock(); + // Check if a new limits/faults message has arrived and do the same + if (getMessage(LM_API_PSTAT_DATA_S2, CAN_MSGID_FULL_M, data, &dataSize)) { + m_mutex.lock(); + m_limits = data[0]; + m_faults = data[1]; + m_mutex.unlock(); - m_receivedStatusMessage2 = true; - } + m_receivedStatusMessage2 = true; + } } /** @@ -623,456 +597,395 @@ void CANJaguar::updatePeriodicStatus() const { * cached versions. If a value isn't available, it gets requested. If a value * doesn't match up, it gets set again. */ -void CANJaguar::verify() -{ - uint8_t dataBuffer[8]; - uint8_t dataSize; +void CANJaguar::verify() { + uint8_t dataBuffer[8]; + uint8_t dataSize; - // If the Jaguar lost power, everything should be considered unverified. - if(getMessage(LM_API_STATUS_POWER, CAN_MSGID_FULL_M, dataBuffer, &dataSize)) - { - bool powerCycled = (bool)dataBuffer[0]; + // If the Jaguar lost power, everything should be considered unverified. + if (getMessage(LM_API_STATUS_POWER, CAN_MSGID_FULL_M, dataBuffer, + &dataSize)) { + bool powerCycled = (bool)dataBuffer[0]; - if(powerCycled) - { - // Clear the power cycled bit - dataBuffer[0] = 1; - sendMessage(LM_API_STATUS_POWER, dataBuffer, sizeof(uint8_t)); + if (powerCycled) { + // Clear the power cycled bit + dataBuffer[0] = 1; + sendMessage(LM_API_STATUS_POWER, dataBuffer, sizeof(uint8_t)); - // Mark everything as unverified - m_controlModeVerified = false; - m_speedRefVerified = false; - m_posRefVerified = false; - m_neutralModeVerified = false; - m_encoderCodesPerRevVerified = false; - m_potentiometerTurnsVerified = false; - m_forwardLimitVerified = false; - m_reverseLimitVerified = false; - m_limitModeVerified = false; - m_maxOutputVoltageVerified = false; - m_faultTimeVerified = false; + // Mark everything as unverified + m_controlModeVerified = false; + m_speedRefVerified = false; + m_posRefVerified = false; + m_neutralModeVerified = false; + m_encoderCodesPerRevVerified = false; + m_potentiometerTurnsVerified = false; + m_forwardLimitVerified = false; + m_reverseLimitVerified = false; + m_limitModeVerified = false; + m_maxOutputVoltageVerified = false; + m_faultTimeVerified = false; - if(m_controlMode == kPercentVbus || m_controlMode == kVoltage) - { - m_voltageRampRateVerified = false; - } - else - { - m_pVerified = false; - m_iVerified = false; - m_dVerified = false; - } + if (m_controlMode == kPercentVbus || m_controlMode == kVoltage) { + m_voltageRampRateVerified = false; + } else { + m_pVerified = false; + m_iVerified = false; + m_dVerified = false; + } - // Verify periodic status messages again - m_receivedStatusMessage0 = false; - m_receivedStatusMessage1 = false; - m_receivedStatusMessage2 = false; + // Verify periodic status messages again + m_receivedStatusMessage0 = false; + m_receivedStatusMessage1 = false; + m_receivedStatusMessage2 = false; - // Remove any old values from netcomms. Otherwise, parameters are - // incorrectly marked as verified based on stale messages. - getMessage(LM_API_SPD_REF, CAN_MSGID_FULL_M, dataBuffer, &dataSize); - getMessage(LM_API_POS_REF, CAN_MSGID_FULL_M, dataBuffer, &dataSize); - getMessage(LM_API_SPD_PC, CAN_MSGID_FULL_M, dataBuffer, &dataSize); - getMessage(LM_API_POS_PC, CAN_MSGID_FULL_M, dataBuffer, &dataSize); - getMessage(LM_API_ICTRL_PC, CAN_MSGID_FULL_M, dataBuffer, &dataSize); - getMessage(LM_API_SPD_IC, CAN_MSGID_FULL_M, dataBuffer, &dataSize); - getMessage(LM_API_POS_IC, CAN_MSGID_FULL_M, dataBuffer, &dataSize); - getMessage(LM_API_ICTRL_IC, CAN_MSGID_FULL_M, dataBuffer, &dataSize); - getMessage(LM_API_SPD_DC, CAN_MSGID_FULL_M, dataBuffer, &dataSize); - getMessage(LM_API_POS_DC, CAN_MSGID_FULL_M, dataBuffer, &dataSize); - getMessage(LM_API_ICTRL_DC, CAN_MSGID_FULL_M, dataBuffer, &dataSize); - getMessage(LM_API_CFG_BRAKE_COAST, CAN_MSGID_FULL_M, dataBuffer, &dataSize); - getMessage(LM_API_CFG_ENC_LINES, CAN_MSGID_FULL_M, dataBuffer, &dataSize); - getMessage(LM_API_CFG_POT_TURNS, CAN_MSGID_FULL_M, dataBuffer, &dataSize); - getMessage(LM_API_CFG_LIMIT_MODE, CAN_MSGID_FULL_M, dataBuffer, &dataSize); - getMessage(LM_API_CFG_LIMIT_FWD, CAN_MSGID_FULL_M, dataBuffer, &dataSize); - getMessage(LM_API_CFG_LIMIT_REV, CAN_MSGID_FULL_M, dataBuffer, &dataSize); - getMessage(LM_API_CFG_MAX_VOUT, CAN_MSGID_FULL_M, dataBuffer, &dataSize); - getMessage(LM_API_VOLT_SET_RAMP, CAN_MSGID_FULL_M, dataBuffer, &dataSize); - getMessage(LM_API_VCOMP_COMP_RAMP, CAN_MSGID_FULL_M, dataBuffer, &dataSize); - getMessage(LM_API_CFG_FAULT_TIME, CAN_MSGID_FULL_M, dataBuffer, &dataSize); - } - } - else - { - requestMessage(LM_API_STATUS_POWER); - } + // Remove any old values from netcomms. Otherwise, parameters are + // incorrectly marked as verified based on stale messages. + getMessage(LM_API_SPD_REF, CAN_MSGID_FULL_M, dataBuffer, &dataSize); + getMessage(LM_API_POS_REF, CAN_MSGID_FULL_M, dataBuffer, &dataSize); + getMessage(LM_API_SPD_PC, CAN_MSGID_FULL_M, dataBuffer, &dataSize); + getMessage(LM_API_POS_PC, CAN_MSGID_FULL_M, dataBuffer, &dataSize); + getMessage(LM_API_ICTRL_PC, CAN_MSGID_FULL_M, dataBuffer, &dataSize); + getMessage(LM_API_SPD_IC, CAN_MSGID_FULL_M, dataBuffer, &dataSize); + getMessage(LM_API_POS_IC, CAN_MSGID_FULL_M, dataBuffer, &dataSize); + getMessage(LM_API_ICTRL_IC, CAN_MSGID_FULL_M, dataBuffer, &dataSize); + getMessage(LM_API_SPD_DC, CAN_MSGID_FULL_M, dataBuffer, &dataSize); + getMessage(LM_API_POS_DC, CAN_MSGID_FULL_M, dataBuffer, &dataSize); + getMessage(LM_API_ICTRL_DC, CAN_MSGID_FULL_M, dataBuffer, &dataSize); + getMessage(LM_API_CFG_BRAKE_COAST, CAN_MSGID_FULL_M, dataBuffer, + &dataSize); + getMessage(LM_API_CFG_ENC_LINES, CAN_MSGID_FULL_M, dataBuffer, &dataSize); + getMessage(LM_API_CFG_POT_TURNS, CAN_MSGID_FULL_M, dataBuffer, &dataSize); + getMessage(LM_API_CFG_LIMIT_MODE, CAN_MSGID_FULL_M, dataBuffer, + &dataSize); + getMessage(LM_API_CFG_LIMIT_FWD, CAN_MSGID_FULL_M, dataBuffer, &dataSize); + getMessage(LM_API_CFG_LIMIT_REV, CAN_MSGID_FULL_M, dataBuffer, &dataSize); + getMessage(LM_API_CFG_MAX_VOUT, CAN_MSGID_FULL_M, dataBuffer, &dataSize); + getMessage(LM_API_VOLT_SET_RAMP, CAN_MSGID_FULL_M, dataBuffer, &dataSize); + getMessage(LM_API_VCOMP_COMP_RAMP, CAN_MSGID_FULL_M, dataBuffer, + &dataSize); + getMessage(LM_API_CFG_FAULT_TIME, CAN_MSGID_FULL_M, dataBuffer, + &dataSize); + } + } else { + requestMessage(LM_API_STATUS_POWER); + } - // Verify that any recently set parameters are correct - if(!m_controlModeVerified && m_controlEnabled) - { - if(getMessage(LM_API_STATUS_CMODE, CAN_MSGID_FULL_M, dataBuffer, &dataSize)) - { - ControlMode mode = (ControlMode)dataBuffer[0]; + // Verify that any recently set parameters are correct + if (!m_controlModeVerified && m_controlEnabled) { + if (getMessage(LM_API_STATUS_CMODE, CAN_MSGID_FULL_M, dataBuffer, + &dataSize)) { + ControlMode mode = (ControlMode)dataBuffer[0]; - if(m_controlMode == mode) - m_controlModeVerified = true; - else - // Enable control again to resend the control mode - EnableControl(); - } - else - { - // Verification is needed but not available - request it again. - requestMessage(LM_API_STATUS_CMODE); - } - } + if (m_controlMode == mode) + m_controlModeVerified = true; + else + // Enable control again to resend the control mode + EnableControl(); + } else { + // Verification is needed but not available - request it again. + requestMessage(LM_API_STATUS_CMODE); + } + } - if(!m_speedRefVerified) - { - if(getMessage(LM_API_SPD_REF, CAN_MSGID_FULL_M, dataBuffer, &dataSize)) - { - uint8_t speedRef = dataBuffer[0]; + if (!m_speedRefVerified) { + if (getMessage(LM_API_SPD_REF, CAN_MSGID_FULL_M, dataBuffer, &dataSize)) { + uint8_t speedRef = dataBuffer[0]; - if(m_speedReference == speedRef) - m_speedRefVerified = true; - else - // It's wrong - set it again - SetSpeedReference(m_speedReference); - } - else - { - // Verification is needed but not available - request it again. - requestMessage(LM_API_SPD_REF); - } - } + if (m_speedReference == speedRef) + m_speedRefVerified = true; + else + // It's wrong - set it again + SetSpeedReference(m_speedReference); + } else { + // Verification is needed but not available - request it again. + requestMessage(LM_API_SPD_REF); + } + } - if(!m_posRefVerified) - { - if(getMessage(LM_API_POS_REF, CAN_MSGID_FULL_M, dataBuffer, &dataSize)) - { - uint8_t posRef = dataBuffer[0]; + if (!m_posRefVerified) { + if (getMessage(LM_API_POS_REF, CAN_MSGID_FULL_M, dataBuffer, &dataSize)) { + uint8_t posRef = dataBuffer[0]; - if(m_positionReference == posRef) - m_posRefVerified = true; - else - // It's wrong - set it again - SetPositionReference(m_positionReference); - } - else - { - // Verification is needed but not available - request it again. - requestMessage(LM_API_POS_REF); - } - } + if (m_positionReference == posRef) + m_posRefVerified = true; + else + // It's wrong - set it again + SetPositionReference(m_positionReference); + } else { + // Verification is needed but not available - request it again. + requestMessage(LM_API_POS_REF); + } + } - if(!m_pVerified) - { - uint32_t message; + if (!m_pVerified) { + uint32_t message; - if(m_controlMode == kSpeed) - message = LM_API_SPD_PC; - else if(m_controlMode == kPosition) - message = LM_API_POS_PC; - else if(m_controlMode == kCurrent) - message = LM_API_ICTRL_PC; - else { - wpi_setWPIErrorWithContext(IncompatibleMode, "PID constants only apply in Speed, Position, and Current mode"); - return; - } - - if(getMessage(message, CAN_MSGID_FULL_M, dataBuffer, &dataSize)) - { - double p = unpackFXP16_16(dataBuffer); - - if(FXP16_EQ(m_p, p)) - m_pVerified = true; - else - // It's wrong - set it again - SetP(m_p); - } - else - { - // Verification is needed but not available - request it again. - requestMessage(message); - } - } - - if(!m_iVerified) - { - uint32_t message; - - if(m_controlMode == kSpeed) - message = LM_API_SPD_IC; - else if(m_controlMode == kPosition) - message = LM_API_POS_IC; - else if(m_controlMode == kCurrent) - message = LM_API_ICTRL_IC; - else { - wpi_setWPIErrorWithContext(IncompatibleMode, "PID constants only apply in Speed, Position, and Current mode"); - return; - } - - if(getMessage(message, CAN_MSGID_FULL_M, dataBuffer, &dataSize)) - { - double i = unpackFXP16_16(dataBuffer); - - if(FXP16_EQ(m_i, i)) - m_iVerified = true; - else - // It's wrong - set it again - SetI(m_i); - } - else - { - // Verification is needed but not available - request it again. - requestMessage(message); - } - } - - if(!m_dVerified) - { - uint32_t message; - - if(m_controlMode == kSpeed) - message = LM_API_SPD_DC; - else if(m_controlMode == kPosition) - message = LM_API_POS_DC; - else if(m_controlMode == kCurrent) - message = LM_API_ICTRL_DC; + if (m_controlMode == kSpeed) + message = LM_API_SPD_PC; + else if (m_controlMode == kPosition) + message = LM_API_POS_PC; + else if (m_controlMode == kCurrent) + message = LM_API_ICTRL_PC; else { - wpi_setWPIErrorWithContext(IncompatibleMode, "PID constants only apply in Speed, Position, and Current mode"); + wpi_setWPIErrorWithContext( + IncompatibleMode, + "PID constants only apply in Speed, Position, and Current mode"); return; } - if(getMessage(message, CAN_MSGID_FULL_M, dataBuffer, &dataSize)) - { - double d = unpackFXP16_16(dataBuffer); + if (getMessage(message, CAN_MSGID_FULL_M, dataBuffer, &dataSize)) { + double p = unpackFXP16_16(dataBuffer); - if(FXP16_EQ(m_d, d)) - m_dVerified = true; - else - // It's wrong - set it again - SetD(m_d); - } - else - { - // Verification is needed but not available - request it again. - requestMessage(message); - } - } + if (FXP16_EQ(m_p, p)) + m_pVerified = true; + else + // It's wrong - set it again + SetP(m_p); + } else { + // Verification is needed but not available - request it again. + requestMessage(message); + } + } - if(!m_neutralModeVerified) - { - if(getMessage(LM_API_CFG_BRAKE_COAST, CAN_MSGID_FULL_M, dataBuffer, &dataSize)) - { - NeutralMode mode = (NeutralMode)dataBuffer[0]; + if (!m_iVerified) { + uint32_t message; - if(mode == m_neutralMode) - m_neutralModeVerified = true; - else - // It's wrong - set it again - ConfigNeutralMode(m_neutralMode); - } - else - { - // Verification is needed but not available - request it again. - requestMessage(LM_API_CFG_BRAKE_COAST); - } - } + if (m_controlMode == kSpeed) + message = LM_API_SPD_IC; + else if (m_controlMode == kPosition) + message = LM_API_POS_IC; + else if (m_controlMode == kCurrent) + message = LM_API_ICTRL_IC; + else { + wpi_setWPIErrorWithContext( + IncompatibleMode, + "PID constants only apply in Speed, Position, and Current mode"); + return; + } - if(!m_encoderCodesPerRevVerified) - { - if(getMessage(LM_API_CFG_ENC_LINES, CAN_MSGID_FULL_M, dataBuffer, &dataSize)) - { - uint16_t codes = unpackint16_t(dataBuffer); + if (getMessage(message, CAN_MSGID_FULL_M, dataBuffer, &dataSize)) { + double i = unpackFXP16_16(dataBuffer); - if(codes == m_encoderCodesPerRev) - m_encoderCodesPerRevVerified = true; - else - // It's wrong - set it again - ConfigEncoderCodesPerRev(m_encoderCodesPerRev); - } - else - { - // Verification is needed but not available - request it again. - requestMessage(LM_API_CFG_ENC_LINES); - } - } + if (FXP16_EQ(m_i, i)) + m_iVerified = true; + else + // It's wrong - set it again + SetI(m_i); + } else { + // Verification is needed but not available - request it again. + requestMessage(message); + } + } - if(!m_potentiometerTurnsVerified) - { - if(getMessage(LM_API_CFG_POT_TURNS, CAN_MSGID_FULL_M, dataBuffer, &dataSize)) - { - uint16_t turns = unpackint16_t(dataBuffer); + if (!m_dVerified) { + uint32_t message; - if(turns == m_potentiometerTurns) - m_potentiometerTurnsVerified = true; - else - // It's wrong - set it again - ConfigPotentiometerTurns(m_potentiometerTurns); - } - else - { - // Verification is needed but not available - request it again. - requestMessage(LM_API_CFG_POT_TURNS); - } - } + if (m_controlMode == kSpeed) + message = LM_API_SPD_DC; + else if (m_controlMode == kPosition) + message = LM_API_POS_DC; + else if (m_controlMode == kCurrent) + message = LM_API_ICTRL_DC; + else { + wpi_setWPIErrorWithContext( + IncompatibleMode, + "PID constants only apply in Speed, Position, and Current mode"); + return; + } - if(!m_limitModeVerified) - { - if(getMessage(LM_API_CFG_LIMIT_MODE, CAN_MSGID_FULL_M, dataBuffer, &dataSize)) - { - LimitMode mode = (LimitMode)dataBuffer[0]; + if (getMessage(message, CAN_MSGID_FULL_M, dataBuffer, &dataSize)) { + double d = unpackFXP16_16(dataBuffer); - if(mode == m_limitMode) - m_limitModeVerified = true; - else - { - // It's wrong - set it again - ConfigLimitMode(m_limitMode); - } - } - else - { - // Verification is needed but not available - request it again. - requestMessage(LM_API_CFG_LIMIT_MODE); - } - } + if (FXP16_EQ(m_d, d)) + m_dVerified = true; + else + // It's wrong - set it again + SetD(m_d); + } else { + // Verification is needed but not available - request it again. + requestMessage(message); + } + } - if(!m_forwardLimitVerified) - { - if(getMessage(LM_API_CFG_LIMIT_FWD, CAN_MSGID_FULL_M, dataBuffer, &dataSize)) - { - double limit = unpackFXP16_16(dataBuffer); + if (!m_neutralModeVerified) { + if (getMessage(LM_API_CFG_BRAKE_COAST, CAN_MSGID_FULL_M, dataBuffer, + &dataSize)) { + NeutralMode mode = (NeutralMode)dataBuffer[0]; - if(FXP16_EQ(limit, m_forwardLimit)) - m_forwardLimitVerified = true; - else - { - // It's wrong - set it again - ConfigForwardLimit(m_forwardLimit); - } - } - else - { - // Verification is needed but not available - request it again. - requestMessage(LM_API_CFG_LIMIT_FWD); - } - } + if (mode == m_neutralMode) + m_neutralModeVerified = true; + else + // It's wrong - set it again + ConfigNeutralMode(m_neutralMode); + } else { + // Verification is needed but not available - request it again. + requestMessage(LM_API_CFG_BRAKE_COAST); + } + } - if(!m_reverseLimitVerified) - { - if(getMessage(LM_API_CFG_LIMIT_REV, CAN_MSGID_FULL_M, dataBuffer, &dataSize)) - { - double limit = unpackFXP16_16(dataBuffer); + if (!m_encoderCodesPerRevVerified) { + if (getMessage(LM_API_CFG_ENC_LINES, CAN_MSGID_FULL_M, dataBuffer, + &dataSize)) { + uint16_t codes = unpackint16_t(dataBuffer); - if(FXP16_EQ(limit, m_reverseLimit)) - m_reverseLimitVerified = true; - else - { - // It's wrong - set it again - ConfigReverseLimit(m_reverseLimit); - } - } - else - { - // Verification is needed but not available - request it again. - requestMessage(LM_API_CFG_LIMIT_REV); - } - } + if (codes == m_encoderCodesPerRev) + m_encoderCodesPerRevVerified = true; + else + // It's wrong - set it again + ConfigEncoderCodesPerRev(m_encoderCodesPerRev); + } else { + // Verification is needed but not available - request it again. + requestMessage(LM_API_CFG_ENC_LINES); + } + } - if(!m_maxOutputVoltageVerified) - { - if(getMessage(LM_API_CFG_MAX_VOUT, CAN_MSGID_FULL_M, dataBuffer, &dataSize)) - { - double voltage = unpackFXP8_8(dataBuffer); + if (!m_potentiometerTurnsVerified) { + if (getMessage(LM_API_CFG_POT_TURNS, CAN_MSGID_FULL_M, dataBuffer, + &dataSize)) { + uint16_t turns = unpackint16_t(dataBuffer); - // The returned max output voltage is sometimes slightly higher or - // lower than what was sent. This should not trigger resending - // the message. - if(std::abs(voltage - m_maxOutputVoltage) < 0.1) - m_maxOutputVoltageVerified = true; - else - { - // It's wrong - set it again - ConfigMaxOutputVoltage(m_maxOutputVoltage); - } - } - else - { - // Verification is needed but not available - request it again. - requestMessage(LM_API_CFG_MAX_VOUT); - } - } + if (turns == m_potentiometerTurns) + m_potentiometerTurnsVerified = true; + else + // It's wrong - set it again + ConfigPotentiometerTurns(m_potentiometerTurns); + } else { + // Verification is needed but not available - request it again. + requestMessage(LM_API_CFG_POT_TURNS); + } + } - if(!m_voltageRampRateVerified) - { - if(m_controlMode == kPercentVbus) - { - if(getMessage(LM_API_VOLT_SET_RAMP, CAN_MSGID_FULL_M, dataBuffer, &dataSize)) - { - double rate = unpackPercentage(dataBuffer); + if (!m_limitModeVerified) { + if (getMessage(LM_API_CFG_LIMIT_MODE, CAN_MSGID_FULL_M, dataBuffer, + &dataSize)) { + LimitMode mode = (LimitMode)dataBuffer[0]; - if(FXP16_EQ(rate, m_voltageRampRate)) - m_voltageRampRateVerified = true; - else - { - // It's wrong - set it again - SetVoltageRampRate(m_voltageRampRate); - } - } - else - { - // Verification is needed but not available - request it again. - requestMessage(LM_API_VOLT_SET_RAMP); - } - } - else if(m_controlMode == kVoltage) - { - if(getMessage(LM_API_VCOMP_COMP_RAMP, CAN_MSGID_FULL_M, dataBuffer, &dataSize)) - { - double rate = unpackFXP8_8(dataBuffer); + if (mode == m_limitMode) + m_limitModeVerified = true; + else { + // It's wrong - set it again + ConfigLimitMode(m_limitMode); + } + } else { + // Verification is needed but not available - request it again. + requestMessage(LM_API_CFG_LIMIT_MODE); + } + } - if(FXP8_EQ(rate, m_voltageRampRate)) - m_voltageRampRateVerified = true; - else - { - // It's wrong - set it again - SetVoltageRampRate(m_voltageRampRate); - } - } - else - { - // Verification is needed but not available - request it again. - requestMessage(LM_API_VCOMP_COMP_RAMP); - } - } - } + if (!m_forwardLimitVerified) { + if (getMessage(LM_API_CFG_LIMIT_FWD, CAN_MSGID_FULL_M, dataBuffer, + &dataSize)) { + double limit = unpackFXP16_16(dataBuffer); - if(!m_faultTimeVerified) - { - if(getMessage(LM_API_CFG_FAULT_TIME, CAN_MSGID_FULL_M, dataBuffer, &dataSize)) - { - uint16_t faultTime = unpackint16_t(dataBuffer); + if (FXP16_EQ(limit, m_forwardLimit)) + m_forwardLimitVerified = true; + else { + // It's wrong - set it again + ConfigForwardLimit(m_forwardLimit); + } + } else { + // Verification is needed but not available - request it again. + requestMessage(LM_API_CFG_LIMIT_FWD); + } + } - if((uint16_t)(m_faultTime * 1000.0) == faultTime) - m_faultTimeVerified = true; - else - { - // It's wrong - set it again - ConfigFaultTime(m_faultTime); - } - } - else - { - // Verification is needed but not available - request it again. - requestMessage(LM_API_CFG_FAULT_TIME); - } - } + if (!m_reverseLimitVerified) { + if (getMessage(LM_API_CFG_LIMIT_REV, CAN_MSGID_FULL_M, dataBuffer, + &dataSize)) { + double limit = unpackFXP16_16(dataBuffer); - if(!m_receivedStatusMessage0 || - !m_receivedStatusMessage1 || - !m_receivedStatusMessage2) - { - // If the periodic status messages haven't been verified as received, - // request periodic status messages again and attempt to unpack any - // available ones. - setupPeriodicStatus(); - GetTemperature(); - GetPosition(); - GetFaults(); - } + if (FXP16_EQ(limit, m_reverseLimit)) + m_reverseLimitVerified = true; + else { + // It's wrong - set it again + ConfigReverseLimit(m_reverseLimit); + } + } else { + // Verification is needed but not available - request it again. + requestMessage(LM_API_CFG_LIMIT_REV); + } + } + + if (!m_maxOutputVoltageVerified) { + if (getMessage(LM_API_CFG_MAX_VOUT, CAN_MSGID_FULL_M, dataBuffer, + &dataSize)) { + double voltage = unpackFXP8_8(dataBuffer); + + // The returned max output voltage is sometimes slightly higher or + // lower than what was sent. This should not trigger resending + // the message. + if (std::abs(voltage - m_maxOutputVoltage) < 0.1) + m_maxOutputVoltageVerified = true; + else { + // It's wrong - set it again + ConfigMaxOutputVoltage(m_maxOutputVoltage); + } + } else { + // Verification is needed but not available - request it again. + requestMessage(LM_API_CFG_MAX_VOUT); + } + } + + if (!m_voltageRampRateVerified) { + if (m_controlMode == kPercentVbus) { + if (getMessage(LM_API_VOLT_SET_RAMP, CAN_MSGID_FULL_M, dataBuffer, + &dataSize)) { + double rate = unpackPercentage(dataBuffer); + + if (FXP16_EQ(rate, m_voltageRampRate)) + m_voltageRampRateVerified = true; + else { + // It's wrong - set it again + SetVoltageRampRate(m_voltageRampRate); + } + } else { + // Verification is needed but not available - request it again. + requestMessage(LM_API_VOLT_SET_RAMP); + } + } else if (m_controlMode == kVoltage) { + if (getMessage(LM_API_VCOMP_COMP_RAMP, CAN_MSGID_FULL_M, dataBuffer, + &dataSize)) { + double rate = unpackFXP8_8(dataBuffer); + + if (FXP8_EQ(rate, m_voltageRampRate)) + m_voltageRampRateVerified = true; + else { + // It's wrong - set it again + SetVoltageRampRate(m_voltageRampRate); + } + } else { + // Verification is needed but not available - request it again. + requestMessage(LM_API_VCOMP_COMP_RAMP); + } + } + } + + if (!m_faultTimeVerified) { + if (getMessage(LM_API_CFG_FAULT_TIME, CAN_MSGID_FULL_M, dataBuffer, + &dataSize)) { + uint16_t faultTime = unpackint16_t(dataBuffer); + + if ((uint16_t)(m_faultTime * 1000.0) == faultTime) + m_faultTimeVerified = true; + else { + // It's wrong - set it again + ConfigFaultTime(m_faultTime); + } + } else { + // Verification is needed but not available - request it again. + requestMessage(LM_API_CFG_FAULT_TIME); + } + } + + if (!m_receivedStatusMessage0 || !m_receivedStatusMessage1 || + !m_receivedStatusMessage2) { + // If the periodic status messages haven't been verified as received, + // request periodic status messages again and attempt to unpack any + // available ones. + setupPeriodicStatus(); + GetTemperature(); + GetPosition(); + GetFaults(); + } } /** @@ -1082,16 +995,15 @@ void CANJaguar::verify() * * @param reference Specify a speed reference. */ -void CANJaguar::SetSpeedReference(uint8_t reference) -{ - uint8_t dataBuffer[8]; +void CANJaguar::SetSpeedReference(uint8_t reference) { + uint8_t dataBuffer[8]; - // Send the speed reference parameter - dataBuffer[0] = reference; - sendMessage(LM_API_SPD_REF, dataBuffer, sizeof(uint8_t)); + // Send the speed reference parameter + dataBuffer[0] = reference; + sendMessage(LM_API_SPD_REF, dataBuffer, sizeof(uint8_t)); - m_speedReference = reference; - m_speedRefVerified = false; + m_speedReference = reference; + m_speedRefVerified = false; } /** @@ -1100,10 +1012,7 @@ void CANJaguar::SetSpeedReference(uint8_t reference) * @return A speed reference indicating the currently selected reference device * for speed controller mode. */ -uint8_t CANJaguar::GetSpeedReference() const -{ - return m_speedReference; -} +uint8_t CANJaguar::GetSpeedReference() const { return m_speedReference; } /** * Set the reference source device for position controller mode. @@ -1113,27 +1022,24 @@ uint8_t CANJaguar::GetSpeedReference() const * * @param reference Specify a PositionReference. */ -void CANJaguar::SetPositionReference(uint8_t reference) -{ - uint8_t dataBuffer[8]; +void CANJaguar::SetPositionReference(uint8_t reference) { + uint8_t dataBuffer[8]; - // Send the position reference parameter - dataBuffer[0] = reference; - sendMessage(LM_API_POS_REF, dataBuffer, sizeof(uint8_t)); + // Send the position reference parameter + dataBuffer[0] = reference; + sendMessage(LM_API_POS_REF, dataBuffer, sizeof(uint8_t)); - m_positionReference = reference; - m_posRefVerified = false; + m_positionReference = reference; + m_posRefVerified = false; } /** * Get the reference source device for position controller mode. * - * @return A PositionReference indicating the currently selected reference device for position controller mode. + * @return A PositionReference indicating the currently selected reference + * device for position controller mode. */ -uint8_t CANJaguar::GetPositionReference() const -{ - return m_positionReference; -} +uint8_t CANJaguar::GetPositionReference() const { return m_positionReference; } /** * Set the P, I, and D constants for the closed loop modes. @@ -1142,11 +1048,10 @@ uint8_t CANJaguar::GetPositionReference() const * @param i The integral gain of the Jaguar's PID controller. * @param d The differential gain of the Jaguar's PID controller. */ -void CANJaguar::SetPID(double p, double i, double d) -{ - SetP(p); - SetI(i); - SetD(d); +void CANJaguar::SetPID(double p, double i, double d) { + SetP(p); + SetI(i); + SetD(d); } /** @@ -1154,34 +1059,34 @@ void CANJaguar::SetPID(double p, double i, double d) * * @param p The proportional gain of the Jaguar's PID controller. */ -void CANJaguar::SetP(double p) -{ - uint8_t dataBuffer[8]; - uint8_t dataSize; +void CANJaguar::SetP(double p) { + uint8_t dataBuffer[8]; + uint8_t dataSize; - switch(m_controlMode) - { - case kPercentVbus: - case kVoltage: - case kFollower: - wpi_setWPIErrorWithContext(IncompatibleMode, "PID constants only apply in Speed, Position, and Current mode"); - break; - case kSpeed: - dataSize = packFXP16_16(dataBuffer, p); - sendMessage(LM_API_SPD_PC, dataBuffer, dataSize); - break; - case kPosition: - dataSize = packFXP16_16(dataBuffer, p); - sendMessage(LM_API_POS_PC, dataBuffer, dataSize); - break; - case kCurrent: - dataSize = packFXP16_16(dataBuffer, p); - sendMessage(LM_API_ICTRL_PC, dataBuffer, dataSize); - break; - } + switch (m_controlMode) { + case kPercentVbus: + case kVoltage: + case kFollower: + wpi_setWPIErrorWithContext( + IncompatibleMode, + "PID constants only apply in Speed, Position, and Current mode"); + break; + case kSpeed: + dataSize = packFXP16_16(dataBuffer, p); + sendMessage(LM_API_SPD_PC, dataBuffer, dataSize); + break; + case kPosition: + dataSize = packFXP16_16(dataBuffer, p); + sendMessage(LM_API_POS_PC, dataBuffer, dataSize); + break; + case kCurrent: + dataSize = packFXP16_16(dataBuffer, p); + sendMessage(LM_API_ICTRL_PC, dataBuffer, dataSize); + break; + } - m_p = p; - m_pVerified = false; + m_p = p; + m_pVerified = false; } /** @@ -1189,34 +1094,34 @@ void CANJaguar::SetP(double p) * * @param i The integral gain of the Jaguar's PID controller. */ -void CANJaguar::SetI(double i) -{ - uint8_t dataBuffer[8]; - uint8_t dataSize; +void CANJaguar::SetI(double i) { + uint8_t dataBuffer[8]; + uint8_t dataSize; - switch(m_controlMode) - { - case kPercentVbus: - case kVoltage: - case kFollower: - wpi_setWPIErrorWithContext(IncompatibleMode, "PID constants only apply in Speed, Position, and Current mode"); - break; - case kSpeed: - dataSize = packFXP16_16(dataBuffer, i); - sendMessage(LM_API_SPD_IC, dataBuffer, dataSize); - break; - case kPosition: - dataSize = packFXP16_16(dataBuffer, i); - sendMessage(LM_API_POS_IC, dataBuffer, dataSize); - break; - case kCurrent: - dataSize = packFXP16_16(dataBuffer, i); - sendMessage(LM_API_ICTRL_IC, dataBuffer, dataSize); - break; - } + switch (m_controlMode) { + case kPercentVbus: + case kVoltage: + case kFollower: + wpi_setWPIErrorWithContext( + IncompatibleMode, + "PID constants only apply in Speed, Position, and Current mode"); + break; + case kSpeed: + dataSize = packFXP16_16(dataBuffer, i); + sendMessage(LM_API_SPD_IC, dataBuffer, dataSize); + break; + case kPosition: + dataSize = packFXP16_16(dataBuffer, i); + sendMessage(LM_API_POS_IC, dataBuffer, dataSize); + break; + case kCurrent: + dataSize = packFXP16_16(dataBuffer, i); + sendMessage(LM_API_ICTRL_IC, dataBuffer, dataSize); + break; + } - m_i = i; - m_iVerified = false; + m_i = i; + m_iVerified = false; } /** @@ -1224,34 +1129,34 @@ void CANJaguar::SetI(double i) * * @param d The derivative gain of the Jaguar's PID controller. */ -void CANJaguar::SetD(double d) -{ - uint8_t dataBuffer[8]; - uint8_t dataSize; +void CANJaguar::SetD(double d) { + uint8_t dataBuffer[8]; + uint8_t dataSize; - switch(m_controlMode) - { - case kPercentVbus: - case kVoltage: - case kFollower: - wpi_setWPIErrorWithContext(IncompatibleMode, "PID constants only apply in Speed, Position, and Current mode"); - break; - case kSpeed: - dataSize = packFXP16_16(dataBuffer, d); - sendMessage(LM_API_SPD_DC, dataBuffer, dataSize); - break; - case kPosition: - dataSize = packFXP16_16(dataBuffer, d); - sendMessage(LM_API_POS_DC, dataBuffer, dataSize); - break; - case kCurrent: - dataSize = packFXP16_16(dataBuffer, d); - sendMessage(LM_API_ICTRL_DC, dataBuffer, dataSize); - break; - } + switch (m_controlMode) { + case kPercentVbus: + case kVoltage: + case kFollower: + wpi_setWPIErrorWithContext( + IncompatibleMode, + "PID constants only apply in Speed, Position, and Current mode"); + break; + case kSpeed: + dataSize = packFXP16_16(dataBuffer, d); + sendMessage(LM_API_SPD_DC, dataBuffer, dataSize); + break; + case kPosition: + dataSize = packFXP16_16(dataBuffer, d); + sendMessage(LM_API_POS_DC, dataBuffer, dataSize); + break; + case kCurrent: + dataSize = packFXP16_16(dataBuffer, d); + sendMessage(LM_API_ICTRL_DC, dataBuffer, dataSize); + break; + } - m_d = d; - m_dVerified = false; + m_d = d; + m_dVerified = false; } /** @@ -1259,15 +1164,15 @@ void CANJaguar::SetD(double d) * * @return The proportional gain. */ -double CANJaguar::GetP() const -{ - if(m_controlMode == kPercentVbus || m_controlMode == kVoltage) - { - wpi_setWPIErrorWithContext(IncompatibleMode, "PID constants only apply in Speed, Position, and Current mode"); - return 0.0; - } +double CANJaguar::GetP() const { + if (m_controlMode == kPercentVbus || m_controlMode == kVoltage) { + wpi_setWPIErrorWithContext( + IncompatibleMode, + "PID constants only apply in Speed, Position, and Current mode"); + return 0.0; + } - return m_p; + return m_p; } /** @@ -1275,15 +1180,15 @@ double CANJaguar::GetP() const * * @return The integral gain. */ -double CANJaguar::GetI() const -{ - if(m_controlMode == kPercentVbus || m_controlMode == kVoltage) - { - wpi_setWPIErrorWithContext(IncompatibleMode, "PID constants only apply in Speed, Position, and Current mode"); - return 0.0; - } +double CANJaguar::GetI() const { + if (m_controlMode == kPercentVbus || m_controlMode == kVoltage) { + wpi_setWPIErrorWithContext( + IncompatibleMode, + "PID constants only apply in Speed, Position, and Current mode"); + return 0.0; + } - return m_i; + return m_i; } /** @@ -1291,15 +1196,15 @@ double CANJaguar::GetI() const * * @return The differential gain. */ -double CANJaguar::GetD() const -{ - if(m_controlMode == kPercentVbus || m_controlMode == kVoltage) - { - wpi_setWPIErrorWithContext(IncompatibleMode, "PID constants only apply in Speed, Position, and Current mode"); - return 0.0; - } +double CANJaguar::GetD() const { + if (m_controlMode == kPercentVbus || m_controlMode == kVoltage) { + wpi_setWPIErrorWithContext( + IncompatibleMode, + "PID constants only apply in Speed, Position, and Current mode"); + return 0.0; + } - return m_d; + return m_d; } /** @@ -1310,38 +1215,40 @@ double CANJaguar::GetD() const * use the encoderInitialPosition parameter to initialize the * encoder state. * - * @param encoderInitialPosition Encoder position to set if position with encoder reference. Ignored otherwise. + * @param encoderInitialPosition Encoder position to set if position with + * encoder reference. Ignored otherwise. */ -void CANJaguar::EnableControl(double encoderInitialPosition) -{ - uint8_t dataBuffer[8]; - uint8_t dataSize = 0; +void CANJaguar::EnableControl(double encoderInitialPosition) { + uint8_t dataBuffer[8]; + uint8_t dataSize = 0; - switch(m_controlMode) - { - case kPercentVbus: - sendMessage(LM_API_VOLT_T_EN, dataBuffer, dataSize); - break; - case kSpeed: - sendMessage(LM_API_SPD_T_EN, dataBuffer, dataSize); - break; - case kPosition: - dataSize = packFXP16_16(dataBuffer, encoderInitialPosition); - sendMessage(LM_API_POS_T_EN, dataBuffer, dataSize); - break; - case kCurrent: - sendMessage(LM_API_ICTRL_T_EN, dataBuffer, dataSize); - break; - case kVoltage: - sendMessage(LM_API_VCOMP_T_EN, dataBuffer, dataSize); - break; - default: - wpi_setWPIErrorWithContext(IncompatibleMode, "The Jaguar only supports Current, Voltage, Position, Speed, and Percent (Throttle) modes."); - return; - } + switch (m_controlMode) { + case kPercentVbus: + sendMessage(LM_API_VOLT_T_EN, dataBuffer, dataSize); + break; + case kSpeed: + sendMessage(LM_API_SPD_T_EN, dataBuffer, dataSize); + break; + case kPosition: + dataSize = packFXP16_16(dataBuffer, encoderInitialPosition); + sendMessage(LM_API_POS_T_EN, dataBuffer, dataSize); + break; + case kCurrent: + sendMessage(LM_API_ICTRL_T_EN, dataBuffer, dataSize); + break; + case kVoltage: + sendMessage(LM_API_VCOMP_T_EN, dataBuffer, dataSize); + break; + default: + wpi_setWPIErrorWithContext(IncompatibleMode, + "The Jaguar only supports Current, Voltage, " + "Position, Speed, and Percent (Throttle) " + "modes."); + return; + } - m_controlEnabled = true; - m_controlModeVerified = false; + m_controlEnabled = true; + m_controlModeVerified = false; } /** @@ -1349,164 +1256,174 @@ void CANJaguar::EnableControl(double encoderInitialPosition) * * Stop driving the output based on the feedback. */ -void CANJaguar::DisableControl() -{ - uint8_t dataBuffer[8]; - uint8_t dataSize = 0; +void CANJaguar::DisableControl() { + uint8_t dataBuffer[8]; + uint8_t dataSize = 0; - // Disable all control - sendMessage(LM_API_VOLT_DIS, dataBuffer, dataSize); - sendMessage(LM_API_SPD_DIS, dataBuffer, dataSize); - sendMessage(LM_API_POS_DIS, dataBuffer, dataSize); - sendMessage(LM_API_ICTRL_DIS, dataBuffer, dataSize); - sendMessage(LM_API_VCOMP_DIS, dataBuffer, dataSize); + // Disable all control + sendMessage(LM_API_VOLT_DIS, dataBuffer, dataSize); + sendMessage(LM_API_SPD_DIS, dataBuffer, dataSize); + sendMessage(LM_API_POS_DIS, dataBuffer, dataSize); + sendMessage(LM_API_ICTRL_DIS, dataBuffer, dataSize); + sendMessage(LM_API_VCOMP_DIS, dataBuffer, dataSize); - // Stop all periodic setpoints - sendMessage(LM_API_VOLT_T_SET, dataBuffer, dataSize, CAN_SEND_PERIOD_STOP_REPEATING); - sendMessage(LM_API_SPD_T_SET, dataBuffer, dataSize, CAN_SEND_PERIOD_STOP_REPEATING); - sendMessage(LM_API_POS_T_SET, dataBuffer, dataSize, CAN_SEND_PERIOD_STOP_REPEATING); - sendMessage(LM_API_ICTRL_T_SET, dataBuffer, dataSize, CAN_SEND_PERIOD_STOP_REPEATING); - sendMessage(LM_API_VCOMP_T_SET, dataBuffer, dataSize, CAN_SEND_PERIOD_STOP_REPEATING); + // Stop all periodic setpoints + sendMessage(LM_API_VOLT_T_SET, dataBuffer, dataSize, + CAN_SEND_PERIOD_STOP_REPEATING); + sendMessage(LM_API_SPD_T_SET, dataBuffer, dataSize, + CAN_SEND_PERIOD_STOP_REPEATING); + sendMessage(LM_API_POS_T_SET, dataBuffer, dataSize, + CAN_SEND_PERIOD_STOP_REPEATING); + sendMessage(LM_API_ICTRL_T_SET, dataBuffer, dataSize, + CAN_SEND_PERIOD_STOP_REPEATING); + sendMessage(LM_API_VCOMP_T_SET, dataBuffer, dataSize, + CAN_SEND_PERIOD_STOP_REPEATING); - m_controlEnabled = false; + m_controlEnabled = false; } /** * Enable controlling the motor voltage as a percentage of the bus voltage * without any position or speed feedback.
- * After calling this you must call {@link CANJaguar#EnableControl()} or {@link CANJaguar#EnableControl(double)} to enable the device. + * After calling this you must call {@link CANJaguar#EnableControl()} or {@link + * CANJaguar#EnableControl(double)} to enable the device. */ -void CANJaguar::SetPercentMode() -{ - SetControlMode(kPercentVbus); - SetPositionReference(LM_REF_NONE); - SetSpeedReference(LM_REF_NONE); +void CANJaguar::SetPercentMode() { + SetControlMode(kPercentVbus); + SetPositionReference(LM_REF_NONE); + SetSpeedReference(LM_REF_NONE); } /** * Enable controlling the motor voltage as a percentage of the bus voltage, * and enable speed sensing from a non-quadrature encoder.
- * After calling this you must call {@link CANJaguar#EnableControl()} or {@link CANJaguar#EnableControl(double)} to enable the device. + * After calling this you must call {@link CANJaguar#EnableControl()} or {@link + * CANJaguar#EnableControl(double)} to enable the device. * * @param tag The constant CANJaguar::Encoder * @param codesPerRev The counts per revolution on the encoder */ -void CANJaguar::SetPercentMode(CANJaguar::EncoderStruct, uint16_t codesPerRev) -{ - SetControlMode(kPercentVbus); - SetPositionReference(LM_REF_NONE); - SetSpeedReference(LM_REF_ENCODER); - ConfigEncoderCodesPerRev(codesPerRev); +void CANJaguar::SetPercentMode(CANJaguar::EncoderStruct, uint16_t codesPerRev) { + SetControlMode(kPercentVbus); + SetPositionReference(LM_REF_NONE); + SetSpeedReference(LM_REF_ENCODER); + ConfigEncoderCodesPerRev(codesPerRev); } /** * Enable controlling the motor voltage as a percentage of the bus voltage, * and enable speed sensing from a non-quadrature encoder.
- * After calling this you must call {@link CANJaguar#EnableControl()} or {@link CANJaguar#EnableControl(double)} to enable the device. + * After calling this you must call {@link CANJaguar#EnableControl()} or {@link + * CANJaguar#EnableControl(double)} to enable the device. * * @param tag The constant CANJaguar::QuadEncoder * @param codesPerRev The counts per revolution on the encoder */ -void CANJaguar::SetPercentMode(CANJaguar::QuadEncoderStruct, uint16_t codesPerRev) -{ - SetControlMode(kPercentVbus); - SetPositionReference(LM_REF_ENCODER); - SetSpeedReference(LM_REF_QUAD_ENCODER); - ConfigEncoderCodesPerRev(codesPerRev); +void CANJaguar::SetPercentMode(CANJaguar::QuadEncoderStruct, + uint16_t codesPerRev) { + SetControlMode(kPercentVbus); + SetPositionReference(LM_REF_ENCODER); + SetSpeedReference(LM_REF_QUAD_ENCODER); + ConfigEncoderCodesPerRev(codesPerRev); } /** * Enable controlling the motor voltage as a percentage of the bus voltage, * and enable position sensing from a potentiometer and no speed feedback.
-* After calling this you must call {@link CANJaguar#EnableControl()} or {@link CANJaguar#EnableControl(double)} to enable the device. +* After calling this you must call {@link CANJaguar#EnableControl()} or {@link +* CANJaguar#EnableControl(double)} to enable the device. * * @param potentiometer The constant CANJaguar::Potentiometer */ -void CANJaguar::SetPercentMode(CANJaguar::PotentiometerStruct) -{ - SetControlMode(kPercentVbus); - SetPositionReference(LM_REF_POT); - SetSpeedReference(LM_REF_NONE); - ConfigPotentiometerTurns(1); +void CANJaguar::SetPercentMode(CANJaguar::PotentiometerStruct) { + SetControlMode(kPercentVbus); + SetPositionReference(LM_REF_POT); + SetSpeedReference(LM_REF_NONE); + ConfigPotentiometerTurns(1); } /** * Enable controlling the motor current with a PID loop.
- * After calling this you must call {@link CANJaguar#EnableControl()} or {@link CANJaguar#EnableControl(double)} to enable the device. + * After calling this you must call {@link CANJaguar#EnableControl()} or {@link + * CANJaguar#EnableControl(double)} to enable the device. * * @param p The proportional gain of the Jaguar's PID controller. * @param i The integral gain of the Jaguar's PID controller. * @param d The differential gain of the Jaguar's PID controller. */ -void CANJaguar::SetCurrentMode(double p, double i, double d) -{ - SetControlMode(kCurrent); - SetPositionReference(LM_REF_NONE); - SetSpeedReference(LM_REF_NONE); - SetPID(p, i, d); +void CANJaguar::SetCurrentMode(double p, double i, double d) { + SetControlMode(kCurrent); + SetPositionReference(LM_REF_NONE); + SetSpeedReference(LM_REF_NONE); + SetPID(p, i, d); } /** * Enable controlling the motor current with a PID loop, and enable speed * sensing from a non-quadrature encoder.
-* After calling this you must call {@link CANJaguar#EnableControl()} or {@link CANJaguar#EnableControl(double)} to enable the device. +* After calling this you must call {@link CANJaguar#EnableControl()} or {@link +* CANJaguar#EnableControl(double)} to enable the device. * * @param encoder The constant CANJaguar::Encoder * @param p The proportional gain of the Jaguar's PID controller. * @param i The integral gain of the Jaguar's PID controller. * @param d The differential gain of the Jaguar's PID controller. */ -void CANJaguar::SetCurrentMode(CANJaguar::EncoderStruct, uint16_t codesPerRev, double p, double i, double d) -{ - SetControlMode(kCurrent); - SetPositionReference(LM_REF_NONE); - SetSpeedReference(LM_REF_NONE); - ConfigEncoderCodesPerRev(codesPerRev); - SetPID(p, i, d); +void CANJaguar::SetCurrentMode(CANJaguar::EncoderStruct, uint16_t codesPerRev, + double p, double i, double d) { + SetControlMode(kCurrent); + SetPositionReference(LM_REF_NONE); + SetSpeedReference(LM_REF_NONE); + ConfigEncoderCodesPerRev(codesPerRev); + SetPID(p, i, d); } /** * Enable controlling the motor current with a PID loop, and enable speed and * position sensing from a quadrature encoder.
-* After calling this you must call {@link CANJaguar#EnableControl()} or {@link CANJaguar#EnableControl(double)} to enable the device. +* After calling this you must call {@link CANJaguar#EnableControl()} or {@link +* CANJaguar#EnableControl(double)} to enable the device. * * @param endoer The constant CANJaguar::QuadEncoder * @param p The proportional gain of the Jaguar's PID controller. * @param i The integral gain of the Jaguar's PID controller. * @param d The differential gain of the Jaguar's PID controller. */ -void CANJaguar::SetCurrentMode(CANJaguar::QuadEncoderStruct, uint16_t codesPerRev, double p, double i, double d) -{ - SetControlMode(kCurrent); - SetPositionReference(LM_REF_ENCODER); - SetSpeedReference(LM_REF_QUAD_ENCODER); - ConfigEncoderCodesPerRev(codesPerRev); - SetPID(p, i, d); +void CANJaguar::SetCurrentMode(CANJaguar::QuadEncoderStruct, + uint16_t codesPerRev, double p, double i, + double d) { + SetControlMode(kCurrent); + SetPositionReference(LM_REF_ENCODER); + SetSpeedReference(LM_REF_QUAD_ENCODER); + ConfigEncoderCodesPerRev(codesPerRev); + SetPID(p, i, d); } /** * Enable controlling the motor current with a PID loop, and enable position * sensing from a potentiometer.
-* After calling this you must call {@link CANJaguar#EnableControl()} or {@link CANJaguar#EnableControl(double)} to enable the device. +* After calling this you must call {@link CANJaguar#EnableControl()} or {@link +* CANJaguar#EnableControl(double)} to enable the device. * * @param potentiometer The constant CANJaguar::Potentiometer * @param p The proportional gain of the Jaguar's PID controller. * @param i The integral gain of the Jaguar's PID controller. * @param d The differential gain of the Jaguar's PID controller. */ -void CANJaguar::SetCurrentMode(CANJaguar::PotentiometerStruct, double p, double i, double d) -{ - SetControlMode(kCurrent); - SetPositionReference(LM_REF_POT); - SetSpeedReference(LM_REF_NONE); - ConfigPotentiometerTurns(1); - SetPID(p, i, d); +void CANJaguar::SetCurrentMode(CANJaguar::PotentiometerStruct, double p, + double i, double d) { + SetControlMode(kCurrent); + SetPositionReference(LM_REF_POT); + SetSpeedReference(LM_REF_NONE); + ConfigPotentiometerTurns(1); + SetPID(p, i, d); } /** * Enable controlling the speed with a feedback loop from a non-quadrature * encoder.
- * After calling this you must call {@link CANJaguar#EnableControl()} or {@link CANJaguar#EnableControl(double)} to enable the device. + * After calling this you must call {@link CANJaguar#EnableControl()} or {@link + * CANJaguar#EnableControl(double)} to enable the device. * * @param encoder The constant CANJaguar::Encoder * @param codesPerRev The counts per revolution on the encoder. @@ -1514,18 +1431,20 @@ void CANJaguar::SetCurrentMode(CANJaguar::PotentiometerStruct, double p, double * @param i The integral gain of the Jaguar's PID controller. * @param d The differential gain of the Jaguar's PID controller. */ -void CANJaguar::SetSpeedMode(CANJaguar::EncoderStruct, uint16_t codesPerRev, double p, double i, double d) -{ - SetControlMode(kSpeed); - SetPositionReference(LM_REF_NONE); - SetSpeedReference(LM_REF_ENCODER); - ConfigEncoderCodesPerRev(codesPerRev); - SetPID(p, i, d); +void CANJaguar::SetSpeedMode(CANJaguar::EncoderStruct, uint16_t codesPerRev, + double p, double i, double d) { + SetControlMode(kSpeed); + SetPositionReference(LM_REF_NONE); + SetSpeedReference(LM_REF_ENCODER); + ConfigEncoderCodesPerRev(codesPerRev); + SetPID(p, i, d); } /** -* Enable controlling the speed with a feedback loop from a quadrature encoder.
-* After calling this you must call {@link CANJaguar#EnableControl()} or {@link CANJaguar#EnableControl(double)} to enable the device. +* Enable controlling the speed with a feedback loop from a quadrature +* encoder.
+* After calling this you must call {@link CANJaguar#EnableControl()} or {@link +* CANJaguar#EnableControl(double)} to enable the device. * * @param encoder The constant CANJaguar::QuadEncoder * @param codesPerRev The counts per revolution on the encoder. @@ -1533,18 +1452,19 @@ void CANJaguar::SetSpeedMode(CANJaguar::EncoderStruct, uint16_t codesPerRev, dou * @param i The integral gain of the Jaguar's PID controller. * @param d The differential gain of the Jaguar's PID controller. */ -void CANJaguar::SetSpeedMode(CANJaguar::QuadEncoderStruct, uint16_t codesPerRev, double p, double i, double d) -{ - SetControlMode(kSpeed); - SetPositionReference(LM_REF_ENCODER); - SetSpeedReference(LM_REF_QUAD_ENCODER); - ConfigEncoderCodesPerRev(codesPerRev); - SetPID(p, i, d); +void CANJaguar::SetSpeedMode(CANJaguar::QuadEncoderStruct, uint16_t codesPerRev, + double p, double i, double d) { + SetControlMode(kSpeed); + SetPositionReference(LM_REF_ENCODER); + SetSpeedReference(LM_REF_QUAD_ENCODER); + ConfigEncoderCodesPerRev(codesPerRev); + SetPID(p, i, d); } /** * Enable controlling the position with a feedback loop using an encoder.
- * After calling this you must call {@link CANJaguar#EnableControl()} or {@link CANJaguar#EnableControl(double)} to enable the device. + * After calling this you must call {@link CANJaguar#EnableControl()} or {@link + * CANJaguar#EnableControl(double)} to enable the device. * * @param encoder The constant CANJaguar::QuadEncoder * @param codesPerRev The counts per revolution on the encoder. @@ -1553,89 +1473,95 @@ void CANJaguar::SetSpeedMode(CANJaguar::QuadEncoderStruct, uint16_t codesPerRev, * @param d The differential gain of the Jaguar's PID controller. * */ -void CANJaguar::SetPositionMode(CANJaguar::QuadEncoderStruct, uint16_t codesPerRev, double p, double i, double d) -{ - SetControlMode(kPosition); - SetPositionReference(LM_REF_ENCODER); - ConfigEncoderCodesPerRev(codesPerRev); - SetPID(p, i, d); +void CANJaguar::SetPositionMode(CANJaguar::QuadEncoderStruct, + uint16_t codesPerRev, double p, double i, + double d) { + SetControlMode(kPosition); + SetPositionReference(LM_REF_ENCODER); + ConfigEncoderCodesPerRev(codesPerRev); + SetPID(p, i, d); } /** -* Enable controlling the position with a feedback loop using a potentiometer.
-* After calling this you must call {@link CANJaguar#EnableControl()} or {@link CANJaguar#EnableControl(double)} to enable the device. +* Enable controlling the position with a feedback loop using a +* potentiometer.
+* After calling this you must call {@link CANJaguar#EnableControl()} or {@link +* CANJaguar#EnableControl(double)} to enable the device. * @param p The proportional gain of the Jaguar's PID controller. * @param i The integral gain of the Jaguar's PID controller. * @param d The differential gain of the Jaguar's PID controller. */ -void CANJaguar::SetPositionMode(CANJaguar::PotentiometerStruct, double p, double i, double d) -{ - SetControlMode(kPosition); - SetPositionReference(LM_REF_POT); - ConfigPotentiometerTurns(1); - SetPID(p, i, d); +void CANJaguar::SetPositionMode(CANJaguar::PotentiometerStruct, double p, + double i, double d) { + SetControlMode(kPosition); + SetPositionReference(LM_REF_POT); + ConfigPotentiometerTurns(1); + SetPID(p, i, d); } /** -* Enable controlling the motor voltage without any position or speed feedback.
-* After calling this you must call {@link CANJaguar#EnableControl()} or {@link CANJaguar#EnableControl(double)} to enable the device. +* Enable controlling the motor voltage without any position or speed +* feedback.
+* After calling this you must call {@link CANJaguar#EnableControl()} or {@link +* CANJaguar#EnableControl(double)} to enable the device. */ -void CANJaguar::SetVoltageMode() -{ - SetControlMode(kVoltage); - SetPositionReference(LM_REF_NONE); - SetSpeedReference(LM_REF_NONE); +void CANJaguar::SetVoltageMode() { + SetControlMode(kVoltage); + SetPositionReference(LM_REF_NONE); + SetSpeedReference(LM_REF_NONE); } /** * Enable controlling the motor voltage with speed feedback from a * non-quadrature encoder and no position feedback.
-* After calling this you must call {@link CANJaguar#EnableControl()} or {@link CANJaguar#EnableControl(double)} to enable the device. +* After calling this you must call {@link CANJaguar#EnableControl()} or {@link +* CANJaguar#EnableControl(double)} to enable the device. * * @param encoder The constant CANJaguar::Encoder * @param codesPerRev The counts per revolution on the encoder */ -void CANJaguar::SetVoltageMode(CANJaguar::EncoderStruct, uint16_t codesPerRev) -{ - SetControlMode(kVoltage); - SetPositionReference(LM_REF_NONE); - SetSpeedReference(LM_REF_ENCODER); - ConfigEncoderCodesPerRev(codesPerRev); +void CANJaguar::SetVoltageMode(CANJaguar::EncoderStruct, uint16_t codesPerRev) { + SetControlMode(kVoltage); + SetPositionReference(LM_REF_NONE); + SetSpeedReference(LM_REF_ENCODER); + ConfigEncoderCodesPerRev(codesPerRev); } /** * Enable controlling the motor voltage with position and speed feedback from a * quadrature encoder.
-* After calling this you must call {@link CANJaguar#EnableControl()} or {@link CANJaguar#EnableControl(double)} to enable the device. +* After calling this you must call {@link CANJaguar#EnableControl()} or {@link +* CANJaguar#EnableControl(double)} to enable the device. * * @param encoder The constant CANJaguar::QuadEncoder * @param codesPerRev The counts per revolution on the encoder */ -void CANJaguar::SetVoltageMode(CANJaguar::QuadEncoderStruct, uint16_t codesPerRev) -{ - SetControlMode(kVoltage); - SetPositionReference(LM_REF_ENCODER); - SetSpeedReference(LM_REF_QUAD_ENCODER); - ConfigEncoderCodesPerRev(codesPerRev); +void CANJaguar::SetVoltageMode(CANJaguar::QuadEncoderStruct, + uint16_t codesPerRev) { + SetControlMode(kVoltage); + SetPositionReference(LM_REF_ENCODER); + SetSpeedReference(LM_REF_QUAD_ENCODER); + ConfigEncoderCodesPerRev(codesPerRev); } /** * Enable controlling the motor voltage with position feedback from a * potentiometer and no speed feedback.
-* After calling this you must call {@link CANJaguar#EnableControl()} or {@link CANJaguar#EnableControl(double)} to enable the device. +* After calling this you must call {@link CANJaguar#EnableControl()} or {@link +* CANJaguar#EnableControl(double)} to enable the device. * * @param potentiometer The constant CANJaguar::Potentiometer */ -void CANJaguar::SetVoltageMode(CANJaguar::PotentiometerStruct) -{ - SetControlMode(kVoltage); - SetPositionReference(LM_REF_POT); - SetSpeedReference(LM_REF_NONE); - ConfigPotentiometerTurns(1); +void CANJaguar::SetVoltageMode(CANJaguar::PotentiometerStruct) { + SetControlMode(kVoltage); + SetPositionReference(LM_REF_POT); + SetSpeedReference(LM_REF_NONE); + ConfigPotentiometerTurns(1); } /** - * Used internally. In order to set the control mode see the methods listed below. + * Used internally. In order to set the control mode see the methods listed + * below. * Change the control mode of this Jaguar object. * * After changing modes, configure any PID constants or other settings needed @@ -1643,19 +1569,22 @@ void CANJaguar::SetVoltageMode(CANJaguar::PotentiometerStruct) * * @param controlMode The new mode. */ -void CANJaguar::SetControlMode(ControlMode controlMode) -{ - // Disable the previous mode - DisableControl(); +void CANJaguar::SetControlMode(ControlMode controlMode) { + // Disable the previous mode + DisableControl(); if (controlMode == kFollower) - wpi_setWPIErrorWithContext(IncompatibleMode, "The Jaguar only supports Current, Voltage, Position, Speed, and Percent (Throttle) modes."); + wpi_setWPIErrorWithContext(IncompatibleMode, + "The Jaguar only supports Current, Voltage, " + "Position, Speed, and Percent (Throttle) " + "modes."); - // Update the local mode - m_controlMode = controlMode; - m_controlModeVerified = false; + // Update the local mode + m_controlMode = controlMode; + m_controlModeVerified = false; - HALReport(HALUsageReporting::kResourceType_CANJaguar, m_deviceNumber, m_controlMode); + HALReport(HALUsageReporting::kResourceType_CANJaguar, m_deviceNumber, + m_controlMode); } /** @@ -1665,9 +1594,8 @@ void CANJaguar::SetControlMode(ControlMode controlMode) * * @return ControlMode that the Jag is in. */ -CANJaguar::ControlMode CANJaguar::GetControlMode() const -{ - return m_controlMode; +CANJaguar::ControlMode CANJaguar::GetControlMode() const { + return m_controlMode; } /** @@ -1675,12 +1603,11 @@ CANJaguar::ControlMode CANJaguar::GetControlMode() const * * @return The bus voltage in volts. */ -float CANJaguar::GetBusVoltage() const -{ - updatePeriodicStatus(); - std::lock_guard lock(m_mutex); +float CANJaguar::GetBusVoltage() const { + updatePeriodicStatus(); + std::lock_guard lock(m_mutex); - return m_busVoltage; + return m_busVoltage; } /** @@ -1688,12 +1615,11 @@ float CANJaguar::GetBusVoltage() const * * @return The output voltage in volts. */ -float CANJaguar::GetOutputVoltage() const -{ - updatePeriodicStatus(); - std::lock_guard lock(m_mutex); +float CANJaguar::GetOutputVoltage() const { + updatePeriodicStatus(); + std::lock_guard lock(m_mutex); - return m_outputVoltage; + return m_outputVoltage; } /** @@ -1701,12 +1627,11 @@ float CANJaguar::GetOutputVoltage() const * * @return The output current in amps. */ -float CANJaguar::GetOutputCurrent() const -{ - updatePeriodicStatus(); - std::lock_guard lock(m_mutex); +float CANJaguar::GetOutputCurrent() const { + updatePeriodicStatus(); + std::lock_guard lock(m_mutex); - return m_outputCurrent; + return m_outputCurrent; } /** @@ -1714,27 +1639,26 @@ float CANJaguar::GetOutputCurrent() const * * @return The temperature of the Jaguar in degrees Celsius. */ -float CANJaguar::GetTemperature() const -{ - updatePeriodicStatus(); - std::lock_guard lock(m_mutex); +float CANJaguar::GetTemperature() const { + updatePeriodicStatus(); + std::lock_guard lock(m_mutex); - return m_temperature; + return m_temperature; } /** * Get the position of the encoder or potentiometer. * - * @return The position of the motor in rotations based on the configured feedback. + * @return The position of the motor in rotations based on the configured + * feedback. * @see CANJaguar#ConfigPotentiometerTurns(int) * @see CANJaguar#ConfigEncoderCodesPerRev(int) */ -double CANJaguar::GetPosition() const -{ - updatePeriodicStatus(); - std::lock_guard lock(m_mutex); +double CANJaguar::GetPosition() const { + updatePeriodicStatus(); + std::lock_guard lock(m_mutex); - return m_position; + return m_position; } /** @@ -1742,12 +1666,11 @@ double CANJaguar::GetPosition() const * * @return The speed of the motor in RPM based on the configured feedback. */ -double CANJaguar::GetSpeed() const -{ - updatePeriodicStatus(); - std::lock_guard lock(m_mutex); +double CANJaguar::GetSpeed() const { + updatePeriodicStatus(); + std::lock_guard lock(m_mutex); - return m_speed; + return m_speed; } /** @@ -1755,12 +1678,11 @@ double CANJaguar::GetSpeed() const * * @return The motor is allowed to turn in the forward direction when true. */ -bool CANJaguar::GetForwardLimitOK() const -{ - updatePeriodicStatus(); - std::lock_guard lock(m_mutex); +bool CANJaguar::GetForwardLimitOK() const { + updatePeriodicStatus(); + std::lock_guard lock(m_mutex); - return m_limits & kForwardLimit; + return m_limits & kForwardLimit; } /** @@ -1768,12 +1690,11 @@ bool CANJaguar::GetForwardLimitOK() const * * @return The motor is allowed to turn in the reverse direction when true. */ -bool CANJaguar::GetReverseLimitOK() const -{ - updatePeriodicStatus(); - std::lock_guard lock(m_mutex); +bool CANJaguar::GetReverseLimitOK() const { + updatePeriodicStatus(); + std::lock_guard lock(m_mutex); - return m_limits & kReverseLimit; + return m_limits & kReverseLimit; } /** @@ -1785,47 +1706,50 @@ bool CANJaguar::GetReverseLimitOK() const * @see #kTemperatureFault * @see #kGateDriverFault */ -uint16_t CANJaguar::GetFaults() const -{ - updatePeriodicStatus(); - std::lock_guard lock(m_mutex); +uint16_t CANJaguar::GetFaults() const { + updatePeriodicStatus(); + std::lock_guard lock(m_mutex); - return m_faults; + return m_faults; } /** * Set the maximum voltage change rate. * - * When in PercentVbus or Voltage output mode, the rate at which the voltage changes can - * be limited to reduce current spikes. Set this to 0.0 to disable rate limiting. + * When in PercentVbus or Voltage output mode, the rate at which the voltage + * changes can + * be limited to reduce current spikes. Set this to 0.0 to disable rate + * limiting. * - * @param rampRate The maximum rate of voltage change in Percent Voltage mode in V/s. + * @param rampRate The maximum rate of voltage change in Percent Voltage mode in + * V/s. */ -void CANJaguar::SetVoltageRampRate(double rampRate) -{ - uint8_t dataBuffer[8]; - uint8_t dataSize; - uint32_t message; +void CANJaguar::SetVoltageRampRate(double rampRate) { + uint8_t dataBuffer[8]; + uint8_t dataSize; + uint32_t message; - switch(m_controlMode) - { - case kPercentVbus: - dataSize = packPercentage(dataBuffer, rampRate / (m_maxOutputVoltage * kControllerRate)); - message = LM_API_VOLT_SET_RAMP; - break; - case kVoltage: - dataSize = packFXP8_8(dataBuffer, rampRate / kControllerRate); - message = LM_API_VCOMP_COMP_RAMP; - break; - default: - wpi_setWPIErrorWithContext(IncompatibleMode, "SetVoltageRampRate only applies in Voltage and Percent mode"); - return; - } + switch (m_controlMode) { + case kPercentVbus: + dataSize = packPercentage( + dataBuffer, rampRate / (m_maxOutputVoltage * kControllerRate)); + message = LM_API_VOLT_SET_RAMP; + break; + case kVoltage: + dataSize = packFXP8_8(dataBuffer, rampRate / kControllerRate); + message = LM_API_VCOMP_COMP_RAMP; + break; + default: + wpi_setWPIErrorWithContext( + IncompatibleMode, + "SetVoltageRampRate only applies in Voltage and Percent mode"); + return; + } - sendMessage(message, dataBuffer, dataSize); + sendMessage(message, dataBuffer, dataSize); - m_voltageRampRate = rampRate; - m_voltageRampRateVerified = false; + m_voltageRampRate = rampRate; + m_voltageRampRateVerified = false; } /** @@ -1833,37 +1757,32 @@ void CANJaguar::SetVoltageRampRate(double rampRate) * * @return The firmware version. 0 if the device did not respond. */ -uint32_t CANJaguar::GetFirmwareVersion() const -{ - return m_firmwareVersion; -} +uint32_t CANJaguar::GetFirmwareVersion() const { return m_firmwareVersion; } /** * Get the version of the Jaguar hardware. * * @return The hardware version. 1: Jaguar, 2: Black Jaguar */ -uint8_t CANJaguar::GetHardwareVersion() const -{ - return m_hardwareVersion; -} +uint8_t CANJaguar::GetHardwareVersion() const { return m_hardwareVersion; } /** - * Configure what the controller does to the H-Bridge when neutral (not driving the output). + * Configure what the controller does to the H-Bridge when neutral (not driving + * the output). * * This allows you to override the jumper configuration for brake or coast. * - * @param mode Select to use the jumper setting or to override it to coast or brake. + * @param mode Select to use the jumper setting or to override it to coast or + * brake. */ -void CANJaguar::ConfigNeutralMode(NeutralMode mode) -{ - uint8_t dataBuffer[8]; +void CANJaguar::ConfigNeutralMode(NeutralMode mode) { + uint8_t dataBuffer[8]; - // Set the neutral mode - sendMessage(LM_API_CFG_BRAKE_COAST, dataBuffer, sizeof(uint8_t)); + // Set the neutral mode + sendMessage(LM_API_CFG_BRAKE_COAST, dataBuffer, sizeof(uint8_t)); - m_neutralMode = mode; - m_neutralModeVerified = false; + m_neutralMode = mode; + m_neutralModeVerified = false; } /** @@ -1871,16 +1790,15 @@ void CANJaguar::ConfigNeutralMode(NeutralMode mode) * * @param codesPerRev The number of counts per revolution in 1X mode. */ -void CANJaguar::ConfigEncoderCodesPerRev(uint16_t codesPerRev) -{ - uint8_t dataBuffer[8]; +void CANJaguar::ConfigEncoderCodesPerRev(uint16_t codesPerRev) { + uint8_t dataBuffer[8]; - // Set the codes per revolution mode - packint16_t(dataBuffer, codesPerRev); - sendMessage(LM_API_CFG_ENC_LINES, dataBuffer, sizeof(uint16_t)); + // Set the codes per revolution mode + packint16_t(dataBuffer, codesPerRev); + sendMessage(LM_API_CFG_ENC_LINES, dataBuffer, sizeof(uint16_t)); - m_encoderCodesPerRev = codesPerRev; - m_encoderCodesPerRevVerified = false; + m_encoderCodesPerRev = codesPerRev; + m_encoderCodesPerRevVerified = false; } /** @@ -1891,35 +1809,38 @@ void CANJaguar::ConfigEncoderCodesPerRev(uint16_t codesPerRev) * * @param turns The number of turns of the potentiometer. */ -void CANJaguar::ConfigPotentiometerTurns(uint16_t turns) -{ - uint8_t dataBuffer[8]; - uint8_t dataSize; +void CANJaguar::ConfigPotentiometerTurns(uint16_t turns) { + uint8_t dataBuffer[8]; + uint8_t dataSize; - // Set the pot turns - dataSize = packint16_t(dataBuffer, turns); - sendMessage(LM_API_CFG_POT_TURNS, dataBuffer, dataSize); + // Set the pot turns + dataSize = packint16_t(dataBuffer, turns); + sendMessage(LM_API_CFG_POT_TURNS, dataBuffer, dataSize); - m_potentiometerTurns = turns; - m_potentiometerTurnsVerified = false; + m_potentiometerTurns = turns; + m_potentiometerTurnsVerified = false; } /** * Configure Soft Position Limits when in Position Controller mode. * - * When controlling position, you can add additional limits on top of the limit switch inputs - * that are based on the position feedback. If the position limit is reached or the + * When controlling position, you can add additional limits on top of the limit + switch inputs + * that are based on the position feedback. If the position limit is reached or + the * switch is opened, that direction will be disabled. * - * @param forwardLimitPosition The position that if exceeded will disable the forward direction. - * @param reverseLimitPosition The position that if exceeded will disable the reverse direction. + * @param forwardLimitPosition The position that if exceeded will disable the + forward direction. + * @param reverseLimitPosition The position that if exceeded will disable the + reverse direction. */ -void CANJaguar::ConfigSoftPositionLimits(double forwardLimitPosition, double reverseLimitPosition) -{ - ConfigLimitMode(kLimitMode_SoftPositionLimits); - ConfigForwardLimit(forwardLimitPosition); - ConfigReverseLimit(reverseLimitPosition); +void CANJaguar::ConfigSoftPositionLimits(double forwardLimitPosition, + double reverseLimitPosition) { + ConfigLimitMode(kLimitMode_SoftPositionLimits); + ConfigForwardLimit(forwardLimitPosition); + ConfigReverseLimit(reverseLimitPosition); } /** @@ -1927,9 +1848,8 @@ void CANJaguar::ConfigSoftPositionLimits(double forwardLimitPosition, double rev * * Soft Position Limits are disabled by default. */ -void CANJaguar::DisableSoftPositionLimits() -{ - ConfigLimitMode(kLimitMode_SwitchInputsOnly); +void CANJaguar::DisableSoftPositionLimits() { + ConfigLimitMode(kLimitMode_SwitchInputsOnly); } /** @@ -1938,15 +1858,14 @@ void CANJaguar::DisableSoftPositionLimits() * Use ConfigSoftPositionLimits or DisableSoftPositionLimits to set this * automatically. */ -void CANJaguar::ConfigLimitMode(LimitMode mode) -{ - uint8_t dataBuffer[8]; +void CANJaguar::ConfigLimitMode(LimitMode mode) { + uint8_t dataBuffer[8]; - dataBuffer[0] = mode; - sendMessage(LM_API_CFG_LIMIT_MODE, dataBuffer, sizeof(uint8_t)); + dataBuffer[0] = mode; + sendMessage(LM_API_CFG_LIMIT_MODE, dataBuffer, sizeof(uint8_t)); - m_limitMode = mode; - m_limitModeVerified = false; + m_limitMode = mode; + m_limitModeVerified = false; } /** @@ -1954,17 +1873,16 @@ void CANJaguar::ConfigLimitMode(LimitMode mode) * * Use ConfigSoftPositionLimits to set this and the limit mode automatically. */ -void CANJaguar::ConfigForwardLimit(double forwardLimitPosition) -{ - uint8_t dataBuffer[8]; - uint8_t dataSize; +void CANJaguar::ConfigForwardLimit(double forwardLimitPosition) { + uint8_t dataBuffer[8]; + uint8_t dataSize; - dataSize = packFXP16_16(dataBuffer, forwardLimitPosition); - dataBuffer[dataSize++] = 1; - sendMessage(LM_API_CFG_LIMIT_FWD, dataBuffer, dataSize); + dataSize = packFXP16_16(dataBuffer, forwardLimitPosition); + dataBuffer[dataSize++] = 1; + sendMessage(LM_API_CFG_LIMIT_FWD, dataBuffer, dataSize); - m_forwardLimit = forwardLimitPosition; - m_forwardLimitVerified = false; + m_forwardLimit = forwardLimitPosition; + m_forwardLimitVerified = false; } /** @@ -1972,17 +1890,16 @@ void CANJaguar::ConfigForwardLimit(double forwardLimitPosition) * * Use ConfigSoftPositionLimits to set this and the limit mode automatically. */ -void CANJaguar::ConfigReverseLimit(double reverseLimitPosition) -{ - uint8_t dataBuffer[8]; - uint8_t dataSize; +void CANJaguar::ConfigReverseLimit(double reverseLimitPosition) { + uint8_t dataBuffer[8]; + uint8_t dataSize; - dataSize = packFXP16_16(dataBuffer, reverseLimitPosition); - dataBuffer[dataSize++] = 0; - sendMessage(LM_API_CFG_LIMIT_REV, dataBuffer, dataSize); + dataSize = packFXP16_16(dataBuffer, reverseLimitPosition); + dataBuffer[dataSize++] = 0; + sendMessage(LM_API_CFG_LIMIT_REV, dataBuffer, dataSize); - m_reverseLimit = reverseLimitPosition; - m_reverseLimitVerified = false; + m_reverseLimit = reverseLimitPosition; + m_reverseLimitVerified = false; } /** @@ -1993,40 +1910,41 @@ void CANJaguar::ConfigReverseLimit(double reverseLimitPosition) * * @param voltage The maximum voltage output by the Jaguar. */ -void CANJaguar::ConfigMaxOutputVoltage(double voltage) -{ - uint8_t dataBuffer[8]; - uint8_t dataSize; +void CANJaguar::ConfigMaxOutputVoltage(double voltage) { + uint8_t dataBuffer[8]; + uint8_t dataSize; - dataSize = packFXP8_8(dataBuffer, voltage); - sendMessage(LM_API_CFG_MAX_VOUT, dataBuffer, dataSize); + dataSize = packFXP8_8(dataBuffer, voltage); + sendMessage(LM_API_CFG_MAX_VOUT, dataBuffer, dataSize); - m_maxOutputVoltage = voltage; - m_maxOutputVoltageVerified = false; + m_maxOutputVoltage = voltage; + m_maxOutputVoltageVerified = false; } /** - * Configure how long the Jaguar waits in the case of a fault before resuming operation. + * Configure how long the Jaguar waits in the case of a fault before resuming + * operation. * * Faults include over temerature, over current, and bus under voltage. * The default is 3.0 seconds, but can be reduced to as low as 0.5 seconds. * * @param faultTime The time to wait before resuming operation, in seconds. */ -void CANJaguar::ConfigFaultTime(float faultTime) -{ - uint8_t dataBuffer[8]; - uint8_t dataSize; +void CANJaguar::ConfigFaultTime(float faultTime) { + uint8_t dataBuffer[8]; + uint8_t dataSize; - if(faultTime < 0.5) faultTime = 0.5; - else if(faultTime > 3.0) faultTime = 3.0; + if (faultTime < 0.5) + faultTime = 0.5; + else if (faultTime > 3.0) + faultTime = 3.0; - // Message takes ms - dataSize = packint16_t(dataBuffer, (int16_t)(faultTime * 1000.0)); - sendMessage(LM_API_CFG_FAULT_TIME, dataBuffer, dataSize); + // Message takes ms + dataSize = packint16_t(dataBuffer, (int16_t)(faultTime * 1000.0)); + sendMessage(LM_API_CFG_FAULT_TIME, dataBuffer, dataSize); - m_faultTime = faultTime; - m_faultTimeVerified = false; + m_faultTime = faultTime; + m_faultTimeVerified = false; } /** @@ -2034,49 +1952,39 @@ void CANJaguar::ConfigFaultTime(float faultTime) * * @param syncGroup A bitmask of groups to generate synchronous output. */ -void CANJaguar::UpdateSyncGroup(uint8_t syncGroup) -{ - sendMessageHelper(CAN_MSGID_API_SYNC, &syncGroup, sizeof(syncGroup), CAN_SEND_PERIOD_NO_REPEAT); +void CANJaguar::UpdateSyncGroup(uint8_t syncGroup) { + sendMessageHelper(CAN_MSGID_API_SYNC, &syncGroup, sizeof(syncGroup), + CAN_SEND_PERIOD_NO_REPEAT); } - -void CANJaguar::SetExpiration(float timeout) -{ - if (m_safetyHelper) m_safetyHelper->SetExpiration(timeout); +void CANJaguar::SetExpiration(float timeout) { + if (m_safetyHelper) m_safetyHelper->SetExpiration(timeout); } -float CANJaguar::GetExpiration() const -{ - if (!m_safetyHelper) return 0.0; - return m_safetyHelper->GetExpiration(); +float CANJaguar::GetExpiration() const { + if (!m_safetyHelper) return 0.0; + return m_safetyHelper->GetExpiration(); } -bool CANJaguar::IsAlive() const -{ - if (!m_safetyHelper) return false; - return m_safetyHelper->IsAlive(); +bool CANJaguar::IsAlive() const { + if (!m_safetyHelper) return false; + return m_safetyHelper->IsAlive(); } -bool CANJaguar::IsSafetyEnabled() const -{ - if (!m_safetyHelper) return false; - return m_safetyHelper->IsSafetyEnabled(); +bool CANJaguar::IsSafetyEnabled() const { + if (!m_safetyHelper) return false; + return m_safetyHelper->IsSafetyEnabled(); } -void CANJaguar::SetSafetyEnabled(bool enabled) -{ - if (m_safetyHelper) m_safetyHelper->SetSafetyEnabled(enabled); +void CANJaguar::SetSafetyEnabled(bool enabled) { + if (m_safetyHelper) m_safetyHelper->SetSafetyEnabled(enabled); } -void CANJaguar::GetDescription(char *desc) const -{ - sprintf(desc, "CANJaguar ID %d", m_deviceNumber); +void CANJaguar::GetDescription(char *desc) const { + sprintf(desc, "CANJaguar ID %d", m_deviceNumber); } -uint8_t CANJaguar::GetDeviceID() const -{ - return m_deviceNumber; -} +uint8_t CANJaguar::GetDeviceID() const { return m_deviceNumber; } /** * Common interface for stopping the motor @@ -2084,38 +1992,29 @@ uint8_t CANJaguar::GetDeviceID() const * * @deprecated Call DisableControl instead. */ -void CANJaguar::StopMotor() -{ - DisableControl(); +void CANJaguar::StopMotor() { DisableControl(); } + +void CANJaguar::ValueChanged(ITable *source, const std::string &key, + EntryValue value, bool isNew) { + Set(value.f); } -void CANJaguar::ValueChanged(ITable* source, const std::string& key, EntryValue value, bool isNew) -{ - Set(value.f); +void CANJaguar::UpdateTable() { + if (m_table != NULL) { + m_table->PutNumber("Value", Get()); + } } -void CANJaguar::UpdateTable() -{ - if (m_table != NULL) - { - m_table->PutNumber("Value", Get()); - } +void CANJaguar::StartLiveWindowMode() { + if (m_table != NULL) { + m_table->AddTableListener("Value", this, true); + } } -void CANJaguar::StartLiveWindowMode() -{ - if (m_table != NULL) - { - m_table->AddTableListener("Value", this, true); - } -} - -void CANJaguar::StopLiveWindowMode() -{ - if (m_table != NULL) - { - m_table->RemoveTableListener(this); - } +void CANJaguar::StopLiveWindowMode() { + if (m_table != NULL) { + m_table->RemoveTableListener(this); + } } /** @@ -2123,9 +2022,7 @@ void CANJaguar::StopLiveWindowMode() * Only works in PercentVbus, speed, and Voltage modes. * @param isInverted The state of inversion, true is inverted */ -void CANJaguar::SetInverted(bool isInverted){ -m_isInverted = isInverted; -} +void CANJaguar::SetInverted(bool isInverted) { m_isInverted = isInverted; } /** * Common interface for the inverting direction of a speed controller. @@ -2133,22 +2030,15 @@ m_isInverted = isInverted; * @return isInverted The state of inversion, true is inverted. * */ -bool CANJaguar::GetInverted() const { - return m_isInverted; +bool CANJaguar::GetInverted() const { return m_isInverted; } + +std::string CANJaguar::GetSmartDashboardType() const { + return "Speed Controller"; } -std::string CANJaguar::GetSmartDashboardType() const -{ - return "Speed Controller"; +void CANJaguar::InitTable(ITable *subTable) { + m_table = subTable; + UpdateTable(); } -void CANJaguar::InitTable(ITable *subTable) -{ - m_table = subTable; - UpdateTable(); -} - -ITable * CANJaguar::GetTable() const -{ - return m_table; -} +ITable *CANJaguar::GetTable() const { return m_table; } diff --git a/wpilibc/wpilibC++Devices/src/CANTalon.cpp b/wpilibc/wpilibC++Devices/src/CANTalon.cpp index 1492b34705..5e4860d754 100644 --- a/wpilibc/wpilibC++Devices/src/CANTalon.cpp +++ b/wpilibc/wpilibC++Devices/src/CANTalon.cpp @@ -7,45 +7,47 @@ #include "CANTalon.h" #include "WPIErrors.h" #include "ctre/CanTalonSRX.h" -#include // usleep -/** - * Constructor for the CANTalon device. - * @param deviceNumber The CAN ID of the Talon SRX - */ +#include // usleep + /** + * Constructor for the CANTalon device. + * @param deviceNumber The CAN ID of the Talon SRX + */ CANTalon::CANTalon(int deviceNumber) - : m_deviceNumber(deviceNumber) - , m_impl(new CanTalonSRX(deviceNumber)) - , m_safetyHelper(new MotorSafetyHelper(this)) - , m_profile(0) - , m_controlEnabled(true) - , m_controlMode(kPercentVbus) - , m_setPoint(0) -{ + : m_deviceNumber(deviceNumber), + m_impl(new CanTalonSRX(deviceNumber)), + m_safetyHelper(new MotorSafetyHelper(this)), + m_profile(0), + m_controlEnabled(true), + m_controlMode(kPercentVbus), + m_setPoint(0) { ApplyControlMode(m_controlMode); m_impl->SetProfileSlotSelect(m_profile); - m_isInverted = false; + m_isInverted = false; } /** * Constructor for the CANTalon device. * @param deviceNumber The CAN ID of the Talon SRX * @param controlPeriodMs The period in ms to send the CAN control frame. - * Period is bounded to [1ms, 95ms]. + * Period is bounded to [1ms, + * 95ms]. */ -CANTalon::CANTalon(int deviceNumber,int controlPeriodMs) - : m_deviceNumber(deviceNumber) - , m_impl(new CanTalonSRX(deviceNumber,controlPeriodMs)) /* bounded underneath to be within [1 ms,95 ms] */ - , m_safetyHelper(new MotorSafetyHelper(this)) - , m_profile(0) - , m_controlEnabled(true) - , m_controlMode(kPercentVbus) - , m_setPoint(0) -{ +CANTalon::CANTalon(int deviceNumber, int controlPeriodMs) + : m_deviceNumber(deviceNumber), + m_impl(new CanTalonSRX( + deviceNumber, + controlPeriodMs)) /* bounded underneath to be within [1 ms,95 ms] */ + , + m_safetyHelper(new MotorSafetyHelper(this)), + m_profile(0), + m_controlEnabled(true), + m_controlMode(kPercentVbus), + m_setPoint(0) { ApplyControlMode(m_controlMode); m_impl->SetProfileSlotSelect(m_profile); } CANTalon::~CANTalon() { - delete m_impl; - delete m_safetyHelper; + delete m_impl; + delete m_safetyHelper; } /** @@ -53,18 +55,16 @@ CANTalon::~CANTalon() { * * @deprecated Call Set instead. * -* @param output Write out the PercentVbus value as was computed by the PIDController +* @param output Write out the PercentVbus value as was computed by the +* PIDController */ -void CANTalon::PIDWrite(float output) -{ - if (GetControlMode() == kPercentVbus) - { - Set(output); - } - else - { - wpi_setWPIErrorWithContext(IncompatibleMode, "PID only supported in PercentVbus mode"); - } +void CANTalon::PIDWrite(float output) { + if (GetControlMode() == kPercentVbus) { + Set(output); + } else { + wpi_setWPIErrorWithContext(IncompatibleMode, + "PID only supported in PercentVbus mode"); + } } /** @@ -72,9 +72,7 @@ void CANTalon::PIDWrite(float output) * * @return The current sensor value of the Talon. */ -double CANTalon::PIDGet() const { - return Get(); -} +double CANTalon::PIDGet() const { return Get(); } /** * Gets the current status of the Talon (usually a sensor value). @@ -86,10 +84,9 @@ double CANTalon::PIDGet() const { * * @return The current sensor value of the Talon. */ -float CANTalon::Get() const -{ +float CANTalon::Get() const { int value; - switch(m_controlMode) { + switch (m_controlMode) { case kVoltage: return GetOutputVoltage(); case kCurrent: @@ -117,37 +114,31 @@ float CANTalon::Get() const * In Speed mode, output value is in position change / 10ms. * In Position mode, output value is in encoder ticks or an analog value, * depending on the sensor. - * In Follower mode, the output value is the integer device ID of the talon to duplicate. + * In Follower mode, the output value is the integer device ID of the talon to + * duplicate. * * @param outputValue The setpoint value, as described above. * @see SelectProfileSlot to choose between the two sets of gains. */ -void CANTalon::Set(float value, uint8_t syncGroup) -{ +void CANTalon::Set(float value, uint8_t syncGroup) { /* feed safety helper since caller just updated our output */ m_safetyHelper->Feed(); - if(m_controlEnabled) { + if (m_controlEnabled) { m_setPoint = value; CTR_Code status = CTR_OKAY; - switch(m_controlMode) { - case CANSpeedController::kPercentVbus: - { - m_impl->Set(m_isInverted ? -value : value); - status = CTR_OKAY; - } - break; - case CANSpeedController::kFollower: - { - status = m_impl->SetDemand((int)value); - } - break; - case CANSpeedController::kVoltage: - { - // Voltage is an 8.8 fixed point number. - int volts = int((m_isInverted ? value: -value) * 256); - status = m_impl->SetDemand(volts); - } - break; + switch (m_controlMode) { + case CANSpeedController::kPercentVbus: { + m_impl->Set(m_isInverted ? -value : value); + status = CTR_OKAY; + } break; + case CANSpeedController::kFollower: { + status = m_impl->SetDemand((int)value); + } break; + case CANSpeedController::kVoltage: { + // Voltage is an 8.8 fixed point number. + int volts = int((m_isInverted ? value : -value) * 256); + status = m_impl->SetDemand(volts); + } break; case CANSpeedController::kSpeed: status = m_impl->SetDemand(m_isInverted ? -value : value); break; @@ -170,16 +161,13 @@ void CANTalon::Set(float value, uint8_t syncGroup) if (status != CTR_OKAY) { wpi_setErrorWithContext(status, getHALErrorMessage(status)); } - } } /** * Sets the setpoint to value. Equivalent to Set(). */ -void CANTalon::SetSetpoint(float value) { - Set(value); -} +void CANTalon::SetSetpoint(float value) { Set(value); } /** * Resets the integral term and disables the controller. @@ -194,8 +182,7 @@ void CANTalon::Reset() { * depending on its mode (see the Talon SRX Software Reference manual * for more information). */ -void CANTalon::Disable() -{ +void CANTalon::Disable() { m_impl->SetModeSelect((int)CANTalon::kDisabled); m_controlEnabled = false; } @@ -211,48 +198,40 @@ void CANTalon::EnableControl() { /** * Enables control of the Talon, allowing the motor to move. */ -void CANTalon::Enable() { - EnableControl(); -} +void CANTalon::Enable() { EnableControl(); } /** * @return Whether the Talon is currently enabled. */ -bool CANTalon::IsControlEnabled() const { - return m_controlEnabled; -} +bool CANTalon::IsControlEnabled() const { return m_controlEnabled; } /** * @return Whether the Talon is currently enabled. */ -bool CANTalon::IsEnabled() const { - return IsControlEnabled(); -} +bool CANTalon::IsEnabled() const { return IsControlEnabled(); } /** * @param p Proportional constant to use in PID loop. * @see SelectProfileSlot to choose between the two sets of gains. */ -void CANTalon::SetP(double p) -{ +void CANTalon::SetP(double p) { CTR_Code status = m_impl->SetPgain(m_profile, p); - if(status != CTR_OKAY) { - wpi_setErrorWithContext(status, getHALErrorMessage(status)); - } + if (status != CTR_OKAY) { + wpi_setErrorWithContext(status, getHALErrorMessage(status)); + } } - /** - * Set the integration constant of the currently selected profile. - * - * @param i Integration constant for the currently selected PID profile. - * @see SelectProfileSlot to choose between the two sets of gains. - */ -void CANTalon::SetI(double i) -{ +/** + * Set the integration constant of the currently selected profile. + * + * @param i Integration constant for the currently selected PID profile. + * @see SelectProfileSlot to choose between the two sets of gains. + */ +void CANTalon::SetI(double i) { CTR_Code status = m_impl->SetIgain(m_profile, i); - if(status != CTR_OKAY) { - wpi_setErrorWithContext(status, getHALErrorMessage(status)); - } + if (status != CTR_OKAY) { + wpi_setErrorWithContext(status, getHALErrorMessage(status)); + } } /** @@ -261,12 +240,11 @@ void CANTalon::SetI(double i) * @param d Derivative constant for the currently selected PID profile. * @see SelectProfileSlot to choose between the two sets of gains. */ -void CANTalon::SetD(double d) -{ +void CANTalon::SetD(double d) { CTR_Code status = m_impl->SetDgain(m_profile, d); - if(status != CTR_OKAY) { - wpi_setErrorWithContext(status, getHALErrorMessage(status)); - } + if (status != CTR_OKAY) { + wpi_setErrorWithContext(status, getHALErrorMessage(status)); + } } /** * Set the feedforward value of the currently selected profile. @@ -274,37 +252,34 @@ void CANTalon::SetD(double d) * @param f Feedforward constant for the currently selected PID profile. * @see SelectProfileSlot to choose between the two sets of gains. */ -void CANTalon::SetF(double f) -{ +void CANTalon::SetF(double f) { CTR_Code status = m_impl->SetFgain(m_profile, f); - if(status != CTR_OKAY) { - wpi_setErrorWithContext(status, getHALErrorMessage(status)); - } + if (status != CTR_OKAY) { + wpi_setErrorWithContext(status, getHALErrorMessage(status)); + } } /** * Set the Izone to a nonzero value to auto clear the integral accumulator - * when the absolute value of CloseLoopError exceeds Izone. + * when the absolute value of CloseLoopError exceeds Izone. * * @see SelectProfileSlot to choose between the two sets of gains. */ -void CANTalon::SetIzone(unsigned iz) -{ +void CANTalon::SetIzone(unsigned iz) { CTR_Code status = m_impl->SetIzone(m_profile, iz); - if(status != CTR_OKAY) { - wpi_setErrorWithContext(status, getHALErrorMessage(status)); - } + if (status != CTR_OKAY) { + wpi_setErrorWithContext(status, getHALErrorMessage(status)); + } } /** * SRX has two available slots for PID. * @param slotIdx one or zero depending on which slot caller wants. */ -void CANTalon::SelectProfileSlot(int slotIdx) -{ - m_profile = (slotIdx == 0) ? 0 : 1; /* only get two slots for now */ - CTR_Code status = m_impl->SetProfileSlotSelect(m_profile); - if(status != CTR_OKAY) { - wpi_setErrorWithContext(status, getHALErrorMessage(status)); - } +void CANTalon::SelectProfileSlot(int slotIdx) { + m_profile = (slotIdx == 0) ? 0 : 1; /* only get two slots for now */ + CTR_Code status = m_impl->SetProfileSlotSelect(m_profile); + if (status != CTR_OKAY) { + wpi_setErrorWithContext(status, getHALErrorMessage(status)); + } } /** * Sets control values for closed loop control. @@ -312,14 +287,14 @@ void CANTalon::SelectProfileSlot(int slotIdx) * @param p Proportional constant. * @param i Integration constant. * @param d Differential constant. - * This function does not modify F-gain. Considerable passing a zero for f using + * This function does not modify F-gain. Considerable passing a zero for f + * using * the four-parameter function. */ -void CANTalon::SetPID(double p, double i, double d) -{ - SetP(p); - SetI(i); - SetD(d); +void CANTalon::SetPID(double p, double i, double d) { + SetP(p); + SetI(i); + SetD(d); } /** * Sets control values for closed loop control. @@ -329,32 +304,29 @@ void CANTalon::SetPID(double p, double i, double d) * @param d Differential constant. * @param f Feedforward constant. */ -void CANTalon::SetPID(double p, double i, double d, double f) -{ - SetP(p); - SetI(i); - SetD(d); - SetF(f); +void CANTalon::SetPID(double p, double i, double d, double f) { + SetP(p); + SetI(i); + SetD(d); + SetF(f); } /** * Select the feedback device to use in closed-loop */ -void CANTalon::SetFeedbackDevice(FeedbackDevice device) -{ - CTR_Code status = m_impl->SetFeedbackDeviceSelect((int)device); - if(status != CTR_OKAY) { - wpi_setErrorWithContext(status, getHALErrorMessage(status)); - } +void CANTalon::SetFeedbackDevice(FeedbackDevice device) { + CTR_Code status = m_impl->SetFeedbackDeviceSelect((int)device); + if (status != CTR_OKAY) { + wpi_setErrorWithContext(status, getHALErrorMessage(status)); + } } /** * Select the feedback device to use in closed-loop */ -void CANTalon::SetStatusFrameRateMs(StatusFrameRate stateFrame, int periodMs) -{ - CTR_Code status = m_impl->SetStatusFrameRate((int)stateFrame,periodMs); - if(status != CTR_OKAY) { - wpi_setErrorWithContext(status, getHALErrorMessage(status)); - } +void CANTalon::SetStatusFrameRateMs(StatusFrameRate stateFrame, int periodMs) { + CTR_Code status = m_impl->SetStatusFrameRate((int)stateFrame, periodMs); + if (status != CTR_OKAY) { + wpi_setErrorWithContext(status, getHALErrorMessage(status)); + } } /** @@ -363,210 +335,204 @@ void CANTalon::SetStatusFrameRateMs(StatusFrameRate stateFrame, int periodMs) * @return double proportional constant for current profile. * @see SelectProfileSlot to choose between the two sets of gains. */ -double CANTalon::GetP() const -{ - CanTalonSRX::param_t param = m_profile ? CanTalonSRX::eProfileParamSlot1_P : CanTalonSRX::eProfileParamSlot0_P; +double CANTalon::GetP() const { + CanTalonSRX::param_t param = m_profile ? CanTalonSRX::eProfileParamSlot1_P + : CanTalonSRX::eProfileParamSlot0_P; // Update the info in m_impl. CTR_Code status = m_impl->RequestParam(param); - if(status != CTR_OKAY) { - wpi_setErrorWithContext(status, getHALErrorMessage(status)); + if (status != CTR_OKAY) { + wpi_setErrorWithContext(status, getHALErrorMessage(status)); } usleep(kDelayForSolicitedSignalsUs); /* small yield for getting response */ double p; status = m_impl->GetPgain(m_profile, p); - if(status != CTR_OKAY) { - wpi_setErrorWithContext(status, getHALErrorMessage(status)); - } - return p; + if (status != CTR_OKAY) { + wpi_setErrorWithContext(status, getHALErrorMessage(status)); + } + return p; } /** * TODO documentation (see CANJaguar.cpp) * @see SelectProfileSlot to choose between the two sets of gains. */ -double CANTalon::GetI() const -{ - CanTalonSRX::param_t param = m_profile ? CanTalonSRX::eProfileParamSlot1_I : CanTalonSRX::eProfileParamSlot0_I; +double CANTalon::GetI() const { + CanTalonSRX::param_t param = m_profile ? CanTalonSRX::eProfileParamSlot1_I + : CanTalonSRX::eProfileParamSlot0_I; // Update the info in m_impl. CTR_Code status = m_impl->RequestParam(param); - if(status != CTR_OKAY) { - wpi_setErrorWithContext(status, getHALErrorMessage(status)); + if (status != CTR_OKAY) { + wpi_setErrorWithContext(status, getHALErrorMessage(status)); } - usleep(kDelayForSolicitedSignalsUs); /* small yield for getting response */ + usleep(kDelayForSolicitedSignalsUs); /* small yield for getting response */ double i; status = m_impl->GetIgain(m_profile, i); - if(status != CTR_OKAY) { - wpi_setErrorWithContext(status, getHALErrorMessage(status)); - } - return i; + if (status != CTR_OKAY) { + wpi_setErrorWithContext(status, getHALErrorMessage(status)); + } + return i; } /** * TODO documentation (see CANJaguar.cpp) * @see SelectProfileSlot to choose between the two sets of gains. */ -double CANTalon::GetD() const -{ - CanTalonSRX::param_t param = m_profile ? CanTalonSRX::eProfileParamSlot1_D : CanTalonSRX::eProfileParamSlot0_D; +double CANTalon::GetD() const { + CanTalonSRX::param_t param = m_profile ? CanTalonSRX::eProfileParamSlot1_D + : CanTalonSRX::eProfileParamSlot0_D; // Update the info in m_impl. CTR_Code status = m_impl->RequestParam(param); - if(status != CTR_OKAY) { - wpi_setErrorWithContext(status, getHALErrorMessage(status)); + if (status != CTR_OKAY) { + wpi_setErrorWithContext(status, getHALErrorMessage(status)); } - usleep(kDelayForSolicitedSignalsUs); /* small yield for getting response */ + usleep(kDelayForSolicitedSignalsUs); /* small yield for getting response */ double d; status = m_impl->GetDgain(m_profile, d); - if(status != CTR_OKAY) { - wpi_setErrorWithContext(status, getHALErrorMessage(status)); - } - return d; + if (status != CTR_OKAY) { + wpi_setErrorWithContext(status, getHALErrorMessage(status)); + } + return d; } /** * * @see SelectProfileSlot to choose between the two sets of gains. */ -double CANTalon::GetF() const -{ - CanTalonSRX::param_t param = m_profile ? CanTalonSRX::eProfileParamSlot1_F : CanTalonSRX::eProfileParamSlot0_F; +double CANTalon::GetF() const { + CanTalonSRX::param_t param = m_profile ? CanTalonSRX::eProfileParamSlot1_F + : CanTalonSRX::eProfileParamSlot0_F; // Update the info in m_impl. CTR_Code status = m_impl->RequestParam(param); - if(status != CTR_OKAY) { - wpi_setErrorWithContext(status, getHALErrorMessage(status)); + if (status != CTR_OKAY) { + wpi_setErrorWithContext(status, getHALErrorMessage(status)); } - usleep(kDelayForSolicitedSignalsUs); /* small yield for getting response */ + usleep(kDelayForSolicitedSignalsUs); /* small yield for getting response */ double f; status = m_impl->GetFgain(m_profile, f); - if(status != CTR_OKAY) { - wpi_setErrorWithContext(status, getHALErrorMessage(status)); - } - return f; + if (status != CTR_OKAY) { + wpi_setErrorWithContext(status, getHALErrorMessage(status)); + } + return f; } /** * @see SelectProfileSlot to choose between the two sets of gains. */ -int CANTalon::GetIzone() const -{ - CanTalonSRX::param_t param = m_profile ? CanTalonSRX::eProfileParamSlot1_IZone: CanTalonSRX::eProfileParamSlot0_IZone; - // Update the info in m_impl. - CTR_Code status = m_impl->RequestParam(param); - if(status != CTR_OKAY) { - wpi_setErrorWithContext(status, getHALErrorMessage(status)); - } - usleep(kDelayForSolicitedSignalsUs); +int CANTalon::GetIzone() const { + CanTalonSRX::param_t param = m_profile + ? CanTalonSRX::eProfileParamSlot1_IZone + : CanTalonSRX::eProfileParamSlot0_IZone; + // Update the info in m_impl. + CTR_Code status = m_impl->RequestParam(param); + if (status != CTR_OKAY) { + wpi_setErrorWithContext(status, getHALErrorMessage(status)); + } + usleep(kDelayForSolicitedSignalsUs); - int iz; - status = m_impl->GetIzone(m_profile, iz); - if(status != CTR_OKAY) { - wpi_setErrorWithContext(status, getHALErrorMessage(status)); - } - return iz; + int iz; + status = m_impl->GetIzone(m_profile, iz); + if (status != CTR_OKAY) { + wpi_setErrorWithContext(status, getHALErrorMessage(status)); + } + return iz; } /** * @return the current setpoint; ie, whatever was last passed to Set(). */ -double CANTalon::GetSetpoint() const { - return m_setPoint; -} +double CANTalon::GetSetpoint() const { return m_setPoint; } /** * Returns the voltage coming in from the battery. * * @return The input voltage in volts. */ -float CANTalon::GetBusVoltage() const -{ +float CANTalon::GetBusVoltage() const { double voltage; CTR_Code status = m_impl->GetBatteryV(voltage); - if(status != CTR_OKAY) { - wpi_setErrorWithContext(status, getHALErrorMessage(status)); - } + if (status != CTR_OKAY) { + wpi_setErrorWithContext(status, getHALErrorMessage(status)); + } return voltage; } /** * @return The voltage being output by the Talon, in Volts. */ -float CANTalon::GetOutputVoltage() const -{ +float CANTalon::GetOutputVoltage() const { int throttle11; CTR_Code status = m_impl->GetAppliedThrottle(throttle11); float voltage = GetBusVoltage() * (float(throttle11) / 1023.0); - if(status != CTR_OKAY) { - wpi_setErrorWithContext(status, getHALErrorMessage(status)); - } - return voltage; + if (status != CTR_OKAY) { + wpi_setErrorWithContext(status, getHALErrorMessage(status)); + } + return voltage; } - /** * Returns the current going through the Talon, in Amperes. */ -float CANTalon::GetOutputCurrent() const -{ +float CANTalon::GetOutputCurrent() const { double current; CTR_Code status = m_impl->GetCurrent(current); - if(status != CTR_OKAY) { - wpi_setErrorWithContext(status, getHALErrorMessage(status)); - } + if (status != CTR_OKAY) { + wpi_setErrorWithContext(status, getHALErrorMessage(status)); + } - return current; + return current; } - /** - * Returns temperature of Talon, in degrees Celsius. - */ -float CANTalon::GetTemperature() const -{ +/** + * Returns temperature of Talon, in degrees Celsius. + */ +float CANTalon::GetTemperature() const { double temp; CTR_Code status = m_impl->GetTemp(temp); - if(temp != CTR_OKAY) { - wpi_setErrorWithContext(status, getHALErrorMessage(status)); - } - return temp; + if (temp != CTR_OKAY) { + wpi_setErrorWithContext(status, getHALErrorMessage(status)); + } + return temp; } /** - * Set the position value of the selected sensor. This is useful for zero-ing quadrature encoders. - * Continuous sensors (like analog encoderes) can also partially be set (the portion of the postion based on overflows). + * Set the position value of the selected sensor. This is useful for zero-ing + * quadrature encoders. + * Continuous sensors (like analog encoderes) can also partially be set (the + * portion of the postion based on overflows). */ -void CANTalon::SetPosition(double pos) -{ - m_impl->SetSensorPosition(pos); -} +void CANTalon::SetPosition(double pos) { m_impl->SetSensorPosition(pos); } /** * TODO documentation (see CANJaguar.cpp) * * @return The position of the sensor currently providing feedback. - * When using analog sensors, 0 units corresponds to 0V, 1023 units corresponds to 3.3V - * When using an analog encoder (wrapping around 1023 => 0 is possible) the units are still 3.3V per 1023 units. - * When using quadrature, each unit is a quadrature edge (4X) mode. + * When using analog sensors, 0 units corresponds to 0V, 1023 + * units corresponds to 3.3V + * When using an analog encoder (wrapping around 1023 => 0 is + * possible) the units are still 3.3V per 1023 units. + * When using quadrature, each unit is a quadrature edge (4X) + * mode. */ -double CANTalon::GetPosition() const -{ +double CANTalon::GetPosition() const { int postition; CTR_Code status = m_impl->GetSensorPosition(postition); - if(status != CTR_OKAY) { - wpi_setErrorWithContext(status, getHALErrorMessage(status)); - } - return (double)postition; + if (status != CTR_OKAY) { + wpi_setErrorWithContext(status, getHALErrorMessage(status)); + } + return (double)postition; } /** * If sensor and motor are out of phase, sensor can be inverted * (position and velocity multiplied by -1). * @see GetPosition and @see GetSpeed. */ -void CANTalon::SetSensorDirection(bool reverseSensor) -{ +void CANTalon::SetSensorDirection(bool reverseSensor) { CTR_Code status = m_impl->SetRevFeedbackSensor(reverseSensor ? 1 : 0); - if(status != CTR_OKAY) { - wpi_setErrorWithContext(status, getHALErrorMessage(status)); - } + if (status != CTR_OKAY) { + wpi_setErrorWithContext(status, getHALErrorMessage(status)); + } } /** @@ -577,9 +543,9 @@ void CANTalon::SetSensorDirection(bool reverseSensor) int CANTalon::GetClosedLoopError() const { int error; CTR_Code status = m_impl->GetCloseLoopErr(error); - if(status != CTR_OKAY) { - wpi_setErrorWithContext(status, getHALErrorMessage(status)); - } + if (status != CTR_OKAY) { + wpi_setErrorWithContext(status, getHALErrorMessage(status)); + } return error; } @@ -591,40 +557,45 @@ int CANTalon::GetClosedLoopError() const { * The speed units will be in the sensor's native ticks per 100ms. * * For analog sensors, 3.3V corresponds to 1023 units. - * So a speed of 200 equates to ~0.645 dV per 100ms or 6.451 dV per second. - * If this is an analog encoder, that likely means 1.9548 rotations per sec. + * So a speed of 200 equates to ~0.645 dV per 100ms or 6.451 dV per + * second. + * If this is an analog encoder, that likely means 1.9548 rotations + * per sec. * For quadrature encoders, each unit corresponds a quadrature edge (4X). - * So a 250 count encoder will produce 1000 edge events per rotation. - * An example speed of 200 would then equate to 20% of a rotation per 100ms, + * So a 250 count encoder will produce 1000 edge events per + * rotation. + * An example speed of 200 would then equate to 20% of a rotation + * per 100ms, * or 10 rotations per second. */ -double CANTalon::GetSpeed() const -{ +double CANTalon::GetSpeed() const { int speed; // TODO convert from int to appropriate units (or at least document it). CTR_Code status = m_impl->GetSensorVelocity(speed); - if(status != CTR_OKAY) { - wpi_setErrorWithContext(status, getHALErrorMessage(status)); - } - return (double)speed; + if (status != CTR_OKAY) { + wpi_setErrorWithContext(status, getHALErrorMessage(status)); + } + return (double)speed; } /** * Get the position of whatever is in the analog pin of the Talon, regardless of * whether it is actually being used for feedback. * - * @returns The 24bit analog value. The bottom ten bits is the ADC (0 - 1023) on - * the analog pin of the Talon. The upper 14 bits - * tracks the overflows and underflows (continuous sensor). + * @returns The 24bit analog value. The bottom ten bits is the ADC (0 - 1023) + * on + * the analog pin of the Talon. + * The upper 14 bits + * tracks the overflows and + * underflows (continuous sensor). */ -int CANTalon::GetAnalogIn() const -{ +int CANTalon::GetAnalogIn() const { int position; CTR_Code status = m_impl->GetAnalogInWithOv(position); - if(status != CTR_OKAY) { - wpi_setErrorWithContext(status, getHALErrorMessage(status)); - } + if (status != CTR_OKAY) { + wpi_setErrorWithContext(status, getHALErrorMessage(status)); + } return position; } /** @@ -633,23 +604,19 @@ int CANTalon::GetAnalogIn() const * * @returns The ADC (0 - 1023) on analog pin of the Talon. */ -int CANTalon::GetAnalogInRaw() const -{ - return GetAnalogIn() & 0x3FF; -} +int CANTalon::GetAnalogInRaw() const { return GetAnalogIn() & 0x3FF; } /** * Get the position of whatever is in the analog pin of the Talon, regardless of * whether it is actually being used for feedback. * * @returns The value (0 - 1023) on the analog pin of the Talon. */ -int CANTalon::GetAnalogInVel() const -{ +int CANTalon::GetAnalogInVel() const { int vel; CTR_Code status = m_impl->GetAnalogInVel(vel); - if(status != CTR_OKAY) { - wpi_setErrorWithContext(status, getHALErrorMessage(status)); - } + if (status != CTR_OKAY) { + wpi_setErrorWithContext(status, getHALErrorMessage(status)); + } return vel; } @@ -659,13 +626,12 @@ int CANTalon::GetAnalogInVel() const * * @returns The value (0 - 1023) on the analog pin of the Talon. */ -int CANTalon::GetEncPosition() const -{ +int CANTalon::GetEncPosition() const { int position; CTR_Code status = m_impl->GetEncPosition(position); - if(status != CTR_OKAY) { - wpi_setErrorWithContext(status, getHALErrorMessage(status)); - } + if (status != CTR_OKAY) { + wpi_setErrorWithContext(status, getHALErrorMessage(status)); + } return position; } @@ -675,400 +641,399 @@ int CANTalon::GetEncPosition() const * * @returns The value (0 - 1023) on the analog pin of the Talon. */ -int CANTalon::GetEncVel() const -{ +int CANTalon::GetEncVel() const { int vel; CTR_Code status = m_impl->GetEncVel(vel); - if(status != CTR_OKAY) { - wpi_setErrorWithContext(status, getHALErrorMessage(status)); - } + if (status != CTR_OKAY) { + wpi_setErrorWithContext(status, getHALErrorMessage(status)); + } return vel; } /** * @return IO level of QUADA pin. */ -int CANTalon::GetPinStateQuadA() const -{ - int retval; - CTR_Code status = m_impl->GetQuadApin(retval); - if(status != CTR_OKAY) { - wpi_setErrorWithContext(status, getHALErrorMessage(status)); - } - return retval; +int CANTalon::GetPinStateQuadA() const { + int retval; + CTR_Code status = m_impl->GetQuadApin(retval); + if (status != CTR_OKAY) { + wpi_setErrorWithContext(status, getHALErrorMessage(status)); + } + return retval; } /** * @return IO level of QUADB pin. */ -int CANTalon::GetPinStateQuadB() const -{ - int retval; - CTR_Code status = m_impl->GetQuadBpin(retval); - if(status != CTR_OKAY) { - wpi_setErrorWithContext(status, getHALErrorMessage(status)); - } - return retval; +int CANTalon::GetPinStateQuadB() const { + int retval; + CTR_Code status = m_impl->GetQuadBpin(retval); + if (status != CTR_OKAY) { + wpi_setErrorWithContext(status, getHALErrorMessage(status)); + } + return retval; } /** * @return IO level of QUAD Index pin. */ -int CANTalon::GetPinStateQuadIdx() const -{ - int retval; - CTR_Code status = m_impl->GetQuadIdxpin(retval); - if(status != CTR_OKAY) { - wpi_setErrorWithContext(status, getHALErrorMessage(status)); - } - return retval; +int CANTalon::GetPinStateQuadIdx() const { + int retval; + CTR_Code status = m_impl->GetQuadIdxpin(retval); + if (status != CTR_OKAY) { + wpi_setErrorWithContext(status, getHALErrorMessage(status)); + } + return retval; } /** * @return '1' iff forward limit switch is closed, 0 iff switch is open. * This function works regardless if limit switch feature is enabled. */ -int CANTalon::IsFwdLimitSwitchClosed() const -{ - int retval; - CTR_Code status = m_impl->GetLimitSwitchClosedFor(retval); /* rename this func, '1' => open, '0' => closed */ - if(status != CTR_OKAY) { - wpi_setErrorWithContext(status, getHALErrorMessage(status)); - } - return retval ? 0 : 1; +int CANTalon::IsFwdLimitSwitchClosed() const { + int retval; + CTR_Code status = m_impl->GetLimitSwitchClosedFor( + retval); /* rename this func, '1' => open, '0' => closed */ + if (status != CTR_OKAY) { + wpi_setErrorWithContext(status, getHALErrorMessage(status)); + } + return retval ? 0 : 1; } /** * @return '1' iff reverse limit switch is closed, 0 iff switch is open. * This function works regardless if limit switch feature is enabled. */ -int CANTalon::IsRevLimitSwitchClosed() const -{ - int retval; - CTR_Code status = m_impl->GetLimitSwitchClosedRev(retval); /* rename this func, '1' => open, '0' => closed */ - if(status != CTR_OKAY) { - wpi_setErrorWithContext(status, getHALErrorMessage(status)); - } - return retval ? 0 : 1; +int CANTalon::IsRevLimitSwitchClosed() const { + int retval; + CTR_Code status = m_impl->GetLimitSwitchClosedRev( + retval); /* rename this func, '1' => open, '0' => closed */ + if (status != CTR_OKAY) { + wpi_setErrorWithContext(status, getHALErrorMessage(status)); + } + return retval ? 0 : 1; } /* * Simple accessor for tracked rise eventso index pin. * @return number of rising edges on idx pin. */ -int CANTalon::GetNumberOfQuadIdxRises() const -{ - int rises; - CTR_Code status = m_impl->GetEncIndexRiseEvents(rises); /* rename this func, '1' => open, '0' => closed */ - if(status != CTR_OKAY) { - wpi_setErrorWithContext(status, getHALErrorMessage(status)); - } - return rises; +int CANTalon::GetNumberOfQuadIdxRises() const { + int rises; + CTR_Code status = m_impl->GetEncIndexRiseEvents( + rises); /* rename this func, '1' => open, '0' => closed */ + if (status != CTR_OKAY) { + wpi_setErrorWithContext(status, getHALErrorMessage(status)); + } + return rises; } /* - * @param rises integral value to set into index-rises register. Great way to zero the index count. + * @param rises integral value to set into index-rises register. Great way to + * zero the index count. */ -void CANTalon::SetNumberOfQuadIdxRises(int rises) -{ - CTR_Code status = m_impl->SetParam(CanTalonSRX::eEncIndexRiseEvents, rises); /* rename this func, '1' => open, '0' => closed */ - if(status != CTR_OKAY) { - wpi_setErrorWithContext(status, getHALErrorMessage(status)); - } +void CANTalon::SetNumberOfQuadIdxRises(int rises) { + CTR_Code status = m_impl->SetParam( + CanTalonSRX::eEncIndexRiseEvents, + rises); /* rename this func, '1' => open, '0' => closed */ + if (status != CTR_OKAY) { + wpi_setErrorWithContext(status, getHALErrorMessage(status)); + } } /** * TODO documentation (see CANJaguar.cpp) */ -bool CANTalon::GetForwardLimitOK() const -{ - int limSwit=0; - int softLim=0; - CTR_Code status = CTR_OKAY; - status = m_impl->GetFault_ForSoftLim(softLim); - if(status != CTR_OKAY) { - wpi_setErrorWithContext(status, getHALErrorMessage(status)); - } - status = m_impl->GetFault_ForLim(limSwit); - if(status != CTR_OKAY) { - wpi_setErrorWithContext(status, getHALErrorMessage(status)); - } - /* If either fault is asserted, signal caller we are disabled (with false?) */ - return (softLim | limSwit) ? false : true; +bool CANTalon::GetForwardLimitOK() const { + int limSwit = 0; + int softLim = 0; + CTR_Code status = CTR_OKAY; + status = m_impl->GetFault_ForSoftLim(softLim); + if (status != CTR_OKAY) { + wpi_setErrorWithContext(status, getHALErrorMessage(status)); + } + status = m_impl->GetFault_ForLim(limSwit); + if (status != CTR_OKAY) { + wpi_setErrorWithContext(status, getHALErrorMessage(status)); + } + /* If either fault is asserted, signal caller we are disabled (with false?) */ + return (softLim | limSwit) ? false : true; } /** * TODO documentation (see CANJaguar.cpp) */ -bool CANTalon::GetReverseLimitOK() const -{ - int limSwit=0; - int softLim=0; - CTR_Code status = CTR_OKAY; - status = m_impl->GetFault_RevSoftLim(softLim); - if(status != CTR_OKAY) { - wpi_setErrorWithContext(status, getHALErrorMessage(status)); - } - status = m_impl->GetFault_RevLim(limSwit); - if(status != CTR_OKAY) { - wpi_setErrorWithContext(status, getHALErrorMessage(status)); - } - /* If either fault is asserted, signal caller we are disabled (with false?) */ - return (softLim | limSwit) ? false : true; +bool CANTalon::GetReverseLimitOK() const { + int limSwit = 0; + int softLim = 0; + CTR_Code status = CTR_OKAY; + status = m_impl->GetFault_RevSoftLim(softLim); + if (status != CTR_OKAY) { + wpi_setErrorWithContext(status, getHALErrorMessage(status)); + } + status = m_impl->GetFault_RevLim(limSwit); + if (status != CTR_OKAY) { + wpi_setErrorWithContext(status, getHALErrorMessage(status)); + } + /* If either fault is asserted, signal caller we are disabled (with false?) */ + return (softLim | limSwit) ? false : true; } /** * TODO documentation (see CANJaguar.cpp) */ -uint16_t CANTalon::GetFaults() const -{ - uint16_t retval = 0; - int val; - CTR_Code status = CTR_OKAY; +uint16_t CANTalon::GetFaults() const { + uint16_t retval = 0; + int val; + CTR_Code status = CTR_OKAY; - /* temperature */ - val = 0; - status = m_impl->GetFault_OverTemp(val); - if(status != CTR_OKAY) - wpi_setErrorWithContext(status, getHALErrorMessage(status)); - retval |= (val) ? CANSpeedController::kTemperatureFault : 0; + /* temperature */ + val = 0; + status = m_impl->GetFault_OverTemp(val); + if (status != CTR_OKAY) + wpi_setErrorWithContext(status, getHALErrorMessage(status)); + retval |= (val) ? CANSpeedController::kTemperatureFault : 0; - /* voltage */ - val = 0; - status = m_impl->GetFault_UnderVoltage(val); - if(status != CTR_OKAY) - wpi_setErrorWithContext(status, getHALErrorMessage(status)); - retval |= (val) ? CANSpeedController::kBusVoltageFault : 0; + /* voltage */ + val = 0; + status = m_impl->GetFault_UnderVoltage(val); + if (status != CTR_OKAY) + wpi_setErrorWithContext(status, getHALErrorMessage(status)); + retval |= (val) ? CANSpeedController::kBusVoltageFault : 0; - /* fwd-limit-switch */ - val = 0; - status = m_impl->GetFault_ForLim(val); - if(status != CTR_OKAY) - wpi_setErrorWithContext(status, getHALErrorMessage(status)); - retval |= (val) ? CANSpeedController::kFwdLimitSwitch : 0; + /* fwd-limit-switch */ + val = 0; + status = m_impl->GetFault_ForLim(val); + if (status != CTR_OKAY) + wpi_setErrorWithContext(status, getHALErrorMessage(status)); + retval |= (val) ? CANSpeedController::kFwdLimitSwitch : 0; - /* rev-limit-switch */ - val = 0; - status = m_impl->GetFault_RevLim(val); - if(status != CTR_OKAY) - wpi_setErrorWithContext(status, getHALErrorMessage(status)); - retval |= (val) ? CANSpeedController::kRevLimitSwitch : 0; + /* rev-limit-switch */ + val = 0; + status = m_impl->GetFault_RevLim(val); + if (status != CTR_OKAY) + wpi_setErrorWithContext(status, getHALErrorMessage(status)); + retval |= (val) ? CANSpeedController::kRevLimitSwitch : 0; - /* fwd-soft-limit */ - val = 0; - status = m_impl->GetFault_ForSoftLim(val); - if(status != CTR_OKAY) - wpi_setErrorWithContext(status, getHALErrorMessage(status)); - retval |= (val) ? CANSpeedController::kFwdSoftLimit : 0; + /* fwd-soft-limit */ + val = 0; + status = m_impl->GetFault_ForSoftLim(val); + if (status != CTR_OKAY) + wpi_setErrorWithContext(status, getHALErrorMessage(status)); + retval |= (val) ? CANSpeedController::kFwdSoftLimit : 0; - /* rev-soft-limit */ - val = 0; - status = m_impl->GetFault_RevSoftLim(val); - if(status != CTR_OKAY) - wpi_setErrorWithContext(status, getHALErrorMessage(status)); - retval |= (val) ? CANSpeedController::kRevSoftLimit : 0; + /* rev-soft-limit */ + val = 0; + status = m_impl->GetFault_RevSoftLim(val); + if (status != CTR_OKAY) + wpi_setErrorWithContext(status, getHALErrorMessage(status)); + retval |= (val) ? CANSpeedController::kRevSoftLimit : 0; - return retval; + return retval; } -uint16_t CANTalon::GetStickyFaults() const -{ - uint16_t retval = 0; - int val; - CTR_Code status = CTR_OKAY; +uint16_t CANTalon::GetStickyFaults() const { + uint16_t retval = 0; + int val; + CTR_Code status = CTR_OKAY; - /* temperature */ - val = 0; - status = m_impl->GetStckyFault_OverTemp(val); - if(status != CTR_OKAY) - wpi_setErrorWithContext(status, getHALErrorMessage(status)); - retval |= (val) ? CANSpeedController::kTemperatureFault : 0; + /* temperature */ + val = 0; + status = m_impl->GetStckyFault_OverTemp(val); + if (status != CTR_OKAY) + wpi_setErrorWithContext(status, getHALErrorMessage(status)); + retval |= (val) ? CANSpeedController::kTemperatureFault : 0; - /* voltage */ - val = 0; - status = m_impl->GetStckyFault_UnderVoltage(val); - if(status != CTR_OKAY) - wpi_setErrorWithContext(status, getHALErrorMessage(status)); - retval |= (val) ? CANSpeedController::kBusVoltageFault : 0; + /* voltage */ + val = 0; + status = m_impl->GetStckyFault_UnderVoltage(val); + if (status != CTR_OKAY) + wpi_setErrorWithContext(status, getHALErrorMessage(status)); + retval |= (val) ? CANSpeedController::kBusVoltageFault : 0; - /* fwd-limit-switch */ - val = 0; - status = m_impl->GetStckyFault_ForLim(val); - if(status != CTR_OKAY) - wpi_setErrorWithContext(status, getHALErrorMessage(status)); - retval |= (val) ? CANSpeedController::kFwdLimitSwitch : 0; + /* fwd-limit-switch */ + val = 0; + status = m_impl->GetStckyFault_ForLim(val); + if (status != CTR_OKAY) + wpi_setErrorWithContext(status, getHALErrorMessage(status)); + retval |= (val) ? CANSpeedController::kFwdLimitSwitch : 0; - /* rev-limit-switch */ - val = 0; - status = m_impl->GetStckyFault_RevLim(val); - if(status != CTR_OKAY) - wpi_setErrorWithContext(status, getHALErrorMessage(status)); - retval |= (val) ? CANSpeedController::kRevLimitSwitch : 0; + /* rev-limit-switch */ + val = 0; + status = m_impl->GetStckyFault_RevLim(val); + if (status != CTR_OKAY) + wpi_setErrorWithContext(status, getHALErrorMessage(status)); + retval |= (val) ? CANSpeedController::kRevLimitSwitch : 0; - /* fwd-soft-limit */ - val = 0; - status = m_impl->GetStckyFault_ForSoftLim(val); - if(status != CTR_OKAY) - wpi_setErrorWithContext(status, getHALErrorMessage(status)); - retval |= (val) ? CANSpeedController::kFwdSoftLimit : 0; + /* fwd-soft-limit */ + val = 0; + status = m_impl->GetStckyFault_ForSoftLim(val); + if (status != CTR_OKAY) + wpi_setErrorWithContext(status, getHALErrorMessage(status)); + retval |= (val) ? CANSpeedController::kFwdSoftLimit : 0; - /* rev-soft-limit */ - val = 0; - status = m_impl->GetStckyFault_RevSoftLim(val); - if(status != CTR_OKAY) - wpi_setErrorWithContext(status, getHALErrorMessage(status)); - retval |= (val) ? CANSpeedController::kRevSoftLimit : 0; + /* rev-soft-limit */ + val = 0; + status = m_impl->GetStckyFault_RevSoftLim(val); + if (status != CTR_OKAY) + wpi_setErrorWithContext(status, getHALErrorMessage(status)); + retval |= (val) ? CANSpeedController::kRevSoftLimit : 0; - return retval; + return retval; } -void CANTalon::ClearStickyFaults() -{ - CTR_Code status = m_impl->ClearStickyFaults(); - wpi_setErrorWithContext(status, getHALErrorMessage(status)); +void CANTalon::ClearStickyFaults() { + CTR_Code status = m_impl->ClearStickyFaults(); + wpi_setErrorWithContext(status, getHALErrorMessage(status)); } /** - * Set the maximum voltage change rate. This ramp rate is in affect regardless of which control mode + * Set the maximum voltage change rate. This ramp rate is in affect regardless + * of which control mode * the TALON is in. * - * When in PercentVbus or Voltage output mode, the rate at which the voltage changes can - * be limited to reduce current spikes. Set this to 0.0 to disable rate limiting. + * When in PercentVbus or Voltage output mode, the rate at which the voltage + * changes can + * be limited to reduce current spikes. Set this to 0.0 to disable rate + * limiting. * - * @param rampRate The maximum rate of voltage change in Percent Voltage mode in V/s. + * @param rampRate The maximum rate of voltage change in Percent Voltage mode in + * V/s. */ -void CANTalon::SetVoltageRampRate(double rampRate) -{ - /* Caller is expressing ramp as Voltage per sec, assuming 12V is full. - Talon's throttle ramp is in dThrot/d10ms. 1023 is full fwd, -1023 is full rev. */ - double rampRatedThrotPer10ms = (rampRate*1023.0/12.0) / 100; - CTR_Code status = m_impl->SetRampThrottle((int)rampRatedThrotPer10ms); - if(status != CTR_OKAY) { - wpi_setErrorWithContext(status, getHALErrorMessage(status)); - } +void CANTalon::SetVoltageRampRate(double rampRate) { + /* Caller is expressing ramp as Voltage per sec, assuming 12V is full. + Talon's throttle ramp is in dThrot/d10ms. 1023 is full fwd, -1023 is + full rev. */ + double rampRatedThrotPer10ms = (rampRate * 1023.0 / 12.0) / 100; + CTR_Code status = m_impl->SetRampThrottle((int)rampRatedThrotPer10ms); + if (status != CTR_OKAY) { + wpi_setErrorWithContext(status, getHALErrorMessage(status)); + } } /** - * Sets a voltage change rate that applies only when a close loop contorl mode is enabled. + * Sets a voltage change rate that applies only when a close loop contorl mode + * is enabled. * This allows close loop specific ramp behavior. * - * @param rampRate The maximum rate of voltage change in Percent Voltage mode in V/s. + * @param rampRate The maximum rate of voltage change in Percent Voltage mode in + * V/s. */ -void CANTalon::SetCloseLoopRampRate(double rampRate) -{ - CTR_Code status = m_impl->SetCloseLoopRampRate(m_profile,rampRate * 1023.0 / 12.0 / 1000.0); - if(status != CTR_OKAY) { - wpi_setErrorWithContext(status, getHALErrorMessage(status)); - } +void CANTalon::SetCloseLoopRampRate(double rampRate) { + CTR_Code status = m_impl->SetCloseLoopRampRate( + m_profile, rampRate * 1023.0 / 12.0 / 1000.0); + if (status != CTR_OKAY) { + wpi_setErrorWithContext(status, getHALErrorMessage(status)); + } } /** * @return The version of the firmware running on the Talon */ -uint32_t CANTalon::GetFirmwareVersion() const -{ - int firmwareVersion; - CTR_Code status = m_impl->RequestParam(CanTalonSRX::eFirmVers); - if(status != CTR_OKAY) { - wpi_setErrorWithContext(status, getHALErrorMessage(status)); - } - usleep(kDelayForSolicitedSignalsUs); - status = m_impl->GetParamResponseInt32(CanTalonSRX::eFirmVers,firmwareVersion); - if(status != CTR_OKAY) { - wpi_setErrorWithContext(status, getHALErrorMessage(status)); - } +uint32_t CANTalon::GetFirmwareVersion() const { + int firmwareVersion; + CTR_Code status = m_impl->RequestParam(CanTalonSRX::eFirmVers); + if (status != CTR_OKAY) { + wpi_setErrorWithContext(status, getHALErrorMessage(status)); + } + usleep(kDelayForSolicitedSignalsUs); + status = + m_impl->GetParamResponseInt32(CanTalonSRX::eFirmVers, firmwareVersion); + if (status != CTR_OKAY) { + wpi_setErrorWithContext(status, getHALErrorMessage(status)); + } - /* only sent once on boot */ - //CTR_Code status = m_impl->GetFirmVers(firmwareVersion); - //if(status != CTR_OKAY) { - // wpi_setErrorWithContext(status, getHALErrorMessage(status)); - //} + /* only sent once on boot */ + // CTR_Code status = m_impl->GetFirmVers(firmwareVersion); + // if(status != CTR_OKAY) { + // wpi_setErrorWithContext(status, getHALErrorMessage(status)); + //} - return firmwareVersion; + return firmwareVersion; } /** * @return The accumulator for I gain. */ -int CANTalon::GetIaccum() const -{ - CTR_Code status = m_impl->RequestParam(CanTalonSRX::ePidIaccum); - if(status != CTR_OKAY) { - wpi_setErrorWithContext(status, getHALErrorMessage(status)); - } - usleep(kDelayForSolicitedSignalsUs); /* small yield for getting response */ - int iaccum; - status = m_impl->GetParamResponseInt32(CanTalonSRX::ePidIaccum,iaccum); - if(status != CTR_OKAY) { - wpi_setErrorWithContext(status, getHALErrorMessage(status)); - } - return iaccum; +int CANTalon::GetIaccum() const { + CTR_Code status = m_impl->RequestParam(CanTalonSRX::ePidIaccum); + if (status != CTR_OKAY) { + wpi_setErrorWithContext(status, getHALErrorMessage(status)); + } + usleep(kDelayForSolicitedSignalsUs); /* small yield for getting response */ + int iaccum; + status = m_impl->GetParamResponseInt32(CanTalonSRX::ePidIaccum, iaccum); + if (status != CTR_OKAY) { + wpi_setErrorWithContext(status, getHALErrorMessage(status)); + } + return iaccum; } /** * Clear the accumulator for I gain. */ -void CANTalon::ClearIaccum() -{ - CTR_Code status = m_impl->SetParam(CanTalonSRX::ePidIaccum, 0); - if(status != CTR_OKAY) { - wpi_setErrorWithContext(status, getHALErrorMessage(status)); - } +void CANTalon::ClearIaccum() { + CTR_Code status = m_impl->SetParam(CanTalonSRX::ePidIaccum, 0); + if (status != CTR_OKAY) { + wpi_setErrorWithContext(status, getHALErrorMessage(status)); + } } /** * TODO documentation (see CANJaguar.cpp) */ -void CANTalon::ConfigNeutralMode(NeutralMode mode) -{ - CTR_Code status = CTR_OKAY; - switch(mode){ - default: - case kNeutralMode_Jumper: /* use default setting in flash based on webdash/BrakeCal button selection */ - status = m_impl->SetOverrideBrakeType(CanTalonSRX::kBrakeOverride_UseDefaultsFromFlash); - break; - case kNeutralMode_Brake: - status = m_impl->SetOverrideBrakeType(CanTalonSRX::kBrakeOverride_OverrideBrake); - break; - case kNeutralMode_Coast: - status = m_impl->SetOverrideBrakeType(CanTalonSRX::kBrakeOverride_OverrideCoast); - break; - } - if(status != CTR_OKAY) { - wpi_setErrorWithContext(status, getHALErrorMessage(status)); - } +void CANTalon::ConfigNeutralMode(NeutralMode mode) { + CTR_Code status = CTR_OKAY; + switch (mode) { + default: + case kNeutralMode_Jumper: /* use default setting in flash based on + webdash/BrakeCal button selection */ + status = m_impl->SetOverrideBrakeType( + CanTalonSRX::kBrakeOverride_UseDefaultsFromFlash); + break; + case kNeutralMode_Brake: + status = m_impl->SetOverrideBrakeType( + CanTalonSRX::kBrakeOverride_OverrideBrake); + break; + case kNeutralMode_Coast: + status = m_impl->SetOverrideBrakeType( + CanTalonSRX::kBrakeOverride_OverrideCoast); + break; + } + if (status != CTR_OKAY) { + wpi_setErrorWithContext(status, getHALErrorMessage(status)); + } } /** - * @return nonzero if brake is enabled during neutral. Zero if coast is enabled during neutral. + * @return nonzero if brake is enabled during neutral. Zero if coast is enabled + * during neutral. */ -int CANTalon::GetBrakeEnableDuringNeutral() const -{ +int CANTalon::GetBrakeEnableDuringNeutral() const { int brakeEn = 0; CTR_Code status = m_impl->GetBrakeIsEnabled(brakeEn); - if(status != CTR_OKAY) { - wpi_setErrorWithContext(status, getHALErrorMessage(status)); - } - return brakeEn; + if (status != CTR_OKAY) { + wpi_setErrorWithContext(status, getHALErrorMessage(status)); + } + return brakeEn; } /** * @deprecated not implemented */ -void CANTalon::ConfigEncoderCodesPerRev(uint16_t codesPerRev) -{ - /* TALON SRX does not scale units, they are raw from the sensor. Unit scaling can be done in API or by caller */ +void CANTalon::ConfigEncoderCodesPerRev(uint16_t codesPerRev) { + /* TALON SRX does not scale units, they are raw from the sensor. Unit scaling + * can be done in API or by caller */ } /** * @deprecated not implemented */ -void CANTalon::ConfigPotentiometerTurns(uint16_t turns) -{ - /* TALON SRX does not scale units, they are raw from the sensor. Unit scaling can be done in API or by caller */ +void CANTalon::ConfigPotentiometerTurns(uint16_t turns) { + /* TALON SRX does not scale units, they are raw from the sensor. Unit scaling + * can be done in API or by caller */ } /** * @deprecated not implemented */ -void CANTalon::ConfigSoftPositionLimits(double forwardLimitPosition, double reverseLimitPosition) -{ - ConfigLimitMode(kLimitMode_SoftPositionLimits); - ConfigForwardLimit(forwardLimitPosition); - ConfigReverseLimit(reverseLimitPosition); +void CANTalon::ConfigSoftPositionLimits(double forwardLimitPosition, + double reverseLimitPosition) { + ConfigLimitMode(kLimitMode_SoftPositionLimits); + ConfigForwardLimit(forwardLimitPosition); + ConfigReverseLimit(reverseLimitPosition); } /** * TODO documentation (see CANJaguar.cpp) */ -void CANTalon::DisableSoftPositionLimits() -{ - ConfigLimitMode(kLimitMode_SwitchInputsOnly); +void CANTalon::DisableSoftPositionLimits() { + ConfigLimitMode(kLimitMode_SwitchInputsOnly); } /** @@ -1076,72 +1041,77 @@ void CANTalon::DisableSoftPositionLimits() * Configures the soft limit enable (wear leveled persistent memory). * Also sets the limit switch overrides. */ -void CANTalon::ConfigLimitMode(LimitMode mode) -{ - CTR_Code status = CTR_OKAY; - switch(mode){ - case kLimitMode_SwitchInputsOnly: /** Only use switches for limits */ - /* turn OFF both limits. SRX has individual enables and polarity for each limit switch.*/ - status = m_impl->SetForwardSoftEnable(false); - if(status != CTR_OKAY) { - wpi_setErrorWithContext(status, getHALErrorMessage(status)); - } - status = m_impl->SetReverseSoftEnable(false); - if(status != CTR_OKAY) { - wpi_setErrorWithContext(status, getHALErrorMessage(status)); - } - /* override enable the limit switches, this circumvents the webdash */ - status = m_impl->SetOverrideLimitSwitchEn(CanTalonSRX::kLimitSwitchOverride_EnableFwd_EnableRev); - if(status != CTR_OKAY) { - wpi_setErrorWithContext(status, getHALErrorMessage(status)); - } - break; - case kLimitMode_SoftPositionLimits: /** Use both switches and soft limits */ - /* turn on both limits. SRX has individual enables and polarity for each limit switch.*/ - status = m_impl->SetForwardSoftEnable(true); - if(status != CTR_OKAY) { - wpi_setErrorWithContext(status, getHALErrorMessage(status)); - } - status = m_impl->SetReverseSoftEnable(true); - if(status != CTR_OKAY) { - wpi_setErrorWithContext(status, getHALErrorMessage(status)); - } - /* override enable the limit switches, this circumvents the webdash */ - status = m_impl->SetOverrideLimitSwitchEn(CanTalonSRX::kLimitSwitchOverride_EnableFwd_EnableRev); - if(status != CTR_OKAY) { - wpi_setErrorWithContext(status, getHALErrorMessage(status)); - } - break; +void CANTalon::ConfigLimitMode(LimitMode mode) { + CTR_Code status = CTR_OKAY; + switch (mode) { + case kLimitMode_SwitchInputsOnly: /** Only use switches for limits */ + /* turn OFF both limits. SRX has individual enables and polarity for each + * limit switch.*/ + status = m_impl->SetForwardSoftEnable(false); + if (status != CTR_OKAY) { + wpi_setErrorWithContext(status, getHALErrorMessage(status)); + } + status = m_impl->SetReverseSoftEnable(false); + if (status != CTR_OKAY) { + wpi_setErrorWithContext(status, getHALErrorMessage(status)); + } + /* override enable the limit switches, this circumvents the webdash */ + status = m_impl->SetOverrideLimitSwitchEn( + CanTalonSRX::kLimitSwitchOverride_EnableFwd_EnableRev); + if (status != CTR_OKAY) { + wpi_setErrorWithContext(status, getHALErrorMessage(status)); + } + break; + case kLimitMode_SoftPositionLimits: /** Use both switches and soft limits */ + /* turn on both limits. SRX has individual enables and polarity for each + * limit switch.*/ + status = m_impl->SetForwardSoftEnable(true); + if (status != CTR_OKAY) { + wpi_setErrorWithContext(status, getHALErrorMessage(status)); + } + status = m_impl->SetReverseSoftEnable(true); + if (status != CTR_OKAY) { + wpi_setErrorWithContext(status, getHALErrorMessage(status)); + } + /* override enable the limit switches, this circumvents the webdash */ + status = m_impl->SetOverrideLimitSwitchEn( + CanTalonSRX::kLimitSwitchOverride_EnableFwd_EnableRev); + if (status != CTR_OKAY) { + wpi_setErrorWithContext(status, getHALErrorMessage(status)); + } + break; - case kLimitMode_SrxDisableSwitchInputs: /** disable both limit switches and soft limits */ - /* turn on both limits. SRX has individual enables and polarity for each limit switch.*/ - status = m_impl->SetForwardSoftEnable(false); - if(status != CTR_OKAY) { - wpi_setErrorWithContext(status, getHALErrorMessage(status)); - } - status = m_impl->SetReverseSoftEnable(false); - if(status != CTR_OKAY) { - wpi_setErrorWithContext(status, getHALErrorMessage(status)); - } - /* override enable the limit switches, this circumvents the webdash */ - status = m_impl->SetOverrideLimitSwitchEn(CanTalonSRX::kLimitSwitchOverride_DisableFwd_DisableRev); - if(status != CTR_OKAY) { - wpi_setErrorWithContext(status, getHALErrorMessage(status)); - } - break; - } + case kLimitMode_SrxDisableSwitchInputs: /** disable both limit switches and + soft limits */ + /* turn on both limits. SRX has individual enables and polarity for each + * limit switch.*/ + status = m_impl->SetForwardSoftEnable(false); + if (status != CTR_OKAY) { + wpi_setErrorWithContext(status, getHALErrorMessage(status)); + } + status = m_impl->SetReverseSoftEnable(false); + if (status != CTR_OKAY) { + wpi_setErrorWithContext(status, getHALErrorMessage(status)); + } + /* override enable the limit switches, this circumvents the webdash */ + status = m_impl->SetOverrideLimitSwitchEn( + CanTalonSRX::kLimitSwitchOverride_DisableFwd_DisableRev); + if (status != CTR_OKAY) { + wpi_setErrorWithContext(status, getHALErrorMessage(status)); + } + break; + } } /** * TODO documentation (see CANJaguar.cpp) */ -void CANTalon::ConfigForwardLimit(double forwardLimitPosition) -{ - CTR_Code status = CTR_OKAY; - status = m_impl->SetForwardSoftLimit(forwardLimitPosition); - if(status != CTR_OKAY) { - wpi_setErrorWithContext(status, getHALErrorMessage(status)); - } +void CANTalon::ConfigForwardLimit(double forwardLimitPosition) { + CTR_Code status = CTR_OKAY; + status = m_impl->SetForwardSoftLimit(forwardLimitPosition); + if (status != CTR_OKAY) { + wpi_setErrorWithContext(status, getHALErrorMessage(status)); + } } /** * Change the fwd limit switch setting to normally open or closed. @@ -1153,12 +1123,13 @@ void CANTalon::ConfigForwardLimit(double forwardLimitPosition) * * @param normallyOpen true for normally open. false for normally closed. */ -void CANTalon::ConfigFwdLimitSwitchNormallyOpen(bool normallyOpen) -{ - CTR_Code status = m_impl->SetParam(CanTalonSRX::eOnBoot_LimitSwitch_Forward_NormallyClosed, normallyOpen ? 0 : 1); - if(status != CTR_OKAY) { - wpi_setErrorWithContext(status, getHALErrorMessage(status)); - } +void CANTalon::ConfigFwdLimitSwitchNormallyOpen(bool normallyOpen) { + CTR_Code status = + m_impl->SetParam(CanTalonSRX::eOnBoot_LimitSwitch_Forward_NormallyClosed, + normallyOpen ? 0 : 1); + if (status != CTR_OKAY) { + wpi_setErrorWithContext(status, getHALErrorMessage(status)); + } } /** * Change the rev limit switch setting to normally open or closed. @@ -1170,41 +1141,41 @@ void CANTalon::ConfigFwdLimitSwitchNormallyOpen(bool normallyOpen) * * @param normallyOpen true for normally open. false for normally closed. */ -void CANTalon::ConfigRevLimitSwitchNormallyOpen(bool normallyOpen) -{ - CTR_Code status = m_impl->SetParam(CanTalonSRX::eOnBoot_LimitSwitch_Reverse_NormallyClosed, normallyOpen ? 0 : 1); - if(status != CTR_OKAY) { - wpi_setErrorWithContext(status, getHALErrorMessage(status)); - } +void CANTalon::ConfigRevLimitSwitchNormallyOpen(bool normallyOpen) { + CTR_Code status = + m_impl->SetParam(CanTalonSRX::eOnBoot_LimitSwitch_Reverse_NormallyClosed, + normallyOpen ? 0 : 1); + if (status != CTR_OKAY) { + wpi_setErrorWithContext(status, getHALErrorMessage(status)); + } } /** * TODO documentation (see CANJaguar.cpp) */ -void CANTalon::ConfigReverseLimit(double reverseLimitPosition) -{ - CTR_Code status = CTR_OKAY; - status = m_impl->SetReverseSoftLimit(reverseLimitPosition); - if(status != CTR_OKAY) { - wpi_setErrorWithContext(status, getHALErrorMessage(status)); - } +void CANTalon::ConfigReverseLimit(double reverseLimitPosition) { + CTR_Code status = CTR_OKAY; + status = m_impl->SetReverseSoftLimit(reverseLimitPosition); + if (status != CTR_OKAY) { + wpi_setErrorWithContext(status, getHALErrorMessage(status)); + } } /** * TODO documentation (see CANJaguar.cpp) */ -void CANTalon::ConfigMaxOutputVoltage(double voltage) -{ - /* SRX does not support max output */ - wpi_setWPIErrorWithContext(IncompatibleMode, "MaxOutputVoltage not supported."); +void CANTalon::ConfigMaxOutputVoltage(double voltage) { + /* SRX does not support max output */ + wpi_setWPIErrorWithContext(IncompatibleMode, + "MaxOutputVoltage not supported."); } /** * TODO documentation (see CANJaguar.cpp) */ -void CANTalon::ConfigFaultTime(float faultTime) -{ - /* SRX does not have fault time. SRX motor drive is only disabled for soft limits and limit-switch faults. */ - wpi_setWPIErrorWithContext(IncompatibleMode, "Fault Time not supported."); +void CANTalon::ConfigFaultTime(float faultTime) { + /* SRX does not have fault time. SRX motor drive is only disabled for soft + * limits and limit-switch faults. */ + wpi_setWPIErrorWithContext(IncompatibleMode, "Fault Time not supported."); } /** @@ -1213,10 +1184,10 @@ void CANTalon::ConfigFaultTime(float faultTime) * @param mode Control mode to ultimately enter once user calls Set(). * @see Set() */ -void CANTalon::ApplyControlMode(CANSpeedController::ControlMode mode) -{ +void CANTalon::ApplyControlMode(CANSpeedController::ControlMode mode) { m_controlMode = mode; - HALReport(HALUsageReporting::kResourceType_CANTalonSRX, m_deviceNumber+1, mode); + HALReport(HALUsageReporting::kResourceType_CANTalonSRX, m_deviceNumber + 1, + mode); switch (mode) { case kPercentVbus: m_sendMode = kThrottle; @@ -1239,18 +1210,17 @@ void CANTalon::ApplyControlMode(CANSpeedController::ControlMode mode) } // Keep the talon disabled until Set() is called. CTR_Code status = m_impl->SetModeSelect((int)kDisabled); - if(status != CTR_OKAY) { - wpi_setErrorWithContext(status, getHALErrorMessage(status)); - } + if (status != CTR_OKAY) { + wpi_setErrorWithContext(status, getHALErrorMessage(status)); + } } /** * TODO documentation (see CANJaguar.cpp) */ -void CANTalon::SetControlMode(CANSpeedController::ControlMode mode) -{ - if(m_controlMode == mode){ +void CANTalon::SetControlMode(CANSpeedController::ControlMode mode) { + if (m_controlMode == mode) { /* we already are in this mode, don't perform disable workaround */ - }else{ + } else { ApplyControlMode(mode); } } @@ -1258,39 +1228,30 @@ void CANTalon::SetControlMode(CANSpeedController::ControlMode mode) /** * TODO documentation (see CANJaguar.cpp) */ -CANSpeedController::ControlMode CANTalon::GetControlMode() const -{ +CANSpeedController::ControlMode CANTalon::GetControlMode() const { return m_controlMode; } -void CANTalon::SetExpiration(float timeout) -{ - m_safetyHelper->SetExpiration(timeout); +void CANTalon::SetExpiration(float timeout) { + m_safetyHelper->SetExpiration(timeout); } -float CANTalon::GetExpiration() const -{ - return m_safetyHelper->GetExpiration(); +float CANTalon::GetExpiration() const { + return m_safetyHelper->GetExpiration(); } -bool CANTalon::IsAlive() const -{ - return m_safetyHelper->IsAlive(); +bool CANTalon::IsAlive() const { return m_safetyHelper->IsAlive(); } + +bool CANTalon::IsSafetyEnabled() const { + return m_safetyHelper->IsSafetyEnabled(); } -bool CANTalon::IsSafetyEnabled() const -{ - return m_safetyHelper->IsSafetyEnabled(); +void CANTalon::SetSafetyEnabled(bool enabled) { + m_safetyHelper->SetSafetyEnabled(enabled); } -void CANTalon::SetSafetyEnabled(bool enabled) -{ - m_safetyHelper->SetSafetyEnabled(enabled); -} - -void CANTalon::GetDescription(char *desc) const -{ - sprintf(desc, "CANTalon ID %d", m_deviceNumber); +void CANTalon::GetDescription(char* desc) const { + sprintf(desc, "CANTalon ID %d", m_deviceNumber); } /** @@ -1298,9 +1259,7 @@ void CANTalon::GetDescription(char *desc) const * Only works in PercentVbus, speed, and Voltage modes. * @param isInverted The state of inversion, true is inverted. */ -void CANTalon::SetInverted(bool isInverted){ -m_isInverted = isInverted; -} +void CANTalon::SetInverted(bool isInverted) { m_isInverted = isInverted; } /** * Common interface for the inverting direction of a speed controller. @@ -1308,9 +1267,7 @@ m_isInverted = isInverted; * @return isInverted The state of inversion, true is inverted. * */ -bool CANTalon::GetInverted() const { - return m_isInverted; -} +bool CANTalon::GetInverted() const { return m_isInverted; } /** * Common interface for stopping the motor @@ -1318,52 +1275,38 @@ bool CANTalon::GetInverted() const { * * @deprecated Call Disable instead. */ -void CANTalon::StopMotor() -{ - Disable(); +void CANTalon::StopMotor() { Disable(); } + +void CANTalon::ValueChanged(ITable* source, const std::string& key, + EntryValue value, bool isNew) { + Set(value.f); } -void CANTalon::ValueChanged(ITable* source, const std::string& key, EntryValue value, bool isNew) -{ - Set(value.f); +void CANTalon::UpdateTable() { + if (m_table != NULL) { + m_table->PutNumber("Value", Get()); + } } -void CANTalon::UpdateTable() -{ - if (m_table != NULL) - { - m_table->PutNumber("Value", Get()); - } +void CANTalon::StartLiveWindowMode() { + if (m_table != NULL) { + m_table->AddTableListener("Value", this, true); + } } -void CANTalon::StartLiveWindowMode() -{ - if (m_table != NULL) - { - m_table->AddTableListener("Value", this, true); - } +void CANTalon::StopLiveWindowMode() { + if (m_table != NULL) { + m_table->RemoveTableListener(this); + } } -void CANTalon::StopLiveWindowMode() -{ - if (m_table != NULL) - { - m_table->RemoveTableListener(this); - } +std::string CANTalon::GetSmartDashboardType() const { + return "Speed Controller"; } -std::string CANTalon::GetSmartDashboardType() const -{ - return "Speed Controller"; +void CANTalon::InitTable(ITable* subTable) { + m_table = subTable; + UpdateTable(); } -void CANTalon::InitTable(ITable *subTable) -{ - m_table = subTable; - UpdateTable(); -} - -ITable * CANTalon::GetTable() const -{ - return m_table; -} +ITable* CANTalon::GetTable() const { return m_table; } diff --git a/wpilibc/wpilibC++Devices/src/CameraServer.cpp b/wpilibc/wpilibC++Devices/src/CameraServer.cpp index d8547bf052..c639a2c004 100644 --- a/wpilibc/wpilibC++Devices/src/CameraServer.cpp +++ b/wpilibc/wpilibC++Devices/src/CameraServer.cpp @@ -10,7 +10,7 @@ #include constexpr uint8_t CameraServer::kMagicNumber[]; -CameraServer *CameraServer::s_instance = nullptr; +CameraServer* CameraServer::s_instance = nullptr; CameraServer* CameraServer::GetInstance() { if (s_instance == NULL) { @@ -19,39 +19,43 @@ CameraServer* CameraServer::GetInstance() { return s_instance; } -CameraServer::CameraServer() : - m_camera(), - m_serverThread(&CameraServer::Serve, this), - m_captureThread(), - m_imageMutex(), - m_newImageVariable(), - m_dataPool(3), - m_quality(50), - m_autoCaptureStarted(false), - m_hwClient(true), - m_imageData(nullptr, 0, 0, false) { - for (int i = 0; i < 3; i++) - m_dataPool.push_back(new uint8_t[kMaxImageSize]); +CameraServer::CameraServer() + : m_camera(), + m_serverThread(&CameraServer::Serve, this), + m_captureThread(), + m_imageMutex(), + m_newImageVariable(), + m_dataPool(3), + m_quality(50), + m_autoCaptureStarted(false), + m_hwClient(true), + m_imageData(nullptr, 0, 0, false) { + for (int i = 0; i < 3; i++) m_dataPool.push_back(new uint8_t[kMaxImageSize]); } -void CameraServer::FreeImageData(std::tuple imageData) { - if (std::get<3>(imageData)) imaqDispose(std::get<0>(imageData)); +void CameraServer::FreeImageData( + std::tuple imageData) { + if (std::get<3>(imageData)) + imaqDispose(std::get<0>(imageData)); else if (std::get<0>(imageData) != nullptr) { std::unique_lock lock(m_imageMutex); m_dataPool.push_back(std::get<0>(imageData)); } } -void CameraServer::SetImageData(uint8_t* data, unsigned int size, unsigned int start, bool imaqData) { +void CameraServer::SetImageData(uint8_t* data, unsigned int size, + unsigned int start, bool imaqData) { std::unique_lock lock(m_imageMutex); FreeImageData(m_imageData); m_imageData = std::make_tuple(data, size, start, imaqData); m_newImageVariable.notify_all(); } - -void CameraServer::SetImage(Image const *image) { + +void CameraServer::SetImage(Image const* image) { unsigned int dataSize = 0; - uint8_t* data = (uint8_t*) imaqFlatten(image, IMAQ_FLATTEN_IMAGE, IMAQ_COMPRESSION_JPEG, 10 * m_quality, &dataSize); + uint8_t* data = + (uint8_t*)imaqFlatten(image, IMAQ_FLATTEN_IMAGE, IMAQ_COMPRESSION_JPEG, + 10 * m_quality, &dataSize); // If we're using a HW camera, then find the start of the data bool hwClient; @@ -63,15 +67,17 @@ void CameraServer::SetImage(Image const *image) { unsigned int start = 0; if (hwClient) { while (start < dataSize - 1) { - if (data[start] == 0xFF && data[start + 1] == 0xD8) break; - else start++; + if (data[start] == 0xFF && data[start + 1] == 0xD8) + break; + else + start++; } } dataSize -= start; wpi_assert(dataSize > 2); SetImageData(data, dataSize, start, true); -} +} void CameraServer::AutoCapture() { Image* frame = imaqCreateImage(IMAQ_IMAGE_RGB, 0); @@ -98,8 +104,9 @@ void CameraServer::AutoCapture() { } } -void CameraServer::StartAutomaticCapture(char const *cameraName) { - std::shared_ptr camera = std::make_shared(cameraName, true); +void CameraServer::StartAutomaticCapture(char const* cameraName) { + std::shared_ptr camera = + std::make_shared(cameraName, true); camera->OpenCamera(); StartAutomaticCapture(camera); } @@ -124,9 +131,12 @@ bool CameraServer::IsAutoCaptureStarted() { void CameraServer::SetSize(unsigned int size) { std::unique_lock lock(m_imageMutex); if (!m_camera) return; - if (size == kSize160x120) m_camera->SetSize(160, 120); - else if (size == kSize320x240) m_camera->SetSize(320, 240); - else if (size == kSize640x480) m_camera->SetSize(640, 480); + if (size == kSize160x120) + m_camera->SetSize(160, 120); + else if (size == kSize320x240) + m_camera->SetSize(320, 240); + else if (size == kSize640x480) + m_camera->SetSize(640, 480); } void CameraServer::SetQuality(unsigned int quality) { @@ -142,11 +152,11 @@ unsigned int CameraServer::GetQuality() { void CameraServer::Serve() { int sock = socket(AF_INET, SOCK_STREAM, 0); - if (sock == -1) - wpi_setErrnoError(); + if (sock == -1) wpi_setErrnoError(); int reuseAddr = 1; - if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &reuseAddr, sizeof(reuseAddr)) == -1) + if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &reuseAddr, + sizeof(reuseAddr)) == -1) wpi_setErrnoError(); sockaddr_in address, clientAddress; @@ -156,16 +166,16 @@ void CameraServer::Serve() { address.sin_addr.s_addr = htonl(INADDR_ANY); address.sin_port = htons(kPort); - if (bind(sock, (struct sockaddr *)&address, sizeof(address)) == -1) + if (bind(sock, (struct sockaddr*)&address, sizeof(address)) == -1) wpi_setErrnoError(); - if (listen(sock, 10) == -1) - wpi_setErrnoError(); + if (listen(sock, 10) == -1) wpi_setErrnoError(); - while(true) { + while (true) { socklen_t clientAddressLen = sizeof(clientAddress); - int conn = accept(sock, (struct sockaddr*)&clientAddress, &clientAddressLen); + int conn = + accept(sock, (struct sockaddr*)&clientAddress, &clientAddressLen); if (conn == -1) { wpi_setErrnoError(); continue; @@ -182,10 +192,12 @@ void CameraServer::Serve() { req.size = ntohl(req.size); } - // TODO: Support the SW Compression. The rest of the code below will work as though this + // TODO: Support the SW Compression. The rest of the code below will work as + // though this // check isn't here if (req.compression != kHardwareCompression) { - wpi_setWPIErrorWithContext(IncompatibleState, "Choose \"USB Camera HW\" on the dashboard"); + wpi_setWPIErrorWithContext(IncompatibleState, + "Choose \"USB Camera HW\" on the dashboard"); close(conn); continue; } @@ -198,8 +210,10 @@ void CameraServer::Serve() { m_newImageVariable.wait(lock); } m_hwClient = req.compression == kHardwareCompression; - if (!m_hwClient) SetQuality(100 - req.compression); - else if (m_camera) m_camera->SetFPS(req.fps); + if (!m_hwClient) + SetQuality(100 - req.compression); + else if (m_camera) + m_camera->SetFPS(req.fps); SetSize(req.size); } @@ -217,12 +231,13 @@ void CameraServer::Serve() { unsigned int size = std::get<1>(imageData); unsigned int netSize = htonl(size); unsigned int start = std::get<2>(imageData); - uint8_t *data = std::get<0>(imageData); + uint8_t* data = std::get<0>(imageData); if (data == nullptr) continue; if (write(conn, kMagicNumber, sizeof(kMagicNumber)) == -1) { - wpi_setErrnoErrorWithContext("[CameraServer] Error sending magic number"); + wpi_setErrnoErrorWithContext( + "[CameraServer] Error sending magic number"); FreeImageData(imageData); break; } diff --git a/wpilibc/wpilibC++Devices/src/Compressor.cpp b/wpilibc/wpilibC++Devices/src/Compressor.cpp index 884cf94d40..79c6131f4c 100644 --- a/wpilibc/wpilibC++Devices/src/Compressor.cpp +++ b/wpilibc/wpilibC++Devices/src/Compressor.cpp @@ -6,10 +6,10 @@ #include "WPIErrors.h" void Compressor::InitCompressor(uint8_t pcmID) { - m_table = 0; - m_pcm_pointer = initializeCompressor(pcmID); + m_table = 0; + m_pcm_pointer = initializeCompressor(pcmID); - SetClosedLoopControl(true); + SetClosedLoopControl(true); } /** @@ -17,52 +17,44 @@ void Compressor::InitCompressor(uint8_t pcmID) { * * Uses the default PCM ID (0) */ -Compressor::Compressor() { - InitCompressor(GetDefaultSolenoidModule()); -} +Compressor::Compressor() { InitCompressor(GetDefaultSolenoidModule()); } /** * Constructor * * @param module The PCM ID to use (0-62) */ -Compressor::Compressor(uint8_t pcmID) { - InitCompressor(pcmID); -} +Compressor::Compressor(uint8_t pcmID) { InitCompressor(pcmID); } -Compressor::~Compressor() { - -} +Compressor::~Compressor() {} /** - * Starts closed-loop control. Note that closed loop control is enabled by default. + * Starts closed-loop control. Note that closed loop control is enabled by + * default. */ -void Compressor::Start() { - SetClosedLoopControl(true); -} +void Compressor::Start() { SetClosedLoopControl(true); } /** - * Stops closed-loop control. Note that closed loop control is enabled by default. + * Stops closed-loop control. Note that closed loop control is enabled by + * default. */ -void Compressor::Stop() { - SetClosedLoopControl(false); -} +void Compressor::Stop() { SetClosedLoopControl(false); } /** * Check if compressor output is active * @return true if the compressor is on */ bool Compressor::Enabled() const { - int32_t status = 0; - bool value; + int32_t status = 0; + bool value; - value = getCompressor(m_pcm_pointer, &status); + value = getCompressor(m_pcm_pointer, &status); - if(status) { - wpi_setWPIError(Timeout); - } + if (status) { + wpi_setWPIError(Timeout); + } - return value; + return value; } /** @@ -70,224 +62,228 @@ bool Compressor::Enabled() const { * @return true if pressure is low */ bool Compressor::GetPressureSwitchValue() const { - int32_t status = 0; - bool value; + int32_t status = 0; + bool value; - value = getPressureSwitch(m_pcm_pointer, &status); + value = getPressureSwitch(m_pcm_pointer, &status); - if(status) { - wpi_setWPIError(Timeout); - } + if (status) { + wpi_setWPIError(Timeout); + } - return value; + return value; } - /** * Query how much current the compressor is drawing * @return The current through the compressor, in amps */ float Compressor::GetCompressorCurrent() const { - int32_t status = 0; - float value; + int32_t status = 0; + float value; - value = getCompressorCurrent(m_pcm_pointer, &status); + value = getCompressorCurrent(m_pcm_pointer, &status); - if(status) { - wpi_setWPIError(Timeout); - } + if (status) { + wpi_setWPIError(Timeout); + } - return value; + return value; } - /** * Enables or disables automatically turning the compressor on when the * pressure is low. - * @param on Set to true to enable closed loop control of the compressor. False to disable. + * @param on Set to true to enable closed loop control of the compressor. False + * to disable. */ void Compressor::SetClosedLoopControl(bool on) { - int32_t status = 0; + int32_t status = 0; - setClosedLoopControl(m_pcm_pointer, on, &status); + setClosedLoopControl(m_pcm_pointer, on, &status); - if(status) { - wpi_setWPIError(Timeout); - } + if (status) { + wpi_setWPIError(Timeout); + } } /** * Returns true if the compressor will automatically turn on when the * pressure is low. - * @return True if closed loop control of the compressor is enabled. False if disabled. + * @return True if closed loop control of the compressor is enabled. False if + * disabled. */ bool Compressor::GetClosedLoopControl() const { - int32_t status = 0; - bool value; + int32_t status = 0; + bool value; - value = getClosedLoopControl(m_pcm_pointer, &status); + value = getClosedLoopControl(m_pcm_pointer, &status); - if(status) { - wpi_setWPIError(Timeout); - } + if (status) { + wpi_setWPIError(Timeout); + } - return value; + return value; } /** * Query if the compressor output has been disabled due to high current draw. - * @return true if PCM is in fault state : Compressor Drive is - * disabled due to compressor current being too high. + * @return true if PCM is in fault state : Compressor Drive is + * disabled due to compressor current being too high. */ bool Compressor::GetCompressorCurrentTooHighFault() const { - int32_t status = 0; - bool value; + int32_t status = 0; + bool value; - value = getCompressorCurrentTooHighFault(m_pcm_pointer, &status); + value = getCompressorCurrentTooHighFault(m_pcm_pointer, &status); - if(status) { - wpi_setWPIError(Timeout); - } + if (status) { + wpi_setWPIError(Timeout); + } - return value; + return value; } /** - * Query if the compressor output has been disabled due to high current draw (sticky). - * A sticky fault will not clear on device reboot, it must be cleared through code or the webdash. - * @return true if PCM sticky fault is set : Compressor Drive is - * disabled due to compressor current being too high. + * Query if the compressor output has been disabled due to high current draw + * (sticky). + * A sticky fault will not clear on device reboot, it must be cleared through + * code or the webdash. + * @return true if PCM sticky fault is set : Compressor Drive is + * disabled due to compressor current being too high. */ bool Compressor::GetCompressorCurrentTooHighStickyFault() const { - int32_t status = 0; - bool value; + int32_t status = 0; + bool value; - value = getCompressorCurrentTooHighStickyFault(m_pcm_pointer, &status); + value = getCompressorCurrentTooHighStickyFault(m_pcm_pointer, &status); - if(status) { - wpi_setWPIError(Timeout); - } + if (status) { + wpi_setWPIError(Timeout); + } - return value; + return value; } /** - * Query if the compressor output has been disabled due to a short circuit (sticky). - * A sticky fault will not clear on device reboot, it must be cleared through code or the webdash. - * @return true if PCM sticky fault is set : Compressor output - * appears to be shorted. + * Query if the compressor output has been disabled due to a short circuit + * (sticky). + * A sticky fault will not clear on device reboot, it must be cleared through + * code or the webdash. + * @return true if PCM sticky fault is set : Compressor output + * appears to be shorted. */ bool Compressor::GetCompressorShortedStickyFault() const { - int32_t status = 0; - bool value; + int32_t status = 0; + bool value; - value = getCompressorShortedStickyFault(m_pcm_pointer, &status); + value = getCompressorShortedStickyFault(m_pcm_pointer, &status); - if(status) { - wpi_setWPIError(Timeout); - } + if (status) { + wpi_setWPIError(Timeout); + } - return value; + return value; } /** * Query if the compressor output has been disabled due to a short circuit. - * @return true if PCM is in fault state : Compressor output - * appears to be shorted. + * @return true if PCM is in fault state : Compressor output + * appears to be shorted. */ bool Compressor::GetCompressorShortedFault() const { - int32_t status = 0; - bool value; + int32_t status = 0; + bool value; - value = getCompressorShortedFault(m_pcm_pointer, &status); + value = getCompressorShortedFault(m_pcm_pointer, &status); - if(status) { - wpi_setWPIError(Timeout); - } + if (status) { + wpi_setWPIError(Timeout); + } - return value; + return value; } /** * Query if the compressor output does not appear to be wired (sticky). - * A sticky fault will not clear on device reboot, it must be cleared through code or the webdash. - * @return true if PCM sticky fault is set : Compressor does not - * appear to be wired, i.e. compressor is + * A sticky fault will not clear on device reboot, it must be cleared through + * code or the webdash. + * @return true if PCM sticky fault is set : Compressor does not + * appear to be wired, i.e. compressor is * not drawing enough current. */ bool Compressor::GetCompressorNotConnectedStickyFault() const { - int32_t status = 0; - bool value; + int32_t status = 0; + bool value; - value = getCompressorNotConnectedStickyFault(m_pcm_pointer, &status); + value = getCompressorNotConnectedStickyFault(m_pcm_pointer, &status); - if(status) { - wpi_setWPIError(Timeout); - } + if (status) { + wpi_setWPIError(Timeout); + } - return value; + return value; } /** * Query if the compressor output does not appear to be wired. - * @return true if PCM is in fault state : Compressor does not - * appear to be wired, i.e. compressor is + * @return true if PCM is in fault state : Compressor does not + * appear to be wired, i.e. compressor is * not drawing enough current. */ bool Compressor::GetCompressorNotConnectedFault() const { - int32_t status = 0; - bool value; + int32_t status = 0; + bool value; - value = getCompressorNotConnectedFault(m_pcm_pointer, &status); + value = getCompressorNotConnectedFault(m_pcm_pointer, &status); - if(status) { - wpi_setWPIError(Timeout); - } + if (status) { + wpi_setWPIError(Timeout); + } - return value; + return value; } /** * Clear ALL sticky faults inside PCM that Compressor is wired to. * - * If a sticky fault is set, then it will be persistently cleared. Compressor drive - * maybe momentarily disable while flags are being cleared. Care should be - * taken to not call this too frequently, otherwise normal compressor - * functionality may be prevented. + * If a sticky fault is set, then it will be persistently cleared. Compressor + * drive + * maybe momentarily disable while flags are being cleared. Care + * should be + * taken to not call this too frequently, otherwise normal + * compressor + * functionality may be prevented. * * If no sticky faults are set then this call will have no effect. */ void Compressor::ClearAllPCMStickyFaults() { - int32_t status = 0; + int32_t status = 0; - clearAllPCMStickyFaults(m_pcm_pointer, &status); + clearAllPCMStickyFaults(m_pcm_pointer, &status); - if(status) { - wpi_setWPIError(Timeout); - } + if (status) { + wpi_setWPIError(Timeout); + } } void Compressor::UpdateTable() { - if(m_table) { - m_table->PutBoolean("Enabled", Enabled()); - m_table->PutBoolean("Pressure switch", GetPressureSwitchValue()); - } + if (m_table) { + m_table->PutBoolean("Enabled", Enabled()); + m_table->PutBoolean("Pressure switch", GetPressureSwitchValue()); + } } -void Compressor::StartLiveWindowMode() { +void Compressor::StartLiveWindowMode() {} + +void Compressor::StopLiveWindowMode() {} + +std::string Compressor::GetSmartDashboardType() const { return "Compressor"; } + +void Compressor::InitTable(ITable* subTable) { + m_table = subTable; + UpdateTable(); } -void Compressor::StopLiveWindowMode() { -} - -std::string Compressor::GetSmartDashboardType() const { - return "Compressor"; -} - -void Compressor::InitTable(ITable *subTable) { - m_table = subTable; - UpdateTable(); -} - -ITable *Compressor::GetTable() const { - return m_table; -} - -void Compressor::ValueChanged(ITable* source, const std::string& key, EntryValue value, bool isNew) { - if(value.b) Start(); - else Stop(); +ITable* Compressor::GetTable() const { return m_table; } +void Compressor::ValueChanged(ITable* source, const std::string& key, + EntryValue value, bool isNew) { + if (value.b) + Start(); + else + Stop(); } diff --git a/wpilibc/wpilibC++Devices/src/ControllerPower.cpp b/wpilibc/wpilibC++Devices/src/ControllerPower.cpp index 157929bcbe..ea508afabd 100644 --- a/wpilibc/wpilibC++Devices/src/ControllerPower.cpp +++ b/wpilibc/wpilibC++Devices/src/ControllerPower.cpp @@ -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. */ /*----------------------------------------------------------------------------*/ @@ -16,10 +17,10 @@ * @return The controller input voltage value in Volts */ double ControllerPower::GetInputVoltage() { - int32_t status = 0; - double retVal = getVinVoltage(&status); - wpi_setGlobalErrorWithContext(status, getHALErrorMessage(status)); - return retVal; + int32_t status = 0; + double retVal = getVinVoltage(&status); + wpi_setGlobalErrorWithContext(status, getHALErrorMessage(status)); + return retVal; } /** @@ -27,10 +28,10 @@ double ControllerPower::GetInputVoltage() { * @return The controller input current value in Amps */ double ControllerPower::GetInputCurrent() { - int32_t status = 0; - double retVal = getVinCurrent(&status); - wpi_setGlobalErrorWithContext(status, getHALErrorMessage(status)); - return retVal; + int32_t status = 0; + double retVal = getVinCurrent(&status); + wpi_setGlobalErrorWithContext(status, getHALErrorMessage(status)); + return retVal; } /** @@ -38,10 +39,10 @@ double ControllerPower::GetInputCurrent() { * @return The controller 6V rail voltage value in Volts */ double ControllerPower::GetVoltage6V() { - int32_t status = 0; - double retVal = getUserVoltage6V(&status); - wpi_setGlobalErrorWithContext(status, getHALErrorMessage(status)); - return retVal; + int32_t status = 0; + double retVal = getUserVoltage6V(&status); + wpi_setGlobalErrorWithContext(status, getHALErrorMessage(status)); + return retVal; } /** @@ -49,33 +50,35 @@ double ControllerPower::GetVoltage6V() { * @return The controller 6V rail output current value in Amps */ double ControllerPower::GetCurrent6V() { - int32_t status = 0; - double retVal = getUserCurrent6V(&status); - wpi_setGlobalErrorWithContext(status, getHALErrorMessage(status)); - return retVal; + int32_t status = 0; + double retVal = getUserCurrent6V(&status); + wpi_setGlobalErrorWithContext(status, getHALErrorMessage(status)); + return retVal; } /** - * Get the enabled state of the 6V rail. The rail may be disabled due to a controller + * Get the enabled state of the 6V rail. The rail may be disabled due to a + * controller * brownout, a short circuit on the rail, or controller over-voltage * @return The controller 6V rail enabled value. True for enabled. */ bool ControllerPower::GetEnabled6V() { - int32_t status = 0; - bool retVal = getUserActive6V(&status); - wpi_setGlobalErrorWithContext(status, getHALErrorMessage(status)); - return retVal; + int32_t status = 0; + bool retVal = getUserActive6V(&status); + wpi_setGlobalErrorWithContext(status, getHALErrorMessage(status)); + return retVal; } /** - * Get the count of the total current faults on the 6V rail since the controller has booted + * Get the count of the total current faults on the 6V rail since the controller + * has booted * @return The number of faults. */ int ControllerPower::GetFaultCount6V() { - int32_t status = 0; - int retVal = getUserCurrentFaults6V(&status); - wpi_setGlobalErrorWithContext(status, getHALErrorMessage(status)); - return retVal; + int32_t status = 0; + int retVal = getUserCurrentFaults6V(&status); + wpi_setGlobalErrorWithContext(status, getHALErrorMessage(status)); + return retVal; } /** @@ -83,10 +86,10 @@ int ControllerPower::GetFaultCount6V() { * @return The controller 5V rail voltage value in Volts */ double ControllerPower::GetVoltage5V() { - int32_t status = 0; - double retVal = getUserVoltage5V(&status); - wpi_setGlobalErrorWithContext(status, getHALErrorMessage(status)); - return retVal; + int32_t status = 0; + double retVal = getUserVoltage5V(&status); + wpi_setGlobalErrorWithContext(status, getHALErrorMessage(status)); + return retVal; } /** @@ -94,33 +97,35 @@ double ControllerPower::GetVoltage5V() { * @return The controller 5V rail output current value in Amps */ double ControllerPower::GetCurrent5V() { - int32_t status = 0; - double retVal = getUserCurrent5V(&status); - wpi_setGlobalErrorWithContext(status, getHALErrorMessage(status)); - return retVal; + int32_t status = 0; + double retVal = getUserCurrent5V(&status); + wpi_setGlobalErrorWithContext(status, getHALErrorMessage(status)); + return retVal; } /** - * Get the enabled state of the 5V rail. The rail may be disabled due to a controller + * Get the enabled state of the 5V rail. The rail may be disabled due to a + * controller * brownout, a short circuit on the rail, or controller over-voltage * @return The controller 5V rail enabled value. True for enabled. */ bool ControllerPower::GetEnabled5V() { - int32_t status = 0; - bool retVal = getUserActive5V(&status); - wpi_setGlobalErrorWithContext(status, getHALErrorMessage(status)); - return retVal; + int32_t status = 0; + bool retVal = getUserActive5V(&status); + wpi_setGlobalErrorWithContext(status, getHALErrorMessage(status)); + return retVal; } /** - * Get the count of the total current faults on the 5V rail since the controller has booted + * Get the count of the total current faults on the 5V rail since the controller + * has booted * @return The number of faults */ int ControllerPower::GetFaultCount5V() { - int32_t status = 0; - int retVal = getUserCurrentFaults5V(&status); - wpi_setGlobalErrorWithContext(status, getHALErrorMessage(status)); - return retVal; + int32_t status = 0; + int retVal = getUserCurrentFaults5V(&status); + wpi_setGlobalErrorWithContext(status, getHALErrorMessage(status)); + return retVal; } /** @@ -128,10 +133,10 @@ int ControllerPower::GetFaultCount5V() { * @return The controller 3.3V rail voltage value in Volts */ double ControllerPower::GetVoltage3V3() { - int32_t status = 0; - double retVal = getUserVoltage3V3(&status); - wpi_setGlobalErrorWithContext(status, getHALErrorMessage(status)); - return retVal; + int32_t status = 0; + double retVal = getUserVoltage3V3(&status); + wpi_setGlobalErrorWithContext(status, getHALErrorMessage(status)); + return retVal; } /** @@ -139,32 +144,33 @@ double ControllerPower::GetVoltage3V3() { * @return The controller 3.3V rail output current value in Amps */ double ControllerPower::GetCurrent3V3() { - int32_t status = 0; - double retVal = getUserCurrent3V3(&status); - wpi_setGlobalErrorWithContext(status, getHALErrorMessage(status)); - return retVal; + int32_t status = 0; + double retVal = getUserCurrent3V3(&status); + wpi_setGlobalErrorWithContext(status, getHALErrorMessage(status)); + return retVal; } - /** - * Get the enabled state of the 3.3V rail. The rail may be disabled due to a controller + * Get the enabled state of the 3.3V rail. The rail may be disabled due to a + * controller * brownout, a short circuit on the rail, or controller over-voltage * @return The controller 3.3V rail enabled value. True for enabled. */ bool ControllerPower::GetEnabled3V3() { - int32_t status = 0; - bool retVal = getUserActive3V3(&status); - wpi_setGlobalErrorWithContext(status, getHALErrorMessage(status)); - return retVal; + int32_t status = 0; + bool retVal = getUserActive3V3(&status); + wpi_setGlobalErrorWithContext(status, getHALErrorMessage(status)); + return retVal; } /** - * Get the count of the total current faults on the 3.3V rail since the controller has booted + * Get the count of the total current faults on the 3.3V rail since the + * controller has booted * @return The number of faults */ int ControllerPower::GetFaultCount3V3() { - int32_t status = 0; - int retVal = getUserCurrentFaults3V3(&status); - wpi_setGlobalErrorWithContext(status, getHALErrorMessage(status)); - return retVal; + int32_t status = 0; + int retVal = getUserCurrentFaults3V3(&status); + wpi_setGlobalErrorWithContext(status, getHALErrorMessage(status)); + return retVal; } \ No newline at end of file diff --git a/wpilibc/wpilibC++Devices/src/Counter.cpp b/wpilibc/wpilibC++Devices/src/Counter.cpp index c477473f6c..b36b2154f5 100644 --- a/wpilibc/wpilibC++Devices/src/Counter.cpp +++ b/wpilibc/wpilibC++Devices/src/Counter.cpp @@ -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,79 +14,78 @@ /** * Create an instance of a counter object. - * This creates a ChipObject counter and initializes status variables appropriately + * This creates a ChipObject counter and initializes status variables + * appropriately * * The counter will start counting immediately. * @param mode The counter mode */ -void Counter::InitCounter(Mode mode) -{ - m_table = NULL; +void Counter::InitCounter(Mode mode) { + m_table = NULL; - int32_t status = 0; - m_index = 0; - m_counter = initializeCounter(mode, &m_index, &status); - wpi_setErrorWithContext(status, getHALErrorMessage(status)); + int32_t status = 0; + m_index = 0; + m_counter = initializeCounter(mode, &m_index, &status); + wpi_setErrorWithContext(status, getHALErrorMessage(status)); - m_upSource = NULL; - m_downSource = NULL; - m_allocatedUpSource = false; - m_allocatedDownSource = false; + m_upSource = NULL; + m_downSource = NULL; + m_allocatedUpSource = false; + m_allocatedDownSource = false; - SetMaxPeriod(.5); + SetMaxPeriod(.5); - HALReport(HALUsageReporting::kResourceType_Counter, m_index, mode); + HALReport(HALUsageReporting::kResourceType_Counter, m_index, mode); } /** * Create an instance of a counter where no sources are selected. - * They all must be selected by calling functions to specify the upsource and the downsource + * They all must be selected by calling functions to specify the upsource and + * the downsource * independently. * * The counter will start counting immediately. */ -Counter::Counter() : - m_upSource(NULL), - m_downSource(NULL), - m_counter(NULL) -{ - InitCounter(); +Counter::Counter() : m_upSource(NULL), m_downSource(NULL), m_counter(NULL) { + InitCounter(); } /** - * Create an instance of a counter from a Digital Source (such as a Digital Input). - * This is used if an existing digital input is to be shared by multiple other objects such - * as encoders or if the Digital Source is not a Digital Input channel (such as an Analog Trigger). + * Create an instance of a counter from a Digital Source (such as a Digital + * Input). + * This is used if an existing digital input is to be shared by multiple other + * objects such + * as encoders or if the Digital Source is not a Digital Input channel (such as + * an Analog Trigger). * * The counter will start counting immediately. - * @param source A pointer to the existing DigitalSource object. It will be set as the Up Source. + * @param source A pointer to the existing DigitalSource object. It will be set + * as the Up Source. */ -Counter::Counter(DigitalSource *source) : - m_upSource(NULL), - m_downSource(NULL), - m_counter(NULL) -{ - InitCounter(); - SetUpSource(source); - ClearDownSource(); +Counter::Counter(DigitalSource *source) + : m_upSource(NULL), m_downSource(NULL), m_counter(NULL) { + InitCounter(); + SetUpSource(source); + ClearDownSource(); } /** - * Create an instance of a counter from a Digital Source (such as a Digital Input). - * This is used if an existing digital input is to be shared by multiple other objects such - * as encoders or if the Digital Source is not a Digital Input channel (such as an Analog Trigger). + * Create an instance of a counter from a Digital Source (such as a Digital + * Input). + * This is used if an existing digital input is to be shared by multiple other + * objects such + * as encoders or if the Digital Source is not a Digital Input channel (such as + * an Analog Trigger). * * The counter will start counting immediately. - * @param source A reference to the existing DigitalSource object. It will be set as the Up Source. + * @param source A reference to the existing DigitalSource object. It will be + * set as the Up Source. */ -Counter::Counter(DigitalSource &source) : - m_upSource(NULL), - m_downSource(NULL), - m_counter(NULL) -{ - InitCounter(); - SetUpSource(&source); - ClearDownSource(); +Counter::Counter(DigitalSource &source) + : m_upSource(NULL), m_downSource(NULL), m_counter(NULL) { + InitCounter(); + SetUpSource(&source); + ClearDownSource(); } /** @@ -93,16 +93,14 @@ Counter::Counter(DigitalSource &source) : * Create an up-Counter instance given a channel. * * The counter will start counting immediately. - * @param channel The DIO channel to use as the up source. 0-9 are on-board, 10-25 are on the MXP + * @param channel The DIO channel to use as the up source. 0-9 are on-board, + * 10-25 are on the MXP */ -Counter::Counter(int32_t channel) : - m_upSource(NULL), - m_downSource(NULL), - m_counter(NULL) -{ - InitCounter(); - SetUpSource(channel); - ClearDownSource(); +Counter::Counter(int32_t channel) + : m_upSource(NULL), m_downSource(NULL), m_counter(NULL) { + InitCounter(); + SetUpSource(channel); + ClearDownSource(); } /** @@ -113,15 +111,12 @@ Counter::Counter(int32_t channel) : * The counter will start counting immediately. * @param trigger The pointer to the existing AnalogTrigger object. */ -Counter::Counter(AnalogTrigger *trigger) : - m_upSource(NULL), - m_downSource(NULL), - m_counter(NULL) -{ - InitCounter(); - SetUpSource(trigger->CreateOutput(kState)); - ClearDownSource(); - m_allocatedUpSource = true; +Counter::Counter(AnalogTrigger *trigger) + : m_upSource(NULL), m_downSource(NULL), m_counter(NULL) { + InitCounter(); + SetUpSource(trigger->CreateOutput(kState)); + ClearDownSource(); + m_allocatedUpSource = true; } /** @@ -132,15 +127,12 @@ Counter::Counter(AnalogTrigger *trigger) : * The counter will start counting immediately. * @param trigger The reference to the existing AnalogTrigger object. */ -Counter::Counter(AnalogTrigger &trigger) : - m_upSource(NULL), - m_downSource(NULL), - m_counter(NULL) -{ - InitCounter(); - SetUpSource(trigger.CreateOutput(kState)); - ClearDownSource(); - m_allocatedUpSource = true; +Counter::Counter(AnalogTrigger &trigger) + : m_upSource(NULL), m_downSource(NULL), m_counter(NULL) { + InitCounter(); + SetUpSource(trigger.CreateOutput(kState)); + ClearDownSource(); + m_allocatedUpSource = true; } /** @@ -151,69 +143,62 @@ Counter::Counter(AnalogTrigger &trigger) : * @param downSource The pointer to the DigitalSource to set as the down source * @param inverted True to invert the output (reverse the direction) */ - -Counter::Counter(EncodingType encodingType, DigitalSource *upSource, DigitalSource *downSource, bool inverted) : - m_upSource(NULL), - m_downSource(NULL), - m_counter(NULL) -{ - if (encodingType != k1X && encodingType != k2X) - { - wpi_setWPIErrorWithContext(ParameterOutOfRange, "Counter only supports 1X and 2X quadrature decoding."); - return; - } - InitCounter(kExternalDirection); - SetUpSource(upSource); - SetDownSource(downSource); - int32_t status = 0; - if (encodingType == k1X) - { - SetUpSourceEdge(true, false); - setCounterAverageSize(m_counter, 1, &status); - } - else - { - SetUpSourceEdge(true, true); - setCounterAverageSize(m_counter, 2, &status); - } +Counter::Counter(EncodingType encodingType, DigitalSource *upSource, + DigitalSource *downSource, bool inverted) + : m_upSource(NULL), m_downSource(NULL), m_counter(NULL) { + if (encodingType != k1X && encodingType != k2X) { + wpi_setWPIErrorWithContext( + ParameterOutOfRange, + "Counter only supports 1X and 2X quadrature decoding."); + return; + } + InitCounter(kExternalDirection); + SetUpSource(upSource); + SetDownSource(downSource); + int32_t status = 0; - wpi_setErrorWithContext(status, getHALErrorMessage(status)); - SetDownSourceEdge(inverted, true); + if (encodingType == k1X) { + SetUpSourceEdge(true, false); + setCounterAverageSize(m_counter, 1, &status); + } else { + SetUpSourceEdge(true, true); + setCounterAverageSize(m_counter, 2, &status); + } + + wpi_setErrorWithContext(status, getHALErrorMessage(status)); + SetDownSourceEdge(inverted, true); } /** * Delete the Counter object. */ -Counter::~Counter() -{ - SetUpdateWhenEmpty(true); - if (m_allocatedUpSource) - { - delete m_upSource; - m_upSource = NULL; - } - if (m_allocatedDownSource) - { - delete m_downSource; - m_downSource = NULL; - } +Counter::~Counter() { + SetUpdateWhenEmpty(true); + if (m_allocatedUpSource) { + delete m_upSource; + m_upSource = NULL; + } + if (m_allocatedDownSource) { + delete m_downSource; + m_downSource = NULL; + } - int32_t status = 0; - freeCounter(m_counter, &status); - wpi_setErrorWithContext(status, getHALErrorMessage(status)); - m_counter = NULL; + int32_t status = 0; + freeCounter(m_counter, &status); + wpi_setErrorWithContext(status, getHALErrorMessage(status)); + m_counter = NULL; } /** * Set the upsource for the counter as a digital input channel. - * @param channel The DIO channel to use as the up source. 0-9 are on-board, 10-25 are on the MXP + * @param channel The DIO channel to use as the up source. 0-9 are on-board, + * 10-25 are on the MXP */ -void Counter::SetUpSource(int32_t channel) -{ - if (StatusIsFatal()) return; - SetUpSource(new DigitalInput(channel)); - m_allocatedUpSource = true; +void Counter::SetUpSource(int32_t channel) { + if (StatusIsFatal()) return; + SetUpSource(new DigitalInput(channel)); + m_allocatedUpSource = true; } /** @@ -221,11 +206,11 @@ void Counter::SetUpSource(int32_t channel) * @param analogTrigger The analog trigger object that is used for the Up Source * @param triggerType The analog trigger output that will trigger the counter. */ -void Counter::SetUpSource(AnalogTrigger *analogTrigger, AnalogTriggerType triggerType) -{ - if (StatusIsFatal()) return; - SetUpSource(analogTrigger->CreateOutput(triggerType)); - m_allocatedUpSource = true; +void Counter::SetUpSource(AnalogTrigger *analogTrigger, + AnalogTriggerType triggerType) { + if (StatusIsFatal()) return; + SetUpSource(analogTrigger->CreateOutput(triggerType)); + m_allocatedUpSource = true; } /** @@ -233,9 +218,9 @@ void Counter::SetUpSource(AnalogTrigger *analogTrigger, AnalogTriggerType trigge * @param analogTrigger The analog trigger object that is used for the Up Source * @param triggerType The analog trigger output that will trigger the counter. */ -void Counter::SetUpSource(AnalogTrigger &analogTrigger, AnalogTriggerType triggerType) -{ - SetUpSource(&analogTrigger, triggerType); +void Counter::SetUpSource(AnalogTrigger &analogTrigger, + AnalogTriggerType triggerType) { + SetUpSource(&analogTrigger, triggerType); } /** @@ -243,27 +228,22 @@ void Counter::SetUpSource(AnalogTrigger &analogTrigger, AnalogTriggerType trigge * Set the up counting DigitalSource. * @param source Pointer to the DigitalSource object to set as the up source */ -void Counter::SetUpSource(DigitalSource *source) -{ - if (StatusIsFatal()) return; - if (m_allocatedUpSource) - { - delete m_upSource; - m_upSource = NULL; - m_allocatedUpSource = false; - } - m_upSource = source; - if (m_upSource->StatusIsFatal()) - { - CloneError(m_upSource); - } - else - { - int32_t status = 0; - setCounterUpSource(m_counter, source->GetChannelForRouting(), - source->GetAnalogTriggerForRouting(), &status); - wpi_setErrorWithContext(status, getHALErrorMessage(status)); - } +void Counter::SetUpSource(DigitalSource *source) { + if (StatusIsFatal()) return; + if (m_allocatedUpSource) { + delete m_upSource; + m_upSource = NULL; + m_allocatedUpSource = false; + } + m_upSource = source; + if (m_upSource->StatusIsFatal()) { + CloneError(m_upSource); + } else { + int32_t status = 0; + setCounterUpSource(m_counter, source->GetChannelForRouting(), + source->GetAnalogTriggerForRouting(), &status); + wpi_setErrorWithContext(status, getHALErrorMessage(status)); + } } /** @@ -271,10 +251,7 @@ void Counter::SetUpSource(DigitalSource *source) * Set the up counting DigitalSource. * @param source Reference to the DigitalSource object to set as the up source */ -void Counter::SetUpSource(DigitalSource &source) -{ - SetUpSource(&source); -} +void Counter::SetUpSource(DigitalSource &source) { SetUpSource(&source); } /** * Set the edge sensitivity on an up counting source. @@ -282,66 +259,66 @@ void Counter::SetUpSource(DigitalSource &source) * @param risingEdge True to trigger on rising edges * @param fallingEdge True to trigger on falling edges */ -void Counter::SetUpSourceEdge(bool risingEdge, bool fallingEdge) -{ - if (StatusIsFatal()) return; - if (m_upSource == NULL) - { - wpi_setWPIErrorWithContext(NullParameter, "Must set non-NULL UpSource before setting UpSourceEdge"); - } - int32_t status = 0; - setCounterUpSourceEdge(m_counter, risingEdge, fallingEdge, &status); - wpi_setErrorWithContext(status, getHALErrorMessage(status)); +void Counter::SetUpSourceEdge(bool risingEdge, bool fallingEdge) { + if (StatusIsFatal()) return; + if (m_upSource == NULL) { + wpi_setWPIErrorWithContext( + NullParameter, + "Must set non-NULL UpSource before setting UpSourceEdge"); + } + int32_t status = 0; + setCounterUpSourceEdge(m_counter, risingEdge, fallingEdge, &status); + wpi_setErrorWithContext(status, getHALErrorMessage(status)); } /** * Disable the up counting source to the counter. */ -void Counter::ClearUpSource() -{ - if (StatusIsFatal()) return; - if (m_allocatedUpSource) - { - delete m_upSource; - m_upSource = NULL; - m_allocatedUpSource = false; - } - int32_t status = 0; - clearCounterUpSource(m_counter, &status); - wpi_setErrorWithContext(status, getHALErrorMessage(status)); +void Counter::ClearUpSource() { + if (StatusIsFatal()) return; + if (m_allocatedUpSource) { + delete m_upSource; + m_upSource = NULL; + m_allocatedUpSource = false; + } + int32_t status = 0; + clearCounterUpSource(m_counter, &status); + wpi_setErrorWithContext(status, getHALErrorMessage(status)); } /** * Set the down counting source to be a digital input channel. - * @param channel The DIO channel to use as the up source. 0-9 are on-board, 10-25 are on the MXP + * @param channel The DIO channel to use as the up source. 0-9 are on-board, + * 10-25 are on the MXP */ -void Counter::SetDownSource(int32_t channel) -{ - if (StatusIsFatal()) return; - SetDownSource(new DigitalInput(channel)); - m_allocatedDownSource = true; +void Counter::SetDownSource(int32_t channel) { + if (StatusIsFatal()) return; + SetDownSource(new DigitalInput(channel)); + m_allocatedDownSource = true; } /** * Set the down counting source to be an analog trigger. - * @param analogTrigger The analog trigger object that is used for the Down Source + * @param analogTrigger The analog trigger object that is used for the Down + * Source * @param triggerType The analog trigger output that will trigger the counter. */ -void Counter::SetDownSource(AnalogTrigger *analogTrigger, AnalogTriggerType triggerType) -{ - if (StatusIsFatal()) return; - SetDownSource(analogTrigger->CreateOutput(triggerType)); - m_allocatedDownSource = true; +void Counter::SetDownSource(AnalogTrigger *analogTrigger, + AnalogTriggerType triggerType) { + if (StatusIsFatal()) return; + SetDownSource(analogTrigger->CreateOutput(triggerType)); + m_allocatedDownSource = true; } /** * Set the down counting source to be an analog trigger. - * @param analogTrigger The analog trigger object that is used for the Down Source + * @param analogTrigger The analog trigger object that is used for the Down + * Source * @param triggerType The analog trigger output that will trigger the counter. */ -void Counter::SetDownSource(AnalogTrigger &analogTrigger, AnalogTriggerType triggerType) -{ - SetDownSource(&analogTrigger, triggerType); +void Counter::SetDownSource(AnalogTrigger &analogTrigger, + AnalogTriggerType triggerType) { + SetDownSource(&analogTrigger, triggerType); } /** @@ -349,27 +326,22 @@ void Counter::SetDownSource(AnalogTrigger &analogTrigger, AnalogTriggerType trig * Set the down counting DigitalSource. * @param source Pointer to the DigitalSource object to set as the down source */ -void Counter::SetDownSource(DigitalSource *source) -{ - if (StatusIsFatal()) return; - if (m_allocatedDownSource) - { - delete m_downSource; - m_downSource = NULL; - m_allocatedDownSource = false; - } - m_downSource = source; - if (m_downSource->StatusIsFatal()) - { - CloneError(m_downSource); - } - else - { - int32_t status = 0; - setCounterDownSource(m_counter, source->GetChannelForRouting(), - source->GetAnalogTriggerForRouting(), &status); - wpi_setErrorWithContext(status, getHALErrorMessage(status)); - } +void Counter::SetDownSource(DigitalSource *source) { + if (StatusIsFatal()) return; + if (m_allocatedDownSource) { + delete m_downSource; + m_downSource = NULL; + m_allocatedDownSource = false; + } + m_downSource = source; + if (m_downSource->StatusIsFatal()) { + CloneError(m_downSource); + } else { + int32_t status = 0; + setCounterDownSource(m_counter, source->GetChannelForRouting(), + source->GetAnalogTriggerForRouting(), &status); + wpi_setErrorWithContext(status, getHALErrorMessage(status)); + } } /** @@ -377,10 +349,7 @@ void Counter::SetDownSource(DigitalSource *source) * Set the down counting DigitalSource. * @param source Reference to the DigitalSource object to set as the down source */ -void Counter::SetDownSource(DigitalSource &source) -{ - SetDownSource(&source); -} +void Counter::SetDownSource(DigitalSource &source) { SetDownSource(&source); } /** * Set the edge sensitivity on a down counting source. @@ -388,45 +357,42 @@ void Counter::SetDownSource(DigitalSource &source) * @param risingEdge True to trigger on rising edges * @param fallingEdge True to trigger on falling edges */ -void Counter::SetDownSourceEdge(bool risingEdge, bool fallingEdge) -{ - if (StatusIsFatal()) return; - if (m_downSource == NULL) - { - wpi_setWPIErrorWithContext(NullParameter, "Must set non-NULL DownSource before setting DownSourceEdge"); - } - int32_t status = 0; - setCounterDownSourceEdge(m_counter, risingEdge, fallingEdge, &status); - wpi_setErrorWithContext(status, getHALErrorMessage(status)); +void Counter::SetDownSourceEdge(bool risingEdge, bool fallingEdge) { + if (StatusIsFatal()) return; + if (m_downSource == NULL) { + wpi_setWPIErrorWithContext( + NullParameter, + "Must set non-NULL DownSource before setting DownSourceEdge"); + } + int32_t status = 0; + setCounterDownSourceEdge(m_counter, risingEdge, fallingEdge, &status); + wpi_setErrorWithContext(status, getHALErrorMessage(status)); } /** * Disable the down counting source to the counter. */ -void Counter::ClearDownSource() -{ - if (StatusIsFatal()) return; - if (m_allocatedDownSource) - { - delete m_downSource; - m_downSource = NULL; - m_allocatedDownSource = false; - } - int32_t status = 0; - clearCounterDownSource(m_counter, &status); - wpi_setErrorWithContext(status, getHALErrorMessage(status)); +void Counter::ClearDownSource() { + if (StatusIsFatal()) return; + if (m_allocatedDownSource) { + delete m_downSource; + m_downSource = NULL; + m_allocatedDownSource = false; + } + int32_t status = 0; + clearCounterDownSource(m_counter, &status); + wpi_setErrorWithContext(status, getHALErrorMessage(status)); } /** * Set standard up / down counting mode on this counter. * Up and down counts are sourced independently from two inputs. */ -void Counter::SetUpDownCounterMode() -{ - if (StatusIsFatal()) return; - int32_t status = 0; - setCounterUpDownMode(m_counter, &status); - wpi_setErrorWithContext(status, getHALErrorMessage(status)); +void Counter::SetUpDownCounterMode() { + if (StatusIsFatal()) return; + int32_t status = 0; + setCounterUpDownMode(m_counter, &status); + wpi_setErrorWithContext(status, getHALErrorMessage(status)); } /** @@ -434,216 +400,217 @@ void Counter::SetUpDownCounterMode() * Counts are sourced on the Up counter input. * The Down counter input represents the direction to count. */ -void Counter::SetExternalDirectionMode() -{ - if (StatusIsFatal()) return; - int32_t status = 0; - setCounterExternalDirectionMode(m_counter, &status); - wpi_setErrorWithContext(status, getHALErrorMessage(status)); +void Counter::SetExternalDirectionMode() { + if (StatusIsFatal()) return; + int32_t status = 0; + setCounterExternalDirectionMode(m_counter, &status); + wpi_setErrorWithContext(status, getHALErrorMessage(status)); } /** * Set Semi-period mode on this counter. * Counts up on both rising and falling edges. */ -void Counter::SetSemiPeriodMode(bool highSemiPeriod) -{ - if (StatusIsFatal()) return; - int32_t status = 0; - setCounterSemiPeriodMode(m_counter, highSemiPeriod, &status); - wpi_setErrorWithContext(status, getHALErrorMessage(status)); +void Counter::SetSemiPeriodMode(bool highSemiPeriod) { + if (StatusIsFatal()) return; + int32_t status = 0; + setCounterSemiPeriodMode(m_counter, highSemiPeriod, &status); + wpi_setErrorWithContext(status, getHALErrorMessage(status)); } /** - * Configure the counter to count in up or down based on the length of the input pulse. + * Configure the counter to count in up or down based on the length of the input + * pulse. * This mode is most useful for direction sensitive gear tooth sensors. - * @param threshold The pulse length beyond which the counter counts the opposite direction. Units are seconds. + * @param threshold The pulse length beyond which the counter counts the + * opposite direction. Units are seconds. */ -void Counter::SetPulseLengthMode(float threshold) -{ - if (StatusIsFatal()) return; - int32_t status = 0; - setCounterPulseLengthMode(m_counter, threshold, &status); - wpi_setErrorWithContext(status, getHALErrorMessage(status)); +void Counter::SetPulseLengthMode(float threshold) { + if (StatusIsFatal()) return; + int32_t status = 0; + setCounterPulseLengthMode(m_counter, threshold, &status); + wpi_setErrorWithContext(status, getHALErrorMessage(status)); } - /** - * Get the Samples to Average which specifies the number of samples of the timer to + * Get the Samples to Average which specifies the number of samples of the timer + * to * average when calculating the period. Perform averaging to account for * mechanical imperfections or as oversampling to increase resolution. * @return SamplesToAverage The number of samples being averaged (from 1 to 127) */ -int Counter::GetSamplesToAverage() const -{ - int32_t status = 0; - int32_t samples = getCounterSamplesToAverage(m_counter, &status); - wpi_setErrorWithContext(status, getHALErrorMessage(status)); - return samples; +int Counter::GetSamplesToAverage() const { + int32_t status = 0; + int32_t samples = getCounterSamplesToAverage(m_counter, &status); + wpi_setErrorWithContext(status, getHALErrorMessage(status)); + return samples; } /** - * Set the Samples to Average which specifies the number of samples of the timer to + * Set the Samples to Average which specifies the number of samples of the timer + * to * average when calculating the period. Perform averaging to account for * mechanical imperfections or as oversampling to increase resolution. * @param samplesToAverage The number of samples to average from 1 to 127. */ -void Counter::SetSamplesToAverage (int samplesToAverage) { - if (samplesToAverage < 1 || samplesToAverage > 127) - { - wpi_setWPIErrorWithContext(ParameterOutOfRange, "Average counter values must be between 1 and 127"); - } - int32_t status = 0; - setCounterSamplesToAverage(m_counter, samplesToAverage, &status); - wpi_setErrorWithContext(status, getHALErrorMessage(status)); +void Counter::SetSamplesToAverage(int samplesToAverage) { + if (samplesToAverage < 1 || samplesToAverage > 127) { + wpi_setWPIErrorWithContext( + ParameterOutOfRange, + "Average counter values must be between 1 and 127"); + } + int32_t status = 0; + setCounterSamplesToAverage(m_counter, samplesToAverage, &status); + wpi_setErrorWithContext(status, getHALErrorMessage(status)); } /** * Read the current counter value. - * Read the value at this instant. It may still be running, so it reflects the current value. Next + * Read the value at this instant. It may still be running, so it reflects the + * current value. Next * time it is read, it might have a different value. */ -int32_t Counter::Get() const -{ - if (StatusIsFatal()) return 0; - int32_t status = 0; - int32_t value = getCounter(m_counter, &status); - wpi_setErrorWithContext(status, getHALErrorMessage(status)); - return value; +int32_t Counter::Get() const { + if (StatusIsFatal()) return 0; + int32_t status = 0; + int32_t value = getCounter(m_counter, &status); + wpi_setErrorWithContext(status, getHALErrorMessage(status)); + return value; } /** * Reset the Counter to zero. - * Set the counter value to zero. This doesn't effect the running state of the counter, just sets + * Set the counter value to zero. This doesn't effect the running state of the + * counter, just sets * the current value to zero. */ -void Counter::Reset() -{ - if (StatusIsFatal()) return; - int32_t status = 0; - resetCounter(m_counter, &status); - wpi_setErrorWithContext(status, getHALErrorMessage(status)); +void Counter::Reset() { + if (StatusIsFatal()) return; + int32_t status = 0; + resetCounter(m_counter, &status); + wpi_setErrorWithContext(status, getHALErrorMessage(status)); } /** * Get the Period of the most recent count. - * Returns the time interval of the most recent count. This can be used for velocity calculations + * Returns the time interval of the most recent count. This can be used for + * velocity calculations * to determine shaft speed. * @returns The period between the last two pulses in units of seconds. */ -double Counter::GetPeriod() const -{ - if (StatusIsFatal()) return 0.0; - int32_t status = 0; - double value = getCounterPeriod(m_counter, &status); - wpi_setErrorWithContext(status, getHALErrorMessage(status)); - return value; +double Counter::GetPeriod() const { + if (StatusIsFatal()) return 0.0; + int32_t status = 0; + double value = getCounterPeriod(m_counter, &status); + wpi_setErrorWithContext(status, getHALErrorMessage(status)); + return value; } /** * Set the maximum period where the device is still considered "moving". - * Sets the maximum period where the device is considered moving. This value is used to determine + * Sets the maximum period where the device is considered moving. This value is + * used to determine * the "stopped" state of the counter using the GetStopped method. - * @param maxPeriod The maximum period where the counted device is considered moving in + * @param maxPeriod The maximum period where the counted device is considered + * moving in * seconds. */ -void Counter::SetMaxPeriod(double maxPeriod) -{ - if (StatusIsFatal()) return; - int32_t status = 0; - setCounterMaxPeriod(m_counter, maxPeriod, &status); - wpi_setErrorWithContext(status, getHALErrorMessage(status)); +void Counter::SetMaxPeriod(double maxPeriod) { + if (StatusIsFatal()) return; + int32_t status = 0; + setCounterMaxPeriod(m_counter, maxPeriod, &status); + wpi_setErrorWithContext(status, getHALErrorMessage(status)); } /** - * Select whether you want to continue updating the event timer output when there are no samples captured. - * The output of the event timer has a buffer of periods that are averaged and posted to - * a register on the FPGA. When the timer detects that the event source has stopped - * (based on the MaxPeriod) the buffer of samples to be averaged is emptied. If you - * enable the update when empty, you will be notified of the stopped source and the event - * time will report 0 samples. If you disable update when empty, the most recent average - * will remain on the output until a new sample is acquired. You will never see 0 samples - * output (except when there have been no events since an FPGA reset) and you will likely not - * see the stopped bit become true (since it is updated at the end of an average and there are + * Select whether you want to continue updating the event timer output when + * there are no samples captured. + * The output of the event timer has a buffer of periods that are averaged and + * posted to + * a register on the FPGA. When the timer detects that the event source has + * stopped + * (based on the MaxPeriod) the buffer of samples to be averaged is emptied. If + * you + * enable the update when empty, you will be notified of the stopped source and + * the event + * time will report 0 samples. If you disable update when empty, the most + * recent average + * will remain on the output until a new sample is acquired. You will never see + * 0 samples + * output (except when there have been no events since an FPGA reset) and you + * will likely not + * see the stopped bit become true (since it is updated at the end of an average + * and there are * no samples to average). * @param enabled True to enable update when empty */ -void Counter::SetUpdateWhenEmpty(bool enabled) -{ - if (StatusIsFatal()) return; - int32_t status = 0; - setCounterUpdateWhenEmpty(m_counter, enabled, &status); - wpi_setErrorWithContext(status, getHALErrorMessage(status)); +void Counter::SetUpdateWhenEmpty(bool enabled) { + if (StatusIsFatal()) return; + int32_t status = 0; + setCounterUpdateWhenEmpty(m_counter, enabled, &status); + wpi_setErrorWithContext(status, getHALErrorMessage(status)); } /** * Determine if the clock is stopped. - * Determine if the clocked input is stopped based on the MaxPeriod value set using the - * SetMaxPeriod method. If the clock exceeds the MaxPeriod, then the device (and counter) are + * Determine if the clocked input is stopped based on the MaxPeriod value set + * using the + * SetMaxPeriod method. If the clock exceeds the MaxPeriod, then the device (and + * counter) are * assumed to be stopped and it returns true. - * @return Returns true if the most recent counter period exceeds the MaxPeriod value set by + * @return Returns true if the most recent counter period exceeds the MaxPeriod + * value set by * SetMaxPeriod. */ -bool Counter::GetStopped() const -{ - if (StatusIsFatal()) return false; - int32_t status = 0; - bool value = getCounterStopped(m_counter, &status); - wpi_setErrorWithContext(status, getHALErrorMessage(status)); - return value; +bool Counter::GetStopped() const { + if (StatusIsFatal()) return false; + int32_t status = 0; + bool value = getCounterStopped(m_counter, &status); + wpi_setErrorWithContext(status, getHALErrorMessage(status)); + return value; } /** * The last direction the counter value changed. * @return The last direction the counter value changed. */ -bool Counter::GetDirection() const -{ - if (StatusIsFatal()) return false; - int32_t status = 0; - bool value = getCounterDirection(m_counter, &status); - wpi_setErrorWithContext(status, getHALErrorMessage(status)); - return value; +bool Counter::GetDirection() const { + if (StatusIsFatal()) return false; + int32_t status = 0; + bool value = getCounterDirection(m_counter, &status); + wpi_setErrorWithContext(status, getHALErrorMessage(status)); + return value; } /** * Set the Counter to return reversed sensing on the direction. - * This allows counters to change the direction they are counting in the case of 1X and 2X + * This allows counters to change the direction they are counting in the case of + * 1X and 2X * quadrature encoding only. Any other counter mode isn't supported. * @param reverseDirection true if the value counted should be negated. */ -void Counter::SetReverseDirection(bool reverseDirection) -{ - if (StatusIsFatal()) return; - int32_t status = 0; - setCounterReverseDirection(m_counter, reverseDirection, &status); - wpi_setErrorWithContext(status, getHALErrorMessage(status)); +void Counter::SetReverseDirection(bool reverseDirection) { + if (StatusIsFatal()) return; + int32_t status = 0; + setCounterReverseDirection(m_counter, reverseDirection, &status); + wpi_setErrorWithContext(status, getHALErrorMessage(status)); } - void Counter::UpdateTable() { - if (m_table != NULL) { - m_table->PutNumber("Value", Get()); - } + if (m_table != NULL) { + m_table->PutNumber("Value", Get()); + } } -void Counter::StartLiveWindowMode() { +void Counter::StartLiveWindowMode() {} -} +void Counter::StopLiveWindowMode() {} -void Counter::StopLiveWindowMode() { - -} - -std::string Counter::GetSmartDashboardType() const { - return "Counter"; -} +std::string Counter::GetSmartDashboardType() const { return "Counter"; } void Counter::InitTable(ITable *subTable) { - m_table = subTable; - UpdateTable(); + m_table = subTable; + UpdateTable(); } -ITable * Counter::GetTable() const { - return m_table; -} +ITable *Counter::GetTable() const { return m_table; } diff --git a/wpilibc/wpilibC++Devices/src/DigitalInput.cpp b/wpilibc/wpilibC++Devices/src/DigitalInput.cpp index c60e3efbe2..afa39cac80 100644 --- a/wpilibc/wpilibC++Devices/src/DigitalInput.cpp +++ b/wpilibc/wpilibC++Devices/src/DigitalInput.cpp @@ -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,25 +16,23 @@ * Creates a digital input given a channel. Common creation routine for all * constructors. */ -void DigitalInput::InitDigitalInput(uint32_t channel) -{ - m_table = NULL; - char buf[64]; +void DigitalInput::InitDigitalInput(uint32_t channel) { + m_table = NULL; + char buf[64]; - if (!CheckDigitalChannel(channel)) - { - snprintf(buf, 64, "Digital Channel %d", channel); - wpi_setWPIErrorWithContext(ChannelIndexOutOfRange, buf); - return; - } - m_channel = channel; + if (!CheckDigitalChannel(channel)) { + snprintf(buf, 64, "Digital Channel %d", channel); + wpi_setWPIErrorWithContext(ChannelIndexOutOfRange, buf); + return; + } + m_channel = channel; - int32_t status = 0; - allocateDIO(m_digital_ports[channel], true, &status); - wpi_setErrorWithContext(status, getHALErrorMessage(status)); + int32_t status = 0; + allocateDIO(m_digital_ports[channel], true, &status); + wpi_setErrorWithContext(status, getHALErrorMessage(status)); - LiveWindow::GetInstance()->AddSensor("DigitalInput", channel, this); - HALReport(HALUsageReporting::kResourceType_DigitalInput, channel); + LiveWindow::GetInstance()->AddSensor("DigitalInput", channel, this); + HALReport(HALUsageReporting::kResourceType_DigitalInput, channel); } /** @@ -42,98 +41,74 @@ void DigitalInput::InitDigitalInput(uint32_t channel) * * @param channel The DIO channel 0-9 are on-board, 10-25 are on the MXP port */ -DigitalInput::DigitalInput(uint32_t channel) -{ - InitDigitalInput(channel); -} +DigitalInput::DigitalInput(uint32_t channel) { InitDigitalInput(channel); } /** * Free resources associated with the Digital Input class. */ -DigitalInput::~DigitalInput() -{ - if (StatusIsFatal()) return; - if (m_interrupt != NULL) - { - int32_t status = 0; - cleanInterrupts(m_interrupt, &status); - wpi_setErrorWithContext(status, getHALErrorMessage(status)); - m_interrupt = NULL; - m_interrupts->Free(m_interruptIndex); - } +DigitalInput::~DigitalInput() { + if (StatusIsFatal()) return; + if (m_interrupt != NULL) { + int32_t status = 0; + cleanInterrupts(m_interrupt, &status); + wpi_setErrorWithContext(status, getHALErrorMessage(status)); + m_interrupt = NULL; + m_interrupts->Free(m_interruptIndex); + } - int32_t status = 0; - freeDIO(m_digital_ports[m_channel], &status); - wpi_setErrorWithContext(status, getHALErrorMessage(status)); + int32_t status = 0; + freeDIO(m_digital_ports[m_channel], &status); + wpi_setErrorWithContext(status, getHALErrorMessage(status)); } /** * Get the value from a digital input channel. * Retrieve the value of a single digital input channel from the FPGA. */ -bool DigitalInput::Get() const -{ - int32_t status = 0; - bool value = getDIO(m_digital_ports[m_channel], &status); - wpi_setErrorWithContext(status, getHALErrorMessage(status)); - return value; +bool DigitalInput::Get() const { + int32_t status = 0; + bool value = getDIO(m_digital_ports[m_channel], &status); + wpi_setErrorWithContext(status, getHALErrorMessage(status)); + return value; } /** * @return The GPIO channel number that this object represents. */ -uint32_t DigitalInput::GetChannel() const -{ - return m_channel; -} +uint32_t DigitalInput::GetChannel() const { return m_channel; } /** * @return The value to be written to the channel field of a routing mux. */ -uint32_t DigitalInput::GetChannelForRouting() const -{ - return GetChannel(); -} +uint32_t DigitalInput::GetChannelForRouting() const { return GetChannel(); } /** * @return The value to be written to the module field of a routing mux. */ -uint32_t DigitalInput::GetModuleForRouting() const -{ - return 0; -} +uint32_t DigitalInput::GetModuleForRouting() const { return 0; } /** * @return The value to be written to the analog trigger field of a routing mux. */ -bool DigitalInput::GetAnalogTriggerForRouting() const -{ - return false; -} +bool DigitalInput::GetAnalogTriggerForRouting() const { return false; } void DigitalInput::UpdateTable() { - if (m_table != NULL) { - m_table->PutBoolean("Value", Get()); - } + if (m_table != NULL) { + m_table->PutBoolean("Value", Get()); + } } -void DigitalInput::StartLiveWindowMode() { +void DigitalInput::StartLiveWindowMode() {} -} - -void DigitalInput::StopLiveWindowMode() { - -} +void DigitalInput::StopLiveWindowMode() {} std::string DigitalInput::GetSmartDashboardType() const { - return "DigitalInput"; + return "DigitalInput"; } void DigitalInput::InitTable(ITable *subTable) { - m_table = subTable; - UpdateTable(); + m_table = subTable; + UpdateTable(); } -ITable * DigitalInput::GetTable() const { - return m_table; -} +ITable *DigitalInput::GetTable() const { return m_table; } diff --git a/wpilibc/wpilibC++Devices/src/DigitalOutput.cpp b/wpilibc/wpilibC++Devices/src/DigitalOutput.cpp index cb7481bcf2..1e597442e6 100644 --- a/wpilibc/wpilibC++Devices/src/DigitalOutput.cpp +++ b/wpilibc/wpilibC++Devices/src/DigitalOutput.cpp @@ -14,50 +14,45 @@ * Creates a digital output given a channel. Common creation routine for all * constructors. */ -void DigitalOutput::InitDigitalOutput(uint32_t channel) -{ - m_table = NULL; - char buf[64]; +void DigitalOutput::InitDigitalOutput(uint32_t channel) { + m_table = NULL; + char buf[64]; - if (!CheckDigitalChannel(channel)) - { - snprintf(buf, 64, "Digital Channel %d", channel); - wpi_setWPIErrorWithContext(ChannelIndexOutOfRange, buf); - return; - } - m_channel = channel; - m_pwmGenerator = (void *)~0ul; + if (!CheckDigitalChannel(channel)) { + snprintf(buf, 64, "Digital Channel %d", channel); + wpi_setWPIErrorWithContext(ChannelIndexOutOfRange, buf); + return; + } + m_channel = channel; + m_pwmGenerator = (void *)~0ul; - int32_t status = 0; - allocateDIO(m_digital_ports[channel], false, &status); - wpi_setErrorWithContext(status, getHALErrorMessage(status)); + int32_t status = 0; + allocateDIO(m_digital_ports[channel], false, &status); + wpi_setErrorWithContext(status, getHALErrorMessage(status)); - HALReport(HALUsageReporting::kResourceType_DigitalOutput, channel); + HALReport(HALUsageReporting::kResourceType_DigitalOutput, channel); } /** * Create an instance of a digital output. * Create a digital output given a channel. * - * @param channel The digital channel 0-9 are on-board, 10-25 are on the MXP port + * @param channel The digital channel 0-9 are on-board, 10-25 are on the MXP + * port */ -DigitalOutput::DigitalOutput(uint32_t channel) -{ - InitDigitalOutput(channel); -} +DigitalOutput::DigitalOutput(uint32_t channel) { InitDigitalOutput(channel); } /** * Free the resources associated with a digital output. */ -DigitalOutput::~DigitalOutput() -{ - if (StatusIsFatal()) return; - // Disable the PWM in case it was running. - DisablePWM(); +DigitalOutput::~DigitalOutput() { + if (StatusIsFatal()) return; + // Disable the PWM in case it was running. + DisablePWM(); - int32_t status = 0; - freeDIO(m_digital_ports[m_channel], &status); - wpi_setErrorWithContext(status, getHALErrorMessage(status)); + int32_t status = 0; + freeDIO(m_digital_ports[m_channel], &status); + wpi_setErrorWithContext(status, getHALErrorMessage(status)); } /** @@ -65,68 +60,63 @@ DigitalOutput::~DigitalOutput() * Set the value of a digital output to either one (true) or zero (false). * @param value 1 (true) for high, 0 (false) for disabled */ -void DigitalOutput::Set(uint32_t value) -{ - if (StatusIsFatal()) return; +void DigitalOutput::Set(uint32_t value) { + if (StatusIsFatal()) return; - int32_t status = 0; - setDIO(m_digital_ports[m_channel], value, &status); - wpi_setErrorWithContext(status, getHALErrorMessage(status)); + int32_t status = 0; + setDIO(m_digital_ports[m_channel], value, &status); + wpi_setErrorWithContext(status, getHALErrorMessage(status)); } /** * @return The GPIO channel number that this object represents. */ -uint32_t DigitalOutput::GetChannel() const -{ - return m_channel; -} +uint32_t DigitalOutput::GetChannel() const { return m_channel; } /** * Output a single pulse on the digital output line. - * Send a single pulse on the digital output line where the pulse duration is specified in seconds. + * Send a single pulse on the digital output line where the pulse duration is + * specified in seconds. * Maximum pulse length is 0.0016 seconds. * @param length The pulselength in seconds */ -void DigitalOutput::Pulse(float length) -{ - if (StatusIsFatal()) return; +void DigitalOutput::Pulse(float length) { + if (StatusIsFatal()) return; - int32_t status = 0; - pulse(m_digital_ports[m_channel], length, &status); - wpi_setErrorWithContext(status, getHALErrorMessage(status)); + int32_t status = 0; + pulse(m_digital_ports[m_channel], length, &status); + wpi_setErrorWithContext(status, getHALErrorMessage(status)); } /** * Determine if the pulse is still going. * Determine if a previously started pulse is still going. */ -bool DigitalOutput::IsPulsing() const -{ - if (StatusIsFatal()) return false; +bool DigitalOutput::IsPulsing() const { + if (StatusIsFatal()) return false; - int32_t status = 0; - bool value = isPulsing(m_digital_ports[m_channel], &status); - wpi_setErrorWithContext(status, getHALErrorMessage(status)); - return value; + int32_t status = 0; + bool value = isPulsing(m_digital_ports[m_channel], &status); + wpi_setErrorWithContext(status, getHALErrorMessage(status)); + return value; } /** * Change the PWM frequency of the PWM output on a Digital Output line. * - * The valid range is from 0.6 Hz to 19 kHz. The frequency resolution is logarithmic. + * The valid range is from 0.6 Hz to 19 kHz. The frequency resolution is + * logarithmic. * * There is only one PWM frequency for all digital channels. * * @param rate The frequency to output all digital output PWM signals. */ -void DigitalOutput::SetPWMRate(float rate) -{ - if (StatusIsFatal()) return; +void DigitalOutput::SetPWMRate(float rate) { + if (StatusIsFatal()) return; - int32_t status = 0; - setPWMRate(rate, &status); - wpi_setErrorWithContext(status, getHALErrorMessage(status)); + int32_t status = 0; + setPWMRate(rate, &status); + wpi_setErrorWithContext(status, getHALErrorMessage(status)); } /** @@ -134,30 +124,30 @@ void DigitalOutput::SetPWMRate(float rate) * * Allocate one of the 6 DO PWM generator resources from this module. * - * Supply the initial duty-cycle to output so as to avoid a glitch when first starting. + * Supply the initial duty-cycle to output so as to avoid a glitch when first + * starting. * * The resolution of the duty cycle is 8-bit for low frequencies (1kHz or less) * but is reduced the higher the frequency of the PWM signal is. * * @param initialDutyCycle The duty-cycle to start generating. [0..1] */ -void DigitalOutput::EnablePWM(float initialDutyCycle) -{ - if(m_pwmGenerator != (void *)~0ul) return; +void DigitalOutput::EnablePWM(float initialDutyCycle) { + if (m_pwmGenerator != (void *)~0ul) return; - int32_t status = 0; + int32_t status = 0; - if(StatusIsFatal()) return; - m_pwmGenerator = allocatePWM(&status); - wpi_setErrorWithContext(status, getHALErrorMessage(status)); + if (StatusIsFatal()) return; + m_pwmGenerator = allocatePWM(&status); + wpi_setErrorWithContext(status, getHALErrorMessage(status)); - if(StatusIsFatal()) return; - setPWMDutyCycle(m_pwmGenerator, initialDutyCycle, &status); - wpi_setErrorWithContext(status, getHALErrorMessage(status)); + if (StatusIsFatal()) return; + setPWMDutyCycle(m_pwmGenerator, initialDutyCycle, &status); + wpi_setErrorWithContext(status, getHALErrorMessage(status)); - if(StatusIsFatal()) return; - setPWMOutputChannel(m_pwmGenerator, m_channel, &status); - wpi_setErrorWithContext(status, getHALErrorMessage(status)); + if (StatusIsFatal()) return; + setPWMOutputChannel(m_pwmGenerator, m_channel, &status); + wpi_setErrorWithContext(status, getHALErrorMessage(status)); } /** @@ -165,21 +155,20 @@ void DigitalOutput::EnablePWM(float initialDutyCycle) * * Free up one of the 6 DO PWM generator resources that were in use. */ -void DigitalOutput::DisablePWM() -{ - if (StatusIsFatal()) return; - if(m_pwmGenerator == (void *)~0ul) return; +void DigitalOutput::DisablePWM() { + if (StatusIsFatal()) return; + if (m_pwmGenerator == (void *)~0ul) return; - int32_t status = 0; + int32_t status = 0; - // Disable the output by routing to a dead bit. - setPWMOutputChannel(m_pwmGenerator, kDigitalChannels, &status); - wpi_setErrorWithContext(status, getHALErrorMessage(status)); + // Disable the output by routing to a dead bit. + setPWMOutputChannel(m_pwmGenerator, kDigitalChannels, &status); + wpi_setErrorWithContext(status, getHALErrorMessage(status)); - freePWM(m_pwmGenerator, &status); - wpi_setErrorWithContext(status, getHALErrorMessage(status)); + freePWM(m_pwmGenerator, &status); + wpi_setErrorWithContext(status, getHALErrorMessage(status)); - m_pwmGenerator = (void *)~0ul; + m_pwmGenerator = (void *)~0ul; } /** @@ -190,67 +179,55 @@ void DigitalOutput::DisablePWM() * * @param dutyCycle The duty-cycle to change to. [0..1] */ -void DigitalOutput::UpdateDutyCycle(float dutyCycle) -{ - if (StatusIsFatal()) return; +void DigitalOutput::UpdateDutyCycle(float dutyCycle) { + if (StatusIsFatal()) return; - int32_t status = 0; - setPWMDutyCycle(m_pwmGenerator, dutyCycle, &status); - wpi_setErrorWithContext(status, getHALErrorMessage(status)); + int32_t status = 0; + setPWMDutyCycle(m_pwmGenerator, dutyCycle, &status); + wpi_setErrorWithContext(status, getHALErrorMessage(status)); } /** * @return The value to be written to the channel field of a routing mux. */ -uint32_t DigitalOutput::GetChannelForRouting() const -{ - return GetChannel(); -} +uint32_t DigitalOutput::GetChannelForRouting() const { return GetChannel(); } /** * @return The value to be written to the module field of a routing mux. */ -uint32_t DigitalOutput::GetModuleForRouting() const -{ - return 0; -} +uint32_t DigitalOutput::GetModuleForRouting() const { return 0; } /** * @return The value to be written to the analog trigger field of a routing mux. */ -bool DigitalOutput::GetAnalogTriggerForRouting() const -{ - return false; +bool DigitalOutput::GetAnalogTriggerForRouting() const { return false; } + +void DigitalOutput::ValueChanged(ITable *source, const std::string &key, + EntryValue value, bool isNew) { + Set(value.b); } -void DigitalOutput::ValueChanged(ITable* source, const std::string& key, EntryValue value, bool isNew) { - Set(value.b); -} - -void DigitalOutput::UpdateTable() { -} +void DigitalOutput::UpdateTable() {} void DigitalOutput::StartLiveWindowMode() { - if (m_table != NULL) { - m_table->AddTableListener("Value", this, true); - } + if (m_table != NULL) { + m_table->AddTableListener("Value", this, true); + } } void DigitalOutput::StopLiveWindowMode() { - if (m_table != NULL) { - m_table->RemoveTableListener(this); - } + if (m_table != NULL) { + m_table->RemoveTableListener(this); + } } std::string DigitalOutput::GetSmartDashboardType() const { - return "Digital Output"; + return "Digital Output"; } void DigitalOutput::InitTable(ITable *subTable) { - m_table = subTable; - UpdateTable(); + m_table = subTable; + UpdateTable(); } -ITable * DigitalOutput::GetTable() const { - return m_table; -} +ITable *DigitalOutput::GetTable() const { return m_table; } diff --git a/wpilibc/wpilibC++Devices/src/DigitalSource.cpp b/wpilibc/wpilibC++Devices/src/DigitalSource.cpp index 40cc75cd43..cc7f0b94cd 100644 --- a/wpilibc/wpilibC++Devices/src/DigitalSource.cpp +++ b/wpilibc/wpilibC++Devices/src/DigitalSource.cpp @@ -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,6 +10,4 @@ /** * DigitalSource destructor. */ -DigitalSource::~DigitalSource() -{ -} +DigitalSource::~DigitalSource() {} diff --git a/wpilibc/wpilibC++Devices/src/DoubleSolenoid.cpp b/wpilibc/wpilibC++Devices/src/DoubleSolenoid.cpp index 1d33c4c8e7..2973bbaf4e 100644 --- a/wpilibc/wpilibC++Devices/src/DoubleSolenoid.cpp +++ b/wpilibc/wpilibC++Devices/src/DoubleSolenoid.cpp @@ -12,49 +12,51 @@ /** * Common function to implement constructor behaviour. */ -void DoubleSolenoid::InitSolenoid() -{ - m_table = NULL; - char buf[64]; - if (!CheckSolenoidModule(m_moduleNumber)) - { - snprintf(buf, 64, "Solenoid Module %d", m_moduleNumber); - wpi_setWPIErrorWithContext(ModuleIndexOutOfRange, buf); - return; - } - if (!CheckSolenoidChannel(m_forwardChannel)) - { - snprintf(buf, 64, "Solenoid Channel %d", m_forwardChannel); - wpi_setWPIErrorWithContext(ChannelIndexOutOfRange, buf); - return; - } - if (!CheckSolenoidChannel(m_reverseChannel)) - { - snprintf(buf, 64, "Solenoid Channel %d", m_reverseChannel); - wpi_setWPIErrorWithContext(ChannelIndexOutOfRange, buf); - return; - } - Resource::CreateResourceObject(&m_allocated, solenoid_kNumDO7_0Elements * kSolenoidChannels); +void DoubleSolenoid::InitSolenoid() { + m_table = NULL; + char buf[64]; + if (!CheckSolenoidModule(m_moduleNumber)) { + snprintf(buf, 64, "Solenoid Module %d", m_moduleNumber); + wpi_setWPIErrorWithContext(ModuleIndexOutOfRange, buf); + return; + } + if (!CheckSolenoidChannel(m_forwardChannel)) { + snprintf(buf, 64, "Solenoid Channel %d", m_forwardChannel); + wpi_setWPIErrorWithContext(ChannelIndexOutOfRange, buf); + return; + } + if (!CheckSolenoidChannel(m_reverseChannel)) { + snprintf(buf, 64, "Solenoid Channel %d", m_reverseChannel); + wpi_setWPIErrorWithContext(ChannelIndexOutOfRange, buf); + return; + } + Resource::CreateResourceObject( + &m_allocated, solenoid_kNumDO7_0Elements * kSolenoidChannels); - snprintf(buf, 64, "Solenoid %d (Module: %d)", m_forwardChannel, m_moduleNumber); - if (m_allocated->Allocate(m_moduleNumber * kSolenoidChannels + m_forwardChannel, buf) == ~0ul) - { - CloneError(m_allocated); - return; - } + snprintf(buf, 64, "Solenoid %d (Module: %d)", m_forwardChannel, + m_moduleNumber); + if (m_allocated->Allocate( + m_moduleNumber * kSolenoidChannels + m_forwardChannel, buf) == ~0ul) { + CloneError(m_allocated); + return; + } - snprintf(buf, 64, "Solenoid %d (Module: %d)", m_reverseChannel, m_moduleNumber); - if (m_allocated->Allocate(m_moduleNumber * kSolenoidChannels + m_reverseChannel, buf) == ~0ul) - { - CloneError(m_allocated); - return; - } - - m_forwardMask = 1 << m_forwardChannel; - m_reverseMask = 1 << m_reverseChannel; - HALReport(HALUsageReporting::kResourceType_Solenoid, m_forwardChannel, m_moduleNumber); - HALReport(HALUsageReporting::kResourceType_Solenoid, m_reverseChannel, m_moduleNumber); - LiveWindow::GetInstance()->AddActuator("DoubleSolenoid", m_moduleNumber, m_forwardChannel, this); + snprintf(buf, 64, "Solenoid %d (Module: %d)", m_reverseChannel, + m_moduleNumber); + if (m_allocated->Allocate( + m_moduleNumber * kSolenoidChannels + m_reverseChannel, buf) == ~0ul) { + CloneError(m_allocated); + return; + } + + m_forwardMask = 1 << m_forwardChannel; + m_reverseMask = 1 << m_reverseChannel; + HALReport(HALUsageReporting::kResourceType_Solenoid, m_forwardChannel, + m_moduleNumber); + HALReport(HALUsageReporting::kResourceType_Solenoid, m_reverseChannel, + m_moduleNumber); + LiveWindow::GetInstance()->AddActuator("DoubleSolenoid", m_moduleNumber, + m_forwardChannel, this); } /** @@ -64,11 +66,10 @@ void DoubleSolenoid::InitSolenoid() * @param reverseChannel The reverse channel number on the PCM (0..7). */ DoubleSolenoid::DoubleSolenoid(uint32_t forwardChannel, uint32_t reverseChannel) - : SolenoidBase (GetDefaultSolenoidModule()) - , m_forwardChannel (forwardChannel) - , m_reverseChannel (reverseChannel) -{ - InitSolenoid(); + : SolenoidBase(GetDefaultSolenoidModule()), + m_forwardChannel(forwardChannel), + m_reverseChannel(reverseChannel) { + InitSolenoid(); } /** @@ -78,24 +79,22 @@ DoubleSolenoid::DoubleSolenoid(uint32_t forwardChannel, uint32_t reverseChannel) * @param forwardChannel The forward channel on the PCM to control (0..7). * @param reverseChannel The reverse channel on the PCM to control (0..7). */ -DoubleSolenoid::DoubleSolenoid(uint8_t moduleNumber, uint32_t forwardChannel, uint32_t reverseChannel) - : SolenoidBase (moduleNumber) - , m_forwardChannel (forwardChannel) - , m_reverseChannel (reverseChannel) -{ - InitSolenoid(); +DoubleSolenoid::DoubleSolenoid(uint8_t moduleNumber, uint32_t forwardChannel, + uint32_t reverseChannel) + : SolenoidBase(moduleNumber), + m_forwardChannel(forwardChannel), + m_reverseChannel(reverseChannel) { + InitSolenoid(); } /** * Destructor. */ -DoubleSolenoid::~DoubleSolenoid() -{ - if (CheckSolenoidModule(m_moduleNumber)) - { - m_allocated->Free(m_moduleNumber * kSolenoidChannels + m_forwardChannel); - m_allocated->Free(m_moduleNumber * kSolenoidChannels + m_reverseChannel); - } +DoubleSolenoid::~DoubleSolenoid() { + if (CheckSolenoidModule(m_moduleNumber)) { + m_allocated->Free(m_moduleNumber * kSolenoidChannels + m_forwardChannel); + m_allocated->Free(m_moduleNumber * kSolenoidChannels + m_reverseChannel); + } } /** @@ -103,25 +102,23 @@ DoubleSolenoid::~DoubleSolenoid() * * @param value The value to set (Off, Forward or Reverse) */ -void DoubleSolenoid::Set(Value value) -{ - if (StatusIsFatal()) return; - uint8_t rawValue = 0x00; +void DoubleSolenoid::Set(Value value) { + if (StatusIsFatal()) return; + uint8_t rawValue = 0x00; - switch(value) - { - case kOff: - rawValue = 0x00; - break; - case kForward: - rawValue = m_forwardMask; - break; - case kReverse: - rawValue = m_reverseMask; - break; - } + switch (value) { + case kOff: + rawValue = 0x00; + break; + case kForward: + rawValue = m_forwardMask; + break; + case kReverse: + rawValue = m_reverseMask; + break; + } - SolenoidBase::Set(rawValue, m_forwardMask | m_reverseMask, m_moduleNumber); + SolenoidBase::Set(rawValue, m_forwardMask | m_reverseMask, m_moduleNumber); } /** @@ -129,81 +126,79 @@ void DoubleSolenoid::Set(Value value) * * @return The current value of the solenoid. */ -DoubleSolenoid::Value DoubleSolenoid::Get() const -{ - if (StatusIsFatal()) return kOff; - uint8_t value = GetAll(m_moduleNumber); +DoubleSolenoid::Value DoubleSolenoid::Get() const { + if (StatusIsFatal()) return kOff; + uint8_t value = GetAll(m_moduleNumber); - if (value & m_forwardMask) return kForward; - if (value & m_reverseMask) return kReverse; - return kOff; + if (value & m_forwardMask) return kForward; + if (value & m_reverseMask) return kReverse; + return kOff; } /** * Check if the forward solenoid is blacklisted. - * If a solenoid is shorted, it is added to the blacklist and - * disabled until power cycle, or until faults are cleared. - * @see ClearAllPCMStickyFaults() + * If a solenoid is shorted, it is added to the blacklist and + * disabled until power cycle, or until faults are cleared. + * @see ClearAllPCMStickyFaults() * * @return If solenoid is disabled due to short. */ -bool DoubleSolenoid::IsFwdSolenoidBlackListed() const -{ - int blackList = GetPCMSolenoidBlackList(m_moduleNumber); - return (blackList & m_forwardMask) ? 1 : 0; +bool DoubleSolenoid::IsFwdSolenoidBlackListed() const { + int blackList = GetPCMSolenoidBlackList(m_moduleNumber); + return (blackList & m_forwardMask) ? 1 : 0; } /** * Check if the reverse solenoid is blacklisted. - * If a solenoid is shorted, it is added to the blacklist and - * disabled until power cycle, or until faults are cleared. - * @see ClearAllPCMStickyFaults() + * If a solenoid is shorted, it is added to the blacklist and + * disabled until power cycle, or until faults are cleared. + * @see ClearAllPCMStickyFaults() * * @return If solenoid is disabled due to short. */ -bool DoubleSolenoid::IsRevSolenoidBlackListed() const -{ - int blackList = GetPCMSolenoidBlackList(m_moduleNumber); - return (blackList & m_reverseMask) ? 1 : 0; +bool DoubleSolenoid::IsRevSolenoidBlackListed() const { + int blackList = GetPCMSolenoidBlackList(m_moduleNumber); + return (blackList & m_reverseMask) ? 1 : 0; } -void DoubleSolenoid::ValueChanged(ITable* source, const std::string& key, EntryValue value, bool isNew) { - Value lvalue = kOff; - std::string *val = (std::string *)value.ptr; - if (*val == "Forward") - lvalue = kForward; - else if (*val == "Reverse") - lvalue = kReverse; - Set(lvalue); +void DoubleSolenoid::ValueChanged(ITable *source, const std::string &key, + EntryValue value, bool isNew) { + Value lvalue = kOff; + std::string *val = (std::string *)value.ptr; + if (*val == "Forward") + lvalue = kForward; + else if (*val == "Reverse") + lvalue = kReverse; + Set(lvalue); } void DoubleSolenoid::UpdateTable() { - if (m_table != NULL) { - m_table->PutString("Value", (Get() == kForward ? "Forward" : (Get() == kReverse ? "Reverse" : "Off"))); - } + if (m_table != NULL) { + m_table->PutString( + "Value", (Get() == kForward ? "Forward" + : (Get() == kReverse ? "Reverse" : "Off"))); + } } void DoubleSolenoid::StartLiveWindowMode() { - Set(kOff); - if (m_table != NULL) { - m_table->AddTableListener("Value", this, true); - } + Set(kOff); + if (m_table != NULL) { + m_table->AddTableListener("Value", this, true); + } } void DoubleSolenoid::StopLiveWindowMode() { - Set(kOff); - if (m_table != NULL) { - m_table->RemoveTableListener(this); - } + Set(kOff); + if (m_table != NULL) { + m_table->RemoveTableListener(this); + } } std::string DoubleSolenoid::GetSmartDashboardType() const { - return "Double Solenoid"; + return "Double Solenoid"; } void DoubleSolenoid::InitTable(ITable *subTable) { - m_table = subTable; - UpdateTable(); + m_table = subTable; + UpdateTable(); } -ITable * DoubleSolenoid::GetTable() const { - return m_table; -} +ITable *DoubleSolenoid::GetTable() const { return m_table; } diff --git a/wpilibc/wpilibC++Devices/src/DriverStation.cpp b/wpilibc/wpilibC++Devices/src/DriverStation.cpp index e70cc3e32d..372383bd2f 100644 --- a/wpilibc/wpilibC++Devices/src/DriverStation.cpp +++ b/wpilibc/wpilibC++Devices/src/DriverStation.cpp @@ -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. */ /*----------------------------------------------------------------------------*/ @@ -20,9 +21,11 @@ TLogLevel dsLogLevel = logDEBUG; const double JOYSTICK_UNPLUGGED_MESSAGE_INTERVAL = 1.0; -#define DS_LOG(level) \ - if (level > dsLogLevel) ; \ - else Log().Get(level) +#define DS_LOG(level) \ + if (level > dsLogLevel) \ + ; \ + else \ + Log().Get(level) const uint32_t DriverStation::kJoystickPorts; DriverStation* DriverStation::m_instance = NULL; @@ -33,107 +36,94 @@ DriverStation* DriverStation::m_instance = NULL; * This is only called once the first time GetInstance() is called */ DriverStation::DriverStation() - : m_task ("DriverStation", (FUNCPTR)DriverStation::InitTask) - , m_newControlData(0) - , m_packetDataAvailableMultiWait(0) - , m_waitForDataSem(0) - , m_userInDisabled(false) - , m_userInAutonomous(false) - , m_userInTeleop(false) - , m_userInTest(false) - , m_nextMessageTime(0) -{ - // All joysticks should default to having zero axes, povs and buttons, so - // uninitialized memory doesn't get sent to speed controllers. - for(unsigned int i = 0; i < kJoystickPorts; i++) { - m_joystickAxes[i].count = 0; - m_joystickPOVs[i].count = 0; - m_joystickButtons[i].count = 0; - m_joystickDescriptor[i].isXbox = 0; - m_joystickDescriptor[i].type = -1; - m_joystickDescriptor[i].name[0] = '\0'; - } - // Create a new semaphore - m_packetDataAvailableMultiWait = initializeMultiWait(); - m_newControlData = initializeSemaphore(SEMAPHORE_EMPTY); + : m_task("DriverStation", (FUNCPTR)DriverStation::InitTask), + m_newControlData(0), + m_packetDataAvailableMultiWait(0), + m_waitForDataSem(0), + m_userInDisabled(false), + m_userInAutonomous(false), + m_userInTeleop(false), + m_userInTest(false), + m_nextMessageTime(0) { + // All joysticks should default to having zero axes, povs and buttons, so + // uninitialized memory doesn't get sent to speed controllers. + for (unsigned int i = 0; i < kJoystickPorts; i++) { + m_joystickAxes[i].count = 0; + m_joystickPOVs[i].count = 0; + m_joystickButtons[i].count = 0; + m_joystickDescriptor[i].isXbox = 0; + m_joystickDescriptor[i].type = -1; + m_joystickDescriptor[i].name[0] = '\0'; + } + // Create a new semaphore + m_packetDataAvailableMultiWait = initializeMultiWait(); + m_newControlData = initializeSemaphore(SEMAPHORE_EMPTY); - m_waitForDataSem = initializeMultiWait(); - m_waitForDataMutex = initializeMutexNormal(); + m_waitForDataSem = initializeMultiWait(); + m_waitForDataMutex = initializeMutexNormal(); - m_packetDataAvailableMultiWait = initializeMultiWait(); - m_packetDataAvailableMutex = initializeMutexNormal(); + m_packetDataAvailableMultiWait = initializeMultiWait(); + m_packetDataAvailableMutex = initializeMutexNormal(); - // Register that semaphore with the network communications task. - // It will signal when new packet data is available. - HALSetNewDataSem(m_packetDataAvailableMultiWait); + // Register that semaphore with the network communications task. + // It will signal when new packet data is available. + HALSetNewDataSem(m_packetDataAvailableMultiWait); - AddToSingletonList(); + AddToSingletonList(); // They need to be identical or it could lead to runtime stack corruption if // the caller and callee push and pop different amounts of data on the stack. static_assert(sizeof(this) == sizeof(uint32_t), "We are passing a pointer through a uint32_t"); - if (!m_task.Start((uint32_t)this)) - { - wpi_setWPIError(DriverStationTaskError); - } + if (!m_task.Start((uint32_t) this)) { + wpi_setWPIError(DriverStationTaskError); + } } -DriverStation::~DriverStation() -{ - m_task.Stop(); - m_instance = NULL; - deleteMultiWait(m_waitForDataSem); - // Unregister our semaphore. - HALSetNewDataSem(0); - deleteMultiWait(m_packetDataAvailableMultiWait); - deleteMutex(m_packetDataAvailableMutex); - deleteMutex(m_waitForDataMutex); +DriverStation::~DriverStation() { + m_task.Stop(); + m_instance = NULL; + deleteMultiWait(m_waitForDataSem); + // Unregister our semaphore. + HALSetNewDataSem(0); + deleteMultiWait(m_packetDataAvailableMultiWait); + deleteMutex(m_packetDataAvailableMutex); + deleteMutex(m_waitForDataMutex); } // XXX: This assumes that the calling convention treats pointers and uint32_ts // identical, which is not necessarily true. -void DriverStation::InitTask(DriverStation *ds) -{ - ds->Run(); -} +void DriverStation::InitTask(DriverStation* ds) { ds->Run(); } -void DriverStation::Run() -{ - int period = 0; - while (true) - { - takeMultiWait(m_packetDataAvailableMultiWait, m_packetDataAvailableMutex, 0); - GetData(); - giveMultiWait(m_waitForDataSem); +void DriverStation::Run() { + int period = 0; + while (true) { + takeMultiWait(m_packetDataAvailableMultiWait, m_packetDataAvailableMutex, + 0); + GetData(); + giveMultiWait(m_waitForDataSem); - if (++period >= 4) - { - MotorSafetyHelper::CheckMotors(); - period = 0; - } - if (m_userInDisabled) - HALNetworkCommunicationObserveUserProgramDisabled(); - if (m_userInAutonomous) - HALNetworkCommunicationObserveUserProgramAutonomous(); - if (m_userInTeleop) - HALNetworkCommunicationObserveUserProgramTeleop(); - if (m_userInTest) - HALNetworkCommunicationObserveUserProgramTest(); - } + if (++period >= 4) { + MotorSafetyHelper::CheckMotors(); + period = 0; + } + if (m_userInDisabled) HALNetworkCommunicationObserveUserProgramDisabled(); + if (m_userInAutonomous) + HALNetworkCommunicationObserveUserProgramAutonomous(); + if (m_userInTeleop) HALNetworkCommunicationObserveUserProgramTeleop(); + if (m_userInTest) HALNetworkCommunicationObserveUserProgramTest(); + } } /** * Return a pointer to the singleton DriverStation. * @return Pointer to the DS instance */ -DriverStation* DriverStation::GetInstance() -{ - if (m_instance == NULL) - { - m_instance = new DriverStation(); - } - return m_instance; +DriverStation* DriverStation::GetInstance() { + if (m_instance == NULL) { + m_instance = new DriverStation(); + } + return m_instance; } /** @@ -141,17 +131,15 @@ DriverStation* DriverStation::GetInstance() * If no new data exists, it will just be returned, otherwise * the data will be copied from the DS polling loop. */ -void DriverStation::GetData() -{ - - // Get the status of all of the joysticks - for(uint8_t stick = 0; stick < kJoystickPorts; stick++) { - HALGetJoystickAxes(stick, &m_joystickAxes[stick]); - HALGetJoystickPOVs(stick, &m_joystickPOVs[stick]); - HALGetJoystickButtons(stick, &m_joystickButtons[stick]); - HALGetJoystickDescriptor(stick, &m_joystickDescriptor[stick]); - } - giveSemaphore(m_newControlData); +void DriverStation::GetData() { + // Get the status of all of the joysticks + for (uint8_t stick = 0; stick < kJoystickPorts; stick++) { + HALGetJoystickAxes(stick, &m_joystickAxes[stick]); + HALGetJoystickPOVs(stick, &m_joystickPOVs[stick]); + HALGetJoystickButtons(stick, &m_joystickButtons[stick]); + HALGetJoystickDescriptor(stick, &m_joystickDescriptor[stick]); + } + giveSemaphore(m_newControlData); } /** @@ -159,13 +147,12 @@ void DriverStation::GetData() * * @return The battery voltage in Volts. */ -float DriverStation::GetBatteryVoltage() const -{ - int32_t status = 0; - float voltage = getVinVoltage(&status); - wpi_setErrorWithContext(status, "getVinVoltage"); +float DriverStation::GetBatteryVoltage() const { + int32_t status = 0; + float voltage = getVinVoltage(&status); + wpi_setErrorWithContext(status, "getVinVoltage"); - return voltage; + return voltage; } /** @@ -173,11 +160,11 @@ float DriverStation::GetBatteryVoltage() const * Throttles the errors so that they don't overwhelm the DS */ void DriverStation::ReportJoystickUnpluggedError(std::string message) { - double currentTime = Timer::GetFPGATimestamp(); - if (currentTime > m_nextMessageTime) { - ReportError(message); - m_nextMessageTime = currentTime + JOYSTICK_UNPLUGGED_MESSAGE_INTERVAL; - } + double currentTime = Timer::GetFPGATimestamp(); + if (currentTime > m_nextMessageTime) { + ReportError(message); + m_nextMessageTime = currentTime + JOYSTICK_UNPLUGGED_MESSAGE_INTERVAL; + } } /** @@ -186,98 +173,86 @@ void DriverStation::ReportJoystickUnpluggedError(std::string message) { * @param stick The joystick port number * @return The number of axes on the indicated joystick */ -int DriverStation::GetStickAxisCount(uint32_t stick) const -{ - if (stick >= kJoystickPorts) - { - wpi_setWPIError(BadJoystickIndex); - return 0; - } - HALJoystickAxes joystickAxes; - HALGetJoystickAxes(stick, &joystickAxes); - return joystickAxes.count; +int DriverStation::GetStickAxisCount(uint32_t stick) const { + if (stick >= kJoystickPorts) { + wpi_setWPIError(BadJoystickIndex); + return 0; + } + HALJoystickAxes joystickAxes; + HALGetJoystickAxes(stick, &joystickAxes); + return joystickAxes.count; } /** - *Returns the name of the joystick at the given port + * Returns the name of the joystick at the given port * - *@param stick The joystick port number - *@return The name of the joystick at the given port + * @param stick The joystick port number + * @return The name of the joystick at the given port */ -std::string DriverStation::GetJoystickName(uint32_t stick) const -{ - if (stick >= kJoystickPorts) - { - wpi_setWPIError(BadJoystickIndex); - } - std::string retVal(m_joystickDescriptor[0].name); - return retVal; +std::string DriverStation::GetJoystickName(uint32_t stick) const { + if (stick >= kJoystickPorts) { + wpi_setWPIError(BadJoystickIndex); + } + std::string retVal(m_joystickDescriptor[0].name); + return retVal; } /** - *Returns the type of joystick at a given port + * Returns the type of joystick at a given port * - *@param stick The joystick port number - *@return The HID type of joystick at the given port + * @param stick The joystick port number + * @return The HID type of joystick at the given port */ -int DriverStation::GetJoystickType(uint32_t stick) const -{ - if (stick >= kJoystickPorts) - { - wpi_setWPIError(BadJoystickIndex); - return -1; - } - return (int)m_joystickDescriptor[stick].type; +int DriverStation::GetJoystickType(uint32_t stick) const { + if (stick >= kJoystickPorts) { + wpi_setWPIError(BadJoystickIndex); + return -1; + } + return (int)m_joystickDescriptor[stick].type; } /** - *Returns a boolean indicating if the controller is an xbox controller. + * Returns a boolean indicating if the controller is an xbox controller. * - *@param stick The joystick port number - *@return A boolean that is true if the controller is an xbox controller. + * @param stick The joystick port number + * @return A boolean that is true if the controller is an xbox controller. */ -bool DriverStation::GetJoystickIsXbox(uint32_t stick) const -{ - if (stick >= kJoystickPorts) - { - wpi_setWPIError(BadJoystickIndex); - return false; - } - return (bool)m_joystickDescriptor[stick].isXbox; +bool DriverStation::GetJoystickIsXbox(uint32_t stick) const { + if (stick >= kJoystickPorts) { + wpi_setWPIError(BadJoystickIndex); + return false; + } + return (bool)m_joystickDescriptor[stick].isXbox; } /** - *Returns the types of Axes on a given joystick port + * Returns the types of Axes on a given joystick port * - *@param stick The joystick port number and the target axis - *@return What type of axis the axis is reporting to be + * @param stick The joystick port number and the target axis + * @return What type of axis the axis is reporting to be */ -int DriverStation::GetJoystickAxisType(uint32_t stick, uint8_t axis) const -{ - if (stick >= kJoystickPorts) - { - wpi_setWPIError(BadJoystickIndex); - return -1; - } - return m_joystickDescriptor[stick].axisTypes[axis]; +int DriverStation::GetJoystickAxisType(uint32_t stick, uint8_t axis) const { + if (stick >= kJoystickPorts) { + wpi_setWPIError(BadJoystickIndex); + return -1; + } + return m_joystickDescriptor[stick].axisTypes[axis]; } -/** +/** * Returns the number of POVs on a given joystick port * * @param stick The joystick port number * @return The number of POVs on the indicated joystick */ -int DriverStation::GetStickPOVCount(uint32_t stick) const -{ - if (stick >= kJoystickPorts) - { - wpi_setWPIError(BadJoystickIndex); - return 0; - } - HALJoystickPOVs joystickPOVs; - HALGetJoystickPOVs(stick, &joystickPOVs); - return joystickPOVs.count; +int DriverStation::GetStickPOVCount(uint32_t stick) const { + if (stick >= kJoystickPorts) { + wpi_setWPIError(BadJoystickIndex); + return 0; + } + HALJoystickPOVs joystickPOVs; + HALGetJoystickPOVs(stick, &joystickPOVs); + return joystickPOVs.count; } /** @@ -286,16 +261,14 @@ int DriverStation::GetStickPOVCount(uint32_t stick) const * @param stick The joystick port number * @return The number of buttons on the indicated joystick */ -int DriverStation::GetStickButtonCount(uint32_t stick) const -{ - if (stick >= kJoystickPorts) - { - wpi_setWPIError(BadJoystickIndex); - return 0; - } - HALJoystickButtons joystickButtons; - HALGetJoystickButtons(stick, &joystickButtons); - return joystickButtons.count; +int DriverStation::GetStickButtonCount(uint32_t stick) const { + if (stick >= kJoystickPorts) { + wpi_setWPIError(BadJoystickIndex); + return 0; + } + HALJoystickButtons joystickButtons; + HALGetJoystickButtons(stick, &joystickButtons); + return joystickButtons.count; } /** @@ -306,33 +279,29 @@ int DriverStation::GetStickButtonCount(uint32_t stick) const * @param axis The analog axis value to read from the joystick. * @return The value of the axis on the joystick. */ -float DriverStation::GetStickAxis(uint32_t stick, uint32_t axis) -{ - if (stick >= kJoystickPorts) - { - wpi_setWPIError(BadJoystickIndex); - return 0; - } +float DriverStation::GetStickAxis(uint32_t stick, uint32_t axis) { + if (stick >= kJoystickPorts) { + wpi_setWPIError(BadJoystickIndex); + return 0; + } - if (axis >= m_joystickAxes[stick].count) - { - if (axis >= kMaxJoystickAxes) - wpi_setWPIError(BadJoystickAxis); - else - ReportJoystickUnpluggedError("WARNING: Joystick Axis missing, check if all controllers are plugged in\n"); - return 0.0f; - } + if (axis >= m_joystickAxes[stick].count) { + if (axis >= kMaxJoystickAxes) + wpi_setWPIError(BadJoystickAxis); + else + ReportJoystickUnpluggedError( + "WARNING: Joystick Axis missing, check if all controllers are " + "plugged in\n"); + return 0.0f; + } - int8_t value = m_joystickAxes[stick].axes[axis]; + int8_t value = m_joystickAxes[stick].axes[axis]; - if(value < 0) - { - return value / 128.0f; - } - else - { - return value / 127.0f; - } + if (value < 0) { + return value / 128.0f; + } else { + return value / 127.0f; + } } /** @@ -341,22 +310,22 @@ float DriverStation::GetStickAxis(uint32_t stick, uint32_t axis) * @return the angle of the POV in degrees, or -1 if the POV is not pressed. */ int DriverStation::GetStickPOV(uint32_t stick, uint32_t pov) { - if (stick >= kJoystickPorts) - { - wpi_setWPIError(BadJoystickIndex); - return -1; - } + if (stick >= kJoystickPorts) { + wpi_setWPIError(BadJoystickIndex); + return -1; + } - if (pov >= m_joystickPOVs[stick].count) - { - if (pov >= kMaxJoystickPOVs) - wpi_setWPIError(BadJoystickAxis); - else - ReportJoystickUnpluggedError("WARNING: Joystick POV missing, check if all controllers are plugged in\n"); - return -1; - } + if (pov >= m_joystickPOVs[stick].count) { + if (pov >= kMaxJoystickPOVs) + wpi_setWPIError(BadJoystickAxis); + else + ReportJoystickUnpluggedError( + "WARNING: Joystick POV missing, check if all controllers are plugged " + "in\n"); + return -1; + } - return m_joystickPOVs[stick].povs[pov]; + return m_joystickPOVs[stick].povs[pov]; } /** @@ -365,15 +334,13 @@ int DriverStation::GetStickPOV(uint32_t stick, uint32_t pov) { * @param stick The joystick to read. * @return The state of the buttons on the joystick. */ -uint32_t DriverStation::GetStickButtons(uint32_t stick) const -{ - if (stick >= kJoystickPorts) - { - wpi_setWPIError(BadJoystickIndex); - return 0; - } +uint32_t DriverStation::GetStickButtons(uint32_t stick) const { + if (stick >= kJoystickPorts) { + wpi_setWPIError(BadJoystickIndex); + return 0; + } - return m_joystickButtons[stick].buttons; + return m_joystickButtons[stick].buttons; } /** @@ -383,143 +350,135 @@ uint32_t DriverStation::GetStickButtons(uint32_t stick) const * @param button The button index, beginning at 1. * @return The state of the joystick button. */ -bool DriverStation::GetStickButton(uint32_t stick, uint8_t button) -{ - if (stick >= kJoystickPorts) - { - wpi_setWPIError(BadJoystickIndex); - return false; - } +bool DriverStation::GetStickButton(uint32_t stick, uint8_t button) { + if (stick >= kJoystickPorts) { + wpi_setWPIError(BadJoystickIndex); + return false; + } - if(button > m_joystickButtons[stick].count) - { - ReportJoystickUnpluggedError("WARNING: Joystick Button missing, check if all controllers are plugged in\n"); - return false; - } - if(button == 0) - { - ReportJoystickUnpluggedError("ERROR: Button indexes begin at 1 in WPILib for C++ and Java"); - return false; - } - return ((0x1 << (button-1)) & m_joystickButtons[stick].buttons) !=0; + if (button > m_joystickButtons[stick].count) { + ReportJoystickUnpluggedError( + "WARNING: Joystick Button missing, check if all controllers are " + "plugged in\n"); + return false; + } + if (button == 0) { + ReportJoystickUnpluggedError( + "ERROR: Button indexes begin at 1 in WPILib for C++ and Java"); + return false; + } + return ((0x1 << (button - 1)) & m_joystickButtons[stick].buttons) != 0; } /** * Check if the DS has enabled the robot * @return True if the robot is enabled and the DS is connected */ -bool DriverStation::IsEnabled() const -{ - HALControlWord controlWord; - memset(&controlWord, 0, sizeof(controlWord)); - HALGetControlWord(&controlWord); - return controlWord.enabled && controlWord.dsAttached; +bool DriverStation::IsEnabled() const { + HALControlWord controlWord; + memset(&controlWord, 0, sizeof(controlWord)); + HALGetControlWord(&controlWord); + return controlWord.enabled && controlWord.dsAttached; } /** * Check if the robot is disabled * @return True if the robot is explicitly disabled or the DS is not connected */ -bool DriverStation::IsDisabled() const -{ - HALControlWord controlWord; - memset(&controlWord, 0, sizeof(controlWord)); - HALGetControlWord(&controlWord); - return !(controlWord.enabled && controlWord.dsAttached); +bool DriverStation::IsDisabled() const { + HALControlWord controlWord; + memset(&controlWord, 0, sizeof(controlWord)); + HALGetControlWord(&controlWord); + return !(controlWord.enabled && controlWord.dsAttached); } /** * Check if the DS is commanding autonomous mode * @return True if the robot is being commanded to be in autonomous mode */ -bool DriverStation::IsAutonomous() const -{ - HALControlWord controlWord; - memset(&controlWord, 0, sizeof(controlWord)); - HALGetControlWord(&controlWord); - return controlWord.autonomous; +bool DriverStation::IsAutonomous() const { + HALControlWord controlWord; + memset(&controlWord, 0, sizeof(controlWord)); + HALGetControlWord(&controlWord); + return controlWord.autonomous; } /** * Check if the DS is commanding teleop mode * @return True if the robot is being commanded to be in teleop mode */ -bool DriverStation::IsOperatorControl() const -{ - HALControlWord controlWord; - memset(&controlWord, 0, sizeof(controlWord)); - HALGetControlWord(&controlWord); - return !(controlWord.autonomous || controlWord.test); +bool DriverStation::IsOperatorControl() const { + HALControlWord controlWord; + memset(&controlWord, 0, sizeof(controlWord)); + HALGetControlWord(&controlWord); + return !(controlWord.autonomous || controlWord.test); } /** * Check if the DS is commanding test mode * @return True if the robot is being commanded to be in test mode */ -bool DriverStation::IsTest() const -{ - HALControlWord controlWord; - HALGetControlWord(&controlWord); - return controlWord.test; +bool DriverStation::IsTest() const { + HALControlWord controlWord; + HALGetControlWord(&controlWord); + return controlWord.test; } /** * Check if the DS is attached * @return True if the DS is connected to the robot */ -bool DriverStation::IsDSAttached() const -{ - HALControlWord controlWord; - memset(&controlWord, 0, sizeof(controlWord)); - HALGetControlWord(&controlWord); - return controlWord.dsAttached; +bool DriverStation::IsDSAttached() const { + HALControlWord controlWord; + memset(&controlWord, 0, sizeof(controlWord)); + HALGetControlWord(&controlWord); + return controlWord.dsAttached; } /** - * Check if the FPGA outputs are enabled. The outputs may be disabled if the robot is disabled + * Check if the FPGA outputs are enabled. The outputs may be disabled if the + * robot is disabled * or e-stopped, the watchdog has expired, or if the roboRIO browns out. * @return True if the FPGA outputs are enabled. */ -bool DriverStation::IsSysActive() const -{ - int32_t status = 0; - bool retVal = HALGetSystemActive(&status); - wpi_setErrorWithContext(status, getHALErrorMessage(status)); - return retVal; +bool DriverStation::IsSysActive() const { + int32_t status = 0; + bool retVal = HALGetSystemActive(&status); + wpi_setErrorWithContext(status, getHALErrorMessage(status)); + return retVal; } /** * Check if the system is browned out. * @return True if the system is browned out */ -bool DriverStation::IsSysBrownedOut() const -{ - int32_t status = 0; - bool retVal = HALGetBrownedOut(&status); - wpi_setErrorWithContext(status, getHALErrorMessage(status)); - return retVal; +bool DriverStation::IsSysBrownedOut() const { + int32_t status = 0; + bool retVal = HALGetBrownedOut(&status); + wpi_setErrorWithContext(status, getHALErrorMessage(status)); + return retVal; } /** - * Has a new control packet from the driver station arrived since the last time this function was called? + * Has a new control packet from the driver station arrived since the last time + * this function was called? * Warning: If you call this function from more than one place at the same time, * you will not get the get the intended behaviour. * @return True if the control data has been updated since the last call. */ -bool DriverStation::IsNewControlData() const -{ - return tryTakeSemaphore(m_newControlData) == 0; +bool DriverStation::IsNewControlData() const { + return tryTakeSemaphore(m_newControlData) == 0; } /** * Is the driver station attached to a Field Management System? - * @return True if the robot is competing on a field being controlled by a Field Management System + * @return True if the robot is competing on a field being controlled by a Field + * Management System */ -bool DriverStation::IsFMSAttached() const -{ - HALControlWord controlWord; - HALGetControlWord(&controlWord); - return controlWord.fmsAttached; +bool DriverStation::IsFMSAttached() const { + HALControlWord controlWord; + HALGetControlWord(&controlWord); + return controlWord.fmsAttached; } /** @@ -527,23 +486,21 @@ bool DriverStation::IsFMSAttached() const * This could return kRed or kBlue * @return The Alliance enum (kRed, kBlue or kInvalid) */ -DriverStation::Alliance DriverStation::GetAlliance() const -{ - HALAllianceStationID allianceStationID; - HALGetAllianceStation(&allianceStationID); - switch(allianceStationID) - { - case kHALAllianceStationID_red1: - case kHALAllianceStationID_red2: - case kHALAllianceStationID_red3: - return kRed; - case kHALAllianceStationID_blue1: - case kHALAllianceStationID_blue2: - case kHALAllianceStationID_blue3: - return kBlue; - default: - return kInvalid; - } +DriverStation::Alliance DriverStation::GetAlliance() const { + HALAllianceStationID allianceStationID; + HALGetAllianceStation(&allianceStationID); + switch (allianceStationID) { + case kHALAllianceStationID_red1: + case kHALAllianceStationID_red2: + case kHALAllianceStationID_red3: + return kRed; + case kHALAllianceStationID_blue1: + case kHALAllianceStationID_blue2: + case kHALAllianceStationID_blue3: + return kBlue; + default: + return kInvalid; + } } /** @@ -551,64 +508,63 @@ DriverStation::Alliance DriverStation::GetAlliance() const * This could return 1, 2, or 3 * @return The location of the driver station (1-3, 0 for invalid) */ -uint32_t DriverStation::GetLocation() const -{ - HALAllianceStationID allianceStationID; - HALGetAllianceStation(&allianceStationID); - switch(allianceStationID) - { - case kHALAllianceStationID_red1: - case kHALAllianceStationID_blue1: - return 1; - case kHALAllianceStationID_red2: - case kHALAllianceStationID_blue2: - return 2; - case kHALAllianceStationID_red3: - case kHALAllianceStationID_blue3: - return 3; - default: - return 0; - } +uint32_t DriverStation::GetLocation() const { + HALAllianceStationID allianceStationID; + HALGetAllianceStation(&allianceStationID); + switch (allianceStationID) { + case kHALAllianceStationID_red1: + case kHALAllianceStationID_blue1: + return 1; + case kHALAllianceStationID_red2: + case kHALAllianceStationID_blue2: + return 2; + case kHALAllianceStationID_red3: + case kHALAllianceStationID_blue3: + return 3; + default: + return 0; + } } /** * Wait until a new packet comes from the driver station * This blocks on a semaphore, so the waiting is efficient. - * This is a good way to delay processing until there is new driver station data to act on + * This is a good way to delay processing until there is new driver station data + * to act on */ -void DriverStation::WaitForData() -{ - takeMultiWait(m_waitForDataSem, m_waitForDataMutex, SEMAPHORE_WAIT_FOREVER); +void DriverStation::WaitForData() { + takeMultiWait(m_waitForDataSem, m_waitForDataMutex, SEMAPHORE_WAIT_FOREVER); } /** * Return the approximate match time - * The FMS does not send an official match time to the robots, but does send an approximate match time. - * The value will count down the time remaining in the current period (auto or teleop). - * Warning: This is not an official time (so it cannot be used to dispute ref calls or guarantee that a function + * The FMS does not send an official match time to the robots, but does send an + * approximate match time. + * The value will count down the time remaining in the current period (auto or + * teleop). + * Warning: This is not an official time (so it cannot be used to dispute ref + * calls or guarantee that a function * will trigger before the match ends) - * The Practice Match function of the DS approximates the behaviour seen on the field. + * The Practice Match function of the DS approximates the behaviour seen on the + * field. * @return Time remaining in current match period (auto or teleop) */ -double DriverStation::GetMatchTime() const -{ - float matchTime; - HALGetMatchTime(&matchTime); - return (double)matchTime; +double DriverStation::GetMatchTime() const { + float matchTime; + HALGetMatchTime(&matchTime); + return (double)matchTime; } /** * Report an error to the DriverStation messages window. * The error is also printed to the program console. */ -void DriverStation::ReportError(std::string error) -{ - std::cout << error << std::endl; - - HALControlWord controlWord; - HALGetControlWord(&controlWord); - if(controlWord.dsAttached) - { - HALSetErrorData(error.c_str(), error.size(), 0); - } +void DriverStation::ReportError(std::string error) { + std::cout << error << std::endl; + + HALControlWord controlWord; + HALGetControlWord(&controlWord); + if (controlWord.dsAttached) { + HALSetErrorData(error.c_str(), error.size(), 0); + } } diff --git a/wpilibc/wpilibC++Devices/src/Encoder.cpp b/wpilibc/wpilibC++Devices/src/Encoder.cpp index 3bdd3d57be..0ff27e251a 100644 --- a/wpilibc/wpilibC++Devices/src/Encoder.cpp +++ b/wpilibc/wpilibC++Devices/src/Encoder.cpp @@ -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. */ /*----------------------------------------------------------------------------*/ @@ -17,61 +18,63 @@ * * The counter will start counting immediately. * - * @param reverseDirection If true, counts down instead of up (this is all relative) - * @param encodingType either k1X, k2X, or k4X to indicate 1X, 2X or 4X decoding. If 4X is - * selected, then an encoder FPGA object is used and the returned counts will be 4x the encoder - * spec'd value since all rising and falling edges are counted. If 1X or 2X are selected then - * a counter object will be used and the returned value will either exactly match the spec'd count + * @param reverseDirection If true, counts down instead of up (this is all + * relative) + * @param encodingType either k1X, k2X, or k4X to indicate 1X, 2X or 4X + * decoding. If 4X is + * selected, then an encoder FPGA object is used and the returned counts will be + * 4x the encoder + * spec'd value since all rising and falling edges are counted. If 1X or 2X are + * selected then + * a counter object will be used and the returned value will either exactly + * match the spec'd count * or be double (2x) the spec'd count. */ -void Encoder::InitEncoder(bool reverseDirection, EncodingType encodingType) -{ - m_table = NULL; - m_encodingType = encodingType; - m_index = 0; - switch (encodingType) - { - case k4X: - { - m_encodingScale = 4; - if (m_aSource->StatusIsFatal()) - { - CloneError(m_aSource); - return; - } - if (m_bSource->StatusIsFatal()) - { - CloneError(m_bSource); - return; - } - int32_t status = 0; - m_encoder = initializeEncoder(m_aSource->GetModuleForRouting(), m_aSource->GetChannelForRouting(), - m_aSource->GetAnalogTriggerForRouting(), - m_bSource->GetModuleForRouting(), m_bSource->GetChannelForRouting(), - m_bSource->GetAnalogTriggerForRouting(), - reverseDirection, &m_index, &status); - wpi_setErrorWithContext(status, getHALErrorMessage(status)); - m_counter = NULL; - SetMaxPeriod(.5); - break; - } - case k1X: - case k2X: - { - m_encodingScale = encodingType == k1X ? 1 : 2; - m_counter = new Counter(m_encodingType, m_aSource, m_bSource, reverseDirection); - m_index = m_counter->GetFPGAIndex(); - break; - } - default: - wpi_setErrorWithContext(-1, "Invalid encodingType argument"); - break; - } - m_distancePerPulse = 1.0; - m_pidSource = kDistance; +void Encoder::InitEncoder(bool reverseDirection, EncodingType encodingType) { + m_table = NULL; + m_encodingType = encodingType; + m_index = 0; + switch (encodingType) { + case k4X: { + m_encodingScale = 4; + if (m_aSource->StatusIsFatal()) { + CloneError(m_aSource); + return; + } + if (m_bSource->StatusIsFatal()) { + CloneError(m_bSource); + return; + } + int32_t status = 0; + m_encoder = initializeEncoder( + m_aSource->GetModuleForRouting(), m_aSource->GetChannelForRouting(), + m_aSource->GetAnalogTriggerForRouting(), + m_bSource->GetModuleForRouting(), m_bSource->GetChannelForRouting(), + m_bSource->GetAnalogTriggerForRouting(), reverseDirection, &m_index, + &status); + wpi_setErrorWithContext(status, getHALErrorMessage(status)); + m_counter = NULL; + SetMaxPeriod(.5); + break; + } + case k1X: + case k2X: { + m_encodingScale = encodingType == k1X ? 1 : 2; + m_counter = + new Counter(m_encodingType, m_aSource, m_bSource, reverseDirection); + m_index = m_counter->GetFPGAIndex(); + break; + } + default: + wpi_setErrorWithContext(-1, "Invalid encodingType argument"); + break; + } + m_distancePerPulse = 1.0; + m_pidSource = kDistance; - HALReport(HALUsageReporting::kResourceType_Encoder, m_index, encodingType); - LiveWindow::GetInstance()->AddSensor("Encoder", m_aSource->GetChannelForRouting(), this); + HALReport(HALUsageReporting::kResourceType_Encoder, m_index, encodingType); + LiveWindow::GetInstance()->AddSensor("Encoder", + m_aSource->GetChannelForRouting(), this); } /** @@ -80,106 +83,120 @@ void Encoder::InitEncoder(bool reverseDirection, EncodingType encodingType) * * The counter will start counting immediately. * - * @param aChannel The a channel DIO channel. 0-9 are on-board, 10-25 are on the MXP port - * @param bChannel The b channel DIO channel. 0-9 are on-board, 10-25 are on the MXP port - * @param reverseDirection represents the orientation of the encoder and inverts the output values + * @param aChannel The a channel DIO channel. 0-9 are on-board, 10-25 are on the + * MXP port + * @param bChannel The b channel DIO channel. 0-9 are on-board, 10-25 are on the + * MXP port + * @param reverseDirection represents the orientation of the encoder and inverts + * the output values * if necessary so forward represents positive values. - * @param encodingType either k1X, k2X, or k4X to indicate 1X, 2X or 4X decoding. If 4X is - * selected, then an encoder FPGA object is used and the returned counts will be 4x the encoder - * spec'd value since all rising and falling edges are counted. If 1X or 2X are selected then - * a counter object will be used and the returned value will either exactly match the spec'd count + * @param encodingType either k1X, k2X, or k4X to indicate 1X, 2X or 4X + * decoding. If 4X is + * selected, then an encoder FPGA object is used and the returned counts will be + * 4x the encoder + * spec'd value since all rising and falling edges are counted. If 1X or 2X are + * selected then + * a counter object will be used and the returned value will either exactly + * match the spec'd count * or be double (2x) the spec'd count. */ -Encoder::Encoder(uint32_t aChannel, uint32_t bChannel, bool reverseDirection, EncodingType encodingType) : - m_encoder(NULL), - m_counter(NULL) -{ - m_aSource = new DigitalInput(aChannel); - m_bSource = new DigitalInput(bChannel); - InitEncoder(reverseDirection, encodingType); - m_allocatedASource = true; - m_allocatedBSource = true; +Encoder::Encoder(uint32_t aChannel, uint32_t bChannel, bool reverseDirection, + EncodingType encodingType) + : m_encoder(NULL), m_counter(NULL) { + m_aSource = new DigitalInput(aChannel); + m_bSource = new DigitalInput(bChannel); + InitEncoder(reverseDirection, encodingType); + m_allocatedASource = true; + m_allocatedBSource = true; } /** * Encoder constructor. - * Construct a Encoder given a and b channels as digital inputs. This is used in the case - * where the digital inputs are shared. The Encoder class will not allocate the digital inputs + * Construct a Encoder given a and b channels as digital inputs. This is used in + * the case + * where the digital inputs are shared. The Encoder class will not allocate the + * digital inputs * and assume that they already are counted. * * The counter will start counting immediately. * * @param aSource The source that should be used for the a channel. * @param bSource the source that should be used for the b channel. - * @param reverseDirection represents the orientation of the encoder and inverts the output values + * @param reverseDirection represents the orientation of the encoder and inverts + * the output values * if necessary so forward represents positive values. - * @param encodingType either k1X, k2X, or k4X to indicate 1X, 2X or 4X decoding. If 4X is - * selected, then an encoder FPGA object is used and the returned counts will be 4x the encoder - * spec'd value since all rising and falling edges are counted. If 1X or 2X are selected then - * a counter object will be used and the returned value will either exactly match the spec'd count + * @param encodingType either k1X, k2X, or k4X to indicate 1X, 2X or 4X + * decoding. If 4X is + * selected, then an encoder FPGA object is used and the returned counts will be + * 4x the encoder + * spec'd value since all rising and falling edges are counted. If 1X or 2X are + * selected then + * a counter object will be used and the returned value will either exactly + * match the spec'd count * or be double (2x) the spec'd count. */ -Encoder::Encoder(DigitalSource *aSource, DigitalSource *bSource, bool reverseDirection, EncodingType encodingType) : - m_encoder(NULL), - m_counter(NULL) -{ - m_aSource = aSource; - m_bSource = bSource; - m_allocatedASource = false; - m_allocatedBSource = false; - if (m_aSource == NULL || m_bSource == NULL) - wpi_setWPIError(NullParameter); - else - InitEncoder(reverseDirection, encodingType); +Encoder::Encoder(DigitalSource *aSource, DigitalSource *bSource, + bool reverseDirection, EncodingType encodingType) + : m_encoder(NULL), m_counter(NULL) { + m_aSource = aSource; + m_bSource = bSource; + m_allocatedASource = false; + m_allocatedBSource = false; + if (m_aSource == NULL || m_bSource == NULL) + wpi_setWPIError(NullParameter); + else + InitEncoder(reverseDirection, encodingType); } /** * Encoder constructor. - * Construct a Encoder given a and b channels as digital inputs. This is used in the case - * where the digital inputs are shared. The Encoder class will not allocate the digital inputs + * Construct a Encoder given a and b channels as digital inputs. This is used in + * the case + * where the digital inputs are shared. The Encoder class will not allocate the + * digital inputs * and assume that they already are counted. * * The counter will start counting immediately. * * @param aSource The source that should be used for the a channel. * @param bSource the source that should be used for the b channel. - * @param reverseDirection represents the orientation of the encoder and inverts the output values + * @param reverseDirection represents the orientation of the encoder and inverts + * the output values * if necessary so forward represents positive values. - * @param encodingType either k1X, k2X, or k4X to indicate 1X, 2X or 4X decoding. If 4X is - * selected, then an encoder FPGA object is used and the returned counts will be 4x the encoder - * spec'd value since all rising and falling edges are counted. If 1X or 2X are selected then - * a counter object will be used and the returned value will either exactly match the spec'd count + * @param encodingType either k1X, k2X, or k4X to indicate 1X, 2X or 4X + * decoding. If 4X is + * selected, then an encoder FPGA object is used and the returned counts will be + * 4x the encoder + * spec'd value since all rising and falling edges are counted. If 1X or 2X are + * selected then + * a counter object will be used and the returned value will either exactly + * match the spec'd count * or be double (2x) the spec'd count. */ -Encoder::Encoder(DigitalSource &aSource, DigitalSource &bSource, bool reverseDirection, EncodingType encodingType) : - m_encoder(NULL), - m_counter(NULL) -{ - m_aSource = &aSource; - m_bSource = &bSource; - m_allocatedASource = false; - m_allocatedBSource = false; - InitEncoder(reverseDirection, encodingType); +Encoder::Encoder(DigitalSource &aSource, DigitalSource &bSource, + bool reverseDirection, EncodingType encodingType) + : m_encoder(NULL), m_counter(NULL) { + m_aSource = &aSource; + m_bSource = &bSource; + m_allocatedASource = false; + m_allocatedBSource = false; + InitEncoder(reverseDirection, encodingType); } /** * Free the resources for an Encoder. * Frees the FPGA resources associated with an Encoder. */ -Encoder::~Encoder() -{ - if (m_allocatedASource) delete m_aSource; - if (m_allocatedBSource) delete m_bSource; - if (m_counter) - { - delete m_counter; - } - else - { - int32_t status = 0; - freeEncoder(m_encoder, &status); - wpi_setErrorWithContext(status, getHALErrorMessage(status)); - } +Encoder::~Encoder() { + if (m_allocatedASource) delete m_aSource; + if (m_allocatedBSource) delete m_bSource; + if (m_counter) { + delete m_counter; + } else { + int32_t status = 0; + freeEncoder(m_encoder, &status); + wpi_setErrorWithContext(status, getHALErrorMessage(status)); + } } /** @@ -194,19 +211,17 @@ int32_t Encoder::GetEncodingScale() const { return m_encodingScale; } * factor. * @return Current raw count from the encoder */ -int32_t Encoder::GetRaw() const -{ - if (StatusIsFatal()) return 0; - int32_t value; - if (m_counter) - value = m_counter->Get(); - else - { - int32_t status = 0; - value = getEncoder(m_encoder, &status); - wpi_setErrorWithContext(status, getHALErrorMessage(status)); - } - return value; +int32_t Encoder::GetRaw() const { + if (StatusIsFatal()) return 0; + int32_t value; + if (m_counter) + value = m_counter->Get(); + else { + int32_t status = 0; + value = getEncoder(m_encoder, &status); + wpi_setErrorWithContext(status, getHALErrorMessage(status)); + } + return value; } /** @@ -214,29 +229,27 @@ int32_t Encoder::GetRaw() const * Returns the current count on the Encoder. * This method compensates for the decoding type. * - * @return Current count from the Encoder adjusted for the 1x, 2x, or 4x scale factor. + * @return Current count from the Encoder adjusted for the 1x, 2x, or 4x scale + * factor. */ -int32_t Encoder::Get() const -{ - if (StatusIsFatal()) return 0; - return (int32_t) (GetRaw() * DecodingScaleFactor()); +int32_t Encoder::Get() const { + if (StatusIsFatal()) return 0; + return (int32_t)(GetRaw() * DecodingScaleFactor()); } /** * Reset the Encoder distance to zero. * Resets the current count to zero on the encoder. */ -void Encoder::Reset() -{ - if (StatusIsFatal()) return; - if (m_counter) - m_counter->Reset(); - else - { - int32_t status = 0; - resetEncoder(m_encoder, &status); - wpi_setErrorWithContext(status, getHALErrorMessage(status)); - } +void Encoder::Reset() { + if (StatusIsFatal()) return; + if (m_counter) + m_counter->Reset(); + else { + int32_t status = 0; + resetEncoder(m_encoder, &status); + wpi_setErrorWithContext(status, getHALErrorMessage(status)); + } } /** @@ -244,248 +257,234 @@ void Encoder::Reset() * Returns the period of the most recent Encoder pulse in seconds. * This method compensates for the decoding type. * - * @deprecated Use GetRate() in favor of this method. This returns unscaled periods and GetRate() scales using value from SetDistancePerPulse(). + * @deprecated Use GetRate() in favor of this method. This returns unscaled + * periods and GetRate() scales using value from SetDistancePerPulse(). * * @return Period in seconds of the most recent pulse. */ -double Encoder::GetPeriod() const -{ - if (StatusIsFatal()) return 0.0; - if (m_counter) - { - return m_counter->GetPeriod() / DecodingScaleFactor(); - } - else - { - int32_t status = 0; - double period = getEncoderPeriod(m_encoder, &status); - wpi_setErrorWithContext(status, getHALErrorMessage(status)); - return period; - } - +double Encoder::GetPeriod() const { + if (StatusIsFatal()) return 0.0; + if (m_counter) { + return m_counter->GetPeriod() / DecodingScaleFactor(); + } else { + int32_t status = 0; + double period = getEncoderPeriod(m_encoder, &status); + wpi_setErrorWithContext(status, getHALErrorMessage(status)); + return period; + } } /** * Sets the maximum period for stopped detection. - * Sets the value that represents the maximum period of the Encoder before it will assume - * that the attached device is stopped. This timeout allows users to determine if the wheels or + * Sets the value that represents the maximum period of the Encoder before it + * will assume + * that the attached device is stopped. This timeout allows users to determine + * if the wheels or * other shaft has stopped rotating. * This method compensates for the decoding type. * - * @deprecated Use SetMinRate() in favor of this method. This takes unscaled periods and SetMinRate() scales using value from SetDistancePerPulse(). + * @deprecated Use SetMinRate() in favor of this method. This takes unscaled + * periods and SetMinRate() scales using value from SetDistancePerPulse(). * - * @param maxPeriod The maximum time between rising and falling edges before the FPGA will + * @param maxPeriod The maximum time between rising and falling edges before the + * FPGA will * report the device stopped. This is expressed in seconds. */ -void Encoder::SetMaxPeriod(double maxPeriod) -{ - if (StatusIsFatal()) return; - if (m_counter) - { - m_counter->SetMaxPeriod(maxPeriod * DecodingScaleFactor()); - } - else - { - int32_t status = 0; - setEncoderMaxPeriod(m_encoder, maxPeriod, &status); - wpi_setErrorWithContext(status, getHALErrorMessage(status)); - } +void Encoder::SetMaxPeriod(double maxPeriod) { + if (StatusIsFatal()) return; + if (m_counter) { + m_counter->SetMaxPeriod(maxPeriod * DecodingScaleFactor()); + } else { + int32_t status = 0; + setEncoderMaxPeriod(m_encoder, maxPeriod, &status); + wpi_setErrorWithContext(status, getHALErrorMessage(status)); + } } /** * Determine if the encoder is stopped. - * Using the MaxPeriod value, a boolean is returned that is true if the encoder is considered - * stopped and false if it is still moving. A stopped encoder is one where the most recent pulse + * Using the MaxPeriod value, a boolean is returned that is true if the encoder + * is considered + * stopped and false if it is still moving. A stopped encoder is one where the + * most recent pulse * width exceeds the MaxPeriod. * @return True if the encoder is considered stopped. */ -bool Encoder::GetStopped() const -{ - if (StatusIsFatal()) return true; - if (m_counter) - { - return m_counter->GetStopped(); - } - else - { - int32_t status = 0; - bool value = getEncoderStopped(m_encoder, &status); - wpi_setErrorWithContext(status, getHALErrorMessage(status)); - return value; - } +bool Encoder::GetStopped() const { + if (StatusIsFatal()) return true; + if (m_counter) { + return m_counter->GetStopped(); + } else { + int32_t status = 0; + bool value = getEncoderStopped(m_encoder, &status); + wpi_setErrorWithContext(status, getHALErrorMessage(status)); + return value; + } } /** * The last direction the encoder value changed. * @return The last direction the encoder value changed. */ -bool Encoder::GetDirection() const -{ - if (StatusIsFatal()) return false; - if (m_counter) - { - return m_counter->GetDirection(); - } - else - { - int32_t status = 0; - bool value = getEncoderDirection(m_encoder, &status); - wpi_setErrorWithContext(status, getHALErrorMessage(status)); - return value; - } +bool Encoder::GetDirection() const { + if (StatusIsFatal()) return false; + if (m_counter) { + return m_counter->GetDirection(); + } else { + int32_t status = 0; + bool value = getEncoderDirection(m_encoder, &status); + wpi_setErrorWithContext(status, getHALErrorMessage(status)); + return value; + } } /** - * The scale needed to convert a raw counter value into a number of encoder pulses. + * The scale needed to convert a raw counter value into a number of encoder + * pulses. */ -double Encoder::DecodingScaleFactor() const -{ - if (StatusIsFatal()) return 0.0; - switch (m_encodingType) - { - case k1X: - return 1.0; - case k2X: - return 0.5; - case k4X: - return 0.25; - default: - return 0.0; - } +double Encoder::DecodingScaleFactor() const { + if (StatusIsFatal()) return 0.0; + switch (m_encodingType) { + case k1X: + return 1.0; + case k2X: + return 0.5; + case k4X: + return 0.25; + default: + return 0.0; + } } /** * Get the distance the robot has driven since the last reset. * - * @return The distance driven since the last reset as scaled by the value from SetDistancePerPulse(). + * @return The distance driven since the last reset as scaled by the value from + * SetDistancePerPulse(). */ -double Encoder::GetDistance() const -{ - if (StatusIsFatal()) return 0.0; - return GetRaw() * DecodingScaleFactor() * m_distancePerPulse; +double Encoder::GetDistance() const { + if (StatusIsFatal()) return 0.0; + return GetRaw() * DecodingScaleFactor() * m_distancePerPulse; } /** * Get the current rate of the encoder. - * Units are distance per second as scaled by the value from SetDistancePerPulse(). + * Units are distance per second as scaled by the value from + * SetDistancePerPulse(). * * @return The current rate of the encoder. */ -double Encoder::GetRate() const -{ - if (StatusIsFatal()) return 0.0; - return (m_distancePerPulse / GetPeriod()); +double Encoder::GetRate() const { + if (StatusIsFatal()) return 0.0; + return (m_distancePerPulse / GetPeriod()); } /** * Set the minimum rate of the device before the hardware reports it stopped. * - * @param minRate The minimum rate. The units are in distance per second as scaled by the value from SetDistancePerPulse(). + * @param minRate The minimum rate. The units are in distance per second as + * scaled by the value from SetDistancePerPulse(). */ -void Encoder::SetMinRate(double minRate) -{ - if (StatusIsFatal()) return; - SetMaxPeriod(m_distancePerPulse / minRate); +void Encoder::SetMinRate(double minRate) { + if (StatusIsFatal()) return; + SetMaxPeriod(m_distancePerPulse / minRate); } /** * Set the distance per pulse for this encoder. - * This sets the multiplier used to determine the distance driven based on the count value + * This sets the multiplier used to determine the distance driven based on the + * count value * from the encoder. - * Do not include the decoding type in this scale. The library already compensates for the decoding type. + * Do not include the decoding type in this scale. The library already + * compensates for the decoding type. * Set this value based on the encoder's rated Pulses per Revolution and * factor in gearing reductions following the encoder shaft. * This distance can be in any units you like, linear or angular. * - * @param distancePerPulse The scale factor that will be used to convert pulses to useful units. + * @param distancePerPulse The scale factor that will be used to convert pulses + * to useful units. */ -void Encoder::SetDistancePerPulse(double distancePerPulse) -{ - if (StatusIsFatal()) return; - m_distancePerPulse = distancePerPulse; +void Encoder::SetDistancePerPulse(double distancePerPulse) { + if (StatusIsFatal()) return; + m_distancePerPulse = distancePerPulse; } /** * Set the direction sensing for this encoder. - * This sets the direction sensing on the encoder so that it could count in the correct + * This sets the direction sensing on the encoder so that it could count in the + * correct * software direction regardless of the mounting. * @param reverseDirection true if the encoder direction should be reversed */ -void Encoder::SetReverseDirection(bool reverseDirection) -{ - if (StatusIsFatal()) return; - if (m_counter) - { - m_counter->SetReverseDirection(reverseDirection); - } - else - { - int32_t status = 0; - setEncoderReverseDirection(m_encoder, reverseDirection, &status); - wpi_setErrorWithContext(status, getHALErrorMessage(status)); - } +void Encoder::SetReverseDirection(bool reverseDirection) { + if (StatusIsFatal()) return; + if (m_counter) { + m_counter->SetReverseDirection(reverseDirection); + } else { + int32_t status = 0; + setEncoderReverseDirection(m_encoder, reverseDirection, &status); + wpi_setErrorWithContext(status, getHALErrorMessage(status)); + } } - /** - * Set the Samples to Average which specifies the number of samples of the timer to + * Set the Samples to Average which specifies the number of samples of the timer + * to * average when calculating the period. Perform averaging to account for * mechanical imperfections or as oversampling to increase resolution. * @param samplesToAverage The number of samples to average from 1 to 127. */ -void Encoder::SetSamplesToAverage(int samplesToAverage) -{ - if (samplesToAverage < 1 || samplesToAverage > 127) - { - wpi_setWPIErrorWithContext(ParameterOutOfRange, "Average counter values must be between 1 and 127"); - } - int32_t status = 0; - switch (m_encodingType) { - case k4X: - setEncoderSamplesToAverage(m_encoder, samplesToAverage, &status); - wpi_setErrorWithContext(status, getHALErrorMessage(status)); - break; - case k1X: - case k2X: - m_counter->SetSamplesToAverage(samplesToAverage); - break; - } +void Encoder::SetSamplesToAverage(int samplesToAverage) { + if (samplesToAverage < 1 || samplesToAverage > 127) { + wpi_setWPIErrorWithContext( + ParameterOutOfRange, + "Average counter values must be between 1 and 127"); + } + int32_t status = 0; + switch (m_encodingType) { + case k4X: + setEncoderSamplesToAverage(m_encoder, samplesToAverage, &status); + wpi_setErrorWithContext(status, getHALErrorMessage(status)); + break; + case k1X: + case k2X: + m_counter->SetSamplesToAverage(samplesToAverage); + break; + } } /** - * Get the Samples to Average which specifies the number of samples of the timer to + * Get the Samples to Average which specifies the number of samples of the timer + * to * average when calculating the period. Perform averaging to account for * mechanical imperfections or as oversampling to increase resolution. * @return SamplesToAverage The number of samples being averaged (from 1 to 127) */ -int Encoder::GetSamplesToAverage() const -{ - int result = 1; - int32_t status = 0; - switch (m_encodingType) { - case k4X: - result = getEncoderSamplesToAverage(m_encoder, &status); - wpi_setErrorWithContext(status, getHALErrorMessage(status)); - break; - case k1X: - case k2X: - result = m_counter->GetSamplesToAverage(); - break; - } - return result; +int Encoder::GetSamplesToAverage() const { + int result = 1; + int32_t status = 0; + switch (m_encodingType) { + case k4X: + result = getEncoderSamplesToAverage(m_encoder, &status); + wpi_setErrorWithContext(status, getHALErrorMessage(status)); + break; + case k1X: + case k2X: + result = m_counter->GetSamplesToAverage(); + break; + } + return result; } - - /** - * Set which parameter of the encoder you are using as a process control variable. + * Set which parameter of the encoder you are using as a process control + * variable. * * @param pidSource An enum to select the parameter. */ -void Encoder::SetPIDSourceParameter(PIDSourceParameter pidSource) -{ - if (StatusIsFatal()) return; - m_pidSource = pidSource; +void Encoder::SetPIDSourceParameter(PIDSourceParameter pidSource) { + if (StatusIsFatal()) return; + m_pidSource = pidSource; } /** @@ -493,89 +492,90 @@ void Encoder::SetPIDSourceParameter(PIDSourceParameter pidSource) * * @return The current value of the selected source parameter. */ -double Encoder::PIDGet() const -{ - if (StatusIsFatal()) return 0.0; - switch (m_pidSource) - { - case kDistance: - return GetDistance(); - case kRate: - return GetRate(); - default: - return 0.0; - } +double Encoder::PIDGet() const { + if (StatusIsFatal()) return 0.0; + switch (m_pidSource) { + case kDistance: + return GetDistance(); + case kRate: + return GetRate(); + default: + return 0.0; + } } /** - * Set the index source for the encoder. When this source is activated, the encoder count automatically resets. + * Set the index source for the encoder. When this source is activated, the + * encoder count automatically resets. * * @param channel A DIO channel to set as the encoder index * @param type The state that will cause the encoder to reset */ void Encoder::SetIndexSource(uint32_t channel, Encoder::IndexingType type) { - int32_t status = 0; - bool activeHigh = (type == kResetWhileHigh) || (type == kResetOnRisingEdge); - bool edgeSensitive = (type == kResetOnFallingEdge) || (type == kResetOnRisingEdge); + int32_t status = 0; + bool activeHigh = (type == kResetWhileHigh) || (type == kResetOnRisingEdge); + bool edgeSensitive = + (type == kResetOnFallingEdge) || (type == kResetOnRisingEdge); - setEncoderIndexSource(m_encoder, channel, false, activeHigh, edgeSensitive, &status); + setEncoderIndexSource(m_encoder, channel, false, activeHigh, edgeSensitive, + &status); wpi_setGlobalErrorWithContext(status, getHALErrorMessage(status)); } /** - * Set the index source for the encoder. When this source is activated, the encoder count automatically resets. + * Set the index source for the encoder. When this source is activated, the + * encoder count automatically resets. * * @param channel A digital source to set as the encoder index * @param type The state that will cause the encoder to reset */ -void Encoder::SetIndexSource(DigitalSource *source, Encoder::IndexingType type) { - int32_t status = 0; - bool activeHigh = (type == kResetWhileHigh) || (type == kResetOnRisingEdge); - bool edgeSensitive = (type == kResetOnFallingEdge) || (type == kResetOnRisingEdge); +void Encoder::SetIndexSource(DigitalSource *source, + Encoder::IndexingType type) { + int32_t status = 0; + bool activeHigh = (type == kResetWhileHigh) || (type == kResetOnRisingEdge); + bool edgeSensitive = + (type == kResetOnFallingEdge) || (type == kResetOnRisingEdge); - setEncoderIndexSource(m_encoder, source->GetChannelForRouting(), source->GetAnalogTriggerForRouting(), activeHigh, - edgeSensitive, &status); + setEncoderIndexSource(m_encoder, source->GetChannelForRouting(), + source->GetAnalogTriggerForRouting(), activeHigh, + edgeSensitive, &status); wpi_setGlobalErrorWithContext(status, getHALErrorMessage(status)); } /** - * Set the index source for the encoder. When this source is activated, the encoder count automatically resets. + * Set the index source for the encoder. When this source is activated, the + * encoder count automatically resets. * * @param channel A digital source to set as the encoder index * @param type The state that will cause the encoder to reset */ -void Encoder::SetIndexSource(DigitalSource &source, Encoder::IndexingType type) { - SetIndexSource(&source, type); +void Encoder::SetIndexSource(DigitalSource &source, + Encoder::IndexingType type) { + SetIndexSource(&source, type); } void Encoder::UpdateTable() { - if (m_table != NULL) { - m_table->PutNumber("Speed", GetRate()); - m_table->PutNumber("Distance", GetDistance()); - m_table->PutNumber("Distance per Tick", m_distancePerPulse); - } + if (m_table != NULL) { + m_table->PutNumber("Speed", GetRate()); + m_table->PutNumber("Distance", GetDistance()); + m_table->PutNumber("Distance per Tick", m_distancePerPulse); + } } -void Encoder::StartLiveWindowMode() { +void Encoder::StartLiveWindowMode() {} -} - -void Encoder::StopLiveWindowMode() { - -} +void Encoder::StopLiveWindowMode() {} std::string Encoder::GetSmartDashboardType() const { - if (m_encodingType == k4X) - return "Quadrature Encoder"; - else - return "Encoder"; + if (m_encodingType == k4X) + return "Quadrature Encoder"; + else + return "Encoder"; } void Encoder::InitTable(ITable *subTable) { - m_table = subTable; - UpdateTable(); + m_table = subTable; + UpdateTable(); } -ITable * Encoder::GetTable() const { - return m_table; -} +ITable *Encoder::GetTable() const { return m_table; } diff --git a/wpilibc/wpilibC++Devices/src/GearTooth.cpp b/wpilibc/wpilibC++Devices/src/GearTooth.cpp index 6a1fd829b1..adc1fd8d83 100644 --- a/wpilibc/wpilibC++Devices/src/GearTooth.cpp +++ b/wpilibc/wpilibC++Devices/src/GearTooth.cpp @@ -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,60 +13,57 @@ constexpr double GearTooth::kGearToothThreshold; /** * Common code called by the constructors. */ -void GearTooth::EnableDirectionSensing(bool directionSensitive) -{ - if (directionSensitive) - { - SetPulseLengthMode(kGearToothThreshold); - } +void GearTooth::EnableDirectionSensing(bool directionSensitive) { + if (directionSensitive) { + SetPulseLengthMode(kGearToothThreshold); + } } /** * Construct a GearTooth sensor given a channel. * - * @param channel The DIO channel that the sensor is connected to. 0-9 are on-board, 10-25 are on the MXP. - * @param directionSensitive True to enable the pulse length decoding in hardware to specify count direction. + * @param channel The DIO channel that the sensor is connected to. 0-9 are + * on-board, 10-25 are on the MXP. + * @param directionSensitive True to enable the pulse length decoding in + * hardware to specify count direction. */ GearTooth::GearTooth(uint32_t channel, bool directionSensitive) - : Counter(channel) -{ - EnableDirectionSensing(directionSensitive); - LiveWindow::GetInstance()->AddSensor("GearTooth", channel, this); + : Counter(channel) { + EnableDirectionSensing(directionSensitive); + LiveWindow::GetInstance()->AddSensor("GearTooth", channel, this); } /** * Construct a GearTooth sensor given a digital input. * This should be used when sharing digital inputs. * - * @param source A pointer to the existing DigitalSource object (such as a DigitalInput) - * @param directionSensitive True to enable the pulse length decoding in hardware to specify count direction. + * @param source A pointer to the existing DigitalSource object (such as a + * DigitalInput) + * @param directionSensitive True to enable the pulse length decoding in + * hardware to specify count direction. */ GearTooth::GearTooth(DigitalSource *source, bool directionSensitive) - : Counter(source) -{ - EnableDirectionSensing(directionSensitive); + : Counter(source) { + EnableDirectionSensing(directionSensitive); } /** * Construct a GearTooth sensor given a digital input. * This should be used when sharing digital inputs. * - * @param source A reference to the existing DigitalSource object (such as a DigitalInput) - * @param directionSensitive True to enable the pulse length decoding in hardware to specify count direction. + * @param source A reference to the existing DigitalSource object (such as a + * DigitalInput) + * @param directionSensitive True to enable the pulse length decoding in + * hardware to specify count direction. */ -GearTooth::GearTooth(DigitalSource &source, bool directionSensitive): Counter(source) -{ - EnableDirectionSensing(directionSensitive); +GearTooth::GearTooth(DigitalSource &source, bool directionSensitive) + : Counter(source) { + EnableDirectionSensing(directionSensitive); } /** * Free the resources associated with a gear tooth sensor. */ -GearTooth::~GearTooth() -{ -} +GearTooth::~GearTooth() {} - -std::string GearTooth::GetSmartDashboardType() const { - return "GearTooth"; -} +std::string GearTooth::GetSmartDashboardType() const { return "GearTooth"; } diff --git a/wpilibc/wpilibC++Devices/src/Gyro.cpp b/wpilibc/wpilibC++Devices/src/Gyro.cpp index a023bef2dd..becfb6156e 100644 --- a/wpilibc/wpilibC++Devices/src/Gyro.cpp +++ b/wpilibc/wpilibC++Devices/src/Gyro.cpp @@ -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,149 +20,147 @@ constexpr float Gyro::kDefaultVoltsPerDegreePerSecond; /** * Initialize the gyro. - * Calibrate the gyro by running for a number of samples and computing the center value. - * Then use the center value as the Accumulator center value for subsequent measurements. - * It's important to make sure that the robot is not moving while the centering calculations are - * in progress, this is typically done when the robot is first turned on while it's sitting at + * Calibrate the gyro by running for a number of samples and computing the + * center value. + * Then use the center value as the Accumulator center value for subsequent + * measurements. + * It's important to make sure that the robot is not moving while the centering + * calculations are + * in progress, this is typically done when the robot is first turned on while + * it's sitting at * rest before the competition starts. */ -void Gyro::InitGyro() -{ - m_table = NULL; - if (!m_analog->IsAccumulatorChannel()) - { - wpi_setWPIErrorWithContext(ParameterOutOfRange, - " channel (must be accumulator channel)"); - if (m_channelAllocated) - { - delete m_analog; - m_analog = NULL; - } - return; - } +void Gyro::InitGyro() { + m_table = NULL; + if (!m_analog->IsAccumulatorChannel()) { + wpi_setWPIErrorWithContext(ParameterOutOfRange, + " channel (must be accumulator channel)"); + if (m_channelAllocated) { + delete m_analog; + m_analog = NULL; + } + return; + } - m_voltsPerDegreePerSecond = kDefaultVoltsPerDegreePerSecond; - m_analog->SetAverageBits(kAverageBits); - m_analog->SetOversampleBits(kOversampleBits); - float sampleRate = kSamplesPerSecond * - (1 << (kAverageBits + kOversampleBits)); - m_analog->SetSampleRate(sampleRate); - Wait(1.0); + m_voltsPerDegreePerSecond = kDefaultVoltsPerDegreePerSecond; + m_analog->SetAverageBits(kAverageBits); + m_analog->SetOversampleBits(kOversampleBits); + float sampleRate = + kSamplesPerSecond * (1 << (kAverageBits + kOversampleBits)); + m_analog->SetSampleRate(sampleRate); + Wait(1.0); - m_analog->InitAccumulator(); + m_analog->InitAccumulator(); - Wait(kCalibrationSampleTime); + Wait(kCalibrationSampleTime); - int64_t value; - uint32_t count; - m_analog->GetAccumulatorOutput(&value, &count); + int64_t value; + uint32_t count; + m_analog->GetAccumulatorOutput(&value, &count); - m_center = (uint32_t)((float)value / (float)count + .5); + m_center = (uint32_t)((float)value / (float)count + .5); - m_offset = ((float)value / (float)count) - (float)m_center; - m_analog->SetAccumulatorCenter(m_center); - m_analog->ResetAccumulator(); + m_offset = ((float)value / (float)count) - (float)m_center; + m_analog->SetAccumulatorCenter(m_center); + m_analog->ResetAccumulator(); - SetDeadband(0.0f); + SetDeadband(0.0f); - SetPIDSourceParameter(kAngle); + SetPIDSourceParameter(kAngle); - HALReport(HALUsageReporting::kResourceType_Gyro, m_analog->GetChannel()); - LiveWindow::GetInstance()->AddSensor("Gyro", m_analog->GetChannel(), this); + HALReport(HALUsageReporting::kResourceType_Gyro, m_analog->GetChannel()); + LiveWindow::GetInstance()->AddSensor("Gyro", m_analog->GetChannel(), this); } /** * Gyro constructor using the Analog Input channel number. * - * @param channel The analog channel the gyro is connected to. Gyros - can only be used on on-board Analog Inputs 0-1. + * @param channel The analog channel the gyro is connected to. Gyros + can only be used on on-board Analog Inputs 0-1. */ -Gyro::Gyro(int32_t channel) -{ - m_analog = new AnalogInput(channel); - m_channelAllocated = true; - InitGyro(); +Gyro::Gyro(int32_t channel) { + m_analog = new AnalogInput(channel); + m_channelAllocated = true; + InitGyro(); } /** * Gyro constructor with a precreated AnalogInput object. * Use this constructor when the analog channel needs to be shared. - * This object will not clean up the AnalogInput object when using this constructor. + * This object will not clean up the AnalogInput object when using this + * constructor. * Gyros can only be used on on-board channels 0-1. - * @param channel A pointer to the AnalogInput object that the gyro is connected to. + * @param channel A pointer to the AnalogInput object that the gyro is connected + * to. */ -Gyro::Gyro(AnalogInput *channel) -{ - m_analog = channel; - m_channelAllocated = false; - if (channel == NULL) - { - wpi_setWPIError(NullParameter); - } - else - { - InitGyro(); - } +Gyro::Gyro(AnalogInput *channel) { + m_analog = channel; + m_channelAllocated = false; + if (channel == NULL) { + wpi_setWPIError(NullParameter); + } else { + InitGyro(); + } } /** * Gyro constructor with a precreated AnalogInput object. * Use this constructor when the analog channel needs to be shared. - * This object will not clean up the AnalogInput object when using this constructor - * @param channel A reference to the AnalogInput object that the gyro is connected to. + * This object will not clean up the AnalogInput object when using this + * constructor + * @param channel A reference to the AnalogInput object that the gyro is + * connected to. */ -Gyro::Gyro(AnalogInput &channel) -{ - m_analog = &channel; - m_channelAllocated = false; - InitGyro(); +Gyro::Gyro(AnalogInput &channel) { + m_analog = &channel; + m_channelAllocated = false; + InitGyro(); } /** * Reset the gyro. - * Resets the gyro to a heading of zero. This can be used if there is significant + * Resets the gyro to a heading of zero. This can be used if there is + * significant * drift in the gyro and it needs to be recalibrated after it has been running. */ -void Gyro::Reset() -{ - m_analog->ResetAccumulator(); -} +void Gyro::Reset() { m_analog->ResetAccumulator(); } /** * Delete (free) the accumulator and the analog components used for the gyro. */ -Gyro::~Gyro() -{ - if (m_channelAllocated) - delete m_analog; +Gyro::~Gyro() { + if (m_channelAllocated) delete m_analog; } /** * Return the actual angle in degrees that the robot is currently facing. * - * The angle is based on the current accumulator value corrected by the oversampling rate, the + * The angle is based on the current accumulator value corrected by the + * oversampling rate, the * gyro type and the A/D calibration values. - * The angle is continuous, that is it will continue from 360->361 degrees. This allows algorithms that wouldn't - * want to see a discontinuity in the gyro output as it sweeps from 360 to 0 on the second time around. + * The angle is continuous, that is it will continue from 360->361 degrees. This + * allows algorithms that wouldn't + * want to see a discontinuity in the gyro output as it sweeps from 360 to 0 on + * the second time around. * - * @return the current heading of the robot in degrees. This heading is based on integration + * @return the current heading of the robot in degrees. This heading is based on + * integration * of the returned rate from the gyro. */ -float Gyro::GetAngle() const -{ - int64_t rawValue; - uint32_t count; - m_analog->GetAccumulatorOutput(&rawValue, &count); +float Gyro::GetAngle() const { + int64_t rawValue; + uint32_t count; + m_analog->GetAccumulatorOutput(&rawValue, &count); - int64_t value = rawValue - (int64_t)((float)count * m_offset); + int64_t value = rawValue - (int64_t)((float)count * m_offset); - double scaledValue = value * 1e-9 * (double)m_analog->GetLSBWeight() * (double)(1 << m_analog->GetAverageBits()) / - (m_analog->GetSampleRate() * m_voltsPerDegreePerSecond); + double scaledValue = value * 1e-9 * (double)m_analog->GetLSBWeight() * + (double)(1 << m_analog->GetAverageBits()) / + (m_analog->GetSampleRate() * m_voltsPerDegreePerSecond); - return (float)scaledValue; + return (float)scaledValue; } - /** * Return the rate of rotation of the gyro * @@ -169,24 +168,24 @@ float Gyro::GetAngle() const * * @return the current rate in degrees per second */ -double Gyro::GetRate() const -{ - return (m_analog->GetAverageValue() - ((double)m_center + m_offset)) * 1e-9 * m_analog->GetLSBWeight() - / ((1 << m_analog->GetOversampleBits()) * m_voltsPerDegreePerSecond); +double Gyro::GetRate() const { + return (m_analog->GetAverageValue() - ((double)m_center + m_offset)) * 1e-9 * + m_analog->GetLSBWeight() / + ((1 << m_analog->GetOversampleBits()) * m_voltsPerDegreePerSecond); } - /** * Set the gyro sensitivity. - * This takes the number of volts/degree/second sensitivity of the gyro and uses it in subsequent - * calculations to allow the code to work with multiple gyros. This value is typically found in + * This takes the number of volts/degree/second sensitivity of the gyro and uses + * it in subsequent + * calculations to allow the code to work with multiple gyros. This value is + * typically found in * the gyro datasheet. * * @param voltsPerDegreePerSecond The sensitivity in Volts/degree/second */ -void Gyro::SetSensitivity( float voltsPerDegreePerSecond ) -{ - m_voltsPerDegreePerSecond = voltsPerDegreePerSecond; +void Gyro::SetSensitivity(float voltsPerDegreePerSecond) { + m_voltsPerDegreePerSecond = voltsPerDegreePerSecond; } /** @@ -197,21 +196,20 @@ void Gyro::SetSensitivity( float voltsPerDegreePerSecond ) * * @param volts The size of the deadband in volts */ -void Gyro::SetDeadband( float volts ) { - int32_t deadband = volts * 1e9 / m_analog->GetLSBWeight() * (1 << m_analog->GetOversampleBits()); - m_analog->SetAccumulatorDeadband(deadband); +void Gyro::SetDeadband(float volts) { + int32_t deadband = volts * 1e9 / m_analog->GetLSBWeight() * + (1 << m_analog->GetOversampleBits()); + m_analog->SetAccumulatorDeadband(deadband); } - /** * Sets the type of output to use with the WPILib PID class * The gyro supports using either rate or angle for PID calculations */ -void Gyro::SetPIDSourceParameter(PIDSourceParameter pidSource) -{ - if(pidSource == 0 || pidSource > 2) - wpi_setWPIErrorWithContext(ParameterOutOfRange, "Gyro pidSource"); - m_pidSource = pidSource; +void Gyro::SetPIDSourceParameter(PIDSourceParameter pidSource) { + if (pidSource == 0 || pidSource > 2) + wpi_setWPIErrorWithContext(ParameterOutOfRange, "Gyro pidSource"); + m_pidSource = pidSource; } /** @@ -220,41 +218,32 @@ void Gyro::SetPIDSourceParameter(PIDSourceParameter pidSource) * * @return The PIDOutput (angle or rate, defaults to angle) */ -double Gyro::PIDGet() const -{ - switch(m_pidSource){ - case kRate: - return GetRate(); - case kAngle: - return GetAngle(); - default: - return 0; - } +double Gyro::PIDGet() const { + switch (m_pidSource) { + case kRate: + return GetRate(); + case kAngle: + return GetAngle(); + default: + return 0; + } } void Gyro::UpdateTable() { - if (m_table != NULL) { - m_table->PutNumber("Value", GetAngle()); - } + if (m_table != NULL) { + m_table->PutNumber("Value", GetAngle()); + } } -void Gyro::StartLiveWindowMode() { +void Gyro::StartLiveWindowMode() {} -} +void Gyro::StopLiveWindowMode() {} -void Gyro::StopLiveWindowMode() { - -} - -std::string Gyro::GetSmartDashboardType() const { - return "Gyro"; -} +std::string Gyro::GetSmartDashboardType() const { return "Gyro"; } void Gyro::InitTable(ITable *subTable) { - m_table = subTable; - UpdateTable(); + m_table = subTable; + UpdateTable(); } -ITable * Gyro::GetTable() const { - return m_table; -} +ITable *Gyro::GetTable() const { return m_table; } diff --git a/wpilibc/wpilibC++Devices/src/I2C.cpp b/wpilibc/wpilibC++Devices/src/I2C.cpp index 19e3f4f7a3..50c3ea71c9 100644 --- a/wpilibc/wpilibC++Devices/src/I2C.cpp +++ b/wpilibc/wpilibC++Devices/src/I2C.cpp @@ -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,29 +16,25 @@ * @param port The I2C port to which the device is connected. * @param deviceAddress The address of the device on the I2C bus. */ -I2C::I2C(Port port, uint8_t deviceAddress) : - m_port (port) - , m_deviceAddress (deviceAddress) -{ - int32_t status = 0; - i2CInitialize(m_port, &status); - //wpi_setErrorWithContext(status, getHALErrorMessage(status)); +I2C::I2C(Port port, uint8_t deviceAddress) + : m_port(port), m_deviceAddress(deviceAddress) { + int32_t status = 0; + i2CInitialize(m_port, &status); + // wpi_setErrorWithContext(status, getHALErrorMessage(status)); - HALReport(HALUsageReporting::kResourceType_I2C, deviceAddress); + HALReport(HALUsageReporting::kResourceType_I2C, deviceAddress); } /** * Destructor. */ -I2C::~I2C() -{ - i2CClose(m_port); -} +I2C::~I2C() { i2CClose(m_port); } /** * Generic transaction. * - * This is a lower-level interface to the I2C hardware giving you more control over each transaction. + * This is a lower-level interface to the I2C hardware giving you more control + * over each transaction. * * @param dataToSend Buffer of data to send as part of the transaction. * @param sendSize Number of bytes to send as part of the transaction. [0..6] @@ -45,24 +42,24 @@ I2C::~I2C() * @param receiveSize Number of bytes to read from the device. [0..7] * @return Transfer Aborted... false for success, true for aborted. */ -bool I2C::Transaction(uint8_t *dataToSend, uint8_t sendSize, uint8_t *dataReceived, uint8_t receiveSize) -{ - if (sendSize > 6) // Optional, provides better error message. - { - wpi_setWPIErrorWithContext(ParameterOutOfRange, "sendSize"); - return true; - } - if (receiveSize > 7) // Optional, provides better error message. - { - wpi_setWPIErrorWithContext(ParameterOutOfRange, "receiveSize"); - return true; - } +bool I2C::Transaction(uint8_t *dataToSend, uint8_t sendSize, + uint8_t *dataReceived, uint8_t receiveSize) { + if (sendSize > 6) // Optional, provides better error message. + { + wpi_setWPIErrorWithContext(ParameterOutOfRange, "sendSize"); + return true; + } + if (receiveSize > 7) // Optional, provides better error message. + { + wpi_setWPIErrorWithContext(ParameterOutOfRange, "receiveSize"); + return true; + } - int32_t status = 0; - status = i2CTransaction(m_port, m_deviceAddress, - dataToSend, sendSize, dataReceived, receiveSize); - //wpi_setErrorWithContext(status, getHALErrorMessage(status)); - return status < 0; + int32_t status = 0; + status = i2CTransaction(m_port, m_deviceAddress, dataToSend, sendSize, + dataReceived, receiveSize); + // wpi_setErrorWithContext(status, getHALErrorMessage(status)); + return status < 0; } /** @@ -73,11 +70,10 @@ bool I2C::Transaction(uint8_t *dataToSend, uint8_t sendSize, uint8_t *dataReceiv * * @return Transfer Aborted... false for success, true for aborted. */ -bool I2C::AddressOnly() -{ - int32_t status = 0; - status = Transaction(NULL, 0, NULL, 0); - return status < 0; +bool I2C::AddressOnly() { + int32_t status = 0; + status = Transaction(NULL, 0, NULL, 0); + return status < 0; } /** @@ -86,18 +82,18 @@ bool I2C::AddressOnly() * Write a single byte to a register on a device and wait until the * transaction is complete. * - * @param registerAddress The address of the register on the device to be written. + * @param registerAddress The address of the register on the device to be + * written. * @param data The byte to write to the register on the device. * @return Transfer Aborted... false for success, true for aborted. */ -bool I2C::Write(uint8_t registerAddress, uint8_t data) -{ - uint8_t buffer[2]; - buffer[0] = registerAddress; - buffer[1] = data; - int32_t status = 0; - status = i2CWrite(m_port, m_deviceAddress, buffer, sizeof(buffer)); - return status < 0; +bool I2C::Write(uint8_t registerAddress, uint8_t data) { + uint8_t buffer[2]; + buffer[0] = registerAddress; + buffer[1] = data; + int32_t status = 0; + status = i2CWrite(m_port, m_deviceAddress, buffer, sizeof(buffer)); + return status < 0; } /** @@ -110,11 +106,10 @@ bool I2C::Write(uint8_t registerAddress, uint8_t data) * @param count The number of bytes to be written. * @return Transfer Aborted... false for success, true for aborted. */ -bool I2C::WriteBulk(uint8_t* data, uint8_t count) -{ - int32_t status = 0; - status = i2CWrite(m_port, m_deviceAddress, data, count); - return status < 0; +bool I2C::WriteBulk(uint8_t *data, uint8_t count) { + int32_t status = 0; + status = i2CWrite(m_port, m_deviceAddress, data, count); + return status < 0; } /** @@ -127,30 +122,30 @@ bool I2C::WriteBulk(uint8_t* data, uint8_t count) * * @param registerAddress The register to read first in the transaction. * @param count The number of bytes to read in the transaction. [1..7] - * @param buffer A pointer to the array of bytes to store the data read from the device. + * @param buffer A pointer to the array of bytes to store the data read from the + * device. * @return Transfer Aborted... false for success, true for aborted. */ -bool I2C::Read(uint8_t registerAddress, uint8_t count, uint8_t *buffer) -{ - if (count < 1 || count > 7) - { - wpi_setWPIErrorWithContext(ParameterOutOfRange, "count"); - return true; - } - if (buffer == NULL) - { - wpi_setWPIErrorWithContext(NullParameter, "buffer"); - return true; - } - int32_t status = 0; - status = Transaction(®isterAddress, sizeof(registerAddress), buffer, count); - return status < 0; +bool I2C::Read(uint8_t registerAddress, uint8_t count, uint8_t *buffer) { + if (count < 1 || count > 7) { + wpi_setWPIErrorWithContext(ParameterOutOfRange, "count"); + return true; + } + if (buffer == NULL) { + wpi_setWPIErrorWithContext(NullParameter, "buffer"); + return true; + } + int32_t status = 0; + status = + Transaction(®isterAddress, sizeof(registerAddress), buffer, count); + return status < 0; } /** * Execute a read only transaction with the device. * - * Read 1 to 7 bytes from a device. This method does not write any data to prompt + * Read 1 to 7 bytes from a device. This method does not write any data to + * prompt * the device. * * @param buffer @@ -160,21 +155,18 @@ bool I2C::Read(uint8_t registerAddress, uint8_t count, uint8_t *buffer) * The number of bytes to read in the transaction. [1..7] * @return Transfer Aborted... false for success, true for aborted. */ -bool I2C::ReadOnly(uint8_t count, uint8_t *buffer) -{ - if (count < 1 || count > 7) - { - wpi_setWPIErrorWithContext(ParameterOutOfRange, "count"); - return true; - } - if (buffer == NULL) - { - wpi_setWPIErrorWithContext(NullParameter, "buffer"); - return true; - } - int32_t status = 0; - status = i2CRead(m_port, m_deviceAddress, buffer, count); - return status < 0; +bool I2C::ReadOnly(uint8_t count, uint8_t *buffer) { + if (count < 1 || count > 7) { + wpi_setWPIErrorWithContext(ParameterOutOfRange, "count"); + return true; + } + if (buffer == NULL) { + wpi_setWPIErrorWithContext(NullParameter, "buffer"); + return true; + } + int32_t status = 0; + status = i2CRead(m_port, m_deviceAddress, buffer, count); + return status < 0; } /** @@ -185,9 +177,7 @@ bool I2C::ReadOnly(uint8_t count, uint8_t *buffer) * @param registerAddress The register to write on all devices on the bus. * @param data The value to write to the devices. */ -void I2C::Broadcast(uint8_t registerAddress, uint8_t data) -{ -} +void I2C::Broadcast(uint8_t registerAddress, uint8_t data) {} /** * Verify that a device's registers contain expected values. @@ -196,26 +186,26 @@ void I2C::Broadcast(uint8_t registerAddress, uint8_t data) * can be used to identify them. This allows an I2C device driver to easily * verify that the device contains the expected value. * - * @pre The device must support and be configured to use register auto-increment. + * @pre The device must support and be configured to use register + * auto-increment. * * @param registerAddress The base register to start reading from the device. * @param count The size of the field to be verified. * @param expected A buffer containing the values expected from the device. */ -bool I2C::VerifySensor(uint8_t registerAddress, uint8_t count, const uint8_t *expected) -{ - // TODO: Make use of all 7 read bytes - uint8_t deviceData[4]; - for (uint8_t i=0, curRegisterAddress = registerAddress; i < count; i+=4, curRegisterAddress+=4) - { - uint8_t toRead = count - i < 4 ? count - i : 4; - // Read the chunk of data. Return false if the sensor does not respond. - if (Read(curRegisterAddress, toRead, deviceData)) return false; +bool I2C::VerifySensor(uint8_t registerAddress, uint8_t count, + const uint8_t *expected) { + // TODO: Make use of all 7 read bytes + uint8_t deviceData[4]; + for (uint8_t i = 0, curRegisterAddress = registerAddress; i < count; + i += 4, curRegisterAddress += 4) { + uint8_t toRead = count - i < 4 ? count - i : 4; + // Read the chunk of data. Return false if the sensor does not respond. + if (Read(curRegisterAddress, toRead, deviceData)) return false; - for (uint8_t j=0; jAllocate("Async Interrupt"); - if (index == ~0ul) - { - CloneError(m_interrupts); - return; - } - m_interruptIndex = index; +void InterruptableSensorBase::RequestInterrupts( + InterruptHandlerFunction handler, void *param) { + if (StatusIsFatal()) return; + uint32_t index = m_interrupts->Allocate("Async Interrupt"); + if (index == ~0ul) { + CloneError(m_interrupts); + return; + } + m_interruptIndex = index; - // Creates a manager too - AllocateInterrupts(false); + // Creates a manager too + AllocateInterrupts(false); - int32_t status = 0; - requestInterrupts(m_interrupt, GetModuleForRouting(), GetChannelForRouting(), - GetAnalogTriggerForRouting(), &status); - SetUpSourceEdge(true, false); - attachInterruptHandler(m_interrupt, handler, param, &status); - wpi_setErrorWithContext(status, getHALErrorMessage(status)); + int32_t status = 0; + requestInterrupts(m_interrupt, GetModuleForRouting(), GetChannelForRouting(), + GetAnalogTriggerForRouting(), &status); + SetUpSourceEdge(true, false); + attachInterruptHandler(m_interrupt, handler, param, &status); + wpi_setErrorWithContext(status, getHALErrorMessage(status)); } /** * Request one of the 8 interrupts synchronously on this digital input. -* Request interrupts in synchronous mode where the user program will have to explicitly +* Request interrupts in synchronous mode where the user program will have to +* explicitly * wait for the interrupt to occur using WaitForInterrupt. * The default is interrupt on rising edges only. */ -void InterruptableSensorBase::RequestInterrupts() -{ - if (StatusIsFatal()) return; - uint32_t index = m_interrupts->Allocate("Sync Interrupt"); - if (index == ~0ul) - { - CloneError(m_interrupts); - return; - } - m_interruptIndex = index; +void InterruptableSensorBase::RequestInterrupts() { + if (StatusIsFatal()) return; + uint32_t index = m_interrupts->Allocate("Sync Interrupt"); + if (index == ~0ul) { + CloneError(m_interrupts); + return; + } + m_interruptIndex = index; - AllocateInterrupts(true); + AllocateInterrupts(true); - int32_t status = 0; - requestInterrupts(m_interrupt, GetModuleForRouting(), GetChannelForRouting(), - GetAnalogTriggerForRouting(), &status); - wpi_setErrorWithContext(status, getHALErrorMessage(status)); - SetUpSourceEdge(true, false); + int32_t status = 0; + requestInterrupts(m_interrupt, GetModuleForRouting(), GetChannelForRouting(), + GetAnalogTriggerForRouting(), &status); + wpi_setErrorWithContext(status, getHALErrorMessage(status)); + SetUpSourceEdge(true, false); } -void InterruptableSensorBase::AllocateInterrupts(bool watcher) -{ - wpi_assert(m_interrupt == NULL); - // Expects the calling leaf class to allocate an interrupt index. - int32_t status = 0; - m_interrupt = initializeInterrupts(m_interruptIndex, watcher, &status); - wpi_setErrorWithContext(status, getHALErrorMessage(status)); +void InterruptableSensorBase::AllocateInterrupts(bool watcher) { + wpi_assert(m_interrupt == NULL); + // Expects the calling leaf class to allocate an interrupt index. + int32_t status = 0; + m_interrupt = initializeInterrupts(m_interruptIndex, watcher, &status); + wpi_setErrorWithContext(status, getHALErrorMessage(status)); } /** * Cancel interrupts on this device. * This deallocates all the chipobject structures and disables any interrupts. */ -void InterruptableSensorBase::CancelInterrupts() -{ - if (StatusIsFatal()) return; - wpi_assert(m_interrupt != NULL); - int32_t status = 0; - cleanInterrupts(m_interrupt, &status); - wpi_setErrorWithContext(status, getHALErrorMessage(status)); - m_interrupt = NULL; - m_interrupts->Free(m_interruptIndex); +void InterruptableSensorBase::CancelInterrupts() { + if (StatusIsFatal()) return; + wpi_assert(m_interrupt != NULL); + int32_t status = 0; + cleanInterrupts(m_interrupt, &status); + wpi_setErrorWithContext(status, getHALErrorMessage(status)); + m_interrupt = NULL; + m_interrupts->Free(m_interruptIndex); } /** - * In synchronous mode, wait for the defined interrupt to occur. You should NOT attempt to read the - * sensor from another thread while waiting for an interrupt. This is not threadsafe, and can cause + * In synchronous mode, wait for the defined interrupt to occur. You should + * NOT attempt to read the + * sensor from another thread while waiting for an interrupt. This is not + * threadsafe, and can cause * memory corruption * @param timeout Timeout in seconds * @param ignorePrevious If true, ignore interrupts that happened before * WaitForInterrupt was called. * @return What interrupts fired */ -InterruptableSensorBase::WaitResult InterruptableSensorBase::WaitForInterrupt(float timeout, bool ignorePrevious) -{ - if (StatusIsFatal()) return InterruptableSensorBase::kTimeout; - wpi_assert(m_interrupt != NULL); - int32_t status = 0; - uint32_t result; +InterruptableSensorBase::WaitResult InterruptableSensorBase::WaitForInterrupt( + float timeout, bool ignorePrevious) { + if (StatusIsFatal()) return InterruptableSensorBase::kTimeout; + wpi_assert(m_interrupt != NULL); + int32_t status = 0; + uint32_t result; - result = waitForInterrupt(m_interrupt, timeout, ignorePrevious, &status); - wpi_setErrorWithContext(status, getHALErrorMessage(status)); + result = waitForInterrupt(m_interrupt, timeout, ignorePrevious, &status); + wpi_setErrorWithContext(status, getHALErrorMessage(status)); - return static_cast(result); + return static_cast(result); } /** * Enable interrupts to occur on this input. - * Interrupts are disabled when the RequestInterrupt call is made. This gives time to do the + * Interrupts are disabled when the RequestInterrupt call is made. This gives + * time to do the * setup of the other options before starting to field interrupts. */ -void InterruptableSensorBase::EnableInterrupts() -{ - if (StatusIsFatal()) return; - wpi_assert(m_interrupt != NULL); - int32_t status = 0; - enableInterrupts(m_interrupt, &status); - wpi_setErrorWithContext(status, getHALErrorMessage(status)); +void InterruptableSensorBase::EnableInterrupts() { + if (StatusIsFatal()) return; + wpi_assert(m_interrupt != NULL); + int32_t status = 0; + enableInterrupts(m_interrupt, &status); + wpi_setErrorWithContext(status, getHALErrorMessage(status)); } /** * Disable Interrupts without without deallocating structures. */ -void InterruptableSensorBase::DisableInterrupts() -{ - if (StatusIsFatal()) return; - wpi_assert(m_interrupt != NULL); - int32_t status = 0; - disableInterrupts(m_interrupt, &status); - wpi_setErrorWithContext(status, getHALErrorMessage(status)); +void InterruptableSensorBase::DisableInterrupts() { + if (StatusIsFatal()) return; + wpi_assert(m_interrupt != NULL); + int32_t status = 0; + disableInterrupts(m_interrupt, &status); + wpi_setErrorWithContext(status, getHALErrorMessage(status)); } /** @@ -155,14 +151,13 @@ void InterruptableSensorBase::DisableInterrupts() * {@link #DigitalInput.SetUpSourceEdge} * @return Timestamp in seconds since boot. */ -double InterruptableSensorBase::ReadRisingTimestamp() -{ - if (StatusIsFatal()) return 0.0; - wpi_assert(m_interrupt != NULL); - int32_t status = 0; - double timestamp = readRisingTimestamp(m_interrupt, &status); - wpi_setErrorWithContext(status, getHALErrorMessage(status)); - return timestamp; +double InterruptableSensorBase::ReadRisingTimestamp() { + if (StatusIsFatal()) return 0.0; + wpi_assert(m_interrupt != NULL); + int32_t status = 0; + double timestamp = readRisingTimestamp(m_interrupt, &status); + wpi_setErrorWithContext(status, getHALErrorMessage(status)); + return timestamp; } /** @@ -172,14 +167,13 @@ double InterruptableSensorBase::ReadRisingTimestamp() * {@link #DigitalInput.SetUpSourceEdge} * @return Timestamp in seconds since boot. */ -double InterruptableSensorBase::ReadFallingTimestamp() -{ - if (StatusIsFatal()) return 0.0; - wpi_assert(m_interrupt != NULL); - int32_t status = 0; - double timestamp = readFallingTimestamp(m_interrupt, &status); - wpi_setErrorWithContext(status, getHALErrorMessage(status)); - return timestamp; +double InterruptableSensorBase::ReadFallingTimestamp() { + if (StatusIsFatal()) return 0.0; + wpi_assert(m_interrupt != NULL); + int32_t status = 0; + double timestamp = readFallingTimestamp(m_interrupt, &status); + wpi_setErrorWithContext(status, getHALErrorMessage(status)); + return timestamp; } /** @@ -190,18 +184,18 @@ double InterruptableSensorBase::ReadFallingTimestamp() * @param fallingEdge * true to interrupt on falling edge */ -void InterruptableSensorBase::SetUpSourceEdge(bool risingEdge, bool fallingEdge) -{ - if (StatusIsFatal()) return; - if (m_interrupt == NULL) - { - wpi_setWPIErrorWithContext(NullParameter, "You must call RequestInterrupts before SetUpSourceEdge"); - return; - } - if (m_interrupt != NULL) - { - int32_t status = 0; - setInterruptUpSourceEdge(m_interrupt, risingEdge, fallingEdge, &status); - wpi_setErrorWithContext(status, getHALErrorMessage(status)); - } +void InterruptableSensorBase::SetUpSourceEdge(bool risingEdge, + bool fallingEdge) { + if (StatusIsFatal()) return; + if (m_interrupt == NULL) { + wpi_setWPIErrorWithContext( + NullParameter, + "You must call RequestInterrupts before SetUpSourceEdge"); + return; + } + if (m_interrupt != NULL) { + int32_t status = 0; + setInterruptUpSourceEdge(m_interrupt, risingEdge, fallingEdge, &status); + wpi_setErrorWithContext(status, getHALErrorMessage(status)); + } } diff --git a/wpilibc/wpilibC++Devices/src/IterativeRobot.cpp b/wpilibc/wpilibC++Devices/src/IterativeRobot.cpp index e8f4259033..3486e02784 100644 --- a/wpilibc/wpilibC++Devices/src/IterativeRobot.cpp +++ b/wpilibc/wpilibC++Devices/src/IterativeRobot.cpp @@ -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. */ /*----------------------------------------------------------------------------*/ @@ -17,250 +18,233 @@ constexpr double IterativeRobot::kDefaultPeriod; /** * Constructor for RobotIterativeBase - * + * * The constructor initializes the instance variables for the robot to indicate * the status of initialization for disabled, autonomous, teleop, and test code. */ IterativeRobot::IterativeRobot() - : m_disabledInitialized (false) - , m_autonomousInitialized (false) - , m_teleopInitialized (false) - , m_testInitialized (false) -{ -} + : m_disabledInitialized(false), + m_autonomousInitialized(false), + m_teleopInitialized(false), + m_testInitialized(false) {} /** * Free the resources for a RobotIterativeBase class. */ -IterativeRobot::~IterativeRobot() -{ -} +IterativeRobot::~IterativeRobot() {} void IterativeRobot::Prestart() { - // Don't immediately say that the robot's ready to be enabled. - // See below. + // Don't immediately say that the robot's ready to be enabled. + // See below. } /** * Provide an alternate "main loop" via StartCompetition(). - * - * This specific StartCompetition() implements "main loop" behaviour synced with the DS packets + * + * This specific StartCompetition() implements "main loop" behaviour synced with + * the DS packets */ -void IterativeRobot::StartCompetition() -{ - HALReport(HALUsageReporting::kResourceType_Framework, HALUsageReporting::kFramework_Iterative); +void IterativeRobot::StartCompetition() { + HALReport(HALUsageReporting::kResourceType_Framework, + HALUsageReporting::kFramework_Iterative); - LiveWindow *lw = LiveWindow::GetInstance(); - // first and one-time initialization - SmartDashboard::init(); - NetworkTable::GetTable("LiveWindow")->GetSubTable("~STATUS~")->PutBoolean("LW Enabled", false); - RobotInit(); + LiveWindow *lw = LiveWindow::GetInstance(); + // first and one-time initialization + SmartDashboard::init(); + NetworkTable::GetTable("LiveWindow") + ->GetSubTable("~STATUS~") + ->PutBoolean("LW Enabled", false); + RobotInit(); - // We call this now (not in Prestart like default) so that the robot - // won't enable until the initialization has finished. This is useful - // because otherwise it's sometimes possible to enable the robot - // before the code is ready. - HALNetworkCommunicationObserveUserProgramStarting(); + // We call this now (not in Prestart like default) so that the robot + // won't enable until the initialization has finished. This is useful + // because otherwise it's sometimes possible to enable the robot + // before the code is ready. + HALNetworkCommunicationObserveUserProgramStarting(); - // loop forever, calling the appropriate mode-dependent function - lw->SetEnabled(false); - while (true) - { - // Call the appropriate function depending upon the current robot mode - if (IsDisabled()) - { - // call DisabledInit() if we are now just entering disabled mode from - // either a different mode or from power-on - if(!m_disabledInitialized) - { - lw->SetEnabled(false); - DisabledInit(); - m_disabledInitialized = true; - // reset the initialization flags for the other modes - m_autonomousInitialized = false; - m_teleopInitialized = false; - m_testInitialized = false; - } - HALNetworkCommunicationObserveUserProgramDisabled(); - DisabledPeriodic(); - } - else if (IsAutonomous()) - { - // call AutonomousInit() if we are now just entering autonomous mode from - // either a different mode or from power-on - if(!m_autonomousInitialized) - { - lw->SetEnabled(false); - AutonomousInit(); - m_autonomousInitialized = true; - // reset the initialization flags for the other modes - m_disabledInitialized = false; - m_teleopInitialized = false; - m_testInitialized = false; - } - HALNetworkCommunicationObserveUserProgramAutonomous(); - AutonomousPeriodic(); - } - else if (IsTest()) - { - // call TestInit() if we are now just entering test mode from - // either a different mode or from power-on - if(!m_testInitialized) - { - lw->SetEnabled(true); - TestInit(); - m_testInitialized = true; - // reset the initialization flags for the other modes - m_disabledInitialized = false; - m_autonomousInitialized = false; - m_teleopInitialized = false; - } - HALNetworkCommunicationObserveUserProgramTest(); - TestPeriodic(); - } - else - { - // call TeleopInit() if we are now just entering teleop mode from - // either a different mode or from power-on - if(!m_teleopInitialized) - { - lw->SetEnabled(false); - TeleopInit(); - m_teleopInitialized = true; - // reset the initialization flags for the other modes - m_disabledInitialized = false; - m_autonomousInitialized = false; - m_testInitialized = false; - Scheduler::GetInstance()->SetEnabled(true); - } - HALNetworkCommunicationObserveUserProgramTeleop(); - TeleopPeriodic(); - } - // wait for driver station data so the loop doesn't hog the CPU - m_ds->WaitForData(); - } + // loop forever, calling the appropriate mode-dependent function + lw->SetEnabled(false); + while (true) { + // Call the appropriate function depending upon the current robot mode + if (IsDisabled()) { + // call DisabledInit() if we are now just entering disabled mode from + // either a different mode or from power-on + if (!m_disabledInitialized) { + lw->SetEnabled(false); + DisabledInit(); + m_disabledInitialized = true; + // reset the initialization flags for the other modes + m_autonomousInitialized = false; + m_teleopInitialized = false; + m_testInitialized = false; + } + HALNetworkCommunicationObserveUserProgramDisabled(); + DisabledPeriodic(); + } else if (IsAutonomous()) { + // call AutonomousInit() if we are now just entering autonomous mode from + // either a different mode or from power-on + if (!m_autonomousInitialized) { + lw->SetEnabled(false); + AutonomousInit(); + m_autonomousInitialized = true; + // reset the initialization flags for the other modes + m_disabledInitialized = false; + m_teleopInitialized = false; + m_testInitialized = false; + } + HALNetworkCommunicationObserveUserProgramAutonomous(); + AutonomousPeriodic(); + } else if (IsTest()) { + // call TestInit() if we are now just entering test mode from + // either a different mode or from power-on + if (!m_testInitialized) { + lw->SetEnabled(true); + TestInit(); + m_testInitialized = true; + // reset the initialization flags for the other modes + m_disabledInitialized = false; + m_autonomousInitialized = false; + m_teleopInitialized = false; + } + HALNetworkCommunicationObserveUserProgramTest(); + TestPeriodic(); + } else { + // call TeleopInit() if we are now just entering teleop mode from + // either a different mode or from power-on + if (!m_teleopInitialized) { + lw->SetEnabled(false); + TeleopInit(); + m_teleopInitialized = true; + // reset the initialization flags for the other modes + m_disabledInitialized = false; + m_autonomousInitialized = false; + m_testInitialized = false; + Scheduler::GetInstance()->SetEnabled(true); + } + HALNetworkCommunicationObserveUserProgramTeleop(); + TeleopPeriodic(); + } + // wait for driver station data so the loop doesn't hog the CPU + m_ds->WaitForData(); + } } /** * Robot-wide initialization code should go here. - * - * Users should override this method for default Robot-wide initialization which will - * be called when the robot is first powered on. It will be called exactly 1 time. + * + * Users should override this method for default Robot-wide initialization which + * will + * be called when the robot is first powered on. It will be called exactly 1 + * time. */ -void IterativeRobot::RobotInit() -{ - printf("Default %s() method... Overload me!\n", __FUNCTION__); +void IterativeRobot::RobotInit() { + printf("Default %s() method... Overload me!\n", __FUNCTION__); } /** * Initialization code for disabled mode should go here. - * - * Users should override this method for initialization code which will be called each time + * + * Users should override this method for initialization code which will be + * called each time * the robot enters disabled mode. */ -void IterativeRobot::DisabledInit() -{ - printf("Default %s() method... Overload me!\n", __FUNCTION__); +void IterativeRobot::DisabledInit() { + printf("Default %s() method... Overload me!\n", __FUNCTION__); } /** * Initialization code for autonomous mode should go here. - * - * Users should override this method for initialization code which will be called each time + * + * Users should override this method for initialization code which will be + * called each time * the robot enters autonomous mode. */ -void IterativeRobot::AutonomousInit() -{ - printf("Default %s() method... Overload me!\n", __FUNCTION__); +void IterativeRobot::AutonomousInit() { + printf("Default %s() method... Overload me!\n", __FUNCTION__); } /** * Initialization code for teleop mode should go here. - * - * Users should override this method for initialization code which will be called each time + * + * Users should override this method for initialization code which will be + * called each time * the robot enters teleop mode. */ -void IterativeRobot::TeleopInit() -{ - printf("Default %s() method... Overload me!\n", __FUNCTION__); +void IterativeRobot::TeleopInit() { + printf("Default %s() method... Overload me!\n", __FUNCTION__); } /** * Initialization code for test mode should go here. - * - * Users should override this method for initialization code which will be called each time + * + * Users should override this method for initialization code which will be + * called each time * the robot enters test mode. */ -void IterativeRobot::TestInit() -{ - printf("Default %s() method... Overload me!\n", __FUNCTION__); +void IterativeRobot::TestInit() { + printf("Default %s() method... Overload me!\n", __FUNCTION__); } /** * Periodic code for disabled mode should go here. - * - * Users should override this method for code which will be called periodically at a regular + * + * Users should override this method for code which will be called periodically + * at a regular * rate while the robot is in disabled mode. */ -void IterativeRobot::DisabledPeriodic() -{ - static bool firstRun = true; - if (firstRun) - { - printf("Default %s() method... Overload me!\n", __FUNCTION__); - firstRun = false; - } - delayTicks(1); +void IterativeRobot::DisabledPeriodic() { + static bool firstRun = true; + if (firstRun) { + printf("Default %s() method... Overload me!\n", __FUNCTION__); + firstRun = false; + } + delayTicks(1); } /** * Periodic code for autonomous mode should go here. * - * Users should override this method for code which will be called periodically at a regular + * Users should override this method for code which will be called periodically + * at a regular * rate while the robot is in autonomous mode. */ -void IterativeRobot::AutonomousPeriodic() -{ - static bool firstRun = true; - if (firstRun) - { - printf("Default %s() method... Overload me!\n", __FUNCTION__); - firstRun = false; - } - delayTicks(1); +void IterativeRobot::AutonomousPeriodic() { + static bool firstRun = true; + if (firstRun) { + printf("Default %s() method... Overload me!\n", __FUNCTION__); + firstRun = false; + } + delayTicks(1); } /** * Periodic code for teleop mode should go here. * - * Users should override this method for code which will be called periodically at a regular + * Users should override this method for code which will be called periodically + * at a regular * rate while the robot is in teleop mode. */ -void IterativeRobot::TeleopPeriodic() -{ - static bool firstRun = true; - if (firstRun) - { - printf("Default %s() method... Overload me!\n", __FUNCTION__); - firstRun = false; - } - delayTicks(1); +void IterativeRobot::TeleopPeriodic() { + static bool firstRun = true; + if (firstRun) { + printf("Default %s() method... Overload me!\n", __FUNCTION__); + firstRun = false; + } + delayTicks(1); } /** * Periodic code for test mode should go here. * - * Users should override this method for code which will be called periodically at a regular + * Users should override this method for code which will be called periodically + * at a regular * rate while the robot is in test mode. */ -void IterativeRobot::TestPeriodic() -{ - static bool firstRun = true; - if (firstRun) - { - printf("Default %s() method... Overload me!\n", __FUNCTION__); - firstRun = false; - } - delayTicks(1); +void IterativeRobot::TestPeriodic() { + static bool firstRun = true; + if (firstRun) { + printf("Default %s() method... Overload me!\n", __FUNCTION__); + firstRun = false; + } + delayTicks(1); } - diff --git a/wpilibc/wpilibC++Devices/src/Jaguar.cpp b/wpilibc/wpilibC++Devices/src/Jaguar.cpp index 5c52bfb5b0..e0d4520274 100644 --- a/wpilibc/wpilibC++Devices/src/Jaguar.cpp +++ b/wpilibc/wpilibC++Devices/src/Jaguar.cpp @@ -1,10 +1,10 @@ /*----------------------------------------------------------------------------*/ -/* 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. */ /*----------------------------------------------------------------------------*/ - #include "Jaguar.h" //#include "NetworkCommunication/UsageReporting.h" #include "LiveWindow/LiveWindow.h" @@ -12,39 +12,34 @@ /** * Common initialization code called by all constructors. */ -void Jaguar::InitJaguar() -{ - /** - * Input profile defined by Luminary Micro. - * - * Full reverse ranges from 0.671325ms to 0.6972211ms - * Proportional reverse ranges from 0.6972211ms to 1.4482078ms - * Neutral ranges from 1.4482078ms to 1.5517922ms - * Proportional forward ranges from 1.5517922ms to 2.3027789ms - * Full forward ranges from 2.3027789ms to 2.328675ms - */ - SetBounds(2.31, 1.55, 1.507, 1.454, .697); - SetPeriodMultiplier(kPeriodMultiplier_1X); - SetRaw(m_centerPwm); - SetZeroLatch(); +void Jaguar::InitJaguar() { + /** + * Input profile defined by Luminary Micro. + * + * Full reverse ranges from 0.671325ms to 0.6972211ms + * Proportional reverse ranges from 0.6972211ms to 1.4482078ms + * Neutral ranges from 1.4482078ms to 1.5517922ms + * Proportional forward ranges from 1.5517922ms to 2.3027789ms + * Full forward ranges from 2.3027789ms to 2.328675ms + */ + SetBounds(2.31, 1.55, 1.507, 1.454, .697); + SetPeriodMultiplier(kPeriodMultiplier_1X); + SetRaw(m_centerPwm); + SetZeroLatch(); - HALReport(HALUsageReporting::kResourceType_Jaguar, GetChannel()); - LiveWindow::GetInstance()->AddActuator("Jaguar", GetChannel(), this); - m_isInverted = false; + HALReport(HALUsageReporting::kResourceType_Jaguar, GetChannel()); + LiveWindow::GetInstance()->AddActuator("Jaguar", GetChannel(), this); + m_isInverted = false; } /** * Constructor for a Jaguar connected via PWM - * @param channel The PWM channel that the Jaguar is attached to. 0-9 are on-board, 10-19 are on the MXP port + * @param channel The PWM channel that the Jaguar is attached to. 0-9 are + * on-board, 10-19 are on the MXP port */ -Jaguar::Jaguar(uint32_t channel) : SafePWM(channel) -{ - InitJaguar(); -} +Jaguar::Jaguar(uint32_t channel) : SafePWM(channel) { InitJaguar(); } -Jaguar::~Jaguar() -{ -} +Jaguar::~Jaguar() {} /** * Set the PWM value. @@ -55,9 +50,8 @@ Jaguar::~Jaguar() * @param speed The speed value between -1.0 and 1.0 to set. * @param syncGroup Unused interface. */ -void Jaguar::Set(float speed, uint8_t syncGroup) -{ - SetSpeed(m_isInverted ? -speed : speed); +void Jaguar::Set(float speed, uint8_t syncGroup) { + SetSpeed(m_isInverted ? -speed : speed); } /** @@ -65,26 +59,18 @@ void Jaguar::Set(float speed, uint8_t syncGroup) * * @return The most recently set value for the PWM between -1.0 and 1.0. */ -float Jaguar::Get() const -{ - return GetSpeed(); -} +float Jaguar::Get() const { return GetSpeed(); } /** * Common interface for disabling a motor. */ -void Jaguar::Disable() -{ - SetRaw(kPwmDisabled); -} +void Jaguar::Disable() { SetRaw(kPwmDisabled); } /** * Common interface for inverting direction of a speed controller. * @param isInverted The state of inversion, true is inverted. */ -void Jaguar::SetInverted(bool isInverted){ -m_isInverted = isInverted; -} +void Jaguar::SetInverted(bool isInverted) { m_isInverted = isInverted; } /** * Common interface for the inverting direction of a speed controller. @@ -92,16 +78,11 @@ m_isInverted = isInverted; * @return isInverted The state of inversion, true is inverted. * */ -bool Jaguar::GetInverted() const { - return m_isInverted; -} +bool Jaguar::GetInverted() const { return m_isInverted; } /** * Write out the PID value as seen in the PIDOutput base object. * * @param output Write out the PWM value as was found in the PIDController */ -void Jaguar::PIDWrite(float output) -{ - Set(output); -} +void Jaguar::PIDWrite(float output) { Set(output); } diff --git a/wpilibc/wpilibC++Devices/src/Joystick.cpp b/wpilibc/wpilibC++Devices/src/Joystick.cpp index 9c099d6d9d..ea18262bb1 100644 --- a/wpilibc/wpilibC++Devices/src/Joystick.cpp +++ b/wpilibc/wpilibC++Devices/src/Joystick.cpp @@ -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,29 +26,29 @@ static bool joySticksInitialized = false; * Construct an instance of a joystick. * The joystick index is the usb port on the drivers station. * - * @param port The port on the driver station that the joystick is plugged into (0-5). + * @param port The port on the driver station that the joystick is plugged into + * (0-5). */ Joystick::Joystick(uint32_t port) - : m_ds (NULL) - , m_port (port) - , m_axes (NULL) - , m_buttons (NULL) - , m_outputs (0) - , m_leftRumble (0) - , m_rightRumble (0) -{ - InitJoystick(kNumAxisTypes, kNumButtonTypes); + : m_ds(NULL), + m_port(port), + m_axes(NULL), + m_buttons(NULL), + m_outputs(0), + m_leftRumble(0), + m_rightRumble(0) { + InitJoystick(kNumAxisTypes, kNumButtonTypes); - m_axes[kXAxis] = kDefaultXAxis; - m_axes[kYAxis] = kDefaultYAxis; - m_axes[kZAxis] = kDefaultZAxis; - m_axes[kTwistAxis] = kDefaultTwistAxis; - m_axes[kThrottleAxis] = kDefaultThrottleAxis; + m_axes[kXAxis] = kDefaultXAxis; + m_axes[kYAxis] = kDefaultYAxis; + m_axes[kZAxis] = kDefaultZAxis; + m_axes[kTwistAxis] = kDefaultTwistAxis; + m_axes[kThrottleAxis] = kDefaultThrottleAxis; - m_buttons[kTriggerButton] = kDefaultTriggerButton; - m_buttons[kTopButton] = kDefaultTopButton; + m_buttons[kTriggerButton] = kDefaultTriggerButton; + m_buttons[kTopButton] = kDefaultTopButton; - HALReport(HALUsageReporting::kResourceType_Joystick, port); + HALReport(HALUsageReporting::kResourceType_Joystick, port); } /** @@ -60,96 +61,81 @@ Joystick::Joystick(uint32_t port) * @param numAxisTypes The number of axis types in the enum. * @param numButtonTypes The number of button types in the enum. */ -Joystick::Joystick(uint32_t port, uint32_t numAxisTypes, uint32_t numButtonTypes) - : m_ds (NULL) - , m_port (port) - , m_axes (NULL) - , m_buttons (NULL) -{ - InitJoystick(numAxisTypes, numButtonTypes); +Joystick::Joystick(uint32_t port, uint32_t numAxisTypes, + uint32_t numButtonTypes) + : m_ds(NULL), m_port(port), m_axes(NULL), m_buttons(NULL) { + InitJoystick(numAxisTypes, numButtonTypes); } -void Joystick::InitJoystick(uint32_t numAxisTypes, uint32_t numButtonTypes) -{ - if ( !joySticksInitialized ) - { - for (unsigned i = 0; i < DriverStation::kJoystickPorts; i++) - joysticks[i] = NULL; - joySticksInitialized = true; - } - if (m_port >= DriverStation::kJoystickPorts) { - wpi_setWPIError(BadJoystickIndex); - } else { - joysticks[m_port] = this; - } +void Joystick::InitJoystick(uint32_t numAxisTypes, uint32_t numButtonTypes) { + if (!joySticksInitialized) { + for (unsigned i = 0; i < DriverStation::kJoystickPorts; i++) + joysticks[i] = NULL; + joySticksInitialized = true; + } + if (m_port >= DriverStation::kJoystickPorts) { + wpi_setWPIError(BadJoystickIndex); + } else { + joysticks[m_port] = this; + } - m_ds = DriverStation::GetInstance(); - m_axes = new uint32_t[numAxisTypes]; - m_buttons = new uint32_t[numButtonTypes]; + m_ds = DriverStation::GetInstance(); + m_axes = new uint32_t[numAxisTypes]; + m_buttons = new uint32_t[numButtonTypes]; } -Joystick * Joystick::GetStickForPort(uint32_t port) -{ - Joystick *stick = joysticks[port]; - if (stick == NULL) - { - stick = new Joystick(port); - joysticks[port] = stick; - } - return stick; +Joystick *Joystick::GetStickForPort(uint32_t port) { + Joystick *stick = joysticks[port]; + if (stick == NULL) { + stick = new Joystick(port); + joysticks[port] = stick; + } + return stick; } -Joystick::~Joystick() -{ - delete [] m_buttons; - delete [] m_axes; +Joystick::~Joystick() { + delete[] m_buttons; + delete[] m_axes; } /** * Get the X value of the joystick. * This depends on the mapping of the joystick connected to the current port. - * @param hand This parameter is ignored for the Joystick class and is only here to complete the GenericHID interface. + * @param hand This parameter is ignored for the Joystick class and is only here + * to complete the GenericHID interface. */ -float Joystick::GetX(JoystickHand hand) const -{ - return GetRawAxis(m_axes[kXAxis]); +float Joystick::GetX(JoystickHand hand) const { + return GetRawAxis(m_axes[kXAxis]); } /** * Get the Y value of the joystick. * This depends on the mapping of the joystick connected to the current port. - * @param hand This parameter is ignored for the Joystick class and is only here to complete the GenericHID interface. + * @param hand This parameter is ignored for the Joystick class and is only here + * to complete the GenericHID interface. */ -float Joystick::GetY(JoystickHand hand) const -{ - return GetRawAxis(m_axes[kYAxis]); +float Joystick::GetY(JoystickHand hand) const { + return GetRawAxis(m_axes[kYAxis]); } /** * Get the Z value of the current joystick. * This depends on the mapping of the joystick connected to the current port. */ -float Joystick::GetZ() const -{ - return GetRawAxis(m_axes[kZAxis]); -} +float Joystick::GetZ() const { return GetRawAxis(m_axes[kZAxis]); } /** * Get the twist value of the current joystick. * This depends on the mapping of the joystick connected to the current port. */ -float Joystick::GetTwist() const -{ - return GetRawAxis(m_axes[kTwistAxis]); -} +float Joystick::GetTwist() const { return GetRawAxis(m_axes[kTwistAxis]); } /** * Get the throttle value of the current joystick. * This depends on the mapping of the joystick connected to the current port. */ -float Joystick::GetThrottle() const -{ - return GetRawAxis(m_axes[kThrottleAxis]); +float Joystick::GetThrottle() const { + return GetRawAxis(m_axes[kThrottleAxis]); } /** @@ -158,33 +144,36 @@ float Joystick::GetThrottle() const * @param axis The axis to read, starting at 0. * @return The value of the axis. */ -float Joystick::GetRawAxis(uint32_t axis) const -{ - return m_ds->GetStickAxis(m_port, axis); +float Joystick::GetRawAxis(uint32_t axis) const { + return m_ds->GetStickAxis(m_port, axis); } /** * For the current joystick, return the axis determined by the argument. * - * This is for cases where the joystick axis is returned programatically, otherwise one of the + * This is for cases where the joystick axis is returned programatically, + * otherwise one of the * previous functions would be preferable (for example GetX()). * * @param axis The axis to read. * @return The value of the axis. */ -float Joystick::GetAxis(AxisType axis) const -{ - switch(axis) - { - case kXAxis: return this->GetX(); - case kYAxis: return this->GetY(); - case kZAxis: return this->GetZ(); - case kTwistAxis: return this->GetTwist(); - case kThrottleAxis: return this->GetThrottle(); - default: - wpi_setWPIError(BadJoystickAxis); - return 0.0; - } +float Joystick::GetAxis(AxisType axis) const { + switch (axis) { + case kXAxis: + return this->GetX(); + case kYAxis: + return this->GetY(); + case kZAxis: + return this->GetZ(); + case kTwistAxis: + return this->GetTwist(); + case kThrottleAxis: + return this->GetThrottle(); + default: + wpi_setWPIError(BadJoystickAxis); + return 0.0; + } } /** @@ -192,12 +181,12 @@ float Joystick::GetAxis(AxisType axis) const * * Look up which button has been assigned to the trigger and read its state. * - * @param hand This parameter is ignored for the Joystick class and is only here to complete the GenericHID interface. + * @param hand This parameter is ignored for the Joystick class and is only here + * to complete the GenericHID interface. * @return The state of the trigger. */ -bool Joystick::GetTrigger(JoystickHand hand) const -{ - return GetRawButton(m_buttons[kTriggerButton]); +bool Joystick::GetTrigger(JoystickHand hand) const { + return GetRawButton(m_buttons[kTriggerButton]); } /** @@ -205,36 +194,35 @@ bool Joystick::GetTrigger(JoystickHand hand) const * * Look up which button has been assigned to the top and read its state. * - * @param hand This parameter is ignored for the Joystick class and is only here to complete the GenericHID interface. + * @param hand This parameter is ignored for the Joystick class and is only here + * to complete the GenericHID interface. * @return The state of the top button. */ -bool Joystick::GetTop(JoystickHand hand) const -{ - return GetRawButton(m_buttons[kTopButton]); +bool Joystick::GetTop(JoystickHand hand) const { + return GetRawButton(m_buttons[kTopButton]); } /** * This is not supported for the Joystick. * This method is only here to complete the GenericHID interface. */ -bool Joystick::GetBumper(JoystickHand hand) const -{ - // Joysticks don't have bumpers. - return false; +bool Joystick::GetBumper(JoystickHand hand) const { + // Joysticks don't have bumpers. + return false; } /** * Get the button value (starting at button 1) * - * The buttons are returned in a single 16 bit value with one bit representing the state + * The buttons are returned in a single 16 bit value with one bit representing + * the state * of each button. The appropriate button is returned as a boolean value. * * @param button The button number to be read (starting at 1) * @return The state of the button. **/ -bool Joystick::GetRawButton(uint32_t button) const -{ - return m_ds->GetStickButton(m_port, button); +bool Joystick::GetRawButton(uint32_t button) const { + return m_ds->GetStickButton(m_port, button); } /** @@ -244,7 +232,7 @@ bool Joystick::GetRawButton(uint32_t button) const * @return the angle of the POV in degrees, or -1 if the POV is not pressed. */ int Joystick::GetPOV(uint32_t pov) const { - return m_ds->GetStickPOV(m_port, pov); + return m_ds->GetStickPOV(m_port, pov); } /** @@ -255,15 +243,15 @@ int Joystick::GetPOV(uint32_t pov) const { * @param button The type of button to read. * @return The state of the button. */ -bool Joystick::GetButton(ButtonType button) const -{ - switch (button) - { - case kTriggerButton: return GetTrigger(); - case kTopButton: return GetTop(); - default: - return false; - } +bool Joystick::GetButton(ButtonType button) const { + switch (button) { + case kTriggerButton: + return GetTrigger(); + case kTopButton: + return GetTop(); + default: + return false; + } } /** @@ -271,29 +259,22 @@ bool Joystick::GetButton(ButtonType button) const * * @return the number of axis for the current joystick */ -int Joystick::GetAxisCount() const -{ - return m_ds->GetStickAxisCount(m_port); -} +int Joystick::GetAxisCount() const { return m_ds->GetStickAxisCount(m_port); } /** * Get the value of isXbox for the joystick. * * @return A boolean that is true if the joystick is an xbox controller. */ -bool Joystick::GetIsXbox() const -{ - return m_ds->GetJoystickIsXbox(m_port); -} +bool Joystick::GetIsXbox() const { return m_ds->GetJoystickIsXbox(m_port); } /** * Get the HID type of the controller. * * @return the HID type of the controller. */ -Joystick::HIDType Joystick::GetType() const -{ - return static_cast(m_ds->GetJoystickType(m_port)); +Joystick::HIDType Joystick::GetType() const { + return static_cast(m_ds->GetJoystickType(m_port)); } /** @@ -301,25 +282,20 @@ Joystick::HIDType Joystick::GetType() const * * @return the name of the controller. */ -std::string Joystick::GetName() const -{ - return m_ds->GetJoystickName(m_port); -} +std::string Joystick::GetName() const { return m_ds->GetJoystickName(m_port); } -//int Joystick::GetAxisType(uint8_t axis) const +// int Joystick::GetAxisType(uint8_t axis) const //{ // return m_ds->GetJoystickAxisType(m_port, axis); //} - /** * Get the number of axis for a joystick * * @return the number of buttons on the current joystick */ -int Joystick::GetButtonCount() const -{ - return m_ds->GetStickButtonCount(m_port); +int Joystick::GetButtonCount() const { + return m_ds->GetStickButtonCount(m_port); } /** @@ -327,11 +303,7 @@ int Joystick::GetButtonCount() const * * @return then umber of POVs for the current joystick */ -int Joystick::GetPOVCount() const -{ - return m_ds->GetStickPOVCount(m_port); -} - +int Joystick::GetPOVCount() const { return m_ds->GetStickPOVCount(m_port); } /** * Get the channel currently associated with the specified axis. @@ -339,10 +311,7 @@ int Joystick::GetPOVCount() const * @param axis The axis to look up the channel for. * @return The channel fr the axis. */ -uint32_t Joystick::GetAxisChannel(AxisType axis) const -{ - return m_axes[axis]; -} +uint32_t Joystick::GetAxisChannel(AxisType axis) const { return m_axes[axis]; } /** * Set the channel associated with a specified axis. @@ -350,9 +319,8 @@ uint32_t Joystick::GetAxisChannel(AxisType axis) const * @param axis The axis to set the channel for. * @param channel The channel to set the axis to. */ -void Joystick::SetAxisChannel(AxisType axis, uint32_t channel) -{ - m_axes[axis] = channel; +void Joystick::SetAxisChannel(AxisType axis, uint32_t channel) { + m_axes[axis] = channel; } /** @@ -362,7 +330,7 @@ void Joystick::SetAxisChannel(AxisType axis, uint32_t channel) * @return The magnitude of the direction vector */ float Joystick::GetMagnitude() const { - return sqrt(pow(GetX(),2) + pow(GetY(),2) ); + return sqrt(pow(GetX(), 2) + pow(GetY(), 2)); } /** @@ -371,9 +339,7 @@ float Joystick::GetMagnitude() const { * * @return The direction of the vector in radians */ -float Joystick::GetDirectionRadians() const { - return atan2(GetX(), -GetY()); -} +float Joystick::GetDirectionRadians() const { return atan2(GetX(), -GetY()); } /** * Get the direction of the vector formed by the joystick and its origin @@ -385,25 +351,26 @@ float Joystick::GetDirectionRadians() const { * @return The direction of the vector in degrees */ float Joystick::GetDirectionDegrees() const { - return (180/acos(-1))*GetDirectionRadians(); + return (180 / acos(-1)) * GetDirectionRadians(); } /** - * Set the rumble output for the joystick. The DS currently supports 2 rumble values, + * Set the rumble output for the joystick. The DS currently supports 2 rumble + * values, * left rumble and right rumble * @param type Which rumble value to set * @param value The normalized value (0 to 1) to set the rumble to */ void Joystick::SetRumble(RumbleType type, float value) { - if (value < 0) - value = 0; - else if (value > 1) - value = 1; - if (type == kLeftRumble) - m_leftRumble = value*65535; - else - m_rightRumble = value*65535; - HALSetJoystickOutputs(m_port, m_outputs, m_leftRumble, m_rightRumble); + if (value < 0) + value = 0; + else if (value > 1) + value = 1; + if (type == kLeftRumble) + m_leftRumble = value * 65535; + else + m_rightRumble = value * 65535; + HALSetJoystickOutputs(m_port, m_outputs, m_leftRumble, m_rightRumble); } /** @@ -411,11 +378,12 @@ void Joystick::SetRumble(RumbleType type, float value) { * @param outputNumber The index of the output to set (1-32) * @param value The value to set the output to */ - -void Joystick::SetOutput(uint8_t outputNumber, bool value) { - m_outputs = (m_outputs & ~(1 << (outputNumber-1))) | (value << (outputNumber-1)); - HALSetJoystickOutputs(m_port, m_outputs, m_leftRumble, m_rightRumble); +void Joystick::SetOutput(uint8_t outputNumber, bool value) { + m_outputs = + (m_outputs & ~(1 << (outputNumber - 1))) | (value << (outputNumber - 1)); + + HALSetJoystickOutputs(m_port, m_outputs, m_leftRumble, m_rightRumble); } /** @@ -423,8 +391,6 @@ void Joystick::SetOutput(uint8_t outputNumber, bool value) { * @param value The 32 bit output value (1 bit for each output) */ void Joystick::SetOutputs(uint32_t value) { - m_outputs = value; - HALSetJoystickOutputs(m_port, m_outputs, m_leftRumble, m_rightRumble); + m_outputs = value; + HALSetJoystickOutputs(m_port, m_outputs, m_leftRumble, m_rightRumble); } - - diff --git a/wpilibc/wpilibC++Devices/src/MotorSafetyHelper.cpp b/wpilibc/wpilibC++Devices/src/MotorSafetyHelper.cpp index 85a20224b8..2fbc04a8f2 100644 --- a/wpilibc/wpilibC++Devices/src/MotorSafetyHelper.cpp +++ b/wpilibc/wpilibC++Devices/src/MotorSafetyHelper.cpp @@ -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,105 +19,98 @@ ReentrantSemaphore MotorSafetyHelper::m_listMutex; /** * The constructor for a MotorSafetyHelper object. - * The helper object is constructed for every object that wants to implement the Motor - * Safety protocol. The helper object has the code to actually do the timing and call the - * motors Stop() method when the timeout expires. The motor object is expected to call the + * The helper object is constructed for every object that wants to implement the + * Motor + * Safety protocol. The helper object has the code to actually do the timing and + * call the + * motors Stop() method when the timeout expires. The motor object is expected + * to call the * Feed() method whenever the motors value is updated. - * @param safeObject a pointer to the motor object implementing MotorSafety. This is used + * @param safeObject a pointer to the motor object implementing MotorSafety. + * This is used * to call the Stop() method on the motor. */ -MotorSafetyHelper::MotorSafetyHelper(MotorSafety *safeObject) -{ - m_safeObject = safeObject; - m_enabled = false; - m_expiration = DEFAULT_SAFETY_EXPIRATION; - m_stopTime = Timer::GetFPGATimestamp(); +MotorSafetyHelper::MotorSafetyHelper(MotorSafety *safeObject) { + m_safeObject = safeObject; + m_enabled = false; + m_expiration = DEFAULT_SAFETY_EXPIRATION; + m_stopTime = Timer::GetFPGATimestamp(); - Synchronized sync(m_listMutex); - m_nextHelper = m_headHelper; - m_headHelper = this; + Synchronized sync(m_listMutex); + m_nextHelper = m_headHelper; + m_headHelper = this; } - -MotorSafetyHelper::~MotorSafetyHelper() -{ - Synchronized sync(m_listMutex); - if (m_headHelper == this) - { - m_headHelper = m_nextHelper; - } - else - { - MotorSafetyHelper *prev = NULL; - MotorSafetyHelper *cur = m_headHelper; - while (cur != this && cur != NULL) - prev = cur, cur = cur->m_nextHelper; - if (cur == this) - prev->m_nextHelper = cur->m_nextHelper; - } +MotorSafetyHelper::~MotorSafetyHelper() { + Synchronized sync(m_listMutex); + if (m_headHelper == this) { + m_headHelper = m_nextHelper; + } else { + MotorSafetyHelper *prev = NULL; + MotorSafetyHelper *cur = m_headHelper; + while (cur != this && cur != NULL) prev = cur, cur = cur->m_nextHelper; + if (cur == this) prev->m_nextHelper = cur->m_nextHelper; + } } /** * Feed the motor safety object. * Resets the timer on this object that is used to do the timeouts. */ -void MotorSafetyHelper::Feed() -{ - Synchronized sync(m_syncMutex); - m_stopTime = Timer::GetFPGATimestamp() + m_expiration; +void MotorSafetyHelper::Feed() { + Synchronized sync(m_syncMutex); + m_stopTime = Timer::GetFPGATimestamp() + m_expiration; } /** * Set the expiration time for the corresponding motor safety object. * @param expirationTime The timeout value in seconds. */ -void MotorSafetyHelper::SetExpiration(float expirationTime) -{ - Synchronized sync(m_syncMutex); - m_expiration = expirationTime; +void MotorSafetyHelper::SetExpiration(float expirationTime) { + Synchronized sync(m_syncMutex); + m_expiration = expirationTime; } /** * Retrieve the timeout value for the corresponding motor safety object. * @return the timeout value in seconds. */ -float MotorSafetyHelper::GetExpiration() const -{ - Synchronized sync(m_syncMutex); - return m_expiration; +float MotorSafetyHelper::GetExpiration() const { + Synchronized sync(m_syncMutex); + return m_expiration; } /** * Determine if the motor is still operating or has timed out. - * @return a true value if the motor is still operating normally and hasn't timed out. + * @return a true value if the motor is still operating normally and hasn't + * timed out. */ -bool MotorSafetyHelper::IsAlive() const -{ - Synchronized sync(m_syncMutex); - return !m_enabled || m_stopTime > Timer::GetFPGATimestamp(); +bool MotorSafetyHelper::IsAlive() const { + Synchronized sync(m_syncMutex); + return !m_enabled || m_stopTime > Timer::GetFPGATimestamp(); } /** * Check if this motor has exceeded its timeout. - * This method is called periodically to determine if this motor has exceeded its timeout - * value. If it has, the stop method is called, and the motor is shut down until its value is + * This method is called periodically to determine if this motor has exceeded + * its timeout + * value. If it has, the stop method is called, and the motor is shut down until + * its value is * updated again. */ -void MotorSafetyHelper::Check() -{ - DriverStation *ds = DriverStation::GetInstance(); - if (!m_enabled || ds->IsDisabled() || ds->IsTest()) return; +void MotorSafetyHelper::Check() { + DriverStation *ds = DriverStation::GetInstance(); + if (!m_enabled || ds->IsDisabled() || ds->IsTest()) return; - Synchronized sync(m_syncMutex); - if (m_stopTime < Timer::GetFPGATimestamp()) - { - char buf[128]; - char desc[64]; - m_safeObject->GetDescription(desc); - snprintf(buf, 128, "%s... Output not updated often enough.", desc); - wpi_setWPIErrorWithContext(Timeout, buf); - m_safeObject->StopMotor(); - } + Synchronized sync(m_syncMutex); + if (m_stopTime < Timer::GetFPGATimestamp()) { + char buf[128]; + char desc[64]; + m_safeObject->GetDescription(desc); + snprintf(buf, 128, "%s... Output not updated often enough.", desc); + wpi_setWPIErrorWithContext(Timeout, buf); + m_safeObject->StopMotor(); + } } /** @@ -124,10 +118,9 @@ void MotorSafetyHelper::Check() * Turn on and off the motor safety option for this PWM object. * @param enabled True if motor safety is enforced for this object */ -void MotorSafetyHelper::SetSafetyEnabled(bool enabled) -{ - Synchronized sync(m_syncMutex); - m_enabled = enabled; +void MotorSafetyHelper::SetSafetyEnabled(bool enabled) { + Synchronized sync(m_syncMutex); + m_enabled = enabled; } /** @@ -135,22 +128,21 @@ void MotorSafetyHelper::SetSafetyEnabled(bool enabled) * Return if the motor safety is currently enabled for this devicce. * @return True if motor safety is enforced for this device */ -bool MotorSafetyHelper::IsSafetyEnabled() const -{ - Synchronized sync(m_syncMutex); - return m_enabled; +bool MotorSafetyHelper::IsSafetyEnabled() const { + Synchronized sync(m_syncMutex); + return m_enabled; } /** * Check the motors to see if any have timed out. - * This static method is called periodically to poll all the motors and stop any that have + * This static method is called periodically to poll all the motors and stop + * any that have * timed out. */ -void MotorSafetyHelper::CheckMotors() -{ - Synchronized sync(m_listMutex); - for (MotorSafetyHelper *msh = m_headHelper; msh != NULL; msh = msh->m_nextHelper) - { - msh->Check(); - } +void MotorSafetyHelper::CheckMotors() { + Synchronized sync(m_listMutex); + for (MotorSafetyHelper *msh = m_headHelper; msh != NULL; + msh = msh->m_nextHelper) { + msh->Check(); + } } diff --git a/wpilibc/wpilibC++Devices/src/Notifier.cpp b/wpilibc/wpilibC++Devices/src/Notifier.cpp index 6901b5ac3e..3511bb3f63 100644 --- a/wpilibc/wpilibC++Devices/src/Notifier.cpp +++ b/wpilibc/wpilibC++Devices/src/Notifier.cpp @@ -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,7 +13,7 @@ Notifier *Notifier::timerQueueHead = NULL; ReentrantSemaphore Notifier::queueSemaphore; -void* Notifier::m_notifier = NULL; +void *Notifier::m_notifier = NULL; int Notifier::refcount = 0; /** @@ -20,29 +21,27 @@ int Notifier::refcount = 0; * @param handler The handler is called at the notification time which is set * using StartSingle or StartPeriodic. */ -Notifier::Notifier(TimerEventHandler handler, void *param) -{ - if (handler == NULL) - wpi_setWPIErrorWithContext(NullParameter, "handler must not be NULL"); - m_handler = handler; - m_param = param; - m_periodic = false; - m_expirationTime = 0; - m_period = 0; - m_nextEvent = NULL; - m_queued = false; - m_handlerSemaphore = initializeSemaphore(SEMAPHORE_FULL); - { - Synchronized sync(queueSemaphore); - // do the first time intialization of static variables - if (refcount == 0) - { - int32_t status = 0; - m_notifier = initializeNotifier(ProcessQueue, &status); - wpi_setErrorWithContext(status, getHALErrorMessage(status)); - } - refcount++; - } +Notifier::Notifier(TimerEventHandler handler, void *param) { + if (handler == NULL) + wpi_setWPIErrorWithContext(NullParameter, "handler must not be NULL"); + m_handler = handler; + m_param = param; + m_periodic = false; + m_expirationTime = 0; + m_period = 0; + m_nextEvent = NULL; + m_queued = false; + m_handlerSemaphore = initializeSemaphore(SEMAPHORE_FULL); + { + Synchronized sync(queueSemaphore); + // do the first time intialization of static variables + if (refcount == 0) { + int32_t status = 0; + m_notifier = initializeNotifier(ProcessQueue, &status); + wpi_setErrorWithContext(status, getHALErrorMessage(status)); + } + refcount++; + } } /** @@ -50,172 +49,160 @@ Notifier::Notifier(TimerEventHandler handler, void *param) * All resources will be freed and the timer event will be removed from the * queue if necessary. */ -Notifier::~Notifier() -{ - { - Synchronized sync(queueSemaphore); - DeleteFromQueue(); +Notifier::~Notifier() { + { + Synchronized sync(queueSemaphore); + DeleteFromQueue(); - // Delete the static variables when the last one is going away - if (!(--refcount)) - { - int32_t status = 0; - cleanNotifier(m_notifier, &status); - wpi_setErrorWithContext(status, getHALErrorMessage(status)); - } - } + // Delete the static variables when the last one is going away + if (!(--refcount)) { + int32_t status = 0; + cleanNotifier(m_notifier, &status); + wpi_setErrorWithContext(status, getHALErrorMessage(status)); + } + } - // Acquire the semaphore; this makes certain that the handler is - // not being executed by the interrupt manager. - takeSemaphore(m_handlerSemaphore); - // Delete while holding the semaphore so there can be no race. - deleteSemaphore(m_handlerSemaphore); + // Acquire the semaphore; this makes certain that the handler is + // not being executed by the interrupt manager. + takeSemaphore(m_handlerSemaphore); + // Delete while holding the semaphore so there can be no race. + deleteSemaphore(m_handlerSemaphore); } /** * Update the alarm hardware to reflect the current first element in the queue. - * Compute the time the next alarm should occur based on the current time and the + * Compute the time the next alarm should occur based on the current time and + * the * period for the first element in the timer queue. - * WARNING: this method does not do synchronization! It must be called from somewhere + * WARNING: this method does not do synchronization! It must be called from + * somewhere * that is taking care of synchronizing access to the queue. */ -void Notifier::UpdateAlarm() -{ - if (timerQueueHead != NULL) - { - int32_t status = 0; - updateNotifierAlarm(m_notifier, (uint32_t)(timerQueueHead->m_expirationTime * 1e6), &status); - wpi_setStaticErrorWithContext(timerQueueHead, status, getHALErrorMessage(status)); - } +void Notifier::UpdateAlarm() { + if (timerQueueHead != NULL) { + int32_t status = 0; + updateNotifierAlarm(m_notifier, + (uint32_t)(timerQueueHead->m_expirationTime * 1e6), + &status); + wpi_setStaticErrorWithContext(timerQueueHead, status, + getHALErrorMessage(status)); + } } /** * ProcessQueue is called whenever there is a timer interrupt. - * We need to wake up and process the current top item in the timer queue as long - * as its scheduled time is after the current time. Then the item is removed or + * We need to wake up and process the current top item in the timer queue as + * long + * as its scheduled time is after the current time. Then the item is removed or * rescheduled (repetitive events) in the queue. */ -void Notifier::ProcessQueue(uint32_t mask, void *params) -{ - Notifier *current; - while (true) // keep processing past events until no more - { - { - Synchronized sync(queueSemaphore); - double currentTime = GetClock(); - current = timerQueueHead; - if (current == NULL || current->m_expirationTime > currentTime) - { - break; // no more timer events to process - } - // need to process this entry - timerQueueHead = current->m_nextEvent; - if (current->m_periodic) - { - // if periodic, requeue the event - // compute when to put into queue - current->InsertInQueue(true); - } - else - { - // not periodic; removed from queue - current->m_queued = false; - } - // Take handler semaphore while holding queue semaphore to make sure - // the handler will execute to completion in case we are being deleted. - takeSemaphore(current->m_handlerSemaphore); - } +void Notifier::ProcessQueue(uint32_t mask, void *params) { + Notifier *current; + while (true) // keep processing past events until no more + { + { + Synchronized sync(queueSemaphore); + double currentTime = GetClock(); + current = timerQueueHead; + if (current == NULL || current->m_expirationTime > currentTime) { + break; // no more timer events to process + } + // need to process this entry + timerQueueHead = current->m_nextEvent; + if (current->m_periodic) { + // if periodic, requeue the event + // compute when to put into queue + current->InsertInQueue(true); + } else { + // not periodic; removed from queue + current->m_queued = false; + } + // Take handler semaphore while holding queue semaphore to make sure + // the handler will execute to completion in case we are being deleted. + takeSemaphore(current->m_handlerSemaphore); + } - current->m_handler(current->m_param); // call the event handler - giveSemaphore(current->m_handlerSemaphore); - } - // reschedule the first item in the queue - Synchronized sync(queueSemaphore); - UpdateAlarm(); + current->m_handler(current->m_param); // call the event handler + giveSemaphore(current->m_handlerSemaphore); + } + // reschedule the first item in the queue + Synchronized sync(queueSemaphore); + UpdateAlarm(); } /** * Insert this Notifier into the timer queue in right place. - * WARNING: this method does not do synchronization! It must be called from somewhere + * WARNING: this method does not do synchronization! It must be called from + * somewhere * that is taking care of synchronizing access to the queue. - * @param reschedule If false, the scheduled alarm is based on the current time and UpdateAlarm + * @param reschedule If false, the scheduled alarm is based on the current time + * and UpdateAlarm * method is called which will enable the alarm if necessary. - * If true, update the time by adding the period (no drift) when rescheduled periodic from ProcessQueue. - * This ensures that the public methods only update the queue after finishing inserting. + * If true, update the time by adding the period (no drift) when rescheduled + * periodic from ProcessQueue. + * This ensures that the public methods only update the queue after finishing + * inserting. */ -void Notifier::InsertInQueue(bool reschedule) -{ - if (reschedule) - { - m_expirationTime += m_period; - } - else - { - m_expirationTime = GetClock() + m_period; - } - if (m_expirationTime > Timer::kRolloverTime) - { - m_expirationTime -= Timer::kRolloverTime; - } - if (timerQueueHead == NULL || timerQueueHead->m_expirationTime >= this->m_expirationTime) - { - // the queue is empty or greater than the new entry - // the new entry becomes the first element - this->m_nextEvent = timerQueueHead; - timerQueueHead = this; - if (!reschedule) - { - // since the first element changed, update alarm, unless we already plan to - UpdateAlarm(); - } - } - else - { - for (Notifier **npp = &(timerQueueHead->m_nextEvent); ; npp = &(*npp)->m_nextEvent) - { - Notifier *n = *npp; - if (n == NULL || n->m_expirationTime > this->m_expirationTime) - { - *npp = this; - this->m_nextEvent = n; - break; - } - } - } - m_queued = true; +void Notifier::InsertInQueue(bool reschedule) { + if (reschedule) { + m_expirationTime += m_period; + } else { + m_expirationTime = GetClock() + m_period; + } + if (m_expirationTime > Timer::kRolloverTime) { + m_expirationTime -= Timer::kRolloverTime; + } + if (timerQueueHead == NULL || + timerQueueHead->m_expirationTime >= this->m_expirationTime) { + // the queue is empty or greater than the new entry + // the new entry becomes the first element + this->m_nextEvent = timerQueueHead; + timerQueueHead = this; + if (!reschedule) { + // since the first element changed, update alarm, unless we already plan + // to + UpdateAlarm(); + } + } else { + for (Notifier **npp = &(timerQueueHead->m_nextEvent);; + npp = &(*npp)->m_nextEvent) { + Notifier *n = *npp; + if (n == NULL || n->m_expirationTime > this->m_expirationTime) { + *npp = this; + this->m_nextEvent = n; + break; + } + } + } + m_queued = true; } /** * Delete this Notifier from the timer queue. - * WARNING: this method does not do synchronization! It must be called from somewhere + * WARNING: this method does not do synchronization! It must be called from + * somewhere * that is taking care of synchronizing access to the queue. - * Remove this Notifier from the timer queue and adjust the next interrupt time to reflect + * Remove this Notifier from the timer queue and adjust the next interrupt time + * to reflect * the current top of the queue. */ -void Notifier::DeleteFromQueue() -{ - if (m_queued) - { - m_queued = false; - wpi_assert(timerQueueHead != NULL); - if (timerQueueHead == this) - { - // remove the first item in the list - update the alarm - timerQueueHead = this->m_nextEvent; - UpdateAlarm(); - } - else - { - for (Notifier *n = timerQueueHead; n != NULL; n = n->m_nextEvent) - { - if (n->m_nextEvent == this) - { - // this element is the next element from *n from the queue - n->m_nextEvent = this->m_nextEvent; // point around this one - } - } - } - } +void Notifier::DeleteFromQueue() { + if (m_queued) { + m_queued = false; + wpi_assert(timerQueueHead != NULL); + if (timerQueueHead == this) { + // remove the first item in the list - update the alarm + timerQueueHead = this->m_nextEvent; + UpdateAlarm(); + } else { + for (Notifier *n = timerQueueHead; n != NULL; n = n->m_nextEvent) { + if (n->m_nextEvent == this) { + // this element is the next element from *n from the queue + n->m_nextEvent = this->m_nextEvent; // point around this one + } + } + } + } } /** @@ -223,43 +210,45 @@ void Notifier::DeleteFromQueue() * A timer event is queued for a single event after the specified delay. * @param delay Seconds to wait before the handler is called. */ -void Notifier::StartSingle(double delay) -{ - Synchronized sync(queueSemaphore); - m_periodic = false; - m_period = delay; - DeleteFromQueue(); - InsertInQueue(false); +void Notifier::StartSingle(double delay) { + Synchronized sync(queueSemaphore); + m_periodic = false; + m_period = delay; + DeleteFromQueue(); + InsertInQueue(false); } /** * Register for periodic event notification. - * A timer event is queued for periodic event notification. Each time the interrupt + * A timer event is queued for periodic event notification. Each time the + * interrupt * occurs, the event will be immediately requeued for the same time interval. - * @param period Period in seconds to call the handler starting one period after the call to this method. + * @param period Period in seconds to call the handler starting one period after + * the call to this method. */ -void Notifier::StartPeriodic(double period) -{ - Synchronized sync(queueSemaphore); - m_periodic = true; - m_period = period; - DeleteFromQueue(); - InsertInQueue(false); +void Notifier::StartPeriodic(double period) { + Synchronized sync(queueSemaphore); + m_periodic = true; + m_period = period; + DeleteFromQueue(); + InsertInQueue(false); } /** * Stop timer events from occuring. - * Stop any repeating timer events from occuring. This will also remove any single + * Stop any repeating timer events from occuring. This will also remove any + * single * notification events from the queue. - * If a timer-based call to the registered handler is in progress, this function will + * If a timer-based call to the registered handler is in progress, this function + * will * block until the handler call is complete. */ -void Notifier::Stop() -{ - { - Synchronized sync(queueSemaphore); - DeleteFromQueue(); - } - // Wait for a currently executing handler to complete before returning from Stop() - Synchronized sync(m_handlerSemaphore); +void Notifier::Stop() { + { + Synchronized sync(queueSemaphore); + DeleteFromQueue(); + } + // Wait for a currently executing handler to complete before returning from + // Stop() + Synchronized sync(m_handlerSemaphore); } diff --git a/wpilibc/wpilibC++Devices/src/PIDController.cpp b/wpilibc/wpilibC++Devices/src/PIDController.cpp index e051d05964..321db72eec 100644 --- a/wpilibc/wpilibC++Devices/src/PIDController.cpp +++ b/wpilibc/wpilibC++Devices/src/PIDController.cpp @@ -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. */ /*----------------------------------------------------------------------------*/ @@ -20,7 +21,6 @@ static const char *kF = "f"; static const char *kSetpoint = "setpoint"; static const char *kEnabled = "enabled"; - /** * Allocate a PID object with the given constants for P, I, D * @param Kp the proportional coefficient @@ -28,15 +28,14 @@ static const char *kEnabled = "enabled"; * @param Kd the derivative coefficient * @param source The PIDSource object that is used to get values * @param output The PIDOutput object that is set to the output value - * @param period the loop time for doing calculations. This particularly effects calculations of the + * @param period the loop time for doing calculations. This particularly effects + * calculations of the * integral and differental terms. The default is 50ms. */ -PIDController::PIDController(float Kp, float Ki, float Kd, - PIDSource *source, PIDOutput *output, - float period) : - m_semaphore (0) -{ - Initialize(Kp, Ki, Kd, 0.0f, source, output, period); +PIDController::PIDController(float Kp, float Ki, float Kd, PIDSource *source, + PIDOutput *output, float period) + : m_semaphore(0) { + Initialize(Kp, Ki, Kd, 0.0f, source, output, period); } /** @@ -46,160 +45,149 @@ PIDController::PIDController(float Kp, float Ki, float Kd, * @param Kd the derivative coefficient * @param source The PIDSource object that is used to get values * @param output The PIDOutput object that is set to the output value - * @param period the loop time for doing calculations. This particularly effects calculations of the + * @param period the loop time for doing calculations. This particularly effects + * calculations of the * integral and differental terms. The default is 50ms. */ PIDController::PIDController(float Kp, float Ki, float Kd, float Kf, - PIDSource *source, PIDOutput *output, - float period) : - m_semaphore (0) -{ - Initialize(Kp, Ki, Kd, Kf, source, output, period); + PIDSource *source, PIDOutput *output, float period) + : m_semaphore(0) { + Initialize(Kp, Ki, Kd, Kf, source, output, period); } - void PIDController::Initialize(float Kp, float Ki, float Kd, float Kf, - PIDSource *source, PIDOutput *output, - float period) -{ - m_table = NULL; + PIDSource *source, PIDOutput *output, + float period) { + m_table = NULL; - m_semaphore = initializeMutexNormal(); + m_semaphore = initializeMutexNormal(); - m_controlLoop = new Notifier(PIDController::CallCalculate, this); + m_controlLoop = new Notifier(PIDController::CallCalculate, this); - m_P = Kp; - m_I = Ki; - m_D = Kd; - m_F = Kf; + m_P = Kp; + m_I = Ki; + m_D = Kd; + m_F = Kf; - m_maximumOutput = 1.0; - m_minimumOutput = -1.0; + m_maximumOutput = 1.0; + m_minimumOutput = -1.0; - m_maximumInput = 0; - m_minimumInput = 0; + m_maximumInput = 0; + m_minimumInput = 0; - m_continuous = false; - m_enabled = false; - m_setpoint = 0; + m_continuous = false; + m_enabled = false; + m_setpoint = 0; - m_prevError = 0; - m_totalError = 0; - m_tolerance = .05; + m_prevError = 0; + m_totalError = 0; + m_tolerance = .05; - m_result = 0; + m_result = 0; - m_pidInput = source; - m_pidOutput = output; - m_period = period; + m_pidInput = source; + m_pidOutput = output; + m_period = period; - m_controlLoop->StartPeriodic(m_period); + m_controlLoop->StartPeriodic(m_period); - static int32_t instances = 0; - instances++; - HALReport(HALUsageReporting::kResourceType_PIDController, instances); + static int32_t instances = 0; + instances++; + HALReport(HALUsageReporting::kResourceType_PIDController, instances); - m_toleranceType = kNoTolerance; + m_toleranceType = kNoTolerance; } /** * Free the PID object */ -PIDController::~PIDController() -{ - takeMutex(m_semaphore); - deleteMutex(m_semaphore); - delete m_controlLoop; +PIDController::~PIDController() { + takeMutex(m_semaphore); + deleteMutex(m_semaphore); + delete m_controlLoop; } /** - * Call the Calculate method as a non-static method. This avoids having to prepend - * all local variables in that method with the class pointer. This way the "this" + * Call the Calculate method as a non-static method. This avoids having to + * prepend + * all local variables in that method with the class pointer. This way the + * "this" * pointer will be set up and class variables can be called more easily. * This method is static and called by the Notifier class. - * @param controller the address of the PID controller object to use in the background loop + * @param controller the address of the PID controller object to use in the + * background loop */ -void PIDController::CallCalculate(void *controller) -{ - PIDController *control = (PIDController*) controller; - control->Calculate(); +void PIDController::CallCalculate(void *controller) { + PIDController *control = (PIDController *)controller; + control->Calculate(); } - /** - * Read the input, calculate the output accordingly, and write to the output. - * This should only be called by the Notifier indirectly through CallCalculate - * and is created during initialization. - */ -void PIDController::Calculate() -{ - bool enabled; - PIDSource *pidInput; - PIDOutput *pidOutput; +/** + * Read the input, calculate the output accordingly, and write to the output. + * This should only be called by the Notifier indirectly through CallCalculate + * and is created during initialization. + */ +void PIDController::Calculate() { + bool enabled; + PIDSource *pidInput; + PIDOutput *pidOutput; - CRITICAL_REGION(m_semaphore) - { - pidInput = m_pidInput; - pidOutput = m_pidOutput; - enabled = m_enabled; - pidInput = m_pidInput; - } - END_REGION; + CRITICAL_REGION(m_semaphore) { + pidInput = m_pidInput; + pidOutput = m_pidOutput; + enabled = m_enabled; + pidInput = m_pidInput; + } + END_REGION; - if (pidInput == NULL) return; - if (pidOutput == NULL) return; + if (pidInput == NULL) return; + if (pidOutput == NULL) return; - if (enabled) - { - { - Synchronized sync(m_semaphore); + if (enabled) { + { + Synchronized sync(m_semaphore); float input = pidInput->PIDGet(); float result; PIDOutput *pidOutput; - m_error = m_setpoint - input; - if (m_continuous) - { - if (fabs(m_error) > (m_maximumInput - m_minimumInput) / 2) - { - if (m_error > 0) - { - m_error = m_error - m_maximumInput + m_minimumInput; - } - else - { - m_error = m_error + m_maximumInput - m_minimumInput; - } - } - } + m_error = m_setpoint - input; + if (m_continuous) { + if (fabs(m_error) > (m_maximumInput - m_minimumInput) / 2) { + if (m_error > 0) { + m_error = m_error - m_maximumInput + m_minimumInput; + } else { + m_error = m_error + m_maximumInput - m_minimumInput; + } + } + } - if(m_I != 0) - { - double potentialIGain = (m_totalError + m_error) * m_I; - if (potentialIGain < m_maximumOutput) - { - if (potentialIGain > m_minimumOutput) - m_totalError += m_error; - else - m_totalError = m_minimumOutput / m_I; - } - else - { - m_totalError = m_maximumOutput / m_I; - } - } + if (m_I != 0) { + double potentialIGain = (m_totalError + m_error) * m_I; + if (potentialIGain < m_maximumOutput) { + if (potentialIGain > m_minimumOutput) + m_totalError += m_error; + else + m_totalError = m_minimumOutput / m_I; + } else { + m_totalError = m_maximumOutput / m_I; + } + } - m_result = m_P * m_error + m_I * m_totalError + m_D * (m_error - m_prevError) + m_setpoint * m_F; - m_prevError = m_error; + m_result = m_P * m_error + m_I * m_totalError + + m_D * (m_error - m_prevError) + m_setpoint * m_F; + m_prevError = m_error; - if (m_result > m_maximumOutput) m_result = m_maximumOutput; - else if (m_result < m_minimumOutput) m_result = m_minimumOutput; + if (m_result > m_maximumOutput) + m_result = m_maximumOutput; + else if (m_result < m_minimumOutput) + m_result = m_minimumOutput; - pidOutput = m_pidOutput; - result = m_result; + pidOutput = m_pidOutput; + result = m_result; pidOutput->PIDWrite(result); - } - } + } + } } /** @@ -209,21 +197,19 @@ void PIDController::Calculate() * @param i Integral coefficient * @param d Differential coefficient */ -void PIDController::SetPID(double p, double i, double d) -{ - CRITICAL_REGION(m_semaphore) - { - m_P = p; - m_I = i; - m_D = d; - } - END_REGION; +void PIDController::SetPID(double p, double i, double d) { + CRITICAL_REGION(m_semaphore) { + m_P = p; + m_I = i; + m_D = d; + } + END_REGION; - if (m_table != NULL) { - m_table->PutNumber("p", m_P); - m_table->PutNumber("i", m_I); - m_table->PutNumber("d", m_D); - } + if (m_table != NULL) { + m_table->PutNumber("p", m_P); + m_table->PutNumber("i", m_I); + m_table->PutNumber("d", m_D); + } } /** @@ -234,75 +220,57 @@ void PIDController::SetPID(double p, double i, double d) * @param d Differential coefficient * @param f Feed forward coefficient */ -void PIDController::SetPID(double p, double i, double d, double f) -{ - CRITICAL_REGION(m_semaphore) - { - m_P = p; - m_I = i; - m_D = d; - m_F = f; - } - END_REGION; +void PIDController::SetPID(double p, double i, double d, double f) { + CRITICAL_REGION(m_semaphore) { + m_P = p; + m_I = i; + m_D = d; + m_F = f; + } + END_REGION; - if (m_table != NULL) { - m_table->PutNumber("p", m_P); - m_table->PutNumber("i", m_I); - m_table->PutNumber("d", m_D); - m_table->PutNumber("f", m_F); - } + if (m_table != NULL) { + m_table->PutNumber("p", m_P); + m_table->PutNumber("i", m_I); + m_table->PutNumber("d", m_D); + m_table->PutNumber("f", m_F); + } } /** * Get the Proportional coefficient * @return proportional coefficient */ -double PIDController::GetP() const -{ - CRITICAL_REGION(m_semaphore) - { - return m_P; - } - END_REGION; +double PIDController::GetP() const { + CRITICAL_REGION(m_semaphore) { return m_P; } + END_REGION; } /** * Get the Integral coefficient * @return integral coefficient */ -double PIDController::GetI() const -{ - CRITICAL_REGION(m_semaphore) - { - return m_I; - } - END_REGION; +double PIDController::GetI() const { + CRITICAL_REGION(m_semaphore) { return m_I; } + END_REGION; } /** * Get the Differential coefficient * @return differential coefficient */ -double PIDController::GetD() const -{ - CRITICAL_REGION(m_semaphore) - { - return m_D; - } - END_REGION; +double PIDController::GetD() const { + CRITICAL_REGION(m_semaphore) { return m_D; } + END_REGION; } /** * Get the Feed forward coefficient * @return Feed forward coefficient */ -double PIDController::GetF() const -{ - CRITICAL_REGION(m_semaphore) - { - return m_F; - } - END_REGION; +double PIDController::GetF() const { + CRITICAL_REGION(m_semaphore) { return m_F; } + END_REGION; } /** @@ -310,15 +278,11 @@ double PIDController::GetF() const * This is always centered on zero and constrained the the max and min outs * @return the latest calculated output */ -float PIDController::Get() const -{ - float result; - CRITICAL_REGION(m_semaphore) - { - result = m_result; - } - END_REGION; - return result; +float PIDController::Get() const { + float result; + CRITICAL_REGION(m_semaphore) { result = m_result; } + END_REGION; + return result; } /** @@ -328,13 +292,9 @@ float PIDController::Get() const * the setpoint. * @param continuous Set to true turns on continuous, false turns off continuous */ -void PIDController::SetContinuous(bool continuous) -{ - CRITICAL_REGION(m_semaphore) - { - m_continuous = continuous; - } - END_REGION; +void PIDController::SetContinuous(bool continuous) { + CRITICAL_REGION(m_semaphore) { m_continuous = continuous; } + END_REGION; } /** @@ -343,16 +303,14 @@ void PIDController::SetContinuous(bool continuous) * @param minimumInput the minimum value expected from the input * @param maximumInput the maximum value expected from the output */ -void PIDController::SetInputRange(float minimumInput, float maximumInput) -{ - CRITICAL_REGION(m_semaphore) - { - m_minimumInput = minimumInput; - m_maximumInput = maximumInput; - } - END_REGION; +void PIDController::SetInputRange(float minimumInput, float maximumInput) { + CRITICAL_REGION(m_semaphore) { + m_minimumInput = minimumInput; + m_maximumInput = maximumInput; + } + END_REGION; - SetSetpoint(m_setpoint); + SetSetpoint(m_setpoint); } /** @@ -361,75 +319,60 @@ void PIDController::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 PIDController::SetOutputRange(float minimumOutput, float maximumOutput) -{ - CRITICAL_REGION(m_semaphore) - { - m_minimumOutput = minimumOutput; - m_maximumOutput = maximumOutput; - } - END_REGION; +void PIDController::SetOutputRange(float minimumOutput, float maximumOutput) { + CRITICAL_REGION(m_semaphore) { + m_minimumOutput = minimumOutput; + m_maximumOutput = maximumOutput; + } + END_REGION; } /** * Set the setpoint for the PIDController * @param setpoint the desired setpoint */ -void PIDController::SetSetpoint(float setpoint) -{ - CRITICAL_REGION(m_semaphore) - { - if (m_maximumInput > m_minimumInput) - { - if (setpoint > m_maximumInput) - m_setpoint = m_maximumInput; - else if (setpoint < m_minimumInput) - m_setpoint = m_minimumInput; - else - m_setpoint = setpoint; - } - else - { - m_setpoint = setpoint; - } - } - END_REGION; +void PIDController::SetSetpoint(float setpoint) { + CRITICAL_REGION(m_semaphore) { + if (m_maximumInput > m_minimumInput) { + if (setpoint > m_maximumInput) + m_setpoint = m_maximumInput; + else if (setpoint < m_minimumInput) + m_setpoint = m_minimumInput; + else + m_setpoint = setpoint; + } else { + m_setpoint = setpoint; + } + } + END_REGION; - if (m_table != NULL) { - m_table->PutNumber("setpoint", m_setpoint); - } + if (m_table != NULL) { + m_table->PutNumber("setpoint", m_setpoint); + } } /** * Returns the current setpoint of the PIDController * @return the current setpoint */ -double PIDController::GetSetpoint() const -{ - float setpoint; - CRITICAL_REGION(m_semaphore) - { - setpoint = m_setpoint; - } - END_REGION; - return setpoint; +double PIDController::GetSetpoint() const { + float setpoint; + CRITICAL_REGION(m_semaphore) { setpoint = m_setpoint; } + END_REGION; + return setpoint; } /** * Retruns the current difference of the input from the setpoint * @return the current error */ -float PIDController::GetError() const -{ - float error; +float PIDController::GetError() const { + float error; double pidInput; - CRITICAL_REGION(m_semaphore) - { - pidInput = m_pidInput->PIDGet(); - } - END_REGION; + CRITICAL_REGION(m_semaphore) { pidInput = m_pidInput->PIDGet(); } + END_REGION; error = GetSetpoint() - pidInput; - return error; + return error; } /* @@ -437,14 +380,12 @@ float PIDController::GetError() const * OnTarget. * @param percentage error which is tolerable */ -void PIDController::SetTolerance(float percent) -{ - CRITICAL_REGION(m_semaphore) - { - m_toleranceType = kPercentTolerance; - m_tolerance = percent; - } - END_REGION; +void PIDController::SetTolerance(float percent) { + CRITICAL_REGION(m_semaphore) { + m_toleranceType = kPercentTolerance; + m_tolerance = percent; + } + END_REGION; } /* @@ -452,14 +393,12 @@ void PIDController::SetTolerance(float percent) * OnTarget. * @param percentage error which is tolerable */ -void PIDController::SetPercentTolerance(float percent) -{ - CRITICAL_REGION(m_semaphore) - { - m_toleranceType = kPercentTolerance; - m_tolerance = percent; - } - END_REGION; +void PIDController::SetPercentTolerance(float percent) { + CRITICAL_REGION(m_semaphore) { + m_toleranceType = kPercentTolerance; + m_tolerance = percent; + } + END_REGION; } /* @@ -467,155 +406,136 @@ void PIDController::SetPercentTolerance(float percent) * OnTarget. * @param percentage error which is tolerable */ -void PIDController::SetAbsoluteTolerance(float absTolerance) -{ - CRITICAL_REGION(m_semaphore) - { - m_toleranceType = kAbsoluteTolerance; - m_tolerance = absTolerance; - } - END_REGION; +void PIDController::SetAbsoluteTolerance(float absTolerance) { + CRITICAL_REGION(m_semaphore) { + m_toleranceType = kAbsoluteTolerance; + m_tolerance = absTolerance; + } + END_REGION; } /* * 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. - * 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. */ -bool PIDController::OnTarget() const -{ - bool temp; +bool PIDController::OnTarget() const { + bool temp; double error = GetError(); - CRITICAL_REGION(m_semaphore) - { - switch (m_toleranceType) { - case kPercentTolerance: - temp = fabs(error) < (m_tolerance / 100 * (m_maximumInput - m_minimumInput)); - break; - case kAbsoluteTolerance: - temp = fabs(error) < m_tolerance; - break; - //TODO: this case needs an error - case kNoTolerance: - temp = false; - } - } - END_REGION; - return temp; + CRITICAL_REGION(m_semaphore) { + switch (m_toleranceType) { + case kPercentTolerance: + temp = fabs(error) < + (m_tolerance / 100 * (m_maximumInput - m_minimumInput)); + break; + case kAbsoluteTolerance: + temp = fabs(error) < m_tolerance; + break; + // TODO: this case needs an error + case kNoTolerance: + temp = false; + } + } + END_REGION; + return temp; } /** * Begin running the PIDController */ -void PIDController::Enable() -{ - CRITICAL_REGION(m_semaphore) - { - m_enabled = true; - } - END_REGION; +void PIDController::Enable() { + CRITICAL_REGION(m_semaphore) { m_enabled = true; } + END_REGION; - if (m_table != NULL) { - m_table->PutBoolean("enabled", true); - } + if (m_table != NULL) { + m_table->PutBoolean("enabled", true); + } } /** * Stop running the PIDController, this sets the output to zero before stopping. */ -void PIDController::Disable() -{ - CRITICAL_REGION(m_semaphore) - { - m_pidOutput->PIDWrite(0); - m_enabled = false; - } - END_REGION; +void PIDController::Disable() { + CRITICAL_REGION(m_semaphore) { + m_pidOutput->PIDWrite(0); + m_enabled = false; + } + END_REGION; - if (m_table != NULL) { - m_table->PutBoolean("enabled", false); - } + if (m_table != NULL) { + m_table->PutBoolean("enabled", false); + } } /** * Return true if PIDController is enabled. */ -bool PIDController::IsEnabled() const -{ - bool enabled; - CRITICAL_REGION(m_semaphore) - { - enabled = m_enabled; - } - END_REGION; - return enabled; +bool PIDController::IsEnabled() const { + bool enabled; + CRITICAL_REGION(m_semaphore) { enabled = m_enabled; } + END_REGION; + return enabled; } /** * Reset the previous error,, the integral term, and disable the controller. */ -void PIDController::Reset() -{ - Disable(); +void PIDController::Reset() { + Disable(); - CRITICAL_REGION(m_semaphore) - { - m_prevError = 0; - m_totalError = 0; - m_result = 0; - } - END_REGION; + CRITICAL_REGION(m_semaphore) { + m_prevError = 0; + m_totalError = 0; + m_result = 0; + } + END_REGION; } std::string PIDController::GetSmartDashboardType() const { - return "PIDController"; + return "PIDController"; } -void PIDController::InitTable(ITable* table){ - if(m_table!=NULL) - m_table->RemoveTableListener(this); - m_table = table; - if(m_table!=NULL){ - m_table->PutNumber(kP, GetP()); - m_table->PutNumber(kI, GetI()); - m_table->PutNumber(kD, GetD()); - m_table->PutNumber(kF, GetF()); - m_table->PutNumber(kSetpoint, GetSetpoint()); - m_table->PutBoolean(kEnabled, IsEnabled()); - m_table->AddTableListener(this, false); - } +void PIDController::InitTable(ITable *table) { + if (m_table != NULL) m_table->RemoveTableListener(this); + m_table = table; + if (m_table != NULL) { + m_table->PutNumber(kP, GetP()); + m_table->PutNumber(kI, GetI()); + m_table->PutNumber(kD, GetD()); + m_table->PutNumber(kF, GetF()); + m_table->PutNumber(kSetpoint, GetSetpoint()); + m_table->PutBoolean(kEnabled, IsEnabled()); + m_table->AddTableListener(this, false); + } } -ITable* PIDController::GetTable() const { - return m_table; +ITable *PIDController::GetTable() const { return m_table; } + +void PIDController::ValueChanged(ITable *source, const std::string &key, + EntryValue value, bool isNew) { + if (key == kP || key == kI || key == kD || key == kF) { + if (m_P != m_table->GetNumber(kP) || m_I != m_table->GetNumber(kI) || + m_D != m_table->GetNumber(kD) || m_F != m_table->GetNumber(kF)) { + SetPID(m_table->GetNumber(kP, 0.0), m_table->GetNumber(kI, 0.0), + m_table->GetNumber(kD, 0.0), m_table->GetNumber(kF, 0.0)); + } + } else if (key == kSetpoint && m_setpoint != value.f) { + SetSetpoint(value.f); + } else if (key == kEnabled && m_enabled != value.b) { + if (value.b) { + Enable(); + } else { + Disable(); + } + } } -void PIDController::ValueChanged(ITable* source, const std::string& key, EntryValue value, bool isNew){ - if (key==kP || key==kI || key==kD || key==kF) { - if (m_P != m_table->GetNumber(kP) || m_I != m_table->GetNumber(kI) || m_D != m_table->GetNumber(kD) || m_F != m_table->GetNumber(kF) ) { - SetPID(m_table->GetNumber(kP, 0.0), m_table->GetNumber(kI, 0.0), m_table->GetNumber(kD, 0.0), m_table->GetNumber(kF, 0.0)); - } - } else if (key==kSetpoint && m_setpoint != value.f) { - SetSetpoint(value.f); - } else if (key==kEnabled && m_enabled != value.b) { - if (value.b) { - Enable(); - } else { - Disable(); - } - } -} +void PIDController::UpdateTable() {} -void PIDController::UpdateTable() { +void PIDController::StartLiveWindowMode() { Disable(); } -} - -void PIDController::StartLiveWindowMode() { - Disable(); -} - -void PIDController::StopLiveWindowMode() { - -} +void PIDController::StopLiveWindowMode() {} diff --git a/wpilibc/wpilibC++Devices/src/PWM.cpp b/wpilibc/wpilibC++Devices/src/PWM.cpp index 54db77d5c8..468db5c0f9 100644 --- a/wpilibc/wpilibC++Devices/src/PWM.cpp +++ b/wpilibc/wpilibC++Devices/src/PWM.cpp @@ -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. */ /*----------------------------------------------------------------------------*/ @@ -20,35 +21,36 @@ const int32_t PWM::kPwmDisabled; /** * Initialize PWMs given a channel. * - * This method is private and is the common path for all the constructors for creating PWM + * This method is private and is the common path for all the constructors for + * creating PWM * instances. Checks channel value range and allocates the appropriate channel. - * The allocation is only done to help users ensure that they don't double assign channels. - * @param channel The PWM channel number. 0-9 are on-board, 10-19 are on the MXP port + * The allocation is only done to help users ensure that they don't double + * assign channels. + * @param channel The PWM channel number. 0-9 are on-board, 10-19 are on the MXP + * port */ -void PWM::InitPWM(uint32_t channel) -{ - m_table = NULL; - char buf[64]; +void PWM::InitPWM(uint32_t channel) { + m_table = NULL; + char buf[64]; - if (!CheckPWMChannel(channel)) - { - snprintf(buf, 64, "PWM Channel %d", channel); - wpi_setWPIErrorWithContext(ChannelIndexOutOfRange, buf); - return; - } + if (!CheckPWMChannel(channel)) { + snprintf(buf, 64, "PWM Channel %d", channel); + wpi_setWPIErrorWithContext(ChannelIndexOutOfRange, buf); + return; + } - int32_t status = 0; - allocatePWMChannel(m_pwm_ports[channel], &status); - wpi_setErrorWithContext(status, getHALErrorMessage(status)); + int32_t status = 0; + allocatePWMChannel(m_pwm_ports[channel], &status); + wpi_setErrorWithContext(status, getHALErrorMessage(status)); - m_channel = channel; + m_channel = channel; - setPWM(m_pwm_ports[m_channel], kPwmDisabled, &status); - wpi_setErrorWithContext(status, getHALErrorMessage(status)); + setPWM(m_pwm_ports[m_channel], kPwmDisabled, &status); + wpi_setErrorWithContext(status, getHALErrorMessage(status)); - m_eliminateDeadband = false; + m_eliminateDeadband = false; - HALReport(HALUsageReporting::kResourceType_PWM, channel); + HALReport(HALUsageReporting::kResourceType_PWM, channel); } /** @@ -56,42 +58,40 @@ void PWM::InitPWM(uint32_t channel) * * @param channel The PWM channel. */ -PWM::PWM(uint32_t channel) -{ - InitPWM(channel); -} +PWM::PWM(uint32_t channel) { InitPWM(channel); } /** * Free the PWM channel. * * Free the resource associated with the PWM channel and set the value to 0. */ -PWM::~PWM() -{ - int32_t status = 0; +PWM::~PWM() { + int32_t status = 0; - setPWM(m_pwm_ports[m_channel], kPwmDisabled, &status); - wpi_setErrorWithContext(status, getHALErrorMessage(status)); + setPWM(m_pwm_ports[m_channel], kPwmDisabled, &status); + wpi_setErrorWithContext(status, getHALErrorMessage(status)); - freePWMChannel(m_pwm_ports[m_channel], &status); - wpi_setErrorWithContext(status, getHALErrorMessage(status)); + freePWMChannel(m_pwm_ports[m_channel], &status); + wpi_setErrorWithContext(status, getHALErrorMessage(status)); } /** * Optionally eliminate the deadband from a speed controller. - * @param eliminateDeadband If true, set the motor curve on the Jaguar to eliminate - * the deadband in the middle of the range. Otherwise, keep the full range without + * @param eliminateDeadband If true, set the motor curve on the Jaguar to + * eliminate + * the deadband in the middle of the range. Otherwise, keep the full range + * without * modifying any values. */ -void PWM::EnableDeadbandElimination(bool eliminateDeadband) -{ - if (StatusIsFatal()) return; - m_eliminateDeadband = eliminateDeadband; +void PWM::EnableDeadbandElimination(bool eliminateDeadband) { + if (StatusIsFatal()) return; + m_eliminateDeadband = eliminateDeadband; } /** * Set the bounds on the PWM values. - * This sets the bounds on the PWM values for a particular each type of controller. The values + * This sets the bounds on the PWM values for a particular each type of + * controller. The values * determine the upper and lower speeds as well as the deadband bracket. * @param max The Minimum pwm value * @param deadbandMax The high end of the deadband range @@ -99,20 +99,20 @@ void PWM::EnableDeadbandElimination(bool eliminateDeadband) * @param deadbandMin The low end of the deadband range * @param min The minimum pwm value */ -void PWM::SetBounds(int32_t max, int32_t deadbandMax, int32_t center, int32_t deadbandMin, int32_t min) -{ - if (StatusIsFatal()) return; - m_maxPwm = max; - m_deadbandMaxPwm = deadbandMax; - m_centerPwm = center; - m_deadbandMinPwm = deadbandMin; - m_minPwm = min; +void PWM::SetBounds(int32_t max, int32_t deadbandMax, int32_t center, + int32_t deadbandMin, int32_t min) { + if (StatusIsFatal()) return; + m_maxPwm = max; + m_deadbandMaxPwm = deadbandMax; + m_centerPwm = center; + m_deadbandMinPwm = deadbandMin; + m_minPwm = min; } - /** * Set the bounds on the PWM pulse widths. - * This sets the bounds on the PWM values for a particular type of controller. The values + * This sets the bounds on the PWM values for a particular type of controller. + * The values * determine the upper and lower speeds as well as the deadband bracket. * @param max The max PWM pulse width in ms * @param deadbandMax The high end of the deadband range pulse width in ms @@ -120,20 +120,26 @@ void PWM::SetBounds(int32_t max, int32_t deadbandMax, int32_t center, int32_t de * @param deadbandMin The low end of the deadband pulse width in ms * @param min The minimum pulse width in ms */ -void PWM::SetBounds(double max, double deadbandMax, double center, double deadbandMin, double min) -{ - // calculate the loop time in milliseconds - int32_t status = 0; - double loopTime = getLoopTiming(&status)/(kSystemClockTicksPerMicrosecond*1e3); - wpi_setErrorWithContext(status, getHALErrorMessage(status)); +void PWM::SetBounds(double max, double deadbandMax, double center, + double deadbandMin, double min) { + // calculate the loop time in milliseconds + int32_t status = 0; + double loopTime = + getLoopTiming(&status) / (kSystemClockTicksPerMicrosecond * 1e3); + wpi_setErrorWithContext(status, getHALErrorMessage(status)); - if (StatusIsFatal()) return; + if (StatusIsFatal()) return; - m_maxPwm = (int32_t)((max-kDefaultPwmCenter)/loopTime+kDefaultPwmStepsDown-1); - m_deadbandMaxPwm = (int32_t)((deadbandMax-kDefaultPwmCenter)/loopTime+kDefaultPwmStepsDown-1); - m_centerPwm = (int32_t)((center-kDefaultPwmCenter)/loopTime+kDefaultPwmStepsDown-1); - m_deadbandMinPwm = (int32_t)((deadbandMin-kDefaultPwmCenter)/loopTime+kDefaultPwmStepsDown-1); - m_minPwm = (int32_t)((min-kDefaultPwmCenter)/loopTime+kDefaultPwmStepsDown-1); + m_maxPwm = (int32_t)((max - kDefaultPwmCenter) / loopTime + + kDefaultPwmStepsDown - 1); + m_deadbandMaxPwm = (int32_t)((deadbandMax - kDefaultPwmCenter) / loopTime + + kDefaultPwmStepsDown - 1); + m_centerPwm = (int32_t)((center - kDefaultPwmCenter) / loopTime + + kDefaultPwmStepsDown - 1); + m_deadbandMinPwm = (int32_t)((deadbandMin - kDefaultPwmCenter) / loopTime + + kDefaultPwmStepsDown - 1); + m_minPwm = (int32_t)((min - kDefaultPwmCenter) / loopTime + + kDefaultPwmStepsDown - 1); } /** @@ -146,27 +152,28 @@ void PWM::SetBounds(double max, double deadbandMax, double center, double deadba * * @param pos The position to set the servo between 0.0 and 1.0. */ -void PWM::SetPosition(float pos) -{ - if (StatusIsFatal()) return; - if (pos < 0.0) - { - pos = 0.0; - } - else if (pos > 1.0) - { - pos = 1.0; - } +void PWM::SetPosition(float pos) { + if (StatusIsFatal()) return; + if (pos < 0.0) { + pos = 0.0; + } else if (pos > 1.0) { + pos = 1.0; + } - // note, need to perform the multiplication below as floating point before converting to int - unsigned short rawValue = (int32_t)( (pos * (float) GetFullRangeScaleFactor()) + GetMinNegativePwm()); -// printf("MinNegPWM: %d FullRangeScaleFactor: %d Raw value: %5d Input value: %4.4f\n", GetMinNegativePwm(), GetFullRangeScaleFactor(), rawValue, pos); + // note, need to perform the multiplication below as floating point before + // converting to int + unsigned short rawValue = + (int32_t)((pos * (float)GetFullRangeScaleFactor()) + GetMinNegativePwm()); + // printf("MinNegPWM: %d FullRangeScaleFactor: %d Raw value: %5d Input + //value: %4.4f\n", GetMinNegativePwm(), GetFullRangeScaleFactor(), rawValue, + //pos); -// wpi_assert((rawValue >= GetMinNegativePwm()) && (rawValue <= GetMaxPositivePwm())); - wpi_assert(rawValue != kPwmDisabled); + // wpi_assert((rawValue >= GetMinNegativePwm()) && (rawValue <= + //GetMaxPositivePwm())); + wpi_assert(rawValue != kPwmDisabled); - // send the computed pwm value to the FPGA - SetRaw((unsigned short)rawValue); + // send the computed pwm value to the FPGA + SetRaw((unsigned short)rawValue); } /** @@ -179,22 +186,17 @@ void PWM::SetPosition(float pos) * * @return The position the servo is set to between 0.0 and 1.0. */ -float PWM::GetPosition() const -{ - if (StatusIsFatal()) return 0.0; - int32_t value = GetRaw(); - if (value < GetMinNegativePwm()) - { - return 0.0; - } - else if (value > GetMaxPositivePwm()) - { - return 1.0; - } - else - { - return (float)(value - GetMinNegativePwm()) / (float)GetFullRangeScaleFactor(); - } +float PWM::GetPosition() const { + if (StatusIsFatal()) return 0.0; + int32_t value = GetRaw(); + if (value < GetMinNegativePwm()) { + return 0.0; + } else if (value > GetMaxPositivePwm()) { + return 1.0; + } else { + return (float)(value - GetMinNegativePwm()) / + (float)GetFullRangeScaleFactor(); + } } /** @@ -210,42 +212,34 @@ float PWM::GetPosition() const * * @param speed The speed to set the speed controller between -1.0 and 1.0. */ -void PWM::SetSpeed(float speed) -{ - if (StatusIsFatal()) return; - // clamp speed to be in the range 1.0 >= speed >= -1.0 - if (speed < -1.0) - { - speed = -1.0; - } - else if (speed > 1.0) - { - speed = 1.0; - } +void PWM::SetSpeed(float speed) { + if (StatusIsFatal()) return; + // clamp speed to be in the range 1.0 >= speed >= -1.0 + if (speed < -1.0) { + speed = -1.0; + } else if (speed > 1.0) { + speed = 1.0; + } - // calculate the desired output pwm value by scaling the speed appropriately - int32_t rawValue; - if (speed == 0.0) - { - rawValue = GetCenterPwm(); - } - else if (speed > 0.0) - { - rawValue = (int32_t)(speed * ((float)GetPositiveScaleFactor()) + - ((float) GetMinPositivePwm()) + 0.5); - } - else - { - rawValue = (int32_t)(speed * ((float)GetNegativeScaleFactor()) + - ((float) GetMaxNegativePwm()) + 0.5); - } + // calculate the desired output pwm value by scaling the speed appropriately + int32_t rawValue; + if (speed == 0.0) { + rawValue = GetCenterPwm(); + } else if (speed > 0.0) { + rawValue = (int32_t)(speed * ((float)GetPositiveScaleFactor()) + + ((float)GetMinPositivePwm()) + 0.5); + } else { + rawValue = (int32_t)(speed * ((float)GetNegativeScaleFactor()) + + ((float)GetMaxNegativePwm()) + 0.5); + } - // the above should result in a pwm_value in the valid range - wpi_assert((rawValue >= GetMinNegativePwm()) && (rawValue <= GetMaxPositivePwm())); - wpi_assert(rawValue != kPwmDisabled); + // the above should result in a pwm_value in the valid range + wpi_assert((rawValue >= GetMinNegativePwm()) && + (rawValue <= GetMaxPositivePwm())); + wpi_assert(rawValue != kPwmDisabled); - // send the computed pwm value to the FPGA - SetRaw(rawValue); + // send the computed pwm value to the FPGA + SetRaw(rawValue); } /** @@ -260,34 +254,24 @@ void PWM::SetSpeed(float speed) * * @return The most recently set speed between -1.0 and 1.0. */ -float PWM::GetSpeed() const -{ - if (StatusIsFatal()) return 0.0; - int32_t value = GetRaw(); - if (value == PWM::kPwmDisabled) - { - return 0.0; - } - else if (value > GetMaxPositivePwm()) - { - return 1.0; - } - else if (value < GetMinNegativePwm()) - { - return -1.0; - } - else if (value > GetMinPositivePwm()) - { - return (float)(value - GetMinPositivePwm()) / (float)GetPositiveScaleFactor(); - } - else if (value < GetMaxNegativePwm()) - { - return (float)(value - GetMaxNegativePwm()) / (float)GetNegativeScaleFactor(); - } - else - { - return 0.0; - } +float PWM::GetSpeed() const { + if (StatusIsFatal()) return 0.0; + int32_t value = GetRaw(); + if (value == PWM::kPwmDisabled) { + return 0.0; + } else if (value > GetMaxPositivePwm()) { + return 1.0; + } else if (value < GetMinNegativePwm()) { + return -1.0; + } else if (value > GetMinPositivePwm()) { + return (float)(value - GetMinPositivePwm()) / + (float)GetPositiveScaleFactor(); + } else if (value < GetMaxNegativePwm()) { + return (float)(value - GetMaxNegativePwm()) / + (float)GetNegativeScaleFactor(); + } else { + return 0.0; + } } /** @@ -297,13 +281,12 @@ float PWM::GetSpeed() const * * @param value Raw PWM value. */ -void PWM::SetRaw(unsigned short value) -{ - if (StatusIsFatal()) return; +void PWM::SetRaw(unsigned short value) { + if (StatusIsFatal()) return; - int32_t status = 0; - setPWM(m_pwm_ports[m_channel], value, &status); - wpi_setErrorWithContext(status, getHALErrorMessage(status)); + int32_t status = 0; + setPWM(m_pwm_ports[m_channel], value, &status); + wpi_setErrorWithContext(status, getHALErrorMessage(status)); } /** @@ -313,15 +296,14 @@ void PWM::SetRaw(unsigned short value) * * @return Raw PWM control value. */ -unsigned short PWM::GetRaw() const -{ - if (StatusIsFatal()) return 0; +unsigned short PWM::GetRaw() const { + if (StatusIsFatal()) return 0; - int32_t status = 0; - unsigned short value = getPWM(m_pwm_ports[m_channel], &status); - wpi_setErrorWithContext(status, getHALErrorMessage(status)); + int32_t status = 0; + unsigned short value = getPWM(m_pwm_ports[m_channel], &status); + wpi_setErrorWithContext(status, getHALErrorMessage(status)); - return value; + return value; } /** @@ -329,74 +311,70 @@ unsigned short PWM::GetRaw() const * * @param mult The period multiplier to apply to this channel */ -void PWM::SetPeriodMultiplier(PeriodMultiplier mult) -{ - if (StatusIsFatal()) return; +void PWM::SetPeriodMultiplier(PeriodMultiplier mult) { + if (StatusIsFatal()) return; - int32_t status = 0; + int32_t status = 0; - switch(mult) - { - case kPeriodMultiplier_4X: - setPWMPeriodScale(m_pwm_ports[m_channel], 3, &status); // Squelch 3 out of 4 outputs - break; - case kPeriodMultiplier_2X: - setPWMPeriodScale(m_pwm_ports[m_channel], 1, &status); // Squelch 1 out of 2 outputs - break; - case kPeriodMultiplier_1X: - setPWMPeriodScale(m_pwm_ports[m_channel], 0, &status); // Don't squelch any outputs - break; - default: - wpi_assert(false); - } + switch (mult) { + case kPeriodMultiplier_4X: + setPWMPeriodScale(m_pwm_ports[m_channel], 3, + &status); // Squelch 3 out of 4 outputs + break; + case kPeriodMultiplier_2X: + setPWMPeriodScale(m_pwm_ports[m_channel], 1, + &status); // Squelch 1 out of 2 outputs + break; + case kPeriodMultiplier_1X: + setPWMPeriodScale(m_pwm_ports[m_channel], 0, + &status); // Don't squelch any outputs + break; + default: + wpi_assert(false); + } - wpi_setErrorWithContext(status, getHALErrorMessage(status)); + wpi_setErrorWithContext(status, getHALErrorMessage(status)); } -void PWM::SetZeroLatch() -{ - if (StatusIsFatal()) return; - - int32_t status = 0; - - latchPWMZero(m_pwm_ports[m_channel], &status); - wpi_setErrorWithContext(status, getHALErrorMessage(status)); +void PWM::SetZeroLatch() { + if (StatusIsFatal()) return; + + int32_t status = 0; + + latchPWMZero(m_pwm_ports[m_channel], &status); + wpi_setErrorWithContext(status, getHALErrorMessage(status)); } - -void PWM::ValueChanged(ITable* source, const std::string& key, EntryValue value, bool isNew) { - SetSpeed(value.f); +void PWM::ValueChanged(ITable* source, const std::string& key, EntryValue value, + bool isNew) { + SetSpeed(value.f); } void PWM::UpdateTable() { - if (m_table != NULL) { - m_table->PutNumber("Value", GetSpeed()); - } + if (m_table != NULL) { + m_table->PutNumber("Value", GetSpeed()); + } } void PWM::StartLiveWindowMode() { - SetSpeed(0); - if (m_table != NULL) { - m_table->AddTableListener("Value", this, true); - } + SetSpeed(0); + if (m_table != NULL) { + m_table->AddTableListener("Value", this, true); + } } void PWM::StopLiveWindowMode() { - SetSpeed(0); - if (m_table != NULL) { - m_table->RemoveTableListener(this); - } + SetSpeed(0); + if (m_table != NULL) { + m_table->RemoveTableListener(this); + } } -std::string PWM::GetSmartDashboardType() const { - return "Speed Controller"; +std::string PWM::GetSmartDashboardType() const { return "Speed Controller"; } + +void PWM::InitTable(ITable* subTable) { + m_table = subTable; + UpdateTable(); } -void PWM::InitTable(ITable *subTable) { - m_table = subTable; - UpdateTable(); -} - -ITable * PWM::GetTable() const { - return m_table; -} +ITable* PWM::GetTable() const { return m_table; } diff --git a/wpilibc/wpilibC++Devices/src/PowerDistributionPanel.cpp b/wpilibc/wpilibC++Devices/src/PowerDistributionPanel.cpp index bbbae8782b..ec48158689 100644 --- a/wpilibc/wpilibC++Devices/src/PowerDistributionPanel.cpp +++ b/wpilibc/wpilibC++Devices/src/PowerDistributionPanel.cpp @@ -1,5 +1,6 @@ /*----------------------------------------------------------------------------*/ -/* Copyright (c) FIRST 2014. All Rights Reserved. */ +/* Copyright (c) FIRST 2014. 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,195 +10,180 @@ #include "HAL/PDP.hpp" #include "LiveWindow/LiveWindow.h" -PowerDistributionPanel::PowerDistributionPanel() { - PowerDistributionPanel(0); -} +PowerDistributionPanel::PowerDistributionPanel() { PowerDistributionPanel(0); } /** * Initialize the PDP. */ PowerDistributionPanel::PowerDistributionPanel(uint8_t module) { - m_table=NULL; - m_module = module; - initializePDP(m_module); + m_table = NULL; + m_module = module; + initializePDP(m_module); } /** * Query the input voltage of the PDP * @return The voltage of the PDP in volts */ -double -PowerDistributionPanel::GetVoltage() const { - int32_t status = 0; - - double voltage = getPDPVoltage(&status, m_module); - - if(status) { - wpi_setWPIErrorWithContext(Timeout, ""); - } - - return voltage; +double PowerDistributionPanel::GetVoltage() const { + int32_t status = 0; + + double voltage = getPDPVoltage(&status, m_module); + + if (status) { + wpi_setWPIErrorWithContext(Timeout, ""); + } + + return voltage; } /** * Query the temperature of the PDP * @return The temperature of the PDP in degrees Celsius */ -double -PowerDistributionPanel::GetTemperature() const { - int32_t status = 0; - - double temperature = getPDPTemperature(&status, m_module); - - if(status) { - wpi_setWPIErrorWithContext(Timeout, ""); - } - - return temperature; +double PowerDistributionPanel::GetTemperature() const { + int32_t status = 0; + + double temperature = getPDPTemperature(&status, m_module); + + if (status) { + wpi_setWPIErrorWithContext(Timeout, ""); + } + + return temperature; } /** * Query the current of a single channel of the PDP * @return The current of one of the PDP channels (channels 0-15) in Amperes */ -double -PowerDistributionPanel::GetCurrent(uint8_t channel) const { - int32_t status = 0; - - if(!CheckPDPChannel(channel)) - { - char buf[64]; - snprintf(buf, 64, "PDP Channel %d", channel); - wpi_setWPIErrorWithContext(ChannelIndexOutOfRange, buf); - } - - double current = getPDPChannelCurrent(channel, &status, m_module); - - if(status) { - wpi_setWPIErrorWithContext(Timeout, ""); - } - - return current; +double PowerDistributionPanel::GetCurrent(uint8_t channel) const { + int32_t status = 0; + + if (!CheckPDPChannel(channel)) { + char buf[64]; + snprintf(buf, 64, "PDP Channel %d", channel); + wpi_setWPIErrorWithContext(ChannelIndexOutOfRange, buf); + } + + double current = getPDPChannelCurrent(channel, &status, m_module); + + if (status) { + wpi_setWPIErrorWithContext(Timeout, ""); + } + + return current; } /** * Query the total current of all monitored PDP channels (0-15) * @return The the total current drawn from the PDP channels in Amperes */ -double -PowerDistributionPanel::GetTotalCurrent() const { - int32_t status = 0; - - double current = getPDPTotalCurrent(&status, m_module); - - if(status) { - wpi_setWPIErrorWithContext(Timeout, ""); - } - - return current; +double PowerDistributionPanel::GetTotalCurrent() const { + int32_t status = 0; + + double current = getPDPTotalCurrent(&status, m_module); + + if (status) { + wpi_setWPIErrorWithContext(Timeout, ""); + } + + return current; } /** * Query the total power drawn from the monitored PDP channels * @return The the total power drawn from the PDP channels in Watts */ -double -PowerDistributionPanel::GetTotalPower() const { - int32_t status = 0; - - double power = getPDPTotalPower(&status, m_module); - - if(status) { - wpi_setWPIErrorWithContext(Timeout, ""); - } - - return power; +double PowerDistributionPanel::GetTotalPower() const { + int32_t status = 0; + + double power = getPDPTotalPower(&status, m_module); + + if (status) { + wpi_setWPIErrorWithContext(Timeout, ""); + } + + return power; } /** * Query the total energy drawn from the monitored PDP channels * @return The the total energy drawn from the PDP channels in Joules */ -double -PowerDistributionPanel::GetTotalEnergy() const { - int32_t status = 0; - - double energy = getPDPTotalEnergy(&status, m_module); - - if(status) { - wpi_setWPIErrorWithContext(Timeout, ""); - } - - return energy; +double PowerDistributionPanel::GetTotalEnergy() const { + int32_t status = 0; + + double energy = getPDPTotalEnergy(&status, m_module); + + if (status) { + wpi_setWPIErrorWithContext(Timeout, ""); + } + + return energy; } /** * Reset the total energy drawn from the PDP * @see PowerDistributionPanel#GetTotalEnergy */ -void -PowerDistributionPanel::ResetTotalEnergy() { - int32_t status = 0; - - resetPDPTotalEnergy(&status, m_module); - - if(status) { - wpi_setWPIErrorWithContext(Timeout, ""); - } +void PowerDistributionPanel::ResetTotalEnergy() { + int32_t status = 0; + + resetPDPTotalEnergy(&status, m_module); + + if (status) { + wpi_setWPIErrorWithContext(Timeout, ""); + } } /** * Remove all of the fault flags on the PDP */ -void -PowerDistributionPanel::ClearStickyFaults() { - int32_t status = 0; - - clearPDPStickyFaults(&status, m_module); - - if(status) { - wpi_setWPIErrorWithContext(Timeout, ""); - } +void PowerDistributionPanel::ClearStickyFaults() { + int32_t status = 0; + + clearPDPStickyFaults(&status, m_module); + + if (status) { + wpi_setWPIErrorWithContext(Timeout, ""); + } } void PowerDistributionPanel::UpdateTable() { - if (m_table != NULL) { - m_table->PutNumber("Chan0", GetCurrent(0)); - m_table->PutNumber("Chan1", GetCurrent(1)); - m_table->PutNumber("Chan2", GetCurrent(2)); - m_table->PutNumber("Chan3", GetCurrent(3)); - m_table->PutNumber("Chan4", GetCurrent(4)); - m_table->PutNumber("Chan5", GetCurrent(5)); - m_table->PutNumber("Chan6", GetCurrent(6)); - m_table->PutNumber("Chan7", GetCurrent(7)); - m_table->PutNumber("Chan8", GetCurrent(8)); - m_table->PutNumber("Chan9", GetCurrent(9)); - m_table->PutNumber("Chan10", GetCurrent(10)); - m_table->PutNumber("Chan11", GetCurrent(11)); - m_table->PutNumber("Chan12", GetCurrent(12)); - m_table->PutNumber("Chan13", GetCurrent(13)); - m_table->PutNumber("Chan14", GetCurrent(14)); - m_table->PutNumber("Chan15", GetCurrent(15)); - m_table->PutNumber("Voltage", GetVoltage()); - m_table->PutNumber("TotalCurrent", GetTotalCurrent()); - } + if (m_table != NULL) { + m_table->PutNumber("Chan0", GetCurrent(0)); + m_table->PutNumber("Chan1", GetCurrent(1)); + m_table->PutNumber("Chan2", GetCurrent(2)); + m_table->PutNumber("Chan3", GetCurrent(3)); + m_table->PutNumber("Chan4", GetCurrent(4)); + m_table->PutNumber("Chan5", GetCurrent(5)); + m_table->PutNumber("Chan6", GetCurrent(6)); + m_table->PutNumber("Chan7", GetCurrent(7)); + m_table->PutNumber("Chan8", GetCurrent(8)); + m_table->PutNumber("Chan9", GetCurrent(9)); + m_table->PutNumber("Chan10", GetCurrent(10)); + m_table->PutNumber("Chan11", GetCurrent(11)); + m_table->PutNumber("Chan12", GetCurrent(12)); + m_table->PutNumber("Chan13", GetCurrent(13)); + m_table->PutNumber("Chan14", GetCurrent(14)); + m_table->PutNumber("Chan15", GetCurrent(15)); + m_table->PutNumber("Voltage", GetVoltage()); + m_table->PutNumber("TotalCurrent", GetTotalCurrent()); + } } -void PowerDistributionPanel::StartLiveWindowMode() { -} +void PowerDistributionPanel::StartLiveWindowMode() {} -void PowerDistributionPanel::StopLiveWindowMode() { -} +void PowerDistributionPanel::StopLiveWindowMode() {} std::string PowerDistributionPanel::GetSmartDashboardType() const { - return "PowerDistributionPanel"; + return "PowerDistributionPanel"; } void PowerDistributionPanel::InitTable(ITable *subTable) { - m_table = subTable; - UpdateTable(); + m_table = subTable; + UpdateTable(); } -ITable * PowerDistributionPanel::GetTable() const { - return m_table; -} +ITable *PowerDistributionPanel::GetTable() const { return m_table; } diff --git a/wpilibc/wpilibC++Devices/src/Preferences.cpp b/wpilibc/wpilibC++Devices/src/Preferences.cpp index 70985bb2a7..aadc7c6f01 100644 --- a/wpilibc/wpilibC++Devices/src/Preferences.cpp +++ b/wpilibc/wpilibC++Devices/src/Preferences.cpp @@ -27,52 +27,45 @@ static const char *kValueSuffix = "\"\n"; /** The singleton instance */ Preferences *Preferences::_instance = NULL; -Preferences::Preferences() : - m_fileLock(NULL), - m_fileOpStarted(NULL), - m_tableLock(NULL), - m_readTask("PreferencesReadTask", (FUNCPTR)Preferences::InitReadTask), - m_writeTask("PreferencesWriteTask", (FUNCPTR)Preferences::InitWriteTask) -{ - m_fileLock = initializeMutexRecursive(); - m_fileOpStarted = initializeSemaphore (SEMAPHORE_EMPTY); - m_tableLock = initializeMutexRecursive(); +Preferences::Preferences() + : m_fileLock(NULL), + m_fileOpStarted(NULL), + m_tableLock(NULL), + m_readTask("PreferencesReadTask", (FUNCPTR)Preferences::InitReadTask), + m_writeTask("PreferencesWriteTask", (FUNCPTR)Preferences::InitWriteTask) { + m_fileLock = initializeMutexRecursive(); + m_fileOpStarted = initializeSemaphore(SEMAPHORE_EMPTY); + m_tableLock = initializeMutexRecursive(); - Synchronized sync(m_fileLock); - m_readTask.Start((uint32_t)this); - takeSemaphore(m_fileOpStarted); + Synchronized sync(m_fileLock); + m_readTask.Start((uint32_t) this); + takeSemaphore(m_fileOpStarted); - HALReport(HALUsageReporting::kResourceType_Preferences, 0); + HALReport(HALUsageReporting::kResourceType_Preferences, 0); } -Preferences::~Preferences() -{ - takeMutex(m_tableLock); - deleteMutex(m_tableLock); - takeMutex(m_fileLock); - deleteSemaphore(m_fileOpStarted); - deleteMutex(m_fileLock); +Preferences::~Preferences() { + takeMutex(m_tableLock); + deleteMutex(m_tableLock); + takeMutex(m_fileLock); + deleteSemaphore(m_fileOpStarted); + deleteMutex(m_fileLock); } /** * Get the one and only {@link Preferences} object * @return pointer to the {@link Preferences} */ -Preferences *Preferences::GetInstance() -{ - if (_instance == NULL) - _instance = new Preferences; - return _instance; +Preferences *Preferences::GetInstance() { + if (_instance == NULL) _instance = new Preferences; + return _instance; } /** * Returns a vector of all the keys * @return a vector of the keys */ -std::vector Preferences::GetKeys() -{ - return m_keys; -} +std::vector Preferences::GetKeys() { return m_keys; } /** * Returns the string at the given key. If this table does not have a value @@ -81,10 +74,9 @@ std::vector Preferences::GetKeys() * @param defaultValue the value to return if none exists in the table * @return either the value in the table, or the defaultValue */ -std::string Preferences::GetString(const char *key, const char *defaultValue) -{ - std::string value = Get(key); - return value.empty() ? defaultValue : value; +std::string Preferences::GetString(const char *key, const char *defaultValue) { + std::string value = Get(key); + return value.empty() ? defaultValue : value; } /** @@ -96,11 +88,11 @@ std::string Preferences::GetString(const char *key, const char *defaultValue) * @param defaultValue the value to return if none exists in the table * @return The size of the returned string */ -int Preferences::GetString(const char *key, char *value, int valueSize, const char *defaultValue) -{ - std::string stringValue = GetString(key, defaultValue); - stringValue.copy(value, valueSize); - return stringValue.size(); +int Preferences::GetString(const char *key, char *value, int valueSize, + const char *defaultValue) { + std::string stringValue = GetString(key, defaultValue); + stringValue.copy(value, valueSize); + return stringValue.size(); } /** @@ -110,13 +102,11 @@ int Preferences::GetString(const char *key, char *value, int valueSize, const ch * @param defaultValue the value to return if none exists in the table * @return either the value in the table, or the defaultValue */ -int Preferences::GetInt(const char *key, int defaultValue) -{ - std::string value = Get(key); - if (value.empty()) - return defaultValue; +int Preferences::GetInt(const char *key, int defaultValue) { + std::string value = Get(key); + if (value.empty()) return defaultValue; - return strtol(value.c_str(), NULL, 0); + return strtol(value.c_str(), NULL, 0); } /** @@ -126,13 +116,11 @@ int Preferences::GetInt(const char *key, int defaultValue) * @param defaultValue the value to return if none exists in the table * @return either the value in the table, or the defaultValue */ -double Preferences::GetDouble(const char *key, double defaultValue) -{ - std::string value = Get(key); - if (value.empty()) - return defaultValue; +double Preferences::GetDouble(const char *key, double defaultValue) { + std::string value = Get(key); + if (value.empty()) return defaultValue; - return strtod(value.c_str(), NULL); + return strtod(value.c_str(), NULL); } /** @@ -142,13 +130,11 @@ double Preferences::GetDouble(const char *key, double defaultValue) * @param defaultValue the value to return if none exists in the table * @return either the value in the table, or the defaultValue */ -float Preferences::GetFloat(const char *key, float defaultValue) -{ - std::string value = Get(key); - if (value.empty()) - return defaultValue; +float Preferences::GetFloat(const char *key, float defaultValue) { + std::string value = Get(key); + if (value.empty()) return defaultValue; - return strtod(value.c_str(), NULL); + return strtod(value.c_str(), NULL); } /** @@ -158,39 +144,38 @@ float Preferences::GetFloat(const char *key, float defaultValue) * @param defaultValue the value to return if none exists in the table * @return either the value in the table, or the defaultValue */ -bool Preferences::GetBoolean(const char *key, bool defaultValue) -{ - std::string value = Get(key); - if (value.empty()) - return defaultValue; +bool Preferences::GetBoolean(const char *key, bool defaultValue) { + std::string value = Get(key); + if (value.empty()) return defaultValue; - if (value.compare("true") == 0) - return true; - else if (value.compare("false") == 0) - return false; + if (value.compare("true") == 0) + return true; + else if (value.compare("false") == 0) + return false; - wpi_setWPIErrorWithContext(ParameterOutOfRange, "Boolean value does not contain \"true\" or \"false\""); - return false; + wpi_setWPIErrorWithContext( + ParameterOutOfRange, + "Boolean value does not contain \"true\" or \"false\""); + return false; } /** - * Returns the long (int64_t) at the given key. If this table does not have a value + * Returns the long (int64_t) at the given key. If this table does not have a + * value * for that position, then the given defaultValue value will be returned. * @param key the key * @param defaultValue the value to return if none exists in the table * @return either the value in the table, or the defaultValue */ -int64_t Preferences::GetLong(const char *key, int64_t defaultValue) -{ - std::string value = Get(key); - if (value.empty()) - return defaultValue; +int64_t Preferences::GetLong(const char *key, int64_t defaultValue) { + std::string value = Get(key); + if (value.empty()) return defaultValue; - // Ummm... not available in our VxWorks... - //return strtoll(value.c_str(), NULL, 0); - int64_t intVal; - sscanf(value.c_str(), "%lld", &intVal); - return intVal; + // Ummm... not available in our VxWorks... + // return strtoll(value.c_str(), NULL, 0); + int64_t intVal; + sscanf(value.c_str(), "%lld", &intVal); + return intVal; } /** @@ -200,24 +185,23 @@ int64_t Preferences::GetLong(const char *key, int64_t defaultValue) * have any whitespace nor an equals sign

* *

This will NOT save the value to memory between power cycles, - * to do that you must call {@link Preferences#Save() Save()} (which must be used with care). + * to do that you must call {@link Preferences#Save() Save()} (which must be + * used with care). * at some point after calling this.

* @param key the key * @param value the value */ -void Preferences::PutString(const char *key, const char *value) -{ - if (value == NULL) - { - wpi_setWPIErrorWithContext(NullParameter, "value"); - return; - } - if (std::string(value).find_first_of("\"") != std::string::npos) - { - wpi_setWPIErrorWithContext(ParameterOutOfRange, "value contains illegal characters"); - return; - } - Put(key, value); +void Preferences::PutString(const char *key, const char *value) { + if (value == NULL) { + wpi_setWPIErrorWithContext(NullParameter, "value"); + return; + } + if (std::string(value).find_first_of("\"") != std::string::npos) { + wpi_setWPIErrorWithContext(ParameterOutOfRange, + "value contains illegal characters"); + return; + } + Put(key, value); } /** @@ -226,16 +210,16 @@ void Preferences::PutString(const char *key, const char *value) *

The key may not have any whitespace nor an equals sign

* *

This will NOT save the value to memory between power cycles, - * to do that you must call {@link Preferences#Save() Save()} (which must be used with care) + * to do that you must call {@link Preferences#Save() Save()} (which must be + * used with care) * at some point after calling this.

* @param key the key * @param value the value */ -void Preferences::PutInt(const char *key, int value) -{ - char buf[32]; - snprintf(buf, 32, "%d", value); - Put(key, buf); +void Preferences::PutInt(const char *key, int value) { + char buf[32]; + snprintf(buf, 32, "%d", value); + Put(key, buf); } /** @@ -244,16 +228,16 @@ void Preferences::PutInt(const char *key, int value) *

The key may not have any whitespace nor an equals sign

* *

This will NOT save the value to memory between power cycles, - * to do that you must call {@link Preferences#Save() Save()} (which must be used with care) + * to do that you must call {@link Preferences#Save() Save()} (which must be + * used with care) * at some point after calling this.

* @param key the key * @param value the value */ -void Preferences::PutDouble(const char *key, double value) -{ - char buf[32]; - snprintf(buf, 32, "%f", value); - Put(key, buf); +void Preferences::PutDouble(const char *key, double value) { + char buf[32]; + snprintf(buf, 32, "%f", value); + Put(key, buf); } /** @@ -262,16 +246,16 @@ void Preferences::PutDouble(const char *key, double value) *

The key may not have any whitespace nor an equals sign

* *

This will NOT save the value to memory between power cycles, - * to do that you must call {@link Preferences#Save() Save()} (which must be used with care) + * to do that you must call {@link Preferences#Save() Save()} (which must be + * used with care) * at some point after calling this.

* @param key the key * @param value the value */ -void Preferences::PutFloat(const char *key, float value) -{ - char buf[32]; - snprintf(buf, 32, "%f", value); - Put(key, buf); +void Preferences::PutFloat(const char *key, float value) { + char buf[32]; + snprintf(buf, 32, "%f", value); + Put(key, buf); } /** @@ -280,14 +264,14 @@ void Preferences::PutFloat(const char *key, float value) *

The key may not have any whitespace nor an equals sign

* *

This will NOT save the value to memory between power cycles, - * to do that you must call {@link Preferences#Save() Save()} (which must be used with care) + * to do that you must call {@link Preferences#Save() Save()} (which must be + * used with care) * at some point after calling this.

* @param key the key * @param value the value */ -void Preferences::PutBoolean(const char *key, bool value) -{ - Put(key, value ? "true" : "false"); +void Preferences::PutBoolean(const char *key, bool value) { + Put(key, value ? "true" : "false"); } /** @@ -296,16 +280,16 @@ void Preferences::PutBoolean(const char *key, bool value) *

The key may not have any whitespace nor an equals sign

* *

This will NOT save the value to memory between power cycles, - * to do that you must call {@link Preferences#Save() Save()} (which must be used with care) + * to do that you must call {@link Preferences#Save() Save()} (which must be + * used with care) * at some point after calling this.

* @param key the key * @param value the value */ -void Preferences::PutLong(const char *key, int64_t value) -{ - char buf[32]; - snprintf(buf, 32, "%lld", value); - Put(key, buf); +void Preferences::PutLong(const char *key, int64_t value) { + char buf[32]; + snprintf(buf, 32, "%lld", value); + Put(key, buf); } /** @@ -317,13 +301,13 @@ void Preferences::PutLong(const char *key, int64_t value) * be called every run of {@link IterativeRobot#TeleopPeriodic()}, etc.

* *

The actual writing of the file is done in a separate thread. - * However, any call to a get or put method will wait until the table is fully saved before continuing.

+ * However, any call to a get or put method will wait until the table is fully + * saved before continuing.

*/ -void Preferences::Save() -{ - Synchronized sync(m_fileLock); - m_writeTask.Start((uint32_t)this); - takeSemaphore(m_fileOpStarted); +void Preferences::Save() { + Synchronized sync(m_fileLock); + m_writeTask.Start((uint32_t) this); + takeSemaphore(m_fileOpStarted); } /** @@ -331,27 +315,21 @@ void Preferences::Save() * @param key the key * @return if there is a value at the given key */ -bool Preferences::ContainsKey(const char *key) -{ - return !Get(key).empty(); -} +bool Preferences::ContainsKey(const char *key) { return !Get(key).empty(); } /** * Remove a preference * @param key the key */ -void Preferences::Remove(const char *key) -{ - m_values.erase(std::string(key)); - std::vector::iterator it = m_keys.begin(); - for (; it != m_keys.end(); it++) - { - if (it->compare(key) == 0) - { - m_keys.erase(it); - break; - } - } +void Preferences::Remove(const char *key) { + m_values.erase(std::string(key)); + std::vector::iterator it = m_keys.begin(); + for (; it != m_keys.end(); it++) { + if (it->compare(key) == 0) { + m_keys.erase(it); + break; + } + } } /** @@ -359,15 +337,13 @@ void Preferences::Remove(const char *key) * @param key the key * @return the value (or empty if none exists) */ -std::string Preferences::Get(const char *key) -{ - Synchronized sync(m_tableLock); - if (key == NULL) - { - wpi_setWPIErrorWithContext(NullParameter, "key"); - return std::string(""); - } - return m_values[std::string(key)]; +std::string Preferences::Get(const char *key) { + Synchronized sync(m_tableLock); + if (key == NULL) { + wpi_setWPIErrorWithContext(NullParameter, "key"); + return std::string(""); + } + return m_values[std::string(key)]; } /** @@ -375,29 +351,27 @@ std::string Preferences::Get(const char *key) * @param key the key * @param value the value */ -void Preferences::Put(const char *key, std::string value) -{ - Synchronized sync(m_tableLock); - if (key == NULL) - { - wpi_setWPIErrorWithContext(NullParameter, "key"); - return; - } +void Preferences::Put(const char *key, std::string value) { + Synchronized sync(m_tableLock); + if (key == NULL) { + wpi_setWPIErrorWithContext(NullParameter, "key"); + return; + } - if (std::string(key).find_first_of("=\n\r \t\"") != std::string::npos) - { - wpi_setWPIErrorWithContext(ParameterOutOfRange, "key contains illegal characters"); - return; - } + if (std::string(key).find_first_of("=\n\r \t\"") != std::string::npos) { + wpi_setWPIErrorWithContext(ParameterOutOfRange, + "key contains illegal characters"); + return; + } - std::pair ret = - m_values.insert(StringMap::value_type(key, value)); - if (ret.second) - m_keys.push_back(key); - else - ret.first->second = value; + std::pair ret = + m_values.insert(StringMap::value_type(key, value)); + if (ret.second) + m_keys.push_back(key); + else + ret.first->second = value; - NetworkTable::GetTable(kTableName)->PutString(key, value); + NetworkTable::GetTable(kTableName)->PutString(key, value); } /** @@ -405,215 +379,181 @@ void Preferences::Put(const char *key, std::string value) * This will be called in its own thread when the preferences singleton is * first created. */ -void Preferences::ReadTaskRun() -{ - Synchronized sync(m_tableLock); - giveSemaphore(m_fileOpStarted); +void Preferences::ReadTaskRun() { + Synchronized sync(m_tableLock); + giveSemaphore(m_fileOpStarted); - std::string comment; + std::string comment; - FILE *file = NULL; - file = fopen(kFileName, "r"); + FILE *file = NULL; + file = fopen(kFileName, "r"); - if (file != NULL) - { - std::string buffer; - while (true) - { - char value; - do - { - value = fgetc(file); - } while (value == ' ' || value == '\t'); + if (file != NULL) { + std::string buffer; + while (true) { + char value; + do { + value = fgetc(file); + } while (value == ' ' || value == '\t'); - if (value == '\n' || value == ';') - { - if (value == '\n') - { - comment += "\n"; - } - else - { - buffer.clear(); - for (; value != '\n' && !feof(file); value = fgetc(file)) - buffer += value; - buffer += '\n'; - comment += buffer; - } - } - else if (value == '[') - { - // Find the end of the section and the new line after it and throw it away - for (; value != ']' && !feof(file); value = fgetc(file)); - for (; value != '\n' && !feof(file); value = fgetc(file)); - } - else - { - buffer.clear(); - for (; value != '=' && !feof(file); ) - { - buffer += value; - do - { - value = fgetc(file); - } while (value == ' ' || value == '\t'); - } - std::string name = buffer; - buffer.clear(); + if (value == '\n' || value == ';') { + if (value == '\n') { + comment += "\n"; + } else { + buffer.clear(); + for (; value != '\n' && !feof(file); value = fgetc(file)) + buffer += value; + buffer += '\n'; + comment += buffer; + } + } else if (value == '[') { + // Find the end of the section and the new line after it and throw it + // away + for (; value != ']' && !feof(file); value = fgetc(file)) + ; + for (; value != '\n' && !feof(file); value = fgetc(file)) + ; + } else { + buffer.clear(); + for (; value != '=' && !feof(file);) { + buffer += value; + do { + value = fgetc(file); + } while (value == ' ' || value == '\t'); + } + std::string name = buffer; + buffer.clear(); - bool shouldBreak = false; + bool shouldBreak = false; - do - { - value = fgetc(file); - } while (value == ' ' || value == '\t'); + do { + value = fgetc(file); + } while (value == ' ' || value == '\t'); - if (value == '"') - { - for (value = fgetc(file); value != '"' && !feof(file); value = fgetc(file)) - buffer += value; + if (value == '"') { + for (value = fgetc(file); value != '"' && !feof(file); + value = fgetc(file)) + buffer += value; - // Clear the line - while (fgetc(file) != '\n' && !feof(file)); - } - else - { - for (; value != '\n' && !feof(file);) - { - buffer += value; - do - { - value = fgetc(file); - } while (value == ' ' || value == '\t'); - } - if (feof(file)) - shouldBreak = true; - } + // Clear the line + while (fgetc(file) != '\n' && !feof(file)) + ; + } else { + for (; value != '\n' && !feof(file);) { + buffer += value; + do { + value = fgetc(file); + } while (value == ' ' || value == '\t'); + } + if (feof(file)) shouldBreak = true; + } - std::string value = buffer; + std::string value = buffer; - if (!name.empty() && !value.empty()) - { - m_keys.push_back(name); - m_values.insert(std::pair(name, value)); - NetworkTable::GetTable(kTableName)->PutString(name, value); + if (!name.empty() && !value.empty()) { + m_keys.push_back(name); + m_values.insert(std::pair(name, value)); + NetworkTable::GetTable(kTableName)->PutString(name, value); - if (!comment.empty()) - { - m_comments.insert(std::pair(name, comment)); - comment.clear(); - } - } + if (!comment.empty()) { + m_comments.insert( + std::pair(name, comment)); + comment.clear(); + } + } - if (shouldBreak) - break; - } - } - } - else - { - wpi_setErrnoErrorWithContext("Opening preferences file"); - } + if (shouldBreak) break; + } + } + } else { + wpi_setErrnoErrorWithContext("Opening preferences file"); + } - if (file != NULL) - fclose(file); + if (file != NULL) fclose(file); - if (!comment.empty()) - m_endComment = comment; + if (!comment.empty()) m_endComment = comment; - NetworkTable::GetTable(kTableName)->PutBoolean(kSaveField, false); - NetworkTable::GetTable(kTableName)->AddTableListener(this); + NetworkTable::GetTable(kTableName)->PutBoolean(kSaveField, false); + NetworkTable::GetTable(kTableName)->AddTableListener(this); } /** * Internal method that actually writes the table to a file. - * This is called in its own thread when {@link Preferences#Save() Save()} is called. + * This is called in its own thread when {@link Preferences#Save() Save()} is + * called. */ -void Preferences::WriteTaskRun() -{ - Synchronized sync(m_tableLock); - giveSemaphore(m_fileOpStarted); +void Preferences::WriteTaskRun() { + Synchronized sync(m_tableLock); + giveSemaphore(m_fileOpStarted); - FILE *file = NULL; - file = fopen(kFileName, "w"); + FILE *file = NULL; + file = fopen(kFileName, "w"); - fputs("[Preferences]\n", file); - std::vector::iterator it = m_keys.begin(); - for (; it != m_keys.end(); it++) - { - std::string key = *it; - std::string value = m_values[key]; - std::string comment = m_comments[key]; + fputs("[Preferences]\n", file); + std::vector::iterator it = m_keys.begin(); + for (; it != m_keys.end(); it++) { + std::string key = *it; + std::string value = m_values[key]; + std::string comment = m_comments[key]; - if (!comment.empty()) - fputs(comment.c_str(), file); + if (!comment.empty()) fputs(comment.c_str(), file); - fputs(key.c_str(), file); - fputs(kValuePrefix, file); - fputs(value.c_str(), file); - fputs(kValueSuffix, file); - } + fputs(key.c_str(), file); + fputs(kValuePrefix, file); + fputs(value.c_str(), file); + fputs(kValueSuffix, file); + } - if (!m_endComment.empty()) - fputs(m_endComment.c_str(), file); + if (!m_endComment.empty()) fputs(m_endComment.c_str(), file); - if (file != NULL) - fclose(file); + if (file != NULL) fclose(file); - NetworkTable::GetTable(kTableName)->PutBoolean(kSaveField, false); + NetworkTable::GetTable(kTableName)->PutBoolean(kSaveField, false); } -static bool isKeyAcceptable(const std::string& value) { - for (unsigned int i = 0; i < value.length(); i++) { - char letter = value.at(i); - switch (letter) { - case '=': - case '\n': - case '\r': - case ' ': - case '\t': - case '[': - case ']': - return false; - } - } - return true; +static bool isKeyAcceptable(const std::string &value) { + for (unsigned int i = 0; i < value.length(); i++) { + char letter = value.at(i); + switch (letter) { + case '=': + case '\n': + case '\r': + case ' ': + case '\t': + case '[': + case ']': + return false; + } + } + return true; } -void Preferences::ValueChanged(ITable* table, const std::string& key, EntryValue value, bool isNew) -{ - if (key==kSaveField) - { - if (table->GetBoolean(kSaveField, false)) - Save(); - } - else - { - Synchronized sync(m_tableLock); +void Preferences::ValueChanged(ITable *table, const std::string &key, + EntryValue value, bool isNew) { + if (key == kSaveField) { + if (table->GetBoolean(kSaveField, false)) Save(); + } else { + Synchronized sync(m_tableLock); - if (!isKeyAcceptable(key) || table->GetString(key, "").find('"')!=std::string::npos) - { - if(m_values.find(key) != m_values.end()){ - m_values.erase(key); - std::vector::iterator it = m_keys.begin(); - for (; it != m_keys.end(); it++) - { - if (key==*it) - { - m_keys.erase(it); - break; - } - } - table->PutString(key, "\""); - } - } - else - { - std::pair ret = - m_values.insert(StringMap::value_type(key, table->GetString(key, ""))); - if (ret.second) - m_keys.push_back(key); - else - ret.first->second = table->GetString(key, ""); - } - } + if (!isKeyAcceptable(key) || + table->GetString(key, "").find('"') != std::string::npos) { + if (m_values.find(key) != m_values.end()) { + m_values.erase(key); + std::vector::iterator it = m_keys.begin(); + for (; it != m_keys.end(); it++) { + if (key == *it) { + m_keys.erase(it); + break; + } + } + table->PutString(key, "\""); + } + } else { + std::pair ret = m_values.insert( + StringMap::value_type(key, table->GetString(key, ""))); + if (ret.second) + m_keys.push_back(key); + else + ret.first->second = table->GetString(key, ""); + } + } } diff --git a/wpilibc/wpilibC++Devices/src/Relay.cpp b/wpilibc/wpilibC++Devices/src/Relay.cpp index 3c4278b998..2813da5f1f 100644 --- a/wpilibc/wpilibC++Devices/src/Relay.cpp +++ b/wpilibc/wpilibC++Devices/src/Relay.cpp @@ -1,6 +1,8 @@ /*----------------------------------------------------------------------------*/ -/* Copyright (c) FIRST 2008. All Rights Reserved. */ -/* Open Source Software - may be modified and shared by FRC teams. The code */ +/* 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. */ /*----------------------------------------------------------------------------*/ @@ -17,50 +19,47 @@ static Resource *relayChannels = NULL; /** * Common relay initialization method. - * This code is common to all Relay constructors and initializes the relay and reserves - * all resources that need to be locked. Initially the relay is set to both lines at 0v. + * This code is common to all Relay constructors and initializes the relay and + * reserves + * all resources that need to be locked. Initially the relay is set to both + * lines at 0v. */ -void Relay::InitRelay() -{ - m_table = NULL; - char buf[64]; - Resource::CreateResourceObject(&relayChannels, dio_kNumSystems * kRelayChannels * 2); - if (!SensorBase::CheckRelayChannel(m_channel)) - { - snprintf(buf, 64, "Relay Channel %d", m_channel); - wpi_setWPIErrorWithContext(ChannelIndexOutOfRange, buf); - return; - } +void Relay::InitRelay() { + m_table = NULL; + char buf[64]; + Resource::CreateResourceObject(&relayChannels, + dio_kNumSystems * kRelayChannels * 2); + if (!SensorBase::CheckRelayChannel(m_channel)) { + snprintf(buf, 64, "Relay Channel %d", m_channel); + wpi_setWPIErrorWithContext(ChannelIndexOutOfRange, buf); + return; + } - if (m_direction == kBothDirections || m_direction == kForwardOnly) - { - snprintf(buf, 64, "Forward Relay %d", m_channel); - if (relayChannels->Allocate(m_channel * 2, buf) == ~0ul) - { - CloneError(relayChannels); - return; - } + if (m_direction == kBothDirections || m_direction == kForwardOnly) { + snprintf(buf, 64, "Forward Relay %d", m_channel); + if (relayChannels->Allocate(m_channel * 2, buf) == ~0ul) { + CloneError(relayChannels); + return; + } - HALReport(HALUsageReporting::kResourceType_Relay, m_channel); - } - if (m_direction == kBothDirections || m_direction == kReverseOnly) - { - snprintf(buf, 64, "Reverse Relay %d", m_channel); - if (relayChannels->Allocate(m_channel * 2 + 1, buf) == ~0ul) - { - CloneError(relayChannels); - return; - } + HALReport(HALUsageReporting::kResourceType_Relay, m_channel); + } + if (m_direction == kBothDirections || m_direction == kReverseOnly) { + snprintf(buf, 64, "Reverse Relay %d", m_channel); + if (relayChannels->Allocate(m_channel * 2 + 1, buf) == ~0ul) { + CloneError(relayChannels); + return; + } - HALReport(HALUsageReporting::kResourceType_Relay, m_channel + 128); - } + HALReport(HALUsageReporting::kResourceType_Relay, m_channel + 128); + } - int32_t status = 0; - setRelayForward(m_relay_ports[m_channel], false, &status); - setRelayReverse(m_relay_ports[m_channel], false, &status); - wpi_setErrorWithContext(status, getHALErrorMessage(status)); + int32_t status = 0; + setRelayForward(m_relay_ports[m_channel], false, &status); + setRelayReverse(m_relay_ports[m_channel], false, &status); + wpi_setErrorWithContext(status, getHALErrorMessage(status)); - LiveWindow::GetInstance()->AddActuator("Relay", 1, m_channel, this); + LiveWindow::GetInstance()->AddActuator("Relay", 1, m_channel, this); } /** @@ -69,109 +68,94 @@ void Relay::InitRelay() * @param direction The direction that the Relay object will control. */ Relay::Relay(uint32_t channel, Relay::Direction direction) - : m_channel (channel) - , m_direction (direction) -{ - InitRelay(); + : m_channel(channel), m_direction(direction) { + InitRelay(); } /** * Free the resource associated with a relay. * The relay channels are set to free and the relay output is turned off. */ -Relay::~Relay() -{ +Relay::~Relay() { + int32_t status = 0; + setRelayForward(m_relay_ports[m_channel], false, &status); + setRelayReverse(m_relay_ports[m_channel], false, &status); + wpi_setErrorWithContext(status, getHALErrorMessage(status)); - int32_t status = 0; - setRelayForward(m_relay_ports[m_channel], false, &status); - setRelayReverse(m_relay_ports[m_channel], false, &status); - wpi_setErrorWithContext(status, getHALErrorMessage(status)); - - if (m_direction == kBothDirections || m_direction == kForwardOnly) - { - relayChannels->Free(m_channel * 2); - } - if (m_direction == kBothDirections || m_direction == kReverseOnly) - { - relayChannels->Free(m_channel * 2 + 1); - } + if (m_direction == kBothDirections || m_direction == kForwardOnly) { + relayChannels->Free(m_channel * 2); + } + if (m_direction == kBothDirections || m_direction == kReverseOnly) { + relayChannels->Free(m_channel * 2 + 1); + } } /** * Set the relay state. * - * Valid values depend on which directions of the relay are controlled by the object. + * Valid values depend on which directions of the relay are controlled by the + * object. * * When set to kBothDirections, the relay can be any of the four states: - * 0v-0v, 0v-12v, 12v-0v, 12v-12v + * 0v-0v, 0v-12v, 12v-0v, 12v-12v * - * When set to kForwardOnly or kReverseOnly, you can specify the constant for the - * direction or you can simply specify kOff and kOn. Using only kOff and kOn is - * recommended. + * When set to kForwardOnly or kReverseOnly, you can specify the constant for + * the + * direction or you can simply specify kOff and kOn. Using only kOff and + * kOn is + * recommended. * * @param value The state to set the relay. */ -void Relay::Set(Relay::Value value) -{ - if (StatusIsFatal()) return; +void Relay::Set(Relay::Value value) { + if (StatusIsFatal()) return; - int32_t status = 0; + int32_t status = 0; - switch (value) - { - case kOff: - if (m_direction == kBothDirections || m_direction == kForwardOnly) - { - setRelayForward(m_relay_ports[m_channel], false, &status); - } - if (m_direction == kBothDirections || m_direction == kReverseOnly) - { - setRelayReverse(m_relay_ports[m_channel], false, &status); - } - break; - case kOn: - if (m_direction == kBothDirections || m_direction == kForwardOnly) - { - setRelayForward(m_relay_ports[m_channel], true, &status); - } - if (m_direction == kBothDirections || m_direction == kReverseOnly) - { - setRelayReverse(m_relay_ports[m_channel], true, &status); - } - break; - case kForward: - if (m_direction == kReverseOnly) - { - wpi_setWPIError(IncompatibleMode); - break; - } - if (m_direction == kBothDirections || m_direction == kForwardOnly) - { - setRelayForward(m_relay_ports[m_channel], true, &status); - } - if (m_direction == kBothDirections) - { - setRelayReverse(m_relay_ports[m_channel], false, &status); - } - break; - case kReverse: - if (m_direction == kForwardOnly) - { - wpi_setWPIError(IncompatibleMode); - break; - } - if (m_direction == kBothDirections) - { - setRelayForward(m_relay_ports[m_channel], false, &status); - } - if (m_direction == kBothDirections || m_direction == kReverseOnly) - { - setRelayReverse(m_relay_ports[m_channel], true, &status); - } - break; - } + switch (value) { + case kOff: + if (m_direction == kBothDirections || m_direction == kForwardOnly) { + setRelayForward(m_relay_ports[m_channel], false, &status); + } + if (m_direction == kBothDirections || m_direction == kReverseOnly) { + setRelayReverse(m_relay_ports[m_channel], false, &status); + } + break; + case kOn: + if (m_direction == kBothDirections || m_direction == kForwardOnly) { + setRelayForward(m_relay_ports[m_channel], true, &status); + } + if (m_direction == kBothDirections || m_direction == kReverseOnly) { + setRelayReverse(m_relay_ports[m_channel], true, &status); + } + break; + case kForward: + if (m_direction == kReverseOnly) { + wpi_setWPIError(IncompatibleMode); + break; + } + if (m_direction == kBothDirections || m_direction == kForwardOnly) { + setRelayForward(m_relay_ports[m_channel], true, &status); + } + if (m_direction == kBothDirections) { + setRelayReverse(m_relay_ports[m_channel], false, &status); + } + break; + case kReverse: + if (m_direction == kForwardOnly) { + wpi_setWPIError(IncompatibleMode); + break; + } + if (m_direction == kBothDirections) { + setRelayForward(m_relay_ports[m_channel], false, &status); + } + if (m_direction == kBothDirections || m_direction == kReverseOnly) { + setRelayReverse(m_relay_ports[m_channel], true, &status); + } + break; + } - wpi_setErrorWithContext(status, getHALErrorMessage(status)); + wpi_setErrorWithContext(status, getHALErrorMessage(status)); } /** @@ -185,79 +169,77 @@ void Relay::Set(Relay::Value value) * @return The current state of the relay as a Relay::Value */ Relay::Value Relay::Get() const { - int32_t status; + int32_t status; - if(getRelayForward(m_relay_ports[m_channel], &status)) { - if(getRelayReverse(m_relay_ports[m_channel], &status)) { - return kOn; - } else { - if(m_direction == kForwardOnly) { - return kOn; - } else { - return kForward; - } - } - } else { - if(getRelayReverse(m_relay_ports[m_channel], &status)) { - if(m_direction == kReverseOnly) { - return kOn; - } else { - return kReverse; - } - } else { - return kOff; - } - } + if (getRelayForward(m_relay_ports[m_channel], &status)) { + if (getRelayReverse(m_relay_ports[m_channel], &status)) { + return kOn; + } else { + if (m_direction == kForwardOnly) { + return kOn; + } else { + return kForward; + } + } + } else { + if (getRelayReverse(m_relay_ports[m_channel], &status)) { + if (m_direction == kReverseOnly) { + return kOn; + } else { + return kReverse; + } + } else { + return kOff; + } + } - wpi_setErrorWithContext(status, getHALErrorMessage(status)); + wpi_setErrorWithContext(status, getHALErrorMessage(status)); } -void Relay::ValueChanged(ITable* source, const std::string& key, EntryValue value, bool isNew) { - std::string *val = (std::string *) value.ptr; - if (*val == "Off") Set(kOff); - else if (*val == "On") Set(kOn); - else if (*val == "Forward") Set(kForward); - else if (*val == "Reverse") Set(kReverse); +void Relay::ValueChanged(ITable *source, const std::string &key, + EntryValue value, bool isNew) { + std::string *val = (std::string *)value.ptr; + if (*val == "Off") + Set(kOff); + else if (*val == "On") + Set(kOn); + else if (*val == "Forward") + Set(kForward); + else if (*val == "Reverse") + Set(kReverse); } void Relay::UpdateTable() { - if(m_table != NULL){ - if (Get() == kOn) { - m_table->PutString("Value", "On"); - } - else if (Get() == kForward) { - m_table->PutString("Value", "Forward"); - } - else if (Get() == kReverse) { - m_table->PutString("Value", "Reverse"); - } - else { - m_table->PutString("Value", "Off"); - } - } + if (m_table != NULL) { + if (Get() == kOn) { + m_table->PutString("Value", "On"); + } else if (Get() == kForward) { + m_table->PutString("Value", "Forward"); + } else if (Get() == kReverse) { + m_table->PutString("Value", "Reverse"); + } else { + m_table->PutString("Value", "Off"); + } + } } void Relay::StartLiveWindowMode() { - if(m_table != NULL){ - m_table->AddTableListener("Value", this, true); - } + if (m_table != NULL) { + m_table->AddTableListener("Value", this, true); + } } void Relay::StopLiveWindowMode() { - if(m_table != NULL){ - m_table->RemoveTableListener(this); - } + if (m_table != NULL) { + m_table->RemoveTableListener(this); + } } -std::string Relay::GetSmartDashboardType() const { - return "Relay"; -} +std::string Relay::GetSmartDashboardType() const { return "Relay"; } void Relay::InitTable(ITable *subTable) { - m_table = subTable; - UpdateTable(); + m_table = subTable; + UpdateTable(); } -ITable * Relay::GetTable() const { - return m_table; -} +ITable *Relay::GetTable() const { return m_table; } diff --git a/wpilibc/wpilibC++Devices/src/RobotBase.cpp b/wpilibc/wpilibC++Devices/src/RobotBase.cpp index 3371720b8e..1ce3953f9c 100644 --- a/wpilibc/wpilibC++Devices/src/RobotBase.cpp +++ b/wpilibc/wpilibC++Devices/src/RobotBase.cpp @@ -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,142 +26,124 @@ #include #endif -RobotBase* RobotBase::m_instance = NULL; +RobotBase *RobotBase::m_instance = NULL; -void RobotBase::setInstance(RobotBase* robot) -{ - wpi_assert(m_instance == NULL); - m_instance = robot; +void RobotBase::setInstance(RobotBase *robot) { + wpi_assert(m_instance == NULL); + m_instance = robot; } -RobotBase &RobotBase::getInstance() -{ - return *m_instance; -} +RobotBase &RobotBase::getInstance() { return *m_instance; } -void RobotBase::robotSetup(RobotBase *robot) -{ - robot->Prestart(); - robot->StartCompetition(); +void RobotBase::robotSetup(RobotBase *robot) { + robot->Prestart(); + robot->StartCompetition(); } /** * Constructor for a generic robot program. - * User code should be placed in the constructor that runs before the Autonomous or Operator - * Control period starts. The constructor will run to completion before Autonomous is entered. + * User code should be placed in the constructor that runs before the Autonomous + * or Operator + * Control period starts. The constructor will run to completion before + * Autonomous is entered. * - * This must be used to ensure that the communications code starts. In the future it would be - * nice to put this code into it's own task that loads on boot so ensure that it runs. + * This must be used to ensure that the communications code starts. In the + * future it would be + * nice to put this code into it's own task that loads on boot so ensure that it + * runs. */ -RobotBase::RobotBase() - : m_task (NULL) - , m_ds (NULL) -{ - m_ds = DriverStation::GetInstance(); - RobotState::SetImplementation(DriverStation::GetInstance()); \ - HLUsageReporting::SetImplementation(new HardwareHLReporting()); \ +RobotBase::RobotBase() : m_task(NULL), m_ds(NULL) { + m_ds = DriverStation::GetInstance(); + RobotState::SetImplementation(DriverStation::GetInstance()); + HLUsageReporting::SetImplementation(new HardwareHLReporting()); - RobotBase::setInstance(this); - - FILE *file = NULL; - file = fopen("/tmp/frc_versions/FRC_Lib_Version.ini", "w"); + RobotBase::setInstance(this); - fputs("2015 C++ 1.2.0", file); - if (file != NULL) - fclose(file); + FILE *file = NULL; + file = fopen("/tmp/frc_versions/FRC_Lib_Version.ini", "w"); + + fputs("2015 C++ 1.2.0", file); + if (file != NULL) fclose(file); } /** * Free the resources for a RobotBase class. - * This includes deleting all classes that might have been allocated as Singletons to they + * This includes deleting all classes that might have been allocated as + * Singletons to they * would never be deleted except here. */ -RobotBase::~RobotBase() -{ - SensorBase::DeleteSingletons(); - delete m_task; - m_task = NULL; - m_instance = NULL; +RobotBase::~RobotBase() { + SensorBase::DeleteSingletons(); + delete m_task; + m_task = NULL; + m_instance = NULL; } /** * Determine if the Robot is currently enabled. * @return True if the Robot is currently enabled by the field controls. */ -bool RobotBase::IsEnabled() const -{ - return m_ds->IsEnabled(); -} +bool RobotBase::IsEnabled() const { return m_ds->IsEnabled(); } /** * Determine if the Robot is currently disabled. * @return True if the Robot is currently disabled by the field controls. */ -bool RobotBase::IsDisabled() const -{ - return m_ds->IsDisabled(); -} +bool RobotBase::IsDisabled() const { return m_ds->IsDisabled(); } /** * Determine if the robot is currently in Autonomous mode. - * @return True if the robot is currently operating Autonomously as determined by the field controls. + * @return True if the robot is currently operating Autonomously as determined + * by the field controls. */ -bool RobotBase::IsAutonomous() const -{ - return m_ds->IsAutonomous(); -} +bool RobotBase::IsAutonomous() const { return m_ds->IsAutonomous(); } /** * Determine if the robot is currently in Operator Control mode. - * @return True if the robot is currently operating in Tele-Op mode as determined by the field controls. + * @return True if the robot is currently operating in Tele-Op mode as + * determined by the field controls. */ -bool RobotBase::IsOperatorControl() const -{ - return m_ds->IsOperatorControl(); -} +bool RobotBase::IsOperatorControl() const { return m_ds->IsOperatorControl(); } /** * Determine if the robot is currently in Test mode. - * @return True if the robot is currently running tests as determined by the field controls. + * @return True if the robot is currently running tests as determined by the + * field controls. */ -bool RobotBase::IsTest() const -{ - return m_ds->IsTest(); -} +bool RobotBase::IsTest() const { return m_ds->IsTest(); } /** - * This hook is called right before startCompetition(). By default, tell the DS that the robot is now ready to - * be enabled. If you don't want for the robot to be enabled yet, you can override this method to do nothing. - * If you do so, you will need to call HALNetworkCommunicationObserveUserProgramStarting() from your code when + * This hook is called right before startCompetition(). By default, tell the DS + * that the robot is now ready to + * be enabled. If you don't want for the robot to be enabled yet, you can + * override this method to do nothing. + * If you do so, you will need to call + * HALNetworkCommunicationObserveUserProgramStarting() from your code when * you are ready for the robot to be enabled. */ -void RobotBase::Prestart() -{ - HALNetworkCommunicationObserveUserProgramStarting(); +void RobotBase::Prestart() { + HALNetworkCommunicationObserveUserProgramStarting(); } /** * Indicates if new data is available from the driver station. - * @return Has new data arrived over the network since the last time this function was called? + * @return Has new data arrived over the network since the last time this + * function was called? */ -bool RobotBase::IsNewDataAvailable() const -{ - return m_ds->IsNewControlData(); -} +bool RobotBase::IsNewDataAvailable() const { return m_ds->IsNewControlData(); } /** - * This class exists for the sole purpose of getting its destructor called when the module unloads. - * Before the module is done unloading, we need to delete the RobotBase derived singleton. This should delete - * the other remaining singletons that were registered. This should also stop all tasks that are using + * This class exists for the sole purpose of getting its destructor called when + * the module unloads. + * Before the module is done unloading, we need to delete the RobotBase derived + * singleton. This should delete + * the other remaining singletons that were registered. This should also stop + * all tasks that are using * the Task class. */ -class RobotDeleter -{ -public: - RobotDeleter() {} - ~RobotDeleter() - { - delete &RobotBase::getInstance(); - } +class RobotDeleter { + public: + RobotDeleter() {} + ~RobotDeleter() { delete &RobotBase::getInstance(); } }; static RobotDeleter g_robotDeleter; diff --git a/wpilibc/wpilibC++Devices/src/RobotDrive.cpp b/wpilibc/wpilibC++Devices/src/RobotDrive.cpp index 31bd8d216b..1c42aedada 100644 --- a/wpilibc/wpilibC++Devices/src/RobotDrive.cpp +++ b/wpilibc/wpilibC++Devices/src/RobotDrive.cpp @@ -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. */ /*----------------------------------------------------------------------------*/ @@ -22,43 +23,47 @@ const int32_t RobotDrive::kMaxNumberOfMotors; /* * Driving functions - * These functions provide an interface to multiple motors that is used for C programming - * The Drive(speed, direction) function is the main part of the set that makes it easy + * These functions provide an interface to multiple motors that is used for C + * programming + * The Drive(speed, direction) function is the main part of the set that makes + * it easy * to set speeds and direction independently in one call. */ /** * Common function to initialize all the robot drive constructors. * Create a motor safety object (the real reason for the common code) and - * initialize all the motor assignments. The default timeout is set for the robot drive. + * initialize all the motor assignments. The default timeout is set for the + * robot drive. */ void RobotDrive::InitRobotDrive() { - m_frontLeftMotor = NULL; - m_frontRightMotor = NULL; - m_rearRightMotor = NULL; - m_rearLeftMotor = NULL; - m_sensitivity = 0.5; - m_maxOutput = 1.0; - m_safetyHelper = new MotorSafetyHelper(this); - m_safetyHelper->SetSafetyEnabled(true); - m_syncGroup = 0; + m_frontLeftMotor = NULL; + m_frontRightMotor = NULL; + m_rearRightMotor = NULL; + m_rearLeftMotor = NULL; + m_sensitivity = 0.5; + m_maxOutput = 1.0; + m_safetyHelper = new MotorSafetyHelper(this); + m_safetyHelper->SetSafetyEnabled(true); + m_syncGroup = 0; } -/** +/** * Constructor for RobotDrive with 2 motors specified with channel numbers. * Set up parameters for a two wheel drive system where the * left and right motor pwm channels are specified in the call. * This call assumes Talons for controlling the motors. - * @param leftMotorChannel The PWM channel number that drives the left motor. 0-9 are on-board, 10-19 are on the MXP port - * @param rightMotorChannel The PWM channel number that drives the right motor. 0-9 are on-board, 10-19 are on the MXP port + * @param leftMotorChannel The PWM channel number that drives the left motor. + * 0-9 are on-board, 10-19 are on the MXP port + * @param rightMotorChannel The PWM channel number that drives the right motor. + * 0-9 are on-board, 10-19 are on the MXP port */ -RobotDrive::RobotDrive(uint32_t leftMotorChannel, uint32_t rightMotorChannel) -{ - InitRobotDrive(); - m_rearLeftMotor = new Talon(leftMotorChannel); - m_rearRightMotor = new Talon(rightMotorChannel); - SetLeftRightMotorOutputs(0.0, 0.0); - m_deleteSpeedControllers = true; +RobotDrive::RobotDrive(uint32_t leftMotorChannel, uint32_t rightMotorChannel) { + InitRobotDrive(); + m_rearLeftMotor = new Talon(leftMotorChannel); + m_rearRightMotor = new Talon(rightMotorChannel); + SetLeftRightMotorOutputs(0.0, 0.0); + m_deleteSpeedControllers = true; } /** @@ -66,148 +71,154 @@ RobotDrive::RobotDrive(uint32_t leftMotorChannel, uint32_t rightMotorChannel) * Set up parameters for a four wheel drive system where all four motor * pwm channels are specified in the call. * This call assumes Talons for controlling the motors. - * @param frontLeftMotor Front left motor channel number. 0-9 are on-board, 10-19 are on the MXP port - * @param rearLeftMotor Rear Left motor channel number. 0-9 are on-board, 10-19 are on the MXP port - * @param frontRightMotor Front right motor channel number. 0-9 are on-board, 10-19 are on the MXP port - * @param rearRightMotor Rear Right motor channel number. 0-9 are on-board, 10-19 are on the MXP port + * @param frontLeftMotor Front left motor channel number. 0-9 are on-board, + * 10-19 are on the MXP port + * @param rearLeftMotor Rear Left motor channel number. 0-9 are on-board, 10-19 + * are on the MXP port + * @param frontRightMotor Front right motor channel number. 0-9 are on-board, + * 10-19 are on the MXP port + * @param rearRightMotor Rear Right motor channel number. 0-9 are on-board, + * 10-19 are on the MXP port */ RobotDrive::RobotDrive(uint32_t frontLeftMotor, uint32_t rearLeftMotor, - uint32_t frontRightMotor, uint32_t rearRightMotor) -{ - InitRobotDrive(); - m_rearLeftMotor = new Talon(rearLeftMotor); - m_rearRightMotor = new Talon(rearRightMotor); - m_frontLeftMotor = new Talon(frontLeftMotor); - m_frontRightMotor = new Talon(frontRightMotor); - SetLeftRightMotorOutputs(0.0, 0.0); - m_deleteSpeedControllers = true; + uint32_t frontRightMotor, uint32_t rearRightMotor) { + InitRobotDrive(); + m_rearLeftMotor = new Talon(rearLeftMotor); + m_rearRightMotor = new Talon(rearRightMotor); + m_frontLeftMotor = new Talon(frontLeftMotor); + m_frontRightMotor = new Talon(frontRightMotor); + SetLeftRightMotorOutputs(0.0, 0.0); + m_deleteSpeedControllers = true; } /** - * Constructor for RobotDrive with 2 motors specified as SpeedController objects. - * The SpeedController version of the constructor enables programs to use the RobotDrive classes with - * subclasses of the SpeedController objects, for example, versions with ramping or reshaping of + * Constructor for RobotDrive with 2 motors specified as SpeedController + * objects. + * The SpeedController version of the constructor enables programs to use the + * RobotDrive classes with + * subclasses of the SpeedController objects, for example, versions with ramping + * or reshaping of * the curve to suit motor bias or deadband elimination. - * @param leftMotor The left SpeedController object used to drive the robot. + * @param leftMotor The left SpeedController object used to drive the robot. * @param rightMotor the right SpeedController object used to drive the robot. */ -RobotDrive::RobotDrive(SpeedController *leftMotor, SpeedController *rightMotor) -{ - InitRobotDrive(); - if (leftMotor == NULL || rightMotor == NULL) - { - wpi_setWPIError(NullParameter); - m_rearLeftMotor = m_rearRightMotor = NULL; - return; - } - m_rearLeftMotor = leftMotor; - m_rearRightMotor = rightMotor; - m_deleteSpeedControllers = false; +RobotDrive::RobotDrive(SpeedController *leftMotor, + SpeedController *rightMotor) { + InitRobotDrive(); + if (leftMotor == NULL || rightMotor == NULL) { + wpi_setWPIError(NullParameter); + m_rearLeftMotor = m_rearRightMotor = NULL; + return; + } + m_rearLeftMotor = leftMotor; + m_rearRightMotor = rightMotor; + m_deleteSpeedControllers = false; } -RobotDrive::RobotDrive(SpeedController &leftMotor, SpeedController &rightMotor) -{ - InitRobotDrive(); - m_rearLeftMotor = &leftMotor; - m_rearRightMotor = &rightMotor; - m_deleteSpeedControllers = false; +RobotDrive::RobotDrive(SpeedController &leftMotor, + SpeedController &rightMotor) { + InitRobotDrive(); + m_rearLeftMotor = &leftMotor; + m_rearRightMotor = &rightMotor; + m_deleteSpeedControllers = false; } /** - * Constructor for RobotDrive with 4 motors specified as SpeedController objects. + * Constructor for RobotDrive with 4 motors specified as SpeedController + * objects. * Speed controller input version of RobotDrive (see previous comments). - * @param rearLeftMotor The back left SpeedController object used to drive the robot. - * @param frontLeftMotor The front left SpeedController object used to drive the robot - * @param rearRightMotor The back right SpeedController object used to drive the robot. - * @param frontRightMotor The front right SpeedController object used to drive the robot. + * @param rearLeftMotor The back left SpeedController object used to drive the + * robot. + * @param frontLeftMotor The front left SpeedController object used to drive the + * robot + * @param rearRightMotor The back right SpeedController object used to drive the + * robot. + * @param frontRightMotor The front right SpeedController object used to drive + * the robot. */ -RobotDrive::RobotDrive(SpeedController *frontLeftMotor, SpeedController *rearLeftMotor, - SpeedController *frontRightMotor, SpeedController *rearRightMotor) -{ - InitRobotDrive(); - if (frontLeftMotor == NULL || rearLeftMotor == NULL || frontRightMotor == NULL || rearRightMotor == NULL) - { - wpi_setWPIError(NullParameter); - return; - } - m_frontLeftMotor = frontLeftMotor; - m_rearLeftMotor = rearLeftMotor; - m_frontRightMotor = frontRightMotor; - m_rearRightMotor = rearRightMotor; - m_deleteSpeedControllers = false; +RobotDrive::RobotDrive(SpeedController *frontLeftMotor, + SpeedController *rearLeftMotor, + SpeedController *frontRightMotor, + SpeedController *rearRightMotor) { + InitRobotDrive(); + if (frontLeftMotor == NULL || rearLeftMotor == NULL || + frontRightMotor == NULL || rearRightMotor == NULL) { + wpi_setWPIError(NullParameter); + return; + } + m_frontLeftMotor = frontLeftMotor; + m_rearLeftMotor = rearLeftMotor; + m_frontRightMotor = frontRightMotor; + m_rearRightMotor = rearRightMotor; + m_deleteSpeedControllers = false; } -RobotDrive::RobotDrive(SpeedController &frontLeftMotor, SpeedController &rearLeftMotor, - SpeedController &frontRightMotor, SpeedController &rearRightMotor) -{ - InitRobotDrive(); - m_frontLeftMotor = &frontLeftMotor; - m_rearLeftMotor = &rearLeftMotor; - m_frontRightMotor = &frontRightMotor; - m_rearRightMotor = &rearRightMotor; - m_deleteSpeedControllers = false; +RobotDrive::RobotDrive(SpeedController &frontLeftMotor, + SpeedController &rearLeftMotor, + SpeedController &frontRightMotor, + SpeedController &rearRightMotor) { + InitRobotDrive(); + m_frontLeftMotor = &frontLeftMotor; + m_rearLeftMotor = &rearLeftMotor; + m_frontRightMotor = &frontRightMotor; + m_rearRightMotor = &rearRightMotor; + m_deleteSpeedControllers = false; } /** * RobotDrive destructor. * Deletes motor objects that were not passed in and created internally only. **/ -RobotDrive::~RobotDrive() -{ - if (m_deleteSpeedControllers) - { - delete m_frontLeftMotor; - delete m_rearLeftMotor; - delete m_frontRightMotor; - delete m_rearRightMotor; - } - delete m_safetyHelper; +RobotDrive::~RobotDrive() { + if (m_deleteSpeedControllers) { + delete m_frontLeftMotor; + delete m_rearLeftMotor; + delete m_frontRightMotor; + delete m_rearRightMotor; + } + delete m_safetyHelper; } /** * Drive the motors at "speed" and "curve". * * The speed and curve are -1.0 to +1.0 values where 0.0 represents stopped and - * not turning. The algorithm for adding in the direction attempts to provide a constant + * not turning. The algorithm for adding in the direction attempts to provide a + * constant * turn radius for differing speeds. * * This function will most likely be used in an autonomous routine. * - * @param outputMagnitude The forward component of the output magnitude to send to the motors. + * @param outputMagnitude The forward component of the output magnitude to send + * to the motors. * @param curve The rate of turn, constant for different forward speeds. */ -void RobotDrive::Drive(float outputMagnitude, float curve) -{ - float leftOutput, rightOutput; - static bool reported = false; - if (!reported) - { - HALReport(HALUsageReporting::kResourceType_RobotDrive, GetNumMotors(), HALUsageReporting::kRobotDrive_ArcadeRatioCurve); - reported = true; - } +void RobotDrive::Drive(float outputMagnitude, float curve) { + float leftOutput, rightOutput; + static bool reported = false; + if (!reported) { + HALReport(HALUsageReporting::kResourceType_RobotDrive, GetNumMotors(), + HALUsageReporting::kRobotDrive_ArcadeRatioCurve); + reported = true; + } - if (curve < 0) - { - float value = log(-curve); - float ratio = (value - m_sensitivity)/(value + m_sensitivity); - if (ratio == 0) ratio =.0000000001; - leftOutput = outputMagnitude / ratio; - rightOutput = outputMagnitude; - } - else if (curve > 0) - { - float value = log(curve); - float ratio = (value - m_sensitivity)/(value + m_sensitivity); - if (ratio == 0) ratio =.0000000001; - leftOutput = outputMagnitude; - rightOutput = outputMagnitude / ratio; - } - else - { - leftOutput = outputMagnitude; - rightOutput = outputMagnitude; - } - SetLeftRightMotorOutputs(leftOutput, rightOutput); + if (curve < 0) { + float value = log(-curve); + float ratio = (value - m_sensitivity) / (value + m_sensitivity); + if (ratio == 0) ratio = .0000000001; + leftOutput = outputMagnitude / ratio; + rightOutput = outputMagnitude; + } else if (curve > 0) { + float value = log(curve); + float ratio = (value - m_sensitivity) / (value + m_sensitivity); + if (ratio == 0) ratio = .0000000001; + leftOutput = outputMagnitude; + rightOutput = outputMagnitude / ratio; + } else { + leftOutput = outputMagnitude; + rightOutput = outputMagnitude; + } + SetLeftRightMotorOutputs(leftOutput, rightOutput); } /** @@ -217,24 +228,24 @@ void RobotDrive::Drive(float outputMagnitude, float curve) * @param leftStick The joystick to control the left side of the robot. * @param rightStick The joystick to control the right side of the robot. */ -void RobotDrive::TankDrive(GenericHID *leftStick, GenericHID *rightStick, bool squaredInputs) -{ - if (leftStick == NULL || rightStick == NULL) - { - wpi_setWPIError(NullParameter); - return; - } - TankDrive(leftStick->GetY(), rightStick->GetY(), squaredInputs); +void RobotDrive::TankDrive(GenericHID *leftStick, GenericHID *rightStick, + bool squaredInputs) { + if (leftStick == NULL || rightStick == NULL) { + wpi_setWPIError(NullParameter); + return; + } + TankDrive(leftStick->GetY(), rightStick->GetY(), squaredInputs); } -void RobotDrive::TankDrive(GenericHID &leftStick, GenericHID &rightStick, bool squaredInputs) -{ - TankDrive(leftStick.GetY(), rightStick.GetY(), squaredInputs); +void RobotDrive::TankDrive(GenericHID &leftStick, GenericHID &rightStick, + bool squaredInputs) { + TankDrive(leftStick.GetY(), rightStick.GetY(), squaredInputs); } /** * Provide tank steering using the stored robot configuration. - * This function lets you pick the axis to be used on each Joystick object for the left + * This function lets you pick the axis to be used on each Joystick object for + * the left * and right sides of the robot. * @param leftStick The Joystick object to use for the left side of the robot. * @param leftAxis The axis to select on the left side Joystick object. @@ -242,133 +253,139 @@ void RobotDrive::TankDrive(GenericHID &leftStick, GenericHID &rightStick, bool s * @param rightAxis The axis to select on the right side Joystick object. */ void RobotDrive::TankDrive(GenericHID *leftStick, uint32_t leftAxis, - GenericHID *rightStick, uint32_t rightAxis, bool squaredInputs) -{ - if (leftStick == NULL || rightStick == NULL) - { - wpi_setWPIError(NullParameter); - return; - } - TankDrive(leftStick->GetRawAxis(leftAxis), rightStick->GetRawAxis(rightAxis), squaredInputs); + GenericHID *rightStick, uint32_t rightAxis, + bool squaredInputs) { + if (leftStick == NULL || rightStick == NULL) { + wpi_setWPIError(NullParameter); + return; + } + TankDrive(leftStick->GetRawAxis(leftAxis), rightStick->GetRawAxis(rightAxis), + squaredInputs); } void RobotDrive::TankDrive(GenericHID &leftStick, uint32_t leftAxis, - GenericHID &rightStick, uint32_t rightAxis, bool squaredInputs) -{ - TankDrive(leftStick.GetRawAxis(leftAxis), rightStick.GetRawAxis(rightAxis), squaredInputs); + GenericHID &rightStick, uint32_t rightAxis, + bool squaredInputs) { + TankDrive(leftStick.GetRawAxis(leftAxis), rightStick.GetRawAxis(rightAxis), + squaredInputs); } - /** * Provide tank steering using the stored robot configuration. * This function lets you directly provide joystick values from any source. * @param leftValue The value of the left stick. * @param rightValue The value of the right stick. */ -void RobotDrive::TankDrive(float leftValue, float rightValue, bool squaredInputs) -{ - static bool reported = false; - if (!reported) - { - HALReport(HALUsageReporting::kResourceType_RobotDrive, GetNumMotors(), HALUsageReporting::kRobotDrive_Tank); - reported = true; - } +void RobotDrive::TankDrive(float leftValue, float rightValue, + bool squaredInputs) { + static bool reported = false; + if (!reported) { + HALReport(HALUsageReporting::kResourceType_RobotDrive, GetNumMotors(), + HALUsageReporting::kRobotDrive_Tank); + reported = true; + } - // square the inputs (while preserving the sign) to increase fine control while permitting full power - leftValue = Limit(leftValue); - rightValue = Limit(rightValue); - if(squaredInputs) - { - if (leftValue >= 0.0) - { - leftValue = (leftValue * leftValue); - } - else - { - leftValue = -(leftValue * leftValue); - } - if (rightValue >= 0.0) - { - rightValue = (rightValue * rightValue); - } - else - { - rightValue = -(rightValue * rightValue); - } - } + // square the inputs (while preserving the sign) to increase fine control + // while permitting full power + leftValue = Limit(leftValue); + rightValue = Limit(rightValue); + if (squaredInputs) { + if (leftValue >= 0.0) { + leftValue = (leftValue * leftValue); + } else { + leftValue = -(leftValue * leftValue); + } + if (rightValue >= 0.0) { + rightValue = (rightValue * rightValue); + } else { + rightValue = -(rightValue * rightValue); + } + } - SetLeftRightMotorOutputs(leftValue, rightValue); + SetLeftRightMotorOutputs(leftValue, rightValue); } /** * Arcade drive implements single stick driving. - * Given a single Joystick, the class assumes the Y axis for the move value and the X axis + * Given a single Joystick, the class assumes the Y axis for the move value and + * the X axis * for the rotate value. * (Should add more information here regarding the way that arcade drive works.) - * @param stick The joystick to use for Arcade single-stick driving. The Y-axis will be selected + * @param stick The joystick to use for Arcade single-stick driving. The Y-axis + * will be selected * for forwards/backwards and the X-axis will be selected for rotation rate. - * @param squaredInputs If true, the sensitivity will be increased for small values + * @param squaredInputs If true, the sensitivity will be increased for small + * values */ -void RobotDrive::ArcadeDrive(GenericHID *stick, bool squaredInputs) -{ - // simply call the full-featured ArcadeDrive with the appropriate values - ArcadeDrive(stick->GetY(), stick->GetX(), squaredInputs); +void RobotDrive::ArcadeDrive(GenericHID *stick, bool squaredInputs) { + // simply call the full-featured ArcadeDrive with the appropriate values + ArcadeDrive(stick->GetY(), stick->GetX(), squaredInputs); } /** * Arcade drive implements single stick driving. - * Given a single Joystick, the class assumes the Y axis for the move value and the X axis + * Given a single Joystick, the class assumes the Y axis for the move value and + * the X axis * for the rotate value. * (Should add more information here regarding the way that arcade drive works.) - * @param stick The joystick to use for Arcade single-stick driving. The Y-axis will be selected + * @param stick The joystick to use for Arcade single-stick driving. The Y-axis + * will be selected * for forwards/backwards and the X-axis will be selected for rotation rate. - * @param squaredInputs If true, the sensitivity will be increased for small values + * @param squaredInputs If true, the sensitivity will be increased for small + * values */ -void RobotDrive::ArcadeDrive(GenericHID &stick, bool squaredInputs) -{ - // simply call the full-featured ArcadeDrive with the appropriate values - ArcadeDrive(stick.GetY(), stick.GetX(), squaredInputs); +void RobotDrive::ArcadeDrive(GenericHID &stick, bool squaredInputs) { + // simply call the full-featured ArcadeDrive with the appropriate values + ArcadeDrive(stick.GetY(), stick.GetX(), squaredInputs); } /** * Arcade drive implements single stick driving. - * Given two joystick instances and two axis, compute the values to send to either two + * Given two joystick instances and two axis, compute the values to send to + * either two * or four motors. - * @param moveStick The Joystick object that represents the forward/backward direction - * @param moveAxis The axis on the moveStick object to use for fowards/backwards (typically Y_AXIS) + * @param moveStick The Joystick object that represents the forward/backward + * direction + * @param moveAxis The axis on the moveStick object to use for fowards/backwards + * (typically Y_AXIS) * @param rotateStick The Joystick object that represents the rotation value - * @param rotateAxis The axis on the rotation object to use for the rotate right/left (typically X_AXIS) - * @param squaredInputs Setting this parameter to true increases the sensitivity at lower speeds + * @param rotateAxis The axis on the rotation object to use for the rotate + * right/left (typically X_AXIS) + * @param squaredInputs Setting this parameter to true increases the sensitivity + * at lower speeds */ -void RobotDrive::ArcadeDrive(GenericHID* moveStick, uint32_t moveAxis, - GenericHID* rotateStick, uint32_t rotateAxis, - bool squaredInputs) -{ - float moveValue = moveStick->GetRawAxis(moveAxis); - float rotateValue = rotateStick->GetRawAxis(rotateAxis); +void RobotDrive::ArcadeDrive(GenericHID *moveStick, uint32_t moveAxis, + GenericHID *rotateStick, uint32_t rotateAxis, + bool squaredInputs) { + float moveValue = moveStick->GetRawAxis(moveAxis); + float rotateValue = rotateStick->GetRawAxis(rotateAxis); - ArcadeDrive(moveValue, rotateValue, squaredInputs); + ArcadeDrive(moveValue, rotateValue, squaredInputs); } /** * Arcade drive implements single stick driving. - * Given two joystick instances and two axis, compute the values to send to either two + * Given two joystick instances and two axis, compute the values to send to + * either two * or four motors. - * @param moveStick The Joystick object that represents the forward/backward direction - * @param moveAxis The axis on the moveStick object to use for fowards/backwards (typically Y_AXIS) + * @param moveStick The Joystick object that represents the forward/backward + * direction + * @param moveAxis The axis on the moveStick object to use for fowards/backwards + * (typically Y_AXIS) * @param rotateStick The Joystick object that represents the rotation value - * @param rotateAxis The axis on the rotation object to use for the rotate right/left (typically X_AXIS) - * @param squaredInputs Setting this parameter to true increases the sensitivity at lower speeds + * @param rotateAxis The axis on the rotation object to use for the rotate + * right/left (typically X_AXIS) + * @param squaredInputs Setting this parameter to true increases the sensitivity + * at lower speeds */ void RobotDrive::ArcadeDrive(GenericHID &moveStick, uint32_t moveAxis, - GenericHID &rotateStick, uint32_t rotateAxis, - bool squaredInputs) -{ - float moveValue = moveStick.GetRawAxis(moveAxis); - float rotateValue = rotateStick.GetRawAxis(rotateAxis); + GenericHID &rotateStick, uint32_t rotateAxis, + bool squaredInputs) { + float moveValue = moveStick.GetRawAxis(moveAxis); + float rotateValue = rotateStick.GetRawAxis(rotateAxis); - ArcadeDrive(moveValue, rotateValue, squaredInputs); + ArcadeDrive(moveValue, rotateValue, squaredInputs); } /** @@ -378,173 +395,173 @@ void RobotDrive::ArcadeDrive(GenericHID &moveStick, uint32_t moveAxis, * @param rotateValue The value to use for the rotate right/left * @param squaredInputs If set, increases the sensitivity at low speeds */ -void RobotDrive::ArcadeDrive(float moveValue, float rotateValue, bool squaredInputs) -{ - static bool reported = false; - if (!reported) - { - HALReport(HALUsageReporting::kResourceType_RobotDrive, GetNumMotors(), HALUsageReporting::kRobotDrive_ArcadeStandard); - reported = true; - } +void RobotDrive::ArcadeDrive(float moveValue, float rotateValue, + bool squaredInputs) { + static bool reported = false; + if (!reported) { + HALReport(HALUsageReporting::kResourceType_RobotDrive, GetNumMotors(), + HALUsageReporting::kRobotDrive_ArcadeStandard); + reported = true; + } - // local variables to hold the computed PWM values for the motors - float leftMotorOutput; - float rightMotorOutput; + // local variables to hold the computed PWM values for the motors + float leftMotorOutput; + float rightMotorOutput; - moveValue = Limit(moveValue); - rotateValue = Limit(rotateValue); + moveValue = Limit(moveValue); + rotateValue = Limit(rotateValue); - if (squaredInputs) - { - // square the inputs (while preserving the sign) to increase fine control while permitting full power - if (moveValue >= 0.0) - { - moveValue = (moveValue * moveValue); - } - else - { - moveValue = -(moveValue * moveValue); - } - if (rotateValue >= 0.0) - { - rotateValue = (rotateValue * rotateValue); - } - else - { - rotateValue = -(rotateValue * rotateValue); - } - } + if (squaredInputs) { + // square the inputs (while preserving the sign) to increase fine control + // while permitting full power + if (moveValue >= 0.0) { + moveValue = (moveValue * moveValue); + } else { + moveValue = -(moveValue * moveValue); + } + if (rotateValue >= 0.0) { + rotateValue = (rotateValue * rotateValue); + } else { + rotateValue = -(rotateValue * rotateValue); + } + } - if (moveValue > 0.0) - { - if (rotateValue > 0.0) - { - leftMotorOutput = moveValue - rotateValue; - rightMotorOutput = std::max(moveValue, rotateValue); - } - else - { - leftMotorOutput = std::max(moveValue, -rotateValue); - rightMotorOutput = moveValue + rotateValue; - } - } - else - { - if (rotateValue > 0.0) - { - leftMotorOutput = - std::max(-moveValue, rotateValue); - rightMotorOutput = moveValue + rotateValue; - } - else - { - leftMotorOutput = moveValue - rotateValue; - rightMotorOutput = - std::max(-moveValue, -rotateValue); - } - } - SetLeftRightMotorOutputs(leftMotorOutput, rightMotorOutput); + if (moveValue > 0.0) { + if (rotateValue > 0.0) { + leftMotorOutput = moveValue - rotateValue; + rightMotorOutput = std::max(moveValue, rotateValue); + } else { + leftMotorOutput = std::max(moveValue, -rotateValue); + rightMotorOutput = moveValue + rotateValue; + } + } else { + if (rotateValue > 0.0) { + leftMotorOutput = -std::max(-moveValue, rotateValue); + rightMotorOutput = moveValue + rotateValue; + } else { + leftMotorOutput = moveValue - rotateValue; + rightMotorOutput = -std::max(-moveValue, -rotateValue); + } + } + SetLeftRightMotorOutputs(leftMotorOutput, rightMotorOutput); } /** * Drive method for Mecanum wheeled robots. * * A method for driving with Mecanum wheeled robots. There are 4 wheels - * on the robot, arranged so that the front and back wheels are toed in 45 degrees. - * When looking at the wheels from the top, the roller axles should form an X across the robot. + * on the robot, arranged so that the front and back wheels are toed in 45 + * degrees. + * When looking at the wheels from the top, the roller axles should form an X + * across the robot. * * This is designed to be directly driven by joystick axes. * - * @param x The speed that the robot should drive in the X direction. [-1.0..1.0] + * @param x The speed that the robot should drive in the X direction. + * [-1.0..1.0] * @param y The speed that the robot should drive in the Y direction. - * This input is inverted to match the forward == -1.0 that joysticks produce. [-1.0..1.0] - * @param rotation The rate of rotation for the robot that is completely independent of + * This input is inverted to match the forward == -1.0 that joysticks produce. + * [-1.0..1.0] + * @param rotation The rate of rotation for the robot that is completely + * independent of * the translation. [-1.0..1.0] - * @param gyroAngle The current angle reading from the gyro. Use this to implement field-oriented controls. + * @param gyroAngle The current angle reading from the gyro. Use this to + * implement field-oriented controls. */ -void RobotDrive::MecanumDrive_Cartesian(float x, float y, float rotation, float gyroAngle) -{ - static bool reported = false; - if (!reported) - { - HALReport(HALUsageReporting::kResourceType_RobotDrive, GetNumMotors(), HALUsageReporting::kRobotDrive_MecanumCartesian); - reported = true; - } +void RobotDrive::MecanumDrive_Cartesian(float x, float y, float rotation, + float gyroAngle) { + static bool reported = false; + if (!reported) { + HALReport(HALUsageReporting::kResourceType_RobotDrive, GetNumMotors(), + HALUsageReporting::kRobotDrive_MecanumCartesian); + reported = true; + } - double xIn = x; - double yIn = y; - // Negate y for the joystick. - yIn = -yIn; - // Compenstate for gyro angle. - RotateVector(xIn, yIn, gyroAngle); + double xIn = x; + double yIn = y; + // Negate y for the joystick. + yIn = -yIn; + // Compenstate for gyro angle. + RotateVector(xIn, yIn, gyroAngle); - double wheelSpeeds[kMaxNumberOfMotors]; - wheelSpeeds[kFrontLeftMotor] = xIn + yIn + rotation; - wheelSpeeds[kFrontRightMotor] = -xIn + yIn - rotation; - wheelSpeeds[kRearLeftMotor] = -xIn + yIn + rotation; - wheelSpeeds[kRearRightMotor] = xIn + yIn - rotation; + double wheelSpeeds[kMaxNumberOfMotors]; + wheelSpeeds[kFrontLeftMotor] = xIn + yIn + rotation; + wheelSpeeds[kFrontRightMotor] = -xIn + yIn - rotation; + wheelSpeeds[kRearLeftMotor] = -xIn + yIn + rotation; + wheelSpeeds[kRearRightMotor] = xIn + yIn - rotation; - Normalize(wheelSpeeds); + Normalize(wheelSpeeds); - m_frontLeftMotor->Set(wheelSpeeds[kFrontLeftMotor] * m_maxOutput, m_syncGroup); - m_frontRightMotor->Set(wheelSpeeds[kFrontRightMotor] * m_maxOutput, m_syncGroup); - m_rearLeftMotor->Set(wheelSpeeds[kRearLeftMotor] * m_maxOutput, m_syncGroup); - m_rearRightMotor->Set(wheelSpeeds[kRearRightMotor] * m_maxOutput, m_syncGroup); + m_frontLeftMotor->Set(wheelSpeeds[kFrontLeftMotor] * m_maxOutput, + m_syncGroup); + m_frontRightMotor->Set(wheelSpeeds[kFrontRightMotor] * m_maxOutput, + m_syncGroup); + m_rearLeftMotor->Set(wheelSpeeds[kRearLeftMotor] * m_maxOutput, m_syncGroup); + m_rearRightMotor->Set(wheelSpeeds[kRearRightMotor] * m_maxOutput, + m_syncGroup); - if (m_syncGroup != 0) - { - CANJaguar::UpdateSyncGroup(m_syncGroup); - } + if (m_syncGroup != 0) { + CANJaguar::UpdateSyncGroup(m_syncGroup); + } - m_safetyHelper->Feed(); + m_safetyHelper->Feed(); } /** * Drive method for Mecanum wheeled robots. * * A method for driving with Mecanum wheeled robots. There are 4 wheels - * on the robot, arranged so that the front and back wheels are toed in 45 degrees. - * When looking at the wheels from the top, the roller axles should form an X across the robot. + * on the robot, arranged so that the front and back wheels are toed in 45 + * degrees. + * When looking at the wheels from the top, the roller axles should form an X + * across the robot. * - * @param magnitude The speed that the robot should drive in a given direction. [-1.0..1.0] - * @param direction The direction the robot should drive in degrees. The direction and maginitute are + * @param magnitude The speed that the robot should drive in a given direction. + * [-1.0..1.0] + * @param direction The direction the robot should drive in degrees. The + * direction and maginitute are * independent of the rotation rate. - * @param rotation The rate of rotation for the robot that is completely independent of + * @param rotation The rate of rotation for the robot that is completely + * independent of * the magnitute or direction. [-1.0..1.0] */ -void RobotDrive::MecanumDrive_Polar(float magnitude, float direction, float rotation) -{ - static bool reported = false; - if (!reported) - { - HALReport(HALUsageReporting::kResourceType_RobotDrive, GetNumMotors(), HALUsageReporting::kRobotDrive_MecanumPolar); - reported = true; - } +void RobotDrive::MecanumDrive_Polar(float magnitude, float direction, + float rotation) { + static bool reported = false; + if (!reported) { + HALReport(HALUsageReporting::kResourceType_RobotDrive, GetNumMotors(), + HALUsageReporting::kRobotDrive_MecanumPolar); + reported = true; + } - // Normalized for full power along the Cartesian axes. - magnitude = Limit(magnitude) * sqrt(2.0); - // The rollers are at 45 degree angles. - double dirInRad = (direction + 45.0) * 3.14159 / 180.0; - double cosD = cos(dirInRad); - double sinD = sin(dirInRad); + // Normalized for full power along the Cartesian axes. + magnitude = Limit(magnitude) * sqrt(2.0); + // The rollers are at 45 degree angles. + double dirInRad = (direction + 45.0) * 3.14159 / 180.0; + double cosD = cos(dirInRad); + double sinD = sin(dirInRad); - double wheelSpeeds[kMaxNumberOfMotors]; - wheelSpeeds[kFrontLeftMotor] = sinD * magnitude + rotation; - wheelSpeeds[kFrontRightMotor] = cosD * magnitude - rotation; - wheelSpeeds[kRearLeftMotor] = cosD * magnitude + rotation; - wheelSpeeds[kRearRightMotor] = sinD * magnitude - rotation; + double wheelSpeeds[kMaxNumberOfMotors]; + wheelSpeeds[kFrontLeftMotor] = sinD * magnitude + rotation; + wheelSpeeds[kFrontRightMotor] = cosD * magnitude - rotation; + wheelSpeeds[kRearLeftMotor] = cosD * magnitude + rotation; + wheelSpeeds[kRearRightMotor] = sinD * magnitude - rotation; - Normalize(wheelSpeeds); + Normalize(wheelSpeeds); - m_frontLeftMotor->Set(wheelSpeeds[kFrontLeftMotor] * m_maxOutput, m_syncGroup); - m_frontRightMotor->Set(wheelSpeeds[kFrontRightMotor] * m_maxOutput, m_syncGroup); - m_rearLeftMotor->Set(wheelSpeeds[kRearLeftMotor] * m_maxOutput, m_syncGroup); - m_rearRightMotor->Set(wheelSpeeds[kRearRightMotor] * m_maxOutput, m_syncGroup); + m_frontLeftMotor->Set(wheelSpeeds[kFrontLeftMotor] * m_maxOutput, + m_syncGroup); + m_frontRightMotor->Set(wheelSpeeds[kFrontRightMotor] * m_maxOutput, + m_syncGroup); + m_rearLeftMotor->Set(wheelSpeeds[kRearLeftMotor] * m_maxOutput, m_syncGroup); + m_rearRightMotor->Set(wheelSpeeds[kRearRightMotor] * m_maxOutput, + m_syncGroup); - if (m_syncGroup != 0) - { - CANJaguar::UpdateSyncGroup(m_syncGroup); - } + if (m_syncGroup != 0) { + CANJaguar::UpdateSyncGroup(m_syncGroup); + } - m_safetyHelper->Feed(); + m_safetyHelper->Feed(); } /** @@ -552,15 +569,18 @@ void RobotDrive::MecanumDrive_Polar(float magnitude, float direction, float rota * * This is an alias to MecanumDrive_Polar() for backward compatability * - * @param magnitude The speed that the robot should drive in a given direction. [-1.0..1.0] - * @param direction The direction the robot should drive. The direction and maginitute are + * @param magnitude The speed that the robot should drive in a given direction. + * [-1.0..1.0] + * @param direction The direction the robot should drive. The direction and + * maginitute are * independent of the rotation rate. - * @param rotation The rate of rotation for the robot that is completely independent of + * @param rotation The rate of rotation for the robot that is completely + * independent of * the magnitute or direction. [-1.0..1.0] */ -void RobotDrive::HolonomicDrive(float magnitude, float direction, float rotation) -{ - MecanumDrive_Polar(magnitude, direction, rotation); +void RobotDrive::HolonomicDrive(float magnitude, float direction, + float rotation) { + MecanumDrive_Polar(magnitude, direction, rotation); } /** Set the speed of the right and left motors. @@ -570,164 +590,153 @@ void RobotDrive::HolonomicDrive(float magnitude, float direction, float rotation * @param leftOutput The speed to send to the left side of the robot. * @param rightOutput The speed to send to the right side of the robot. */ -void RobotDrive::SetLeftRightMotorOutputs(float leftOutput, float rightOutput) -{ - wpi_assert(m_rearLeftMotor != NULL && m_rearRightMotor != NULL); +void RobotDrive::SetLeftRightMotorOutputs(float leftOutput, float rightOutput) { + wpi_assert(m_rearLeftMotor != NULL && m_rearRightMotor != NULL); - if (m_frontLeftMotor != NULL) - m_frontLeftMotor->Set(Limit(leftOutput) * m_maxOutput, m_syncGroup); - m_rearLeftMotor->Set(Limit(leftOutput) * m_maxOutput, m_syncGroup); + if (m_frontLeftMotor != NULL) + m_frontLeftMotor->Set(Limit(leftOutput) * m_maxOutput, m_syncGroup); + m_rearLeftMotor->Set(Limit(leftOutput) * m_maxOutput, m_syncGroup); - if (m_frontRightMotor != NULL) - m_frontRightMotor->Set(-Limit(rightOutput) * m_maxOutput, m_syncGroup); - m_rearRightMotor->Set(-Limit(rightOutput) * m_maxOutput, m_syncGroup); + if (m_frontRightMotor != NULL) + m_frontRightMotor->Set(-Limit(rightOutput) * m_maxOutput, m_syncGroup); + m_rearRightMotor->Set(-Limit(rightOutput) * m_maxOutput, m_syncGroup); - if (m_syncGroup != 0) - { - CANJaguar::UpdateSyncGroup(m_syncGroup); - } + if (m_syncGroup != 0) { + CANJaguar::UpdateSyncGroup(m_syncGroup); + } - m_safetyHelper->Feed(); + m_safetyHelper->Feed(); } /** * Limit motor values to the -1.0 to +1.0 range. */ -float RobotDrive::Limit(float num) -{ - if (num > 1.0) - { - return 1.0; - } - if (num < -1.0) - { - return -1.0; - } - return num; +float RobotDrive::Limit(float num) { + if (num > 1.0) { + return 1.0; + } + if (num < -1.0) { + return -1.0; + } + return num; } /** * Normalize all wheel speeds if the magnitude of any wheel is greater than 1.0. */ -void RobotDrive::Normalize(double *wheelSpeeds) -{ - double maxMagnitude = fabs(wheelSpeeds[0]); - int32_t i; - for (i=1; i 1.0) - { - for (i=0; i 1.0) { + for (i = 0; i < kMaxNumberOfMotors; i++) { + wheelSpeeds[i] = wheelSpeeds[i] / maxMagnitude; + } + } } /** * Rotate a vector in Cartesian space. */ -void RobotDrive::RotateVector(double &x, double &y, double angle) -{ - double cosA = cos(angle * (3.14159 / 180.0)); - double sinA = sin(angle * (3.14159 / 180.0)); - double xOut = x * cosA - y * sinA; - double yOut = x * sinA + y * cosA; - x = xOut; - y = yOut; +void RobotDrive::RotateVector(double &x, double &y, double angle) { + double cosA = cos(angle * (3.14159 / 180.0)); + double sinA = sin(angle * (3.14159 / 180.0)); + double xOut = x * cosA - y * sinA; + double yOut = x * sinA + y * cosA; + x = xOut; + y = yOut; } /* * Invert a motor direction. * This is used when a motor should run in the opposite direction as the drive - * code would normally run it. Motors that are direct drive would be inverted, the + * code would normally run it. Motors that are direct drive would be inverted, + * the * Drive code assumes that the motors are geared with one reversal. * @param motor The motor index to invert. * @param isInverted True if the motor should be inverted when operated. */ -void RobotDrive::SetInvertedMotor(MotorType motor, bool isInverted) -{ - if (motor < 0 || motor > 3) - { - wpi_setWPIError(InvalidMotorIndex); - return; - } - switch(motor){ - case kFrontLeftMotor: m_frontLeftMotor -> SetInverted(isInverted); break; - case kFrontRightMotor: m_frontRightMotor -> SetInverted(isInverted); break; - case kRearLeftMotor: m_rearLeftMotor -> SetInverted(isInverted); break; - case kRearRightMotor: m_rearRightMotor -> SetInverted(isInverted); break; - } +void RobotDrive::SetInvertedMotor(MotorType motor, bool isInverted) { + if (motor < 0 || motor > 3) { + wpi_setWPIError(InvalidMotorIndex); + return; + } + switch (motor) { + case kFrontLeftMotor: + m_frontLeftMotor->SetInverted(isInverted); + break; + case kFrontRightMotor: + m_frontRightMotor->SetInverted(isInverted); + break; + case kRearLeftMotor: + m_rearLeftMotor->SetInverted(isInverted); + break; + case kRearRightMotor: + m_rearRightMotor->SetInverted(isInverted); + break; + } } /** * Set the turning sensitivity. * * This only impacts the Drive() entry-point. - * @param sensitivity Effectively sets the turning sensitivity (or turn radius for a given value) + * @param sensitivity Effectively sets the turning sensitivity (or turn radius + * for a given value) */ -void RobotDrive::SetSensitivity(float sensitivity) -{ - m_sensitivity = sensitivity; +void RobotDrive::SetSensitivity(float sensitivity) { + m_sensitivity = sensitivity; } /** - * Configure the scaling factor for using RobotDrive with motor controllers in a mode other than PercentVbus. - * @param maxOutput Multiplied with the output percentage computed by the drive functions. + * Configure the scaling factor for using RobotDrive with motor controllers in a + * mode other than PercentVbus. + * @param maxOutput Multiplied with the output percentage computed by the drive + * functions. */ -void RobotDrive::SetMaxOutput(double maxOutput) -{ - m_maxOutput = maxOutput; -} +void RobotDrive::SetMaxOutput(double maxOutput) { m_maxOutput = maxOutput; } /** - * Set the number of the sync group for the motor controllers. If the motor controllers are {@link CANJaguar}s, - * then they will all be added to this sync group, causing them to update their values at the same time. + * Set the number of the sync group for the motor controllers. If the motor + * controllers are {@link CANJaguar}s, + * then they will all be added to this sync group, causing them to update their + * values at the same time. * * @param syncGroup the update group to add the motor controllers to */ void RobotDrive::SetCANJaguarSyncGroup(uint8_t syncGroup) { - m_syncGroup = syncGroup; + m_syncGroup = syncGroup; } -void RobotDrive::SetExpiration(float timeout) -{ - m_safetyHelper->SetExpiration(timeout); +void RobotDrive::SetExpiration(float timeout) { + m_safetyHelper->SetExpiration(timeout); } -float RobotDrive::GetExpiration() const -{ - return m_safetyHelper->GetExpiration(); +float RobotDrive::GetExpiration() const { + return m_safetyHelper->GetExpiration(); } -bool RobotDrive::IsAlive() const -{ - return m_safetyHelper->IsAlive(); +bool RobotDrive::IsAlive() const { return m_safetyHelper->IsAlive(); } + +bool RobotDrive::IsSafetyEnabled() const { + return m_safetyHelper->IsSafetyEnabled(); } -bool RobotDrive::IsSafetyEnabled() const -{ - return m_safetyHelper->IsSafetyEnabled(); +void RobotDrive::SetSafetyEnabled(bool enabled) { + m_safetyHelper->SetSafetyEnabled(enabled); } -void RobotDrive::SetSafetyEnabled(bool enabled) -{ - m_safetyHelper->SetSafetyEnabled(enabled); +void RobotDrive::GetDescription(char *desc) const { + sprintf(desc, "RobotDrive"); } -void RobotDrive::GetDescription(char *desc) const -{ - sprintf(desc, "RobotDrive"); -} - -void RobotDrive::StopMotor() -{ - if (m_frontLeftMotor != NULL) m_frontLeftMotor->Disable(); - if (m_frontRightMotor != NULL) m_frontRightMotor->Disable(); - if (m_rearLeftMotor != NULL) m_rearLeftMotor->Disable(); - if (m_rearRightMotor != NULL) m_rearRightMotor->Disable(); - m_safetyHelper->Feed(); +void RobotDrive::StopMotor() { + if (m_frontLeftMotor != NULL) m_frontLeftMotor->Disable(); + if (m_frontRightMotor != NULL) m_frontRightMotor->Disable(); + if (m_rearLeftMotor != NULL) m_rearLeftMotor->Disable(); + if (m_rearRightMotor != NULL) m_rearRightMotor->Disable(); + m_safetyHelper->Feed(); } diff --git a/wpilibc/wpilibC++Devices/src/SPI.cpp b/wpilibc/wpilibC++Devices/src/SPI.cpp index 4878dd9e3e..3d00828fd8 100644 --- a/wpilibc/wpilibC++Devices/src/SPI.cpp +++ b/wpilibc/wpilibC++Devices/src/SPI.cpp @@ -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,126 +12,115 @@ #include - /** * Constructor * * @param SPIport the physical SPI port */ -SPI::SPI(Port SPIport) -{ - m_port = SPIport; - int32_t status = 0; - spiInitialize(m_port, &status); - wpi_setErrorWithContext(status, getHALErrorMessage(status)); +SPI::SPI(Port SPIport) { + m_port = SPIport; + int32_t status = 0; + spiInitialize(m_port, &status); + wpi_setErrorWithContext(status, getHALErrorMessage(status)); - static int32_t instances = 0; - instances++; - HALReport(HALUsageReporting::kResourceType_SPI, instances); + static int32_t instances = 0; + instances++; + HALReport(HALUsageReporting::kResourceType_SPI, instances); } /** * Destructor. */ -SPI::~SPI() -{ - spiClose(m_port); -} +SPI::~SPI() { spiClose(m_port); } /** * Configure the rate of the generated clock signal. - * + * * The default value is 500,000Hz. * The maximum value is 4,000,000Hz. * * @param hz The clock rate in Hertz. */ -void SPI::SetClockRate(double hz) -{ - spiSetSpeed(m_port, hz); -} +void SPI::SetClockRate(double hz) { spiSetSpeed(m_port, hz); } /** * Configure the order that bits are sent and received on the wire * to be most significant bit first. */ -void SPI::SetMSBFirst() -{ - m_msbFirst = true; - spiSetOpts(m_port, (int) m_msbFirst, (int) m_sampleOnTrailing, (int) m_clk_idle_high); +void SPI::SetMSBFirst() { + m_msbFirst = true; + spiSetOpts(m_port, (int)m_msbFirst, (int)m_sampleOnTrailing, + (int)m_clk_idle_high); } /** * Configure the order that bits are sent and received on the wire * to be least significant bit first. */ -void SPI::SetLSBFirst() -{ - m_msbFirst = false; - spiSetOpts(m_port, (int) m_msbFirst, (int) m_sampleOnTrailing, (int) m_clk_idle_high); +void SPI::SetLSBFirst() { + m_msbFirst = false; + spiSetOpts(m_port, (int)m_msbFirst, (int)m_sampleOnTrailing, + (int)m_clk_idle_high); } /** * Configure that the data is stable on the falling edge and the data * changes on the rising edge. */ -void SPI::SetSampleDataOnFalling() -{ - m_sampleOnTrailing = true; - spiSetOpts(m_port, (int) m_msbFirst, (int) m_sampleOnTrailing, (int) m_clk_idle_high); +void SPI::SetSampleDataOnFalling() { + m_sampleOnTrailing = true; + spiSetOpts(m_port, (int)m_msbFirst, (int)m_sampleOnTrailing, + (int)m_clk_idle_high); } /** * Configure that the data is stable on the rising edge and the data * changes on the falling edge. */ -void SPI::SetSampleDataOnRising() -{ - m_sampleOnTrailing = false; - spiSetOpts(m_port, (int) m_msbFirst, (int) m_sampleOnTrailing, (int) m_clk_idle_high); +void SPI::SetSampleDataOnRising() { + m_sampleOnTrailing = false; + spiSetOpts(m_port, (int)m_msbFirst, (int)m_sampleOnTrailing, + (int)m_clk_idle_high); } /** * Configure the clock output line to be active low. * This is sometimes called clock polarity high or clock idle high. */ -void SPI::SetClockActiveLow() -{ - m_clk_idle_high = true; - spiSetOpts(m_port, (int) m_msbFirst, (int) m_sampleOnTrailing, (int) m_clk_idle_high); +void SPI::SetClockActiveLow() { + m_clk_idle_high = true; + spiSetOpts(m_port, (int)m_msbFirst, (int)m_sampleOnTrailing, + (int)m_clk_idle_high); } /** * Configure the clock output line to be active high. * This is sometimes called clock polarity low or clock idle low. */ -void SPI::SetClockActiveHigh() -{ - m_clk_idle_high = false; - spiSetOpts(m_port, (int) m_msbFirst, (int) m_sampleOnTrailing, (int) m_clk_idle_high); +void SPI::SetClockActiveHigh() { + m_clk_idle_high = false; + spiSetOpts(m_port, (int)m_msbFirst, (int)m_sampleOnTrailing, + (int)m_clk_idle_high); } /** * Configure the chip select line to be active high. */ -void SPI::SetChipSelectActiveHigh() -{ - int32_t status = 0; - spiSetChipSelectActiveHigh(m_port, &status); - wpi_setErrorWithContext(status, getHALErrorMessage(status)); +void SPI::SetChipSelectActiveHigh() { + int32_t status = 0; + spiSetChipSelectActiveHigh(m_port, &status); + wpi_setErrorWithContext(status, getHALErrorMessage(status)); } /** * Configure the chip select line to be active low. */ -void SPI::SetChipSelectActiveLow() -{ - int32_t status = 0; - spiSetChipSelectActiveLow(m_port, &status); - wpi_setErrorWithContext(status, getHALErrorMessage(status)); +void SPI::SetChipSelectActiveLow() { + int32_t status = 0; + spiSetChipSelectActiveLow(m_port, &status); + wpi_setErrorWithContext(status, getHALErrorMessage(status)); } - /** * Write data to the slave device. Blocks until there is space in the * output FIFO. @@ -138,11 +128,10 @@ void SPI::SetChipSelectActiveLow() * If not running in output only mode, also saves the data received * on the MISO input during the transfer into the receive FIFO. */ -int32_t SPI::Write(uint8_t* data, uint8_t size) -{ - int32_t retVal = 0; - retVal = spiWrite(m_port, data, size); - return retVal; +int32_t SPI::Write(uint8_t* data, uint8_t size) { + int32_t retVal = 0; + retVal = spiWrite(m_port, data, size); + return retVal; } /** @@ -154,21 +143,20 @@ int32_t SPI::Write(uint8_t* data, uint8_t size) * is false, errors. * * @param initiate If true, this function pushes "0" into the - * transmit buffer and initiates a transfer. - * If false, this function assumes that data is - * already in the receive FIFO from a previous write. + * transmit buffer and initiates a transfer. + * If false, this function assumes that data is + * already in the receive FIFO from a previous + * write. */ -int32_t SPI::Read(bool initiate, uint8_t* dataReceived, uint8_t size) -{ - int32_t retVal = 0; - if(initiate){ - uint8_t* dataToSend = new uint8_t[size]; - memset(dataToSend, 0, size); - retVal = spiTransaction(m_port, dataToSend, dataReceived, size); - } - else - retVal = spiRead(m_port, dataReceived, size); - return retVal; +int32_t SPI::Read(bool initiate, uint8_t* dataReceived, uint8_t size) { + int32_t retVal = 0; + if (initiate) { + uint8_t* dataToSend = new uint8_t[size]; + memset(dataToSend, 0, size); + retVal = spiTransaction(m_port, dataToSend, dataReceived, size); + } else + retVal = spiRead(m_port, dataReceived, size); + return retVal; } /** @@ -178,8 +166,9 @@ int32_t SPI::Read(bool initiate, uint8_t* dataReceived, uint8_t size) * @param dataReceived Buffer to receive data from the device * @param size The length of the transaction, in bytes */ -int32_t SPI::Transaction(uint8_t* dataToSend, uint8_t* dataReceived, uint8_t size){ - int32_t retVal = 0; - retVal = spiTransaction(m_port, dataToSend, dataReceived, size); - return retVal; +int32_t SPI::Transaction(uint8_t* dataToSend, uint8_t* dataReceived, + uint8_t size) { + int32_t retVal = 0; + retVal = spiTransaction(m_port, dataToSend, dataReceived, size); + return retVal; } diff --git a/wpilibc/wpilibC++Devices/src/SafePWM.cpp b/wpilibc/wpilibC++Devices/src/SafePWM.cpp index f61cf877d8..dd4d1aba07 100644 --- a/wpilibc/wpilibC++Devices/src/SafePWM.cpp +++ b/wpilibc/wpilibC++Devices/src/SafePWM.cpp @@ -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,96 +12,79 @@ /** * Initialize a SafePWM object by setting defaults */ -void SafePWM::InitSafePWM() -{ - m_safetyHelper = new MotorSafetyHelper(this); - m_safetyHelper->SetSafetyEnabled(false); +void SafePWM::InitSafePWM() { + m_safetyHelper = new MotorSafetyHelper(this); + m_safetyHelper->SetSafetyEnabled(false); } /** * Constructor for a SafePWM object taking a channel number. - * @param channel The PWM channel number 0-9 are on-board, 10-19 are on the MXP port + * @param channel The PWM channel number 0-9 are on-board, 10-19 are on the MXP + * port */ -SafePWM::SafePWM(uint32_t channel): PWM(channel) -{ - InitSafePWM(); -} +SafePWM::SafePWM(uint32_t channel) : PWM(channel) { InitSafePWM(); } -SafePWM::~SafePWM() -{ - delete m_safetyHelper; -} +SafePWM::~SafePWM() { delete m_safetyHelper; } /** * Set the expiration time for the PWM object * @param timeout The timeout (in seconds) for this motor object */ -void SafePWM::SetExpiration(float timeout) -{ - m_safetyHelper->SetExpiration(timeout); +void SafePWM::SetExpiration(float timeout) { + m_safetyHelper->SetExpiration(timeout); } /** * Return the expiration time for the PWM object. * @returns The expiration time value. */ -float SafePWM::GetExpiration() const -{ - return m_safetyHelper->GetExpiration(); -} +float SafePWM::GetExpiration() const { return m_safetyHelper->GetExpiration(); } /** * Check if the PWM object is currently alive or stopped due to a timeout. - * @returns a bool value that is true if the motor has NOT timed out and should still + * @returns a bool value that is true if the motor has NOT timed out and should + * still * be running. */ -bool SafePWM::IsAlive() const -{ - return m_safetyHelper->IsAlive(); -} +bool SafePWM::IsAlive() const { return m_safetyHelper->IsAlive(); } /** * Stop the motor associated with this PWM object. - * This is called by the MotorSafetyHelper object when it has a timeout for this PWM and needs to + * This is called by the MotorSafetyHelper object when it has a timeout for this + * PWM and needs to * stop it from running. */ -void SafePWM::StopMotor() -{ - SetRaw(kPwmDisabled); -} +void SafePWM::StopMotor() { SetRaw(kPwmDisabled); } /** * Enable/disable motor safety for this device * Turn on and off the motor safety option for this PWM object. * @param enabled True if motor safety is enforced for this object */ -void SafePWM::SetSafetyEnabled(bool enabled) -{ - m_safetyHelper->SetSafetyEnabled(enabled); +void SafePWM::SetSafetyEnabled(bool enabled) { + m_safetyHelper->SetSafetyEnabled(enabled); } /** * Check if motor safety is enabled for this object * @returns True if motor safety is enforced for this object */ -bool SafePWM::IsSafetyEnabled() const -{ - return m_safetyHelper->IsSafetyEnabled(); +bool SafePWM::IsSafetyEnabled() const { + return m_safetyHelper->IsSafetyEnabled(); } -void SafePWM::GetDescription(char *desc) const -{ - sprintf(desc, "PWM %d", GetChannel()); +void SafePWM::GetDescription(char *desc) const { + sprintf(desc, "PWM %d", GetChannel()); } /** * Feed the MotorSafety timer when setting the speed. - * This method is called by the subclass motor whenever it updates its speed, thereby reseting + * This method is called by the subclass motor whenever it updates its speed, + * thereby reseting * the timeout value. * @param speed Value to pass to the PWM class */ -void SafePWM::SetSpeed(float speed) -{ - PWM::SetSpeed(speed); - m_safetyHelper->Feed(); +void SafePWM::SetSpeed(float speed) { + PWM::SetSpeed(speed); + m_safetyHelper->Feed(); } diff --git a/wpilibc/wpilibC++Devices/src/SampleRobot.cpp b/wpilibc/wpilibC++Devices/src/SampleRobot.cpp index 3cb0602fed..407e60ef4a 100644 --- a/wpilibc/wpilibC++Devices/src/SampleRobot.cpp +++ b/wpilibc/wpilibC++Devices/src/SampleRobot.cpp @@ -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,137 +14,134 @@ #include "LiveWindow/LiveWindow.h" #include "networktables/NetworkTable.h" -SampleRobot::SampleRobot() - : m_robotMainOverridden (true) -{ -} +SampleRobot::SampleRobot() : m_robotMainOverridden(true) {} /** * Robot-wide initialization code should go here. - * - * Programmers should override this method for default Robot-wide initialization which will + * + * Programmers should override this method for default Robot-wide initialization + * which will * be called each time the robot enters the disabled state. */ -void SampleRobot::RobotInit() -{ - printf("Default %s() method... Override me!\n", __FUNCTION__); +void SampleRobot::RobotInit() { + printf("Default %s() method... Override me!\n", __FUNCTION__); } /** * Disabled should go here. - * Programmers should override this method to run code that should run while the field is + * Programmers should override this method to run code that should run while the + * field is * disabled. */ -void SampleRobot::Disabled() -{ - printf("Default %s() method... Override me!\n", __FUNCTION__); +void SampleRobot::Disabled() { + printf("Default %s() method... Override me!\n", __FUNCTION__); } /** * Autonomous should go here. - * Programmers should override this method to run code that should run while the field is - * in the autonomous period. This will be called once each time the robot enters the + * Programmers should override this method to run code that should run while the + * field is + * in the autonomous period. This will be called once each time the robot enters + * the * autonomous state. */ -void SampleRobot::Autonomous() -{ - printf("Default %s() method... Override me!\n", __FUNCTION__); +void SampleRobot::Autonomous() { + printf("Default %s() method... Override me!\n", __FUNCTION__); } /** * Operator control (tele-operated) code should go here. - * Programmers should override this method to run code that should run while the field is - * in the Operator Control (tele-operated) period. This is called once each time the robot + * Programmers should override this method to run code that should run while the + * field is + * in the Operator Control (tele-operated) period. This is called once each time + * the robot * enters the teleop state. */ -void SampleRobot::OperatorControl() -{ - printf("Default %s() method... Override me!\n", __FUNCTION__); +void SampleRobot::OperatorControl() { + printf("Default %s() method... Override me!\n", __FUNCTION__); } /** * Test program should go here. - * Programmers should override this method to run code that executes while the robot is + * Programmers should override this method to run code that executes while the + * robot is * in test mode. This will be called once whenever the robot enters test mode */ -void SampleRobot::Test() -{ - printf("Default %s() method... Override me!\n", __FUNCTION__); +void SampleRobot::Test() { + printf("Default %s() method... Override me!\n", __FUNCTION__); } /** * Robot main program for free-form programs. - * - * This should be overridden by user subclasses if the intent is to not use the Autonomous() and - * OperatorControl() methods. In that case, the program is responsible for sensing when to run + * + * This should be overridden by user subclasses if the intent is to not use the + * Autonomous() and + * OperatorControl() methods. In that case, the program is responsible for + * sensing when to run * the autonomous and operator control functions in their program. - * - * This method will be called immediately after the constructor is called. If it has not been - * overridden by a user subclass (i.e. the default version runs), then the Autonomous() and + * + * This method will be called immediately after the constructor is called. If it + * has not been + * overridden by a user subclass (i.e. the default version runs), then the + * Autonomous() and * OperatorControl() methods will be called. */ -void SampleRobot::RobotMain() -{ - m_robotMainOverridden = false; -} +void SampleRobot::RobotMain() { m_robotMainOverridden = false; } /** * Start a competition. - * This code needs to track the order of the field starting to ensure that everything happens - * in the right order. Repeatedly run the correct method, either Autonomous or OperatorControl - * or Test when the robot is enabled. After running the correct method, wait for some state to - * change, either the other mode starts or the robot is disabled. Then go back and wait for the + * This code needs to track the order of the field starting to ensure that + * everything happens + * in the right order. Repeatedly run the correct method, either Autonomous or + * OperatorControl + * or Test when the robot is enabled. After running the correct method, wait for + * some state to + * change, either the other mode starts or the robot is disabled. Then go back + * and wait for the * robot to be enabled again. */ -void SampleRobot::StartCompetition() -{ - LiveWindow *lw = LiveWindow::GetInstance(); +void SampleRobot::StartCompetition() { + LiveWindow *lw = LiveWindow::GetInstance(); - HALReport(HALUsageReporting::kResourceType_Framework, HALUsageReporting::kFramework_Simple); + HALReport(HALUsageReporting::kResourceType_Framework, + HALUsageReporting::kFramework_Simple); - SmartDashboard::init(); - NetworkTable::GetTable("LiveWindow")->GetSubTable("~STATUS~")->PutBoolean("LW Enabled", false); + SmartDashboard::init(); + NetworkTable::GetTable("LiveWindow") + ->GetSubTable("~STATUS~") + ->PutBoolean("LW Enabled", false); - RobotMain(); - - if (!m_robotMainOverridden) - { - // first and one-time initialization - lw->SetEnabled(false); - RobotInit(); + RobotMain(); - while (true) - { - if (IsDisabled()) - { - m_ds->InDisabled(true); - Disabled(); - m_ds->InDisabled(false); - while (IsDisabled()) m_ds->WaitForData(); - } - else if (IsAutonomous()) - { - m_ds->InAutonomous(true); - Autonomous(); - m_ds->InAutonomous(false); - while (IsAutonomous() && IsEnabled()) m_ds->WaitForData(); - } - else if (IsTest()) - { - lw->SetEnabled(true); - m_ds->InTest(true); - Test(); - m_ds->InTest(false); - while (IsTest() && IsEnabled()) m_ds->WaitForData(); - lw->SetEnabled(false); - } - else - { - m_ds->InOperatorControl(true); - OperatorControl(); - m_ds->InOperatorControl(false); - while (IsOperatorControl() && IsEnabled()) m_ds->WaitForData(); - } - } - } + if (!m_robotMainOverridden) { + // first and one-time initialization + lw->SetEnabled(false); + RobotInit(); + + while (true) { + if (IsDisabled()) { + m_ds->InDisabled(true); + Disabled(); + m_ds->InDisabled(false); + while (IsDisabled()) m_ds->WaitForData(); + } else if (IsAutonomous()) { + m_ds->InAutonomous(true); + Autonomous(); + m_ds->InAutonomous(false); + while (IsAutonomous() && IsEnabled()) m_ds->WaitForData(); + } else if (IsTest()) { + lw->SetEnabled(true); + m_ds->InTest(true); + Test(); + m_ds->InTest(false); + while (IsTest() && IsEnabled()) m_ds->WaitForData(); + lw->SetEnabled(false); + } else { + m_ds->InOperatorControl(true); + OperatorControl(); + m_ds->InOperatorControl(false); + while (IsOperatorControl() && IsEnabled()) m_ds->WaitForData(); + } + } + } } diff --git a/wpilibc/wpilibC++Devices/src/SensorBase.cpp b/wpilibc/wpilibC++Devices/src/SensorBase.cpp index d403b148b5..991cc950c9 100644 --- a/wpilibc/wpilibC++Devices/src/SensorBase.cpp +++ b/wpilibc/wpilibC++Devices/src/SensorBase.cpp @@ -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,7 +19,7 @@ const uint32_t SensorBase::kPwmChannels; const uint32_t SensorBase::kRelayChannels; const uint32_t SensorBase::kPDPChannels; const uint32_t SensorBase::kChassisSlots; -SensorBase *SensorBase::m_singletonList = NULL; +SensorBase* SensorBase::m_singletonList = NULL; static bool portsInitialized = false; void* SensorBase::m_digital_ports[kDigitalChannels]; @@ -28,41 +29,35 @@ void* SensorBase::m_pwm_ports[kPwmChannels]; /** * Creates an instance of the sensor base and gets an FPGA handle */ -SensorBase::SensorBase() -{ - if(!portsInitialized) { - for (uint32_t i = 0; i < kDigitalChannels; i++) - { - void* port = getPort(i); - int32_t status = 0; - m_digital_ports[i] = initializeDigitalPort(port, &status); - wpi_setErrorWithContext(status, getHALErrorMessage(status)); - } +SensorBase::SensorBase() { + if (!portsInitialized) { + for (uint32_t i = 0; i < kDigitalChannels; i++) { + void* port = getPort(i); + int32_t status = 0; + m_digital_ports[i] = initializeDigitalPort(port, &status); + wpi_setErrorWithContext(status, getHALErrorMessage(status)); + } - for (uint32_t i = 0; i < kRelayChannels; i++) - { - void* port = getPort(i); - int32_t status = 0; - m_relay_ports[i] = initializeDigitalPort(port, &status); - wpi_setErrorWithContext(status, getHALErrorMessage(status)); - } + for (uint32_t i = 0; i < kRelayChannels; i++) { + void* port = getPort(i); + int32_t status = 0; + m_relay_ports[i] = initializeDigitalPort(port, &status); + wpi_setErrorWithContext(status, getHALErrorMessage(status)); + } - for (uint32_t i = 0; i < kPwmChannels; i++) - { - void* port = getPort(i); - int32_t status = 0; - m_pwm_ports[i] = initializeDigitalPort(port, &status); - wpi_setErrorWithContext(status, getHALErrorMessage(status)); - } - } + for (uint32_t i = 0; i < kPwmChannels; i++) { + void* port = getPort(i); + int32_t status = 0; + m_pwm_ports[i] = initializeDigitalPort(port, &status); + wpi_setErrorWithContext(status, getHALErrorMessage(status)); + } + } } /** * Frees the resources for a SensorBase. */ -SensorBase::~SensorBase() -{ -} +SensorBase::~SensorBase() {} /** * Add sensor to the singleton list. @@ -71,12 +66,12 @@ SensorBase::~SensorBase() * that is they aren't allocated directly with new, but instead are allocated * by the static GetInstance method. As a result, they are never deleted when * the program exits. Consequently these sensors may still be holding onto - * resources and need to have their destructors called at the end of the program. + * resources and need to have their destructors called at the end of the + * program. */ -void SensorBase::AddToSingletonList() -{ - m_nextSingleton = m_singletonList; - m_singletonList = this; +void SensorBase::AddToSingletonList() { + m_nextSingleton = m_singletonList; + m_singletonList = this; } /** @@ -84,15 +79,13 @@ void SensorBase::AddToSingletonList() * All the classes that were allocated as singletons need to be deleted so * their resources can be freed. */ -void SensorBase::DeleteSingletons() -{ - for (SensorBase *next = m_singletonList; next != NULL;) - { - SensorBase *tmp = next; - next = next->m_nextSingleton; - delete tmp; - } - m_singletonList = NULL; +void SensorBase::DeleteSingletons() { + for (SensorBase* next = m_singletonList; next != NULL;) { + SensorBase* tmp = next; + next = next->m_nextSingleton; + delete tmp; + } + m_singletonList = NULL; } /** @@ -100,81 +93,74 @@ void SensorBase::DeleteSingletons() * * @return Solenoid module is valid and present */ -bool SensorBase::CheckSolenoidModule(uint8_t moduleNumber) -{ - if (moduleNumber < 64) - return true; - return false; +bool SensorBase::CheckSolenoidModule(uint8_t moduleNumber) { + if (moduleNumber < 64) return true; + return false; } /** * Check that the digital channel number is valid. - * Verify that the channel number is one of the legal channel numbers. Channel numbers are + * Verify that the channel number is one of the legal channel numbers. Channel + * numbers are * 1-based. * * @return Digital channel is valid */ -bool SensorBase::CheckDigitalChannel(uint32_t channel) -{ - if (channel < kDigitalChannels) - return true; - return false; +bool SensorBase::CheckDigitalChannel(uint32_t channel) { + if (channel < kDigitalChannels) return true; + return false; } /** * Check that the digital channel number is valid. - * Verify that the channel number is one of the legal channel numbers. Channel numbers are + * Verify that the channel number is one of the legal channel numbers. Channel + * numbers are * 1-based. * * @return Relay channel is valid */ -bool SensorBase::CheckRelayChannel(uint32_t channel) -{ - if (channel < kRelayChannels) - return true; - return false; +bool SensorBase::CheckRelayChannel(uint32_t channel) { + if (channel < kRelayChannels) return true; + return false; } /** * Check that the digital channel number is valid. - * Verify that the channel number is one of the legal channel numbers. Channel numbers are + * Verify that the channel number is one of the legal channel numbers. Channel + * numbers are * 1-based. * * @return PWM channel is valid */ -bool SensorBase::CheckPWMChannel(uint32_t channel) -{ - if (channel < kPwmChannels) - return true; - return false; +bool SensorBase::CheckPWMChannel(uint32_t channel) { + if (channel < kPwmChannels) return true; + return false; } /** * Check that the analog input number is value. - * Verify that the analog input number is one of the legal channel numbers. Channel numbers + * Verify that the analog input number is one of the legal channel numbers. + * Channel numbers * are 0-based. * * @return Analog channel is valid */ -bool SensorBase::CheckAnalogInput(uint32_t channel) -{ - if (channel < kAnalogInputs) - return true; - return false; +bool SensorBase::CheckAnalogInput(uint32_t channel) { + if (channel < kAnalogInputs) return true; + return false; } /** * Check that the analog output number is valid. - * Verify that the analog output number is one of the legal channel numbers. Channel numbers + * Verify that the analog output number is one of the legal channel numbers. + * Channel numbers * are 0-based. * * @return Analog channel is valid */ -bool SensorBase::CheckAnalogOutput(uint32_t channel) -{ - if (channel < kAnalogOutputs) - return true; - return false; +bool SensorBase::CheckAnalogOutput(uint32_t channel) { + if (channel < kAnalogOutputs) return true; + return false; } /** @@ -182,11 +168,9 @@ bool SensorBase::CheckAnalogOutput(uint32_t channel) * * @return Solenoid channel is valid */ -bool SensorBase::CheckSolenoidChannel(uint32_t channel) -{ - if (channel < kSolenoidChannels) - return true; - return false; +bool SensorBase::CheckSolenoidChannel(uint32_t channel) { + if (channel < kSolenoidChannels) return true; + return false; } /** @@ -194,9 +178,7 @@ bool SensorBase::CheckSolenoidChannel(uint32_t channel) * * @return PDP channel is valid */ -bool SensorBase::CheckPDPChannel(uint32_t channel) -{ - if (channel < kPDPChannels) - return true; - return false; +bool SensorBase::CheckPDPChannel(uint32_t channel) { + if (channel < kPDPChannels) return true; + return false; } diff --git a/wpilibc/wpilibC++Devices/src/SerialPort.cpp b/wpilibc/wpilibC++Devices/src/SerialPort.cpp index ff6c156055..80b0089eee 100644 --- a/wpilibc/wpilibC++Devices/src/SerialPort.cpp +++ b/wpilibc/wpilibC++Devices/src/SerialPort.cpp @@ -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,59 +11,60 @@ #include "HAL/HAL.hpp" #include -//static ViStatus _VI_FUNCH ioCompleteHandler (ViSession vi, ViEventType eventType, ViEvent event, ViAddr userHandle); +// static ViStatus _VI_FUNCH ioCompleteHandler (ViSession vi, ViEventType +// eventType, ViEvent event, ViAddr userHandle); /** * Create an instance of a Serial Port class. * * @param baudRate The baud rate to configure the serial port. * @param port The physical port to use - * @param dataBits The number of data bits per transfer. Valid values are between 5 and 8 bits. + * @param dataBits The number of data bits per transfer. Valid values are + * between 5 and 8 bits. * @param parity Select the type of parity checking to use. - * @param stopBits The number of stop bits to use as defined by the enum StopBits. + * @param stopBits The number of stop bits to use as defined by the enum + * StopBits. */ -SerialPort::SerialPort(uint32_t baudRate, Port port, uint8_t dataBits, SerialPort::Parity parity, SerialPort::StopBits stopBits) - : m_resourceManagerHandle (0) - , m_portHandle (0) - , m_consoleModeEnabled (false) -{ - int32_t status = 0; - - m_port = port; - - serialInitializePort(port, &status); - wpi_setErrorWithContext(status, getHALErrorMessage(status)); - serialSetBaudRate(port, baudRate, &status); - wpi_setErrorWithContext(status, getHALErrorMessage(status)); - serialSetDataBits(port, dataBits, &status); - wpi_setErrorWithContext(status, getHALErrorMessage(status)); - serialSetParity(port, parity, &status); - wpi_setErrorWithContext(status, getHALErrorMessage(status)); - serialSetStopBits(port, stopBits, &status); - wpi_setErrorWithContext(status, getHALErrorMessage(status)); +SerialPort::SerialPort(uint32_t baudRate, Port port, uint8_t dataBits, + SerialPort::Parity parity, SerialPort::StopBits stopBits) + : m_resourceManagerHandle(0), m_portHandle(0), m_consoleModeEnabled(false) { + int32_t status = 0; - // Set the default timeout to 5 seconds. - SetTimeout(5.0f); + m_port = port; - // Don't wait until the buffer is full to transmit. - SetWriteBufferMode(kFlushOnAccess); + serialInitializePort(port, &status); + wpi_setErrorWithContext(status, getHALErrorMessage(status)); + serialSetBaudRate(port, baudRate, &status); + wpi_setErrorWithContext(status, getHALErrorMessage(status)); + serialSetDataBits(port, dataBits, &status); + wpi_setErrorWithContext(status, getHALErrorMessage(status)); + serialSetParity(port, parity, &status); + wpi_setErrorWithContext(status, getHALErrorMessage(status)); + serialSetStopBits(port, stopBits, &status); + wpi_setErrorWithContext(status, getHALErrorMessage(status)); - EnableTermination(); + // Set the default timeout to 5 seconds. + SetTimeout(5.0f); - //viInstallHandler(m_portHandle, VI_EVENT_IO_COMPLETION, ioCompleteHandler, this); - //viEnableEvent(m_portHandle, VI_EVENT_IO_COMPLETION, VI_HNDLR, VI_NULL); - - HALReport(HALUsageReporting::kResourceType_SerialPort, 0); + // Don't wait until the buffer is full to transmit. + SetWriteBufferMode(kFlushOnAccess); + + EnableTermination(); + + // viInstallHandler(m_portHandle, VI_EVENT_IO_COMPLETION, ioCompleteHandler, + // this); + // viEnableEvent(m_portHandle, VI_EVENT_IO_COMPLETION, VI_HNDLR, VI_NULL); + + HALReport(HALUsageReporting::kResourceType_SerialPort, 0); } /** * Destructor. */ -SerialPort::~SerialPort() -{ - int32_t status = 0; - serialClose(m_port, &status); - wpi_setErrorWithContext(status, getHALErrorMessage(status)); +SerialPort::~SerialPort() { + int32_t status = 0; + serialClose(m_port, &status); + wpi_setErrorWithContext(status, getHALErrorMessage(status)); } /** @@ -70,11 +72,10 @@ SerialPort::~SerialPort() * * By default, flow control is disabled. */ -void SerialPort::SetFlowControl(SerialPort::FlowControl flowControl) -{ - int32_t status = 0; - serialSetFlowControl(m_port, flowControl, &status); - wpi_setErrorWithContext(status, getHALErrorMessage(status)); +void SerialPort::SetFlowControl(SerialPort::FlowControl flowControl) { + int32_t status = 0; + serialSetFlowControl(m_port, flowControl, &status); + wpi_setErrorWithContext(status, getHALErrorMessage(status)); } /** @@ -86,21 +87,19 @@ void SerialPort::SetFlowControl(SerialPort::FlowControl flowControl) * * @param terminator The character to use for termination. */ -void SerialPort::EnableTermination(char terminator) -{ - int32_t status = 0; - serialEnableTermination(m_port, terminator, &status); - wpi_setErrorWithContext(status, getHALErrorMessage(status)); +void SerialPort::EnableTermination(char terminator) { + int32_t status = 0; + serialEnableTermination(m_port, terminator, &status); + wpi_setErrorWithContext(status, getHALErrorMessage(status)); } /** * Disable termination behavior. */ -void SerialPort::DisableTermination() -{ - int32_t status = 0; - serialDisableTermination(m_port, &status); - wpi_setErrorWithContext(status, getHALErrorMessage(status)); +void SerialPort::DisableTermination() { + int32_t status = 0; + serialDisableTermination(m_port, &status); + wpi_setErrorWithContext(status, getHALErrorMessage(status)); } /** @@ -108,12 +107,11 @@ void SerialPort::DisableTermination() * * @return The number of bytes available to read */ -int32_t SerialPort::GetBytesReceived() -{ - int32_t status = 0; - int32_t retVal = serialGetBytesReceived(m_port, &status); - wpi_setErrorWithContext(status, getHALErrorMessage(status)); - return retVal; +int32_t SerialPort::GetBytesReceived() { + int32_t status = 0; + int32_t retVal = serialGetBytesReceived(m_port, &status); + wpi_setErrorWithContext(status, getHALErrorMessage(status)); + return retVal; } /** @@ -123,12 +121,11 @@ int32_t SerialPort::GetBytesReceived() * @param count The maximum number of bytes to read. * @return The number of bytes actually read into the buffer. */ -uint32_t SerialPort::Read(char *buffer, int32_t count) -{ - int32_t status = 0; - int32_t retVal = serialRead(m_port, buffer, count, &status); - wpi_setErrorWithContext(status, getHALErrorMessage(status)); - return retVal; +uint32_t SerialPort::Read(char *buffer, int32_t count) { + int32_t status = 0; + int32_t retVal = serialRead(m_port, buffer, count, &status); + wpi_setErrorWithContext(status, getHALErrorMessage(status)); + return retVal; } /** @@ -138,12 +135,11 @@ uint32_t SerialPort::Read(char *buffer, int32_t count) * @param count The maximum number of bytes to write. * @return The number of bytes actually written into the port. */ -uint32_t SerialPort::Write(const char *buffer, int32_t count) -{ - int32_t status = 0; - int32_t retVal = serialWrite(m_port, buffer, count, &status); - wpi_setErrorWithContext(status, getHALErrorMessage(status)); - return retVal; +uint32_t SerialPort::Write(const char *buffer, int32_t count) { + int32_t status = 0; + int32_t retVal = serialWrite(m_port, buffer, count, &status); + wpi_setErrorWithContext(status, getHALErrorMessage(status)); + return retVal; } /** @@ -154,11 +150,10 @@ uint32_t SerialPort::Write(const char *buffer, int32_t count) * * @param timeout The number of seconds to to wait for I/O. */ -void SerialPort::SetTimeout(float timeout) -{ - int32_t status = 0; - serialSetTimeout(m_port, timeout, &status); - wpi_setErrorWithContext(status, getHALErrorMessage(status)); +void SerialPort::SetTimeout(float timeout) { + int32_t status = 0; + serialSetTimeout(m_port, timeout, &status); + wpi_setErrorWithContext(status, getHALErrorMessage(status)); } /** @@ -173,11 +168,10 @@ void SerialPort::SetTimeout(float timeout) * * @param size The read buffer size. */ -void SerialPort::SetReadBufferSize(uint32_t size) -{ - int32_t status = 0; - serialSetReadBufferSize(m_port, size, &status); - wpi_setErrorWithContext(status, getHALErrorMessage(status)); +void SerialPort::SetReadBufferSize(uint32_t size) { + int32_t status = 0; + serialSetReadBufferSize(m_port, size, &status); + wpi_setErrorWithContext(status, getHALErrorMessage(status)); } /** @@ -188,11 +182,10 @@ void SerialPort::SetReadBufferSize(uint32_t size) * * @param size The write buffer size. */ -void SerialPort::SetWriteBufferSize(uint32_t size) -{ - int32_t status = 0; - serialSetWriteBufferSize(m_port, size, &status); - wpi_setErrorWithContext(status, getHALErrorMessage(status)); +void SerialPort::SetWriteBufferSize(uint32_t size) { + int32_t status = 0; + serialSetWriteBufferSize(m_port, size, &status); + wpi_setErrorWithContext(status, getHALErrorMessage(status)); } /** @@ -206,11 +199,10 @@ void SerialPort::SetWriteBufferSize(uint32_t size) * * @param mode The write buffer mode. */ -void SerialPort::SetWriteBufferMode(SerialPort::WriteBufferMode mode) -{ - int32_t status = 0; - serialSetWriteMode(m_port, mode, &status); - wpi_setErrorWithContext(status, getHALErrorMessage(status)); +void SerialPort::SetWriteBufferMode(SerialPort::WriteBufferMode mode) { + int32_t status = 0; + serialSetWriteMode(m_port, mode, &status); + wpi_setErrorWithContext(status, getHALErrorMessage(status)); } /** @@ -219,11 +211,10 @@ void SerialPort::SetWriteBufferMode(SerialPort::WriteBufferMode mode) * This is used when SetWriteBufferMode() is set to kFlushWhenFull to force a * flush before the buffer is full. */ -void SerialPort::Flush() -{ - int32_t status = 0; - serialFlush(m_port, &status); - wpi_setErrorWithContext(status, getHALErrorMessage(status)); +void SerialPort::Flush() { + int32_t status = 0; + serialFlush(m_port, &status); + wpi_setErrorWithContext(status, getHALErrorMessage(status)); } /** @@ -231,9 +222,8 @@ void SerialPort::Flush() * * Empty the transmit and receive buffers in the device and formatted I/O. */ -void SerialPort::Reset() -{ - int32_t status = 0; - serialClear(m_port, &status); - wpi_setErrorWithContext(status, getHALErrorMessage(status)); +void SerialPort::Reset() { + int32_t status = 0; + serialClear(m_port, &status); + wpi_setErrorWithContext(status, getHALErrorMessage(status)); } \ No newline at end of file diff --git a/wpilibc/wpilibC++Devices/src/Servo.cpp b/wpilibc/wpilibC++Devices/src/Servo.cpp index 9a78f50c1e..0ab2c2179d 100644 --- a/wpilibc/wpilibC++Devices/src/Servo.cpp +++ b/wpilibc/wpilibC++Devices/src/Servo.cpp @@ -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,132 +19,121 @@ constexpr float Servo::kDefaultMinServoPWM; /** * Common initialization code called by all constructors. * - * InitServo() assigns defaults for the period multiplier for the servo PWM control signal, as + * InitServo() assigns defaults for the period multiplier for the servo PWM + * control signal, as * well as the minimum and maximum PWM values supported by the servo. */ -void Servo::InitServo() -{ - m_table = NULL; - SetBounds(kDefaultMaxServoPWM, 0.0, 0.0, 0.0, kDefaultMinServoPWM); - SetPeriodMultiplier(kPeriodMultiplier_4X); +void Servo::InitServo() { + m_table = NULL; + SetBounds(kDefaultMaxServoPWM, 0.0, 0.0, 0.0, kDefaultMinServoPWM); + SetPeriodMultiplier(kPeriodMultiplier_4X); - LiveWindow::GetInstance()->AddActuator("Servo", GetChannel(), this); - HALReport(HALUsageReporting::kResourceType_Servo, GetChannel()); + LiveWindow::GetInstance()->AddActuator("Servo", GetChannel(), this); + HALReport(HALUsageReporting::kResourceType_Servo, GetChannel()); } /** - * @param channel The PWM channel to which the servo is attached. 0-9 are on-board, 10-19 are on the MXP port + * @param channel The PWM channel to which the servo is attached. 0-9 are + * on-board, 10-19 are on the MXP port */ -Servo::Servo(uint32_t channel) : SafePWM(channel) -{ - InitServo(); -// printf("Done initializing servo %d\n", channel); +Servo::Servo(uint32_t channel) : SafePWM(channel) { + InitServo(); + // printf("Done initializing servo %d\n", channel); } -Servo::~Servo() -{ -} +Servo::~Servo() {} /** * Set the servo position. * - * Servo values range from 0.0 to 1.0 corresponding to the range of full left to full right. + * Servo values range from 0.0 to 1.0 corresponding to the range of full left to + * full right. * * @param value Position from 0.0 to 1.0. */ -void Servo::Set(float value) -{ - SetPosition(value); -} +void Servo::Set(float value) { SetPosition(value); } /** * Set the servo to offline. * * Set the servo raw value to 0 (undriven) */ -void Servo::SetOffline() { - SetRaw(0); -} +void Servo::SetOffline() { SetRaw(0); } /** * Get the servo position. * - * Servo values range from 0.0 to 1.0 corresponding to the range of full left to full right. + * Servo values range from 0.0 to 1.0 corresponding to the range of full left to + * full right. * * @return Position from 0.0 to 1.0. */ -float Servo::Get() const -{ - return GetPosition(); -} +float Servo::Get() const { return GetPosition(); } /** * Set the servo angle. * - * Assume that the servo angle is linear with respect to the PWM value (big assumption, need to test). + * Assume that the servo angle is linear with respect to the PWM value (big + * assumption, need to test). * - * Servo angles that are out of the supported range of the servo simply "saturate" in that direction - * In other words, if the servo has a range of (X degrees to Y degrees) than angles of less than X - * result in an angle of X being set and angles of more than Y degrees result in an angle of Y being set. + * Servo angles that are out of the supported range of the servo simply + * "saturate" in that direction + * In other words, if the servo has a range of (X degrees to Y degrees) than + * angles of less than X + * result in an angle of X being set and angles of more than Y degrees result in + * an angle of Y being set. * * @param degrees The angle in degrees to set the servo. */ -void Servo::SetAngle(float degrees) -{ - if (degrees < kMinServoAngle) - { - degrees = kMinServoAngle; - } - else if (degrees > kMaxServoAngle) - { - degrees = kMaxServoAngle; - } +void Servo::SetAngle(float degrees) { + if (degrees < kMinServoAngle) { + degrees = kMinServoAngle; + } else if (degrees > kMaxServoAngle) { + degrees = kMaxServoAngle; + } - SetPosition(((float) (degrees - kMinServoAngle)) / GetServoAngleRange()); + SetPosition(((float)(degrees - kMinServoAngle)) / GetServoAngleRange()); } /** * Get the servo angle. * - * Assume that the servo angle is linear with respect to the PWM value (big assumption, need to test). + * Assume that the servo angle is linear with respect to the PWM value (big + * assumption, need to test). * @return The angle in degrees to which the servo is set. */ -float Servo::GetAngle() const -{ - return (float)GetPosition() * GetServoAngleRange() + kMinServoAngle; +float Servo::GetAngle() const { + return (float)GetPosition() * GetServoAngleRange() + kMinServoAngle; } -void Servo::ValueChanged(ITable* source, const std::string& key, EntryValue value, bool isNew) { - Set(value.f); +void Servo::ValueChanged(ITable* source, const std::string& key, + EntryValue value, bool isNew) { + Set(value.f); } void Servo::UpdateTable() { - if (m_table != NULL) { - m_table->PutNumber("Value", Get()); - } + if (m_table != NULL) { + m_table->PutNumber("Value", Get()); + } } void Servo::StartLiveWindowMode() { - if (m_table != NULL) { - m_table->AddTableListener("Value", this, true); - } + if (m_table != NULL) { + m_table->AddTableListener("Value", this, true); + } } void Servo::StopLiveWindowMode() { - if (m_table != NULL) { - m_table->RemoveTableListener(this); - } + if (m_table != NULL) { + m_table->RemoveTableListener(this); + } } -std::string Servo::GetSmartDashboardType() const { - return "Servo"; +std::string Servo::GetSmartDashboardType() const { return "Servo"; } + +void Servo::InitTable(ITable* subTable) { + m_table = subTable; + UpdateTable(); } -void Servo::InitTable(ITable *subTable) { - m_table = subTable; - UpdateTable(); -} - -ITable * Servo::GetTable() const { - return m_table; -} +ITable* Servo::GetTable() const { return m_table; } diff --git a/wpilibc/wpilibC++Devices/src/Solenoid.cpp b/wpilibc/wpilibC++Devices/src/Solenoid.cpp index 14f8edaf72..ab84754390 100644 --- a/wpilibc/wpilibC++Devices/src/Solenoid.cpp +++ b/wpilibc/wpilibC++Devices/src/Solenoid.cpp @@ -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,33 +13,32 @@ /** * Common function to implement constructor behavior. */ -void Solenoid::InitSolenoid() -{ - m_table = NULL; - char buf[64]; - if (!CheckSolenoidModule(m_moduleNumber)) - { - snprintf(buf, 64, "Solenoid Module %d", m_moduleNumber); - wpi_setWPIErrorWithContext(ModuleIndexOutOfRange, buf); - return; - } - if (!CheckSolenoidChannel(m_channel)) - { - snprintf(buf, 64, "Solenoid Channel %d", m_channel); - wpi_setWPIErrorWithContext(ChannelIndexOutOfRange, buf); - return; - } - Resource::CreateResourceObject(&m_allocated, kSolenoidChannels * 63); +void Solenoid::InitSolenoid() { + m_table = NULL; + char buf[64]; + if (!CheckSolenoidModule(m_moduleNumber)) { + snprintf(buf, 64, "Solenoid Module %d", m_moduleNumber); + wpi_setWPIErrorWithContext(ModuleIndexOutOfRange, buf); + return; + } + if (!CheckSolenoidChannel(m_channel)) { + snprintf(buf, 64, "Solenoid Channel %d", m_channel); + wpi_setWPIErrorWithContext(ChannelIndexOutOfRange, buf); + return; + } + Resource::CreateResourceObject(&m_allocated, kSolenoidChannels * 63); - snprintf(buf, 64, "Solenoid %d (Module: %d)", m_channel, m_moduleNumber); - if (m_allocated->Allocate(m_moduleNumber * kSolenoidChannels + m_channel, buf) == ~0ul) - { - CloneError(m_allocated); - return; - } + snprintf(buf, 64, "Solenoid %d (Module: %d)", m_channel, m_moduleNumber); + if (m_allocated->Allocate(m_moduleNumber * kSolenoidChannels + m_channel, + buf) == ~0ul) { + CloneError(m_allocated); + return; + } - LiveWindow::GetInstance()->AddActuator("Solenoid", m_moduleNumber, m_channel, this); - HALReport(HALUsageReporting::kResourceType_Solenoid, m_channel, m_moduleNumber); + LiveWindow::GetInstance()->AddActuator("Solenoid", m_moduleNumber, m_channel, + this); + HALReport(HALUsageReporting::kResourceType_Solenoid, m_channel, + m_moduleNumber); } /** @@ -47,10 +47,8 @@ void Solenoid::InitSolenoid() * @param channel The channel on the PCM to control (0..7). */ Solenoid::Solenoid(uint32_t channel) - : SolenoidBase (GetDefaultSolenoidModule()) - , m_channel (channel) -{ - InitSolenoid(); + : SolenoidBase(GetDefaultSolenoidModule()), m_channel(channel) { + InitSolenoid(); } /** @@ -60,21 +58,17 @@ Solenoid::Solenoid(uint32_t channel) * @param channel The channel on the PCM to control (0..7). */ Solenoid::Solenoid(uint8_t moduleNumber, uint32_t channel) - : SolenoidBase (moduleNumber) - , m_channel (channel) -{ - InitSolenoid(); + : SolenoidBase(moduleNumber), m_channel(channel) { + InitSolenoid(); } /** * Destructor. */ -Solenoid::~Solenoid() -{ - if (CheckSolenoidModule(m_moduleNumber)) - { - m_allocated->Free(m_moduleNumber * kSolenoidChannels + m_channel); - } +Solenoid::~Solenoid() { + if (CheckSolenoidModule(m_moduleNumber)) { + m_allocated->Free(m_moduleNumber * kSolenoidChannels + m_channel); + } } /** @@ -82,13 +76,12 @@ Solenoid::~Solenoid() * * @param on Turn the solenoid output off or on. */ -void Solenoid::Set(bool on) -{ - if (StatusIsFatal()) return; - uint8_t value = on ? 0xFF : 0x00; - uint8_t mask = 1 << m_channel; +void Solenoid::Set(bool on) { + if (StatusIsFatal()) return; + uint8_t value = on ? 0xFF : 0x00; + uint8_t mask = 1 << m_channel; - SolenoidBase::Set(value, mask, m_moduleNumber); + SolenoidBase::Set(value, mask, m_moduleNumber); } /** @@ -96,59 +89,54 @@ void Solenoid::Set(bool on) * * @return The current value of the solenoid. */ -bool Solenoid::Get() const -{ - if (StatusIsFatal()) return false; - uint8_t value = GetAll(m_moduleNumber) & ( 1 << m_channel); - return (value != 0); +bool Solenoid::Get() const { + if (StatusIsFatal()) return false; + uint8_t value = GetAll(m_moduleNumber) & (1 << m_channel); + return (value != 0); } /** * Check if solenoid is blacklisted. - * If a solenoid is shorted, it is added to the blacklist and - * disabled until power cycle, or until faults are cleared. - * @see ClearAllPCMStickyFaults() + * If a solenoid is shorted, it is added to the blacklist and + * disabled until power cycle, or until faults are cleared. + * @see ClearAllPCMStickyFaults() * * @return If solenoid is disabled due to short. */ -bool Solenoid::IsBlackListed() const -{ - int value = GetPCMSolenoidBlackList(m_moduleNumber) & ( 1 << m_channel); - return (value != 0); +bool Solenoid::IsBlackListed() const { + int value = GetPCMSolenoidBlackList(m_moduleNumber) & (1 << m_channel); + return (value != 0); } -void Solenoid::ValueChanged(ITable* source, const std::string& key, EntryValue value, bool isNew) { - Set(value.b); +void Solenoid::ValueChanged(ITable* source, const std::string& key, + EntryValue value, bool isNew) { + Set(value.b); } void Solenoid::UpdateTable() { - if (m_table != NULL) { - m_table->PutBoolean("Value", Get()); - } + if (m_table != NULL) { + m_table->PutBoolean("Value", Get()); + } } void Solenoid::StartLiveWindowMode() { - Set(false); - if (m_table != NULL) { - m_table->AddTableListener("Value", this, true); - } + Set(false); + if (m_table != NULL) { + m_table->AddTableListener("Value", this, true); + } } void Solenoid::StopLiveWindowMode() { - Set(false); - if (m_table != NULL) { - m_table->RemoveTableListener(this); - } + Set(false); + if (m_table != NULL) { + m_table->RemoveTableListener(this); + } } -std::string Solenoid::GetSmartDashboardType() const { - return "Solenoid"; +std::string Solenoid::GetSmartDashboardType() const { return "Solenoid"; } + +void Solenoid::InitTable(ITable* subTable) { + m_table = subTable; + UpdateTable(); } -void Solenoid::InitTable(ITable *subTable) { - m_table = subTable; - UpdateTable(); -} - -ITable * Solenoid::GetTable() const { - return m_table; -} +ITable* Solenoid::GetTable() const { return m_table; } diff --git a/wpilibc/wpilibC++Devices/src/SolenoidBase.cpp b/wpilibc/wpilibC++Devices/src/SolenoidBase.cpp index bd21b752c3..8d8dfc3b7a 100644 --- a/wpilibc/wpilibC++Devices/src/SolenoidBase.cpp +++ b/wpilibc/wpilibC++Devices/src/SolenoidBase.cpp @@ -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,110 +8,104 @@ #include "SolenoidBase.h" // Needs to be global since the protected resource spans all Solenoid objects. -Resource *SolenoidBase::m_allocated = NULL; +Resource* SolenoidBase::m_allocated = NULL; void* SolenoidBase::m_ports[m_maxModules][m_maxPorts]; /** * Constructor - * + * * @param moduleNumber The CAN PCM ID. */ SolenoidBase::SolenoidBase(uint8_t moduleNumber) - : m_moduleNumber (moduleNumber) -{ - for (uint32_t i = 0; i < kSolenoidChannels; i++) - { - void* port = getPortWithModule(moduleNumber, i); - int32_t status = 0; - SolenoidBase::m_ports[moduleNumber][i] = initializeSolenoidPort(port, &status); - wpi_setErrorWithContext(status, getHALErrorMessage(status)); - } + : m_moduleNumber(moduleNumber) { + for (uint32_t i = 0; i < kSolenoidChannels; i++) { + void* port = getPortWithModule(moduleNumber, i); + int32_t status = 0; + SolenoidBase::m_ports[moduleNumber][i] = + initializeSolenoidPort(port, &status); + wpi_setErrorWithContext(status, getHALErrorMessage(status)); + } } /** * Destructor. */ -SolenoidBase::~SolenoidBase() -{ -} +SolenoidBase::~SolenoidBase() {} /** * Set the value of a solenoid. - * + * * @param value The value you want to set on the module. * @param mask The channels you want to be affected. */ -void SolenoidBase::Set(uint8_t value, uint8_t mask, int module) -{ - int32_t status = 0; - for (int i = 0; i < m_maxPorts; i++) { - uint8_t local_mask = 1 << i; - if (mask & local_mask) - setSolenoid(m_ports[module][i], value & local_mask, &status); - } - wpi_setErrorWithContext(status, getHALErrorMessage(status)); +void SolenoidBase::Set(uint8_t value, uint8_t mask, int module) { + int32_t status = 0; + for (int i = 0; i < m_maxPorts; i++) { + uint8_t local_mask = 1 << i; + if (mask & local_mask) + setSolenoid(m_ports[module][i], value & local_mask, &status); + } + wpi_setErrorWithContext(status, getHALErrorMessage(status)); } /** * Read all 8 solenoids as a single byte - * + * * @return The current value of all 8 solenoids on the module. */ -uint8_t SolenoidBase::GetAll(int module) const -{ - uint8_t value = 0; - int32_t status = 0; - for (int i = 0; i < m_maxPorts; i++) { - value |= getSolenoid(m_ports[module][i], &status) << i; - } - return value; +uint8_t SolenoidBase::GetAll(int module) const { + uint8_t value = 0; + int32_t status = 0; + for (int i = 0; i < m_maxPorts; i++) { + value |= getSolenoid(m_ports[module][i], &status) << i; + } + return value; } /** * Reads complete solenoid blacklist for all 8 solenoids as a single byte. - * - * If a solenoid is shorted, it is added to the blacklist and - * disabled until power cycle, or until faults are cleared. - * @see ClearAllPCMStickyFaults() - * + * + * If a solenoid is shorted, it is added to the blacklist and + * disabled until power cycle, or until faults are cleared. + * @see ClearAllPCMStickyFaults() + * * @return The solenoid blacklist of all 8 solenoids on the module. */ -uint8_t SolenoidBase::GetPCMSolenoidBlackList(int module) const -{ - int32_t status = 0; - return getPCMSolenoidBlackList(m_ports[module][0], &status); +uint8_t SolenoidBase::GetPCMSolenoidBlackList(int module) const { + int32_t status = 0; + return getPCMSolenoidBlackList(m_ports[module][0], &status); } /** - * @return true if PCM sticky fault is set : The common - * highside solenoid voltage rail is too low, - * most likely a solenoid channel is shorted. + * @return true if PCM sticky fault is set : The common + * highside solenoid voltage rail is too low, + * most likely a solenoid channel is shorted. */ -bool SolenoidBase::GetPCMSolenoidVoltageStickyFault(int module) const -{ - int32_t status = 0; - return getPCMSolenoidVoltageStickyFault(m_ports[module][0], &status); +bool SolenoidBase::GetPCMSolenoidVoltageStickyFault(int module) const { + int32_t status = 0; + return getPCMSolenoidVoltageStickyFault(m_ports[module][0], &status); } /** - * @return true if PCM is in fault state : The common - * highside solenoid voltage rail is too low, - * most likely a solenoid channel is shorted. + * @return true if PCM is in fault state : The common + * highside solenoid voltage rail is too low, + * most likely a solenoid channel is shorted. */ -bool SolenoidBase::GetPCMSolenoidVoltageFault(int module) const -{ - int32_t status = 0; - return getPCMSolenoidVoltageFault(m_ports[module][0], &status); +bool SolenoidBase::GetPCMSolenoidVoltageFault(int module) const { + int32_t status = 0; + return getPCMSolenoidVoltageFault(m_ports[module][0], &status); } /** * Clear ALL sticky faults inside PCM that Compressor is wired to. * - * If a sticky fault is set, then it will be persistently cleared. Compressor drive - * maybe momentarily disable while flags are being cleared. Care should be - * taken to not call this too frequently, otherwise normal compressor - * functionality may be prevented. + * If a sticky fault is set, then it will be persistently cleared. Compressor + * drive + * maybe momentarily disable while flags are being cleared. Care + * should be + * taken to not call this too frequently, otherwise normal + * compressor + * functionality may be prevented. * * If no sticky faults are set then this call will have no effect. */ -void SolenoidBase::ClearAllPCMStickyFaults(int module) -{ - int32_t status = 0; - return clearAllPCMStickyFaults_sol(m_ports[module][0], &status); +void SolenoidBase::ClearAllPCMStickyFaults(int module) { + int32_t status = 0; + return clearAllPCMStickyFaults_sol(m_ports[module][0], &status); } diff --git a/wpilibc/wpilibC++Devices/src/Talon.cpp b/wpilibc/wpilibC++Devices/src/Talon.cpp index d1c551c32c..8e63b7fffe 100644 --- a/wpilibc/wpilibC++Devices/src/Talon.cpp +++ b/wpilibc/wpilibC++Devices/src/Talon.cpp @@ -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,10 +13,14 @@ /** * Common initialization code called by all constructors. * - * Note that the Talon uses the following bounds for PWM values. These values should work reasonably well for - * most controllers, but if users experience issues such as asymmetric behavior around - * the deadband or inability to saturate the controller in either direction, calibration is recommended. - * The calibration procedure can be found in the Talon User Manual available from CTRE. + * Note that the Talon uses the following bounds for PWM values. These values + * should work reasonably well for + * most controllers, but if users experience issues such as asymmetric behavior + * around + * the deadband or inability to saturate the controller in either direction, + * calibration is recommended. + * The calibration procedure can be found in the Talon User Manual available + * from CTRE. * * 2.037ms = full "forward" * 1.539ms = the "high end" of the deadband range @@ -24,28 +29,24 @@ * 0.989ms = full "reverse" */ void Talon::InitTalon() { - SetBounds(2.037, 1.539, 1.513, 1.487, .989); - SetPeriodMultiplier(kPeriodMultiplier_1X); - SetRaw(m_centerPwm); - SetZeroLatch(); + SetBounds(2.037, 1.539, 1.513, 1.487, .989); + SetPeriodMultiplier(kPeriodMultiplier_1X); + SetRaw(m_centerPwm); + SetZeroLatch(); - HALReport(HALUsageReporting::kResourceType_Talon, GetChannel()); - LiveWindow::GetInstance()->AddActuator("Talon", GetChannel(), this); - m_isInverted = false; + HALReport(HALUsageReporting::kResourceType_Talon, GetChannel()); + LiveWindow::GetInstance()->AddActuator("Talon", GetChannel(), this); + m_isInverted = false; } /** * Constructor for a Talon (original or Talon SR) - * @param channel The PWM channel number that the Talon is attached to. 0-9 are on-board, 10-19 are on the MXP port + * @param channel The PWM channel number that the Talon is attached to. 0-9 are + * on-board, 10-19 are on the MXP port */ -Talon::Talon(uint32_t channel) : SafePWM(channel) -{ - InitTalon(); -} +Talon::Talon(uint32_t channel) : SafePWM(channel) { InitTalon(); } -Talon::~Talon() -{ -} +Talon::~Talon() {} /** * Set the PWM value. @@ -56,9 +57,8 @@ Talon::~Talon() * @param speed The speed value between -1.0 and 1.0 to set. * @param syncGroup Unused interface. */ -void Talon::Set(float speed, uint8_t syncGroup) -{ - SetSpeed(m_isInverted ? -speed : speed); +void Talon::Set(float speed, uint8_t syncGroup) { + SetSpeed(m_isInverted ? -speed : speed); } /** @@ -66,26 +66,18 @@ void Talon::Set(float speed, uint8_t syncGroup) * * @return The most recently set value for the PWM between -1.0 and 1.0. */ -float Talon::Get() const -{ - return GetSpeed(); -} +float Talon::Get() const { return GetSpeed(); } /** * Common interface for disabling a motor. */ -void Talon::Disable() -{ - SetRaw(kPwmDisabled); -} +void Talon::Disable() { SetRaw(kPwmDisabled); } /** * common interface for inverting direction of a speed controller * @param isInverted The state of inversion true is inverted */ -void Talon::SetInverted(bool isInverted){ -m_isInverted = isInverted; -} +void Talon::SetInverted(bool isInverted) { m_isInverted = isInverted; } /** * Common interface for the inverting direction of a speed controller. @@ -93,16 +85,11 @@ m_isInverted = isInverted; * @return isInverted The state of inversion, true is inverted. * */ -bool Talon::GetInverted() const { - return m_isInverted; -} +bool Talon::GetInverted() const { return m_isInverted; } /** * Write out the PID value as seen in the PIDOutput base object. * * @param output Write out the PWM value as was found in the PIDController */ -void Talon::PIDWrite(float output) -{ - Set(output); -} +void Talon::PIDWrite(float output) { Set(output); } diff --git a/wpilibc/wpilibC++Devices/src/TalonSRX.cpp b/wpilibc/wpilibC++Devices/src/TalonSRX.cpp index 180aaf95a6..246b35f258 100644 --- a/wpilibc/wpilibC++Devices/src/TalonSRX.cpp +++ b/wpilibc/wpilibC++Devices/src/TalonSRX.cpp @@ -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,10 +13,14 @@ /** * Common initialization code called by all constructors. * - * Note that the TalonSRX uses the following bounds for PWM values. These values should work reasonably well for - * most controllers, but if users experience issues such as asymmetric behaviour around - * the deadband or inability to saturate the controller in either direction, calibration is recommended. - * The calibration procedure can be found in the TalonSRX User Manual available from Cross The Road Electronics. + * Note that the TalonSRX uses the following bounds for PWM values. These values + * should work reasonably well for + * most controllers, but if users experience issues such as asymmetric behaviour + * around + * the deadband or inability to saturate the controller in either direction, + * calibration is recommended. + * The calibration procedure can be found in the TalonSRX User Manual available + * from Cross The Road Electronics. * 2.004ms = full "forward" * 1.52ms = the "high end" of the deadband range * 1.50ms = center of the deadband range (off) @@ -23,28 +28,24 @@ * 0.997ms = full "reverse" */ void TalonSRX::InitTalonSRX() { - SetBounds(2.004, 1.52, 1.50, 1.48, .997); - SetPeriodMultiplier(kPeriodMultiplier_1X); - SetRaw(m_centerPwm); - SetZeroLatch(); + SetBounds(2.004, 1.52, 1.50, 1.48, .997); + SetPeriodMultiplier(kPeriodMultiplier_1X); + SetRaw(m_centerPwm); + SetZeroLatch(); - HALReport(HALUsageReporting::kResourceType_TalonSRX, GetChannel()); - LiveWindow::GetInstance()->AddActuator("TalonSRX", GetChannel(), this); - m_isInverted = false; + HALReport(HALUsageReporting::kResourceType_TalonSRX, GetChannel()); + LiveWindow::GetInstance()->AddActuator("TalonSRX", GetChannel(), this); + m_isInverted = false; } /** * Construct a TalonSRX connected via PWM - * @param channel The PWM channel that the TalonSRX is attached to. 0-9 are on-board, 10-19 are on the MXP port + * @param channel The PWM channel that the TalonSRX is attached to. 0-9 are + * on-board, 10-19 are on the MXP port */ -TalonSRX::TalonSRX(uint32_t channel) : SafePWM(channel) -{ - InitTalonSRX(); -} +TalonSRX::TalonSRX(uint32_t channel) : SafePWM(channel) { InitTalonSRX(); } -TalonSRX::~TalonSRX() -{ -} +TalonSRX::~TalonSRX() {} /** * Set the PWM value. @@ -55,36 +56,25 @@ TalonSRX::~TalonSRX() * @param speed The speed value between -1.0 and 1.0 to set. * @param syncGroup Unused interface. */ -void TalonSRX::Set(float speed, uint8_t syncGroup) -{ - SetSpeed(speed); -} +void TalonSRX::Set(float speed, uint8_t syncGroup) { SetSpeed(speed); } /** * Get the recently set value of the PWM. * * @return The most recently set value for the PWM between -1.0 and 1.0. */ -float TalonSRX::Get() const -{ - return GetSpeed(); -} +float TalonSRX::Get() const { return GetSpeed(); } /** * Common interface for disabling a motor. */ -void TalonSRX::Disable() -{ - SetRaw(kPwmDisabled); -} +void TalonSRX::Disable() { SetRaw(kPwmDisabled); } /** * Common interface for inverting direction of a speed controller. * @param isInverted The state of inversion, true is inverted. */ -void TalonSRX::SetInverted(bool isInverted){ -m_isInverted = isInverted; -} +void TalonSRX::SetInverted(bool isInverted) { m_isInverted = isInverted; } /** * Common interface for the inverting direction of a speed controller. @@ -92,16 +82,11 @@ m_isInverted = isInverted; * @return isInverted The state of inversion, true is inverted. * */ -bool TalonSRX::GetInverted() const { - return m_isInverted; -} +bool TalonSRX::GetInverted() const { return m_isInverted; } /** * Write out the PID value as seen in the PIDOutput base object. * * @param output Write out the PWM value as was found in the PIDController */ -void TalonSRX::PIDWrite(float output) -{ - Set(output); -} +void TalonSRX::PIDWrite(float output) { Set(output); } diff --git a/wpilibc/wpilibC++Devices/src/Task.cpp b/wpilibc/wpilibC++Devices/src/Task.cpp index 6f7050effe..316eaf8e08 100644 --- a/wpilibc/wpilibC++Devices/src/Task.cpp +++ b/wpilibc/wpilibC++Devices/src/Task.cpp @@ -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. */ /*----------------------------------------------------------------------------*/ @@ -22,129 +23,111 @@ const uint32_t Task::kDefaultPriority; * @param priority The VxWorks priority for the task. * @param stackSize The size of the stack for the task */ -Task::Task(const char* name, FUNCPTR function, int32_t priority, uint32_t stackSize) -{ - m_taskID = NULL_TASK; - m_function = function; - m_priority = priority; - m_stackSize = stackSize; - m_taskName = new char[strlen(name) + 5]; - strcpy(m_taskName, "FRC_"); - strcpy(m_taskName+4, name); +Task::Task(const char* name, FUNCPTR function, int32_t priority, + uint32_t stackSize) { + m_taskID = NULL_TASK; + m_function = function; + m_priority = priority; + m_stackSize = stackSize; + m_taskName = new char[strlen(name) + 5]; + strcpy(m_taskName, "FRC_"); + strcpy(m_taskName + 4, name); - static int32_t instances = 0; - instances++; - HALReport(HALUsageReporting::kResourceType_Task, instances, 0, m_taskName); + static int32_t instances = 0; + instances++; + HALReport(HALUsageReporting::kResourceType_Task, instances, 0, m_taskName); } -Task::~Task() -{ - if (m_taskID != NULL_TASK) Stop(); - delete [] m_taskName; - m_taskName = NULL; +Task::~Task() { + if (m_taskID != NULL_TASK) Stop(); + delete[] m_taskName; + m_taskName = NULL; } /** * Starts this task. * If it is already running or unable to start, it fails and returns false. */ -bool Task::Start(uint32_t arg0, uint32_t arg1, uint32_t arg2, uint32_t arg3, uint32_t arg4, - uint32_t arg5, uint32_t arg6, uint32_t arg7, uint32_t arg8, uint32_t arg9) -{ - m_taskID = spawnTask(m_taskName, - m_priority, - VXWORKS_FP_TASK, // options - m_stackSize, // stack size - m_function, // function to start - arg0, arg1, arg2, arg3, arg4, // parameter 1 - pointer to this class - arg5, arg6, arg7, arg8, arg9);// additional unused parameters - if (m_taskID == NULL_TASK) { - HandleError(ERROR); - return false; - } - return true; +bool Task::Start(uint32_t arg0, uint32_t arg1, uint32_t arg2, uint32_t arg3, + uint32_t arg4, uint32_t arg5, uint32_t arg6, uint32_t arg7, + uint32_t arg8, uint32_t arg9) { + m_taskID = spawnTask( + m_taskName, m_priority, + VXWORKS_FP_TASK, // options + m_stackSize, // stack size + m_function, // function to start + arg0, arg1, arg2, arg3, arg4, // parameter 1 - pointer to this class + arg5, arg6, arg7, arg8, arg9); // additional unused parameters + if (m_taskID == NULL_TASK) { + HandleError(ERROR); + return false; + } + return true; } /** * Restarts a running task. * If the task isn't started, it starts it. - * @return false if the task is running and we are unable to kill the previous instance + * @return false if the task is running and we are unable to kill the previous + * instance */ -bool Task::Restart() -{ - return HandleError(restartTask(m_taskID)); -} +bool Task::Restart() { return HandleError(restartTask(m_taskID)); } /** * Kills the running task. - * @returns true on success false if the task doesn't exist or we are unable to kill it. + * @returns true on success false if the task doesn't exist or we are unable to + * kill it. */ -bool Task::Stop() -{ - bool ok = true; - if (Verify()) - { - ok = HandleError(deleteTask(m_taskID)); - } - m_taskID = NULL_TASK; - return ok; +bool Task::Stop() { + bool ok = true; + if (Verify()) { + ok = HandleError(deleteTask(m_taskID)); + } + m_taskID = NULL_TASK; + return ok; } /** - * Returns true if the task is ready to execute (i.e. not suspended, delayed, or blocked). + * Returns true if the task is ready to execute (i.e. not suspended, delayed, or + * blocked). * @return true if ready, false if not ready. */ -bool Task::IsReady() const -{ - return isTaskReady(m_taskID); -} +bool Task::IsReady() const { return isTaskReady(m_taskID); } /** * Returns true if the task was explicitly suspended by calling Suspend() * @return true if suspended, false if not suspended. */ -bool Task::IsSuspended() const -{ - return isTaskSuspended(m_taskID); -} +bool Task::IsSuspended() const { return isTaskSuspended(m_taskID); } /** * Pauses a running task. * Returns true on success, false if unable to pause or the task isn't running. */ -bool Task::Suspend() -{ - return HandleError(suspendTask(m_taskID)); -} +bool Task::Suspend() { return HandleError(suspendTask(m_taskID)); } /** * Resumes a paused task. - * Returns true on success, false if unable to resume or if the task isn't running/paused. + * Returns true on success, false if unable to resume or if the task isn't + * running/paused. */ -bool Task::Resume() -{ - return HandleError(resumeTask(m_taskID)); -} +bool Task::Resume() { return HandleError(resumeTask(m_taskID)); } /** * Verifies a task still exists. * @returns true on success. */ -bool Task::Verify() const -{ - return verifyTaskID(m_taskID) == OK; -} +bool Task::Verify() const { return verifyTaskID(m_taskID) == OK; } /** * Gets the priority of a task. * @returns task priority or 0 if an error occured */ -int32_t Task::GetPriority() -{ - if (HandleError(getTaskPriority(m_taskID, &m_priority))) - return m_priority; - else - return 0; +int32_t Task::GetPriority() { + if (HandleError(getTaskPriority(m_taskID, &m_priority))) + return m_priority; + else + return 0; } /** @@ -154,53 +137,46 @@ int32_t Task::GetPriority() * @param priority The priority the task should run at. * @returns true on success. */ -bool Task::SetPriority(int32_t priority) -{ - m_priority = priority; - return HandleError(setTaskPriority(m_taskID, m_priority)); +bool Task::SetPriority(int32_t priority) { + m_priority = priority; + return HandleError(setTaskPriority(m_taskID, m_priority)); } /** * Returns the name of the task. * @returns Pointer to the name of the task or NULL if not allocated */ -const char* Task::GetName() const -{ - return m_taskName; -} +const char* Task::GetName() const { return m_taskName; } /** * Get the ID of a task - * @returns Task ID of this task. Task::kInvalidTaskID (-1) if the task has not been started or has already exited. + * @returns Task ID of this task. Task::kInvalidTaskID (-1) if the task has not + * been started or has already exited. */ -TASK Task::GetID() const -{ - if (Verify()) - return m_taskID; - return NULL_TASK; +TASK Task::GetID() const { + if (Verify()) return m_taskID; + return NULL_TASK; } /** * Handles errors generated by task related code. */ -bool Task::HandleError(STATUS results) -{ - if (results != ERROR) return true; - int errsv = errno; - if (errsv == HAL_objLib_OBJ_ID_ERROR) { - wpi_setWPIErrorWithContext(TaskIDError, m_taskName); - } else if (errsv == HAL_objLib_OBJ_DELETED) { - wpi_setWPIErrorWithContext(TaskDeletedError, m_taskName); - } else if (errsv == HAL_taskLib_ILLEGAL_OPTIONS) { - wpi_setWPIErrorWithContext(TaskOptionsError, m_taskName); - } else if (errsv == HAL_memLib_NOT_ENOUGH_MEMORY) { - wpi_setWPIErrorWithContext(TaskMemoryError, m_taskName); - } else if (errsv == HAL_taskLib_ILLEGAL_PRIORITY) { - wpi_setWPIErrorWithContext(TaskPriorityError, m_taskName); - } else { - printf("ERROR: errno=%i", errsv); - wpi_setWPIErrorWithContext(TaskError, m_taskName); - } - return false; +bool Task::HandleError(STATUS results) { + if (results != ERROR) return true; + int errsv = errno; + if (errsv == HAL_objLib_OBJ_ID_ERROR) { + wpi_setWPIErrorWithContext(TaskIDError, m_taskName); + } else if (errsv == HAL_objLib_OBJ_DELETED) { + wpi_setWPIErrorWithContext(TaskDeletedError, m_taskName); + } else if (errsv == HAL_taskLib_ILLEGAL_OPTIONS) { + wpi_setWPIErrorWithContext(TaskOptionsError, m_taskName); + } else if (errsv == HAL_memLib_NOT_ENOUGH_MEMORY) { + wpi_setWPIErrorWithContext(TaskMemoryError, m_taskName); + } else if (errsv == HAL_taskLib_ILLEGAL_PRIORITY) { + wpi_setWPIErrorWithContext(TaskPriorityError, m_taskName); + } else { + printf("ERROR: errno=%i", errsv); + wpi_setWPIErrorWithContext(TaskError, m_taskName); + } + return false; } - diff --git a/wpilibc/wpilibC++Devices/src/Timer.cpp b/wpilibc/wpilibC++Devices/src/Timer.cpp index 6b5c6bfaa5..29440aa83c 100644 --- a/wpilibc/wpilibC++Devices/src/Timer.cpp +++ b/wpilibc/wpilibC++Devices/src/Timer.cpp @@ -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,16 +17,18 @@ /** * Pause the task for a specified time. * - * Pause the execution of the program for a specified period of time given in seconds. - * Motors will continue to run at their last assigned values, and sensors will continue to - * update. Only the task containing the wait will pause until the wait time is expired. + * Pause the execution of the program for a specified period of time given in + * seconds. + * Motors will continue to run at their last assigned values, and sensors will + * continue to + * update. Only the task containing the wait will pause until the wait time is + * expired. * * @param seconds Length of time to pause, in seconds. */ -void Wait(double seconds) -{ - if (seconds < 0.0) return; - delaySeconds(seconds); +void Wait(double seconds) { + if (seconds < 0.0) return; + delaySeconds(seconds); } /** @@ -33,90 +36,82 @@ void Wait(double seconds) * This is deprecated and just forwards to Timer::GetFPGATimestamp(). * @return Robot running time in seconds. */ -double GetClock() -{ - return Timer::GetFPGATimestamp(); -} +double GetClock() { return Timer::GetFPGATimestamp(); } /** * @brief Gives real-time clock system time with nanosecond resolution - * @return The time, just in case you want the robot to start autonomous at 8pm on Saturday. + * @return The time, just in case you want the robot to start autonomous at 8pm + * on Saturday. */ -double GetTime() -{ - struct timespec tp; +double GetTime() { + struct timespec tp; - clock_gettime(CLOCK_REALTIME,&tp); - double realTime = (double)tp.tv_sec + (double)((double)tp.tv_nsec*1e-9); + clock_gettime(CLOCK_REALTIME, &tp); + double realTime = (double)tp.tv_sec + (double)((double)tp.tv_nsec * 1e-9); - return (realTime); + return (realTime); } /** * Create a new timer object. * - * Create a new timer object and reset the time to zero. The timer is initially not running and + * Create a new timer object and reset the time to zero. The timer is initially + * not running and * must be started. */ Timer::Timer() - : m_startTime (0.0) - , m_accumulatedTime (0.0) - , m_running (false) - , m_semaphore (0) -{ - //Creates a semaphore to control access to critical regions. - //Initially 'open' - m_semaphore = initializeMutexNormal(); - Reset(); + : m_startTime(0.0), + m_accumulatedTime(0.0), + m_running(false), + m_semaphore(0) { + // Creates a semaphore to control access to critical regions. + // Initially 'open' + m_semaphore = initializeMutexNormal(); + Reset(); } -Timer::~Timer() -{ - deleteMutex(m_semaphore); -} +Timer::~Timer() { deleteMutex(m_semaphore); } /** - * Get the current time from the timer. If the clock is running it is derived from - * the current system clock the start time stored in the timer class. If the clock + * Get the current time from the timer. If the clock is running it is derived + * from + * the current system clock the start time stored in the timer class. If the + * clock * is not running, then return the time when it was last stopped. * * @return Current time value for this timer in seconds */ -double Timer::Get() const -{ - double result; - double currentTime = GetFPGATimestamp(); +double Timer::Get() const { + double result; + double currentTime = GetFPGATimestamp(); - Synchronized sync(m_semaphore); - if(m_running) - { - // If the current time is before the start time, then the FPGA clock - // rolled over. Compensate by adding the ~71 minutes that it takes - // to roll over to the current time. - if(currentTime < m_startTime) { - currentTime += kRolloverTime; - } + Synchronized sync(m_semaphore); + if (m_running) { + // If the current time is before the start time, then the FPGA clock + // rolled over. Compensate by adding the ~71 minutes that it takes + // to roll over to the current time. + if (currentTime < m_startTime) { + currentTime += kRolloverTime; + } - result = (currentTime - m_startTime) + m_accumulatedTime; - } - else - { - result = m_accumulatedTime; - } + result = (currentTime - m_startTime) + m_accumulatedTime; + } else { + result = m_accumulatedTime; + } - return result; + return result; } /** * Reset the timer by setting the time to 0. * - * Make the timer startTime the current time so new requests will be relative to now + * Make the timer startTime the current time so new requests will be relative to + * now */ -void Timer::Reset() -{ - Synchronized sync(m_semaphore); - m_accumulatedTime = 0; - m_startTime = GetFPGATimestamp(); +void Timer::Reset() { + Synchronized sync(m_semaphore); + m_accumulatedTime = 0; + m_startTime = GetFPGATimestamp(); } /** @@ -124,14 +119,12 @@ void Timer::Reset() * Just set the running flag to true indicating that all time requests should be * relative to the system clock. */ -void Timer::Start() -{ - Synchronized sync(m_semaphore); - if (!m_running) - { - m_startTime = GetFPGATimestamp(); - m_running = true; - } +void Timer::Start() { + Synchronized sync(m_semaphore); + if (!m_running) { + m_startTime = GetFPGATimestamp(); + m_running = true; + } } /** @@ -140,16 +133,14 @@ void Timer::Start() * subsequent time requests to be read from the accumulated time rather than * looking at the system clock. */ -void Timer::Stop() -{ - double temp = Get(); +void Timer::Stop() { + double temp = Get(); - Synchronized sync(m_semaphore); - if (m_running) - { - m_accumulatedTime = temp; - m_running = false; - } + Synchronized sync(m_semaphore); + if (m_running) { + m_accumulatedTime = temp; + m_running = false; + } } /** @@ -160,17 +151,15 @@ void Timer::Stop() * @param period The period to check for (in seconds). * @return True if the period has passed. */ -bool Timer::HasPeriodPassed(double period) -{ - if (Get() > period) - { - Synchronized sync(m_semaphore); - // Advance the start time by the period. - m_startTime += period; - // Don't set it to the current time... we want to avoid drift. - return true; - } - return false; +bool Timer::HasPeriodPassed(double period) { + if (Get() > period) { + Synchronized sync(m_semaphore); + // Advance the start time by the period. + m_startTime += period; + // Don't set it to the current time... we want to avoid drift. + return true; + } + return false; } /** @@ -181,16 +170,14 @@ bool Timer::HasPeriodPassed(double period) * Rolls over after 71 minutes. * @returns Robot running time in seconds. */ -double Timer::GetFPGATimestamp() -{ - // FPGA returns the timestamp in microseconds - // Call the helper GetFPGATime() in Utility.cpp - return GetFPGATime() * 1.0e-6; +double Timer::GetFPGATimestamp() { + // FPGA returns the timestamp in microseconds + // Call the helper GetFPGATime() in Utility.cpp + return GetFPGATime() * 1.0e-6; } // Internal function that reads the PPC timestamp counter. -extern "C" -{ - uint32_t niTimestamp32(void); - uint64_t niTimestamp64(void); +extern "C" { +uint32_t niTimestamp32(void); +uint64_t niTimestamp64(void); } diff --git a/wpilibc/wpilibC++Devices/src/USBCamera.cpp b/wpilibc/wpilibC++Devices/src/USBCamera.cpp index 8d36be1cb1..7e577a0f36 100644 --- a/wpilibc/wpilibC++Devices/src/USBCamera.cpp +++ b/wpilibc/wpilibC++Devices/src/USBCamera.cpp @@ -12,9 +12,10 @@ // properly checked for an error, calling the wpi_setImaqErrorWithContext // macro // To call it, just give the name of the function and the arguments -#define SAFE_IMAQ_CALL(funName, ...) { \ - unsigned int error = funName(__VA_ARGS__); \ - if (error != IMAQdxErrorSuccess) \ +#define SAFE_IMAQ_CALL(funName, ...) \ + { \ + unsigned int error = funName(__VA_ARGS__); \ + if (error != IMAQdxErrorSuccess) \ wpi_setImaqErrorWithContext(error, #funName); \ } @@ -29,40 +30,44 @@ static const std::string MANUAL = "Manual"; * the SOS flag explanation. */ unsigned int USBCamera::GetJpegSize(void* buffer, unsigned int buffSize) { - uint8_t* data = (uint8_t*) buffer; + uint8_t* data = (uint8_t*)buffer; if (!wpi_assert(data[0] == 0xff && data[1] == 0xd8)) return 0; unsigned int pos = 2; while (pos < buffSize) { // All control markers start with 0xff, so if this isn't present, // the JPEG is not valid if (!wpi_assert(data[pos] == 0xff)) return 0; - unsigned char t = data[pos+1]; + unsigned char t = data[pos + 1]; // These are RST markers. We just skip them and move onto the next marker if (t == 0x01 || (t >= 0xd0 && t <= 0xd7)) { pos += 2; } else if (t == 0xd9) { // End of Image, add 2 for this and 0-indexed return pos + 2; - } else if (!wpi_assert(t != 0xd8)) { + } else if (!wpi_assert(t != 0xd8)) { // Another start of image, invalid image return 0; } else if (t == 0xda) { // SOS marker. The next two bytes are a 16-bit big-endian int that is // the length of the SOS header, skip that - unsigned int len = (((unsigned int) (data[pos+2] & 0xff)) << 8 | ((unsigned int) data[pos+3] & 0xff)); + unsigned int len = (((unsigned int)(data[pos + 2] & 0xff)) << 8 | + ((unsigned int)data[pos + 3] & 0xff)); pos += len + 2; // The next marker is the first marker that is 0xff followed by a non-RST // element. 0xff followed by 0x00 is an escaped 0xff. 0xd0-0xd7 are RST // markers - while (data[pos] != 0xff || data[pos+1] == 0x00 || (data[pos+1] >= 0xd0 && data[pos+1] <= 0xd7)) { + while (data[pos] != 0xff || data[pos + 1] == 0x00 || + (data[pos + 1] >= 0xd0 && data[pos + 1] <= 0xd7)) { pos += 1; if (pos >= buffSize) return 0; } } else { - // This is one of several possible markers. The next two bytes are a 16-bit + // This is one of several possible markers. The next two bytes are a + // 16-bit // big-endian int with the length of the marker header, skip that then // continue searching - unsigned int len = (((unsigned int) (data[pos+2] & 0xff)) << 8 | ((unsigned int) data[pos+3] & 0xff)); + unsigned int len = (((unsigned int)(data[pos + 2] & 0xff)) << 8 | + ((unsigned int)data[pos + 3] & 0xff)); pos += len + 2; } } @@ -70,36 +75,35 @@ unsigned int USBCamera::GetJpegSize(void* buffer, unsigned int buffSize) { return 0; } -USBCamera::USBCamera(std::string name, bool useJpeg) : - m_id(0), - m_name(name), - m_useJpeg(useJpeg), - m_active(false), - m_open(false), - m_mutex(), - m_width(320), - m_height(240), - m_fps(30), - m_whiteBalance(AUTO), - m_whiteBalanceValue(0), - m_whiteBalanceValuePresent(false), - m_exposure(MANUAL), - m_exposureValue(50), - m_exposureValuePresent(false), - m_brightness(80), - m_needSettingsUpdate(true) { -} +USBCamera::USBCamera(std::string name, bool useJpeg) + : m_id(0), + m_name(name), + m_useJpeg(useJpeg), + m_active(false), + m_open(false), + m_mutex(), + m_width(320), + m_height(240), + m_fps(30), + m_whiteBalance(AUTO), + m_whiteBalanceValue(0), + m_whiteBalanceValuePresent(false), + m_exposure(MANUAL), + m_exposureValue(50), + m_exposureValuePresent(false), + m_brightness(80), + m_needSettingsUpdate(true) {} void USBCamera::OpenCamera() { std::unique_lock lock(m_mutex); for (unsigned int i = 0; i < 3; i++) { uInt32 id = 0; // Can't use SAFE_IMAQ_CALL here because we only error on the third time - IMAQdxError error = IMAQdxOpenCamera(m_name.c_str(), IMAQdxCameraControlModeController, &id); + IMAQdxError error = IMAQdxOpenCamera( + m_name.c_str(), IMAQdxCameraControlModeController, &id); if (error != IMAQdxErrorSuccess) { // Only error on the 3rd try - if (i >= 2) - wpi_setImaqErrorWithContext(error, "IMAQdxOpenCamera"); + if (i >= 2) wpi_setImaqErrorWithContext(error, "IMAQdxOpenCamera"); // Sleep for a few seconds to ensure the error has been dealt with std::this_thread::sleep_for(std::chrono::milliseconds(2000)); } else { @@ -138,10 +142,8 @@ void USBCamera::UpdateSettings() { std::unique_lock lock(m_mutex); bool wasActive = m_active; - if (wasActive) - StopCapture(); - if (m_open) - CloseCamera(); + if (wasActive) StopCapture(); + if (m_open) CloseCamera(); OpenCamera(); uInt32 count = 0; @@ -163,63 +165,71 @@ void USBCamera::UpdateSettings() { // Loop through the modes, and find the match with the lowest fps for (unsigned int i = 0; i < count; i++) { std::cmatch m; - if (!std::regex_match(modes[i].Name, m, reMode)) - continue; - unsigned int width = (unsigned int) std::stoul(m[1].str()); - unsigned int height = (unsigned int) std::stoul(m[2].str()); - if (width != m_width) - continue; - if (height != m_height) - continue; + if (!std::regex_match(modes[i].Name, m, reMode)) continue; + unsigned int width = (unsigned int)std::stoul(m[1].str()); + unsigned int height = (unsigned int)std::stoul(m[2].str()); + if (width != m_width) continue; + if (height != m_height) continue; double fps = atof(m[4].str().c_str()); - if (fps < m_fps) - continue; - if (fps > foundFps) - continue; - bool isJpeg = m[3].str().compare("jpeg") == 0 || m[3].str().compare("JPEG") == 0; - if ((m_useJpeg && !isJpeg) || (!m_useJpeg && isJpeg)) - continue; + if (fps < m_fps) continue; + if (fps > foundFps) continue; + bool isJpeg = + m[3].str().compare("jpeg") == 0 || m[3].str().compare("JPEG") == 0; + if ((m_useJpeg && !isJpeg) || (!m_useJpeg && isJpeg)) continue; foundMode = &modes[i]; foundFps = fps; } if (foundMode != nullptr) { if (foundMode->Value != currentModePtr->Value) { - SAFE_IMAQ_CALL(IMAQdxSetAttribute, m_id, IMAQdxAttributeVideoMode, IMAQdxValueTypeU32, foundMode->Value); + SAFE_IMAQ_CALL(IMAQdxSetAttribute, m_id, IMAQdxAttributeVideoMode, + IMAQdxValueTypeU32, foundMode->Value); } - } + } if (m_whiteBalance.compare(AUTO) == 0) { - SAFE_IMAQ_CALL(IMAQdxSetAttribute, m_id, ATTR_WB_MODE, IMAQdxValueTypeString, AUTO.c_str()); + SAFE_IMAQ_CALL(IMAQdxSetAttribute, m_id, ATTR_WB_MODE, + IMAQdxValueTypeString, AUTO.c_str()); } else { - SAFE_IMAQ_CALL(IMAQdxSetAttribute, m_id, ATTR_WB_MODE, IMAQdxValueTypeString, MANUAL.c_str()); + SAFE_IMAQ_CALL(IMAQdxSetAttribute, m_id, ATTR_WB_MODE, + IMAQdxValueTypeString, MANUAL.c_str()); if (m_whiteBalanceValuePresent) - SAFE_IMAQ_CALL(IMAQdxSetAttribute, m_id, ATTR_WB_VALUE, IMAQdxValueTypeU32, m_whiteBalanceValue); + SAFE_IMAQ_CALL(IMAQdxSetAttribute, m_id, ATTR_WB_VALUE, + IMAQdxValueTypeU32, m_whiteBalanceValue); } if (m_exposure.compare(AUTO) == 0) { - SAFE_IMAQ_CALL(IMAQdxSetAttribute, m_id, ATTR_EX_MODE, IMAQdxValueTypeString, std::string("AutoAperaturePriority").c_str()); + SAFE_IMAQ_CALL(IMAQdxSetAttribute, m_id, ATTR_EX_MODE, + IMAQdxValueTypeString, + std::string("AutoAperaturePriority").c_str()); } else { - SAFE_IMAQ_CALL(IMAQdxSetAttribute, m_id, ATTR_EX_MODE, IMAQdxValueTypeString, MANUAL.c_str()); + SAFE_IMAQ_CALL(IMAQdxSetAttribute, m_id, ATTR_EX_MODE, + IMAQdxValueTypeString, MANUAL.c_str()); if (m_exposureValuePresent) { double minv = 0.0; double maxv = 0.0; - SAFE_IMAQ_CALL(IMAQdxGetAttributeMinimum, m_id, ATTR_EX_VALUE, IMAQdxValueTypeF64, &minv); - SAFE_IMAQ_CALL(IMAQdxGetAttributeMaximum, m_id, ATTR_EX_VALUE, IMAQdxValueTypeF64, &maxv); - double val = minv + ((maxv - minv) * ((double) m_exposureValue / 100.0)); - SAFE_IMAQ_CALL(IMAQdxSetAttribute, m_id, ATTR_EX_VALUE, IMAQdxValueTypeF64, val); + SAFE_IMAQ_CALL(IMAQdxGetAttributeMinimum, m_id, ATTR_EX_VALUE, + IMAQdxValueTypeF64, &minv); + SAFE_IMAQ_CALL(IMAQdxGetAttributeMaximum, m_id, ATTR_EX_VALUE, + IMAQdxValueTypeF64, &maxv); + double val = minv + ((maxv - minv) * ((double)m_exposureValue / 100.0)); + SAFE_IMAQ_CALL(IMAQdxSetAttribute, m_id, ATTR_EX_VALUE, + IMAQdxValueTypeF64, val); } } - SAFE_IMAQ_CALL(IMAQdxSetAttribute, m_id, ATTR_BR_MODE, IMAQdxValueTypeString, MANUAL.c_str()); + SAFE_IMAQ_CALL(IMAQdxSetAttribute, m_id, ATTR_BR_MODE, IMAQdxValueTypeString, + MANUAL.c_str()); double minv = 0.0; double maxv = 0.0; - SAFE_IMAQ_CALL(IMAQdxGetAttributeMinimum, m_id, ATTR_BR_VALUE, IMAQdxValueTypeF64, &minv); - SAFE_IMAQ_CALL(IMAQdxGetAttributeMaximum, m_id, ATTR_BR_VALUE, IMAQdxValueTypeF64, &maxv); - double val = minv + ((maxv - minv) * ((double) m_brightness / 100.0)); - SAFE_IMAQ_CALL(IMAQdxSetAttribute, m_id, ATTR_BR_VALUE, IMAQdxValueTypeF64, val); + SAFE_IMAQ_CALL(IMAQdxGetAttributeMinimum, m_id, ATTR_BR_VALUE, + IMAQdxValueTypeF64, &minv); + SAFE_IMAQ_CALL(IMAQdxGetAttributeMaximum, m_id, ATTR_BR_VALUE, + IMAQdxValueTypeF64, &maxv); + double val = minv + ((maxv - minv) * ((double)m_brightness / 100.0)); + SAFE_IMAQ_CALL(IMAQdxSetAttribute, m_id, ATTR_BR_VALUE, IMAQdxValueTypeF64, + val); - if (wasActive) - StartCapture(); + if (wasActive) StartCapture(); } void USBCamera::SetFPS(double fps) { @@ -295,8 +305,10 @@ void USBCamera::SetExposureHoldCurrent() { void USBCamera::SetExposureManual(unsigned int level) { std::unique_lock lock(m_mutex); m_exposure = MANUAL; - if (level > 100) m_exposureValue = 100; - else m_exposureValue = level; + if (level > 100) + m_exposureValue = 100; + else + m_exposureValue = level; m_exposureValuePresent = true; m_needSettingsUpdate = true; } @@ -323,6 +335,7 @@ unsigned int USBCamera::GetImageData(void* buffer, unsigned int bufferSize) { } // BufNum is not actually used for anything at our level uInt32 bufNum; - SAFE_IMAQ_CALL(IMAQdxGetImageData, m_id, buffer, bufferSize, IMAQdxBufferNumberModeLast, 0, &bufNum); + SAFE_IMAQ_CALL(IMAQdxGetImageData, m_id, buffer, bufferSize, + IMAQdxBufferNumberModeLast, 0, &bufNum); return GetJpegSize(buffer, bufferSize); } diff --git a/wpilibc/wpilibC++Devices/src/Ultrasonic.cpp b/wpilibc/wpilibC++Devices/src/Ultrasonic.cpp index a49fd115f4..82b8c8713a 100644 --- a/wpilibc/wpilibC++Devices/src/Ultrasonic.cpp +++ b/wpilibc/wpilibC++Devices/src/Ultrasonic.cpp @@ -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,320 +16,317 @@ #include "WPIErrors.h" #include "LiveWindow/LiveWindow.h" -constexpr double Ultrasonic::kPingTime; ///< Time (sec) for the ping trigger pulse. -const uint32_t Ultrasonic::kPriority; ///< Priority that the ultrasonic round robin task runs. -constexpr double Ultrasonic::kMaxUltrasonicTime; ///< Max time (ms) between readings. +constexpr double + Ultrasonic::kPingTime; ///< Time (sec) for the ping trigger pulse. +const uint32_t Ultrasonic::kPriority; ///< Priority that the ultrasonic round + ///robin task runs. +constexpr double + Ultrasonic::kMaxUltrasonicTime; ///< Max time (ms) between readings. constexpr double Ultrasonic::kSpeedOfSoundInchesPerSec; -Task Ultrasonic::m_task("UltrasonicChecker", (FUNCPTR)UltrasonicChecker); // task doing the round-robin automatic sensing -Ultrasonic *Ultrasonic::m_firstSensor = NULL; // head of the ultrasonic sensor list -bool Ultrasonic::m_automaticEnabled = false; // automatic round robin mode +Task Ultrasonic::m_task( + "UltrasonicChecker", + (FUNCPTR) + UltrasonicChecker); // task doing the round-robin automatic sensing +Ultrasonic *Ultrasonic::m_firstSensor = + NULL; // head of the ultrasonic sensor list +bool Ultrasonic::m_automaticEnabled = false; // automatic round robin mode SEMAPHORE_ID Ultrasonic::m_semaphore = 0; /** - * Background task that goes through the list of ultrasonic sensors and pings each one in turn. The counter + * Background task that goes through the list of ultrasonic sensors and pings + * each one in turn. The counter * is configured to read the timing of the returned echo pulse. * * DANGER WILL ROBINSON, DANGER WILL ROBINSON: - * This code runs as a task and assumes that none of the ultrasonic sensors will change while it's - * running. If one does, then this will certainly break. Make sure to disable automatic mode before changing + * This code runs as a task and assumes that none of the ultrasonic sensors will + * change while it's + * running. If one does, then this will certainly break. Make sure to disable + * automatic mode before changing * anything with the sensors!! */ -void Ultrasonic::UltrasonicChecker() -{ - Ultrasonic *u = NULL; - while (m_automaticEnabled) - { - if (u == NULL) u = m_firstSensor; - if (u == NULL) return; - if (u->IsEnabled()) - u->m_pingChannel->Pulse(kPingTime); // do the ping - u = u->m_nextSensor; - Wait(0.1); // wait for ping to return - } +void Ultrasonic::UltrasonicChecker() { + Ultrasonic *u = NULL; + while (m_automaticEnabled) { + if (u == NULL) u = m_firstSensor; + if (u == NULL) return; + if (u->IsEnabled()) u->m_pingChannel->Pulse(kPingTime); // do the ping + u = u->m_nextSensor; + Wait(0.1); // wait for ping to return + } } /** * Initialize the Ultrasonic Sensor. - * This is the common code that initializes the ultrasonic sensor given that there - * are two digital I/O channels allocated. If the system was running in automatic mode (round robin) - * when the new sensor is added, it is stopped, the sensor is added, then automatic mode is + * This is the common code that initializes the ultrasonic sensor given that + * there + * are two digital I/O channels allocated. If the system was running in + * automatic mode (round robin) + * when the new sensor is added, it is stopped, the sensor is added, then + * automatic mode is * restored. */ -void Ultrasonic::Initialize() -{ - m_table = NULL; - bool originalMode = m_automaticEnabled; - if (m_semaphore == 0) m_semaphore = initializeSemaphore(SEMAPHORE_FULL); - SetAutomaticMode(false); // kill task when adding a new sensor - takeSemaphore(m_semaphore); // link this instance on the list - { - m_nextSensor = m_firstSensor; - m_firstSensor = this; - } - giveSemaphore(m_semaphore); +void Ultrasonic::Initialize() { + m_table = NULL; + bool originalMode = m_automaticEnabled; + if (m_semaphore == 0) m_semaphore = initializeSemaphore(SEMAPHORE_FULL); + SetAutomaticMode(false); // kill task when adding a new sensor + takeSemaphore(m_semaphore); // link this instance on the list + { + m_nextSensor = m_firstSensor; + m_firstSensor = this; + } + giveSemaphore(m_semaphore); - m_counter = new Counter(m_echoChannel); // set up counter for this sensor - m_counter->SetMaxPeriod(1.0); - m_counter->SetSemiPeriodMode(true); - m_counter->Reset(); - m_enabled = true; // make it available for round robin scheduling - SetAutomaticMode(originalMode); + m_counter = new Counter(m_echoChannel); // set up counter for this sensor + m_counter->SetMaxPeriod(1.0); + m_counter->SetSemiPeriodMode(true); + m_counter->Reset(); + m_enabled = true; // make it available for round robin scheduling + SetAutomaticMode(originalMode); - static int instances = 0; - instances++; - HALReport(HALUsageReporting::kResourceType_Ultrasonic, instances); - LiveWindow::GetInstance()->AddSensor("Ultrasonic", m_echoChannel->GetChannel(), this); + static int instances = 0; + instances++; + HALReport(HALUsageReporting::kResourceType_Ultrasonic, instances); + LiveWindow::GetInstance()->AddSensor("Ultrasonic", + m_echoChannel->GetChannel(), this); } /** * Create an instance of the Ultrasonic Sensor - * This is designed to supchannel the Daventech SRF04 and Vex ultrasonic sensors. - * @param pingChannel The digital output channel that sends the pulse to initiate the sensor sending + * This is designed to supchannel the Daventech SRF04 and Vex ultrasonic + * sensors. + * @param pingChannel The digital output channel that sends the pulse to + * initiate the sensor sending * the ping. - * @param echoChannel The digital input channel that receives the echo. The length of time that the + * @param echoChannel The digital input channel that receives the echo. The + * length of time that the * echo is high represents the round trip time of the ping, and the distance. * @param units The units returned in either kInches or kMilliMeters */ -Ultrasonic::Ultrasonic(uint32_t pingChannel, uint32_t echoChannel, DistanceUnit units) -{ - m_pingChannel = new DigitalOutput(pingChannel); - m_echoChannel = new DigitalInput(echoChannel); - m_allocatedChannels = true; - m_units = units; - Initialize(); +Ultrasonic::Ultrasonic(uint32_t pingChannel, uint32_t echoChannel, + DistanceUnit units) { + m_pingChannel = new DigitalOutput(pingChannel); + m_echoChannel = new DigitalInput(echoChannel); + m_allocatedChannels = true; + m_units = units; + Initialize(); } /** - * Create an instance of an Ultrasonic Sensor from a DigitalInput for the echo channel and a DigitalOutput + * Create an instance of an Ultrasonic Sensor from a DigitalInput for the echo + * channel and a DigitalOutput * for the ping channel. - * @param pingChannel The digital output object that starts the sensor doing a ping. Requires a 10uS pulse to start. - * @param echoChannel The digital input object that times the return pulse to determine the range. + * @param pingChannel The digital output object that starts the sensor doing a + * ping. Requires a 10uS pulse to start. + * @param echoChannel The digital input object that times the return pulse to + * determine the range. * @param units The units returned in either kInches or kMilliMeters */ -Ultrasonic::Ultrasonic(DigitalOutput *pingChannel, DigitalInput *echoChannel, DistanceUnit units) -{ - if (pingChannel == NULL || echoChannel == NULL) - { - wpi_setWPIError(NullParameter); - return; - } - m_allocatedChannels = false; - m_pingChannel = pingChannel; - m_echoChannel = echoChannel; - m_units = units; - Initialize(); +Ultrasonic::Ultrasonic(DigitalOutput *pingChannel, DigitalInput *echoChannel, + DistanceUnit units) { + if (pingChannel == NULL || echoChannel == NULL) { + wpi_setWPIError(NullParameter); + return; + } + m_allocatedChannels = false; + m_pingChannel = pingChannel; + m_echoChannel = echoChannel; + m_units = units; + Initialize(); } /** - * Create an instance of an Ultrasonic Sensor from a DigitalInput for the echo channel and a DigitalOutput + * Create an instance of an Ultrasonic Sensor from a DigitalInput for the echo + * channel and a DigitalOutput * for the ping channel. - * @param pingChannel The digital output object that starts the sensor doing a ping. Requires a 10uS pulse to start. - * @param echoChannel The digital input object that times the return pulse to determine the range. + * @param pingChannel The digital output object that starts the sensor doing a + * ping. Requires a 10uS pulse to start. + * @param echoChannel The digital input object that times the return pulse to + * determine the range. * @param units The units returned in either kInches or kMilliMeters */ -Ultrasonic::Ultrasonic(DigitalOutput &pingChannel, DigitalInput &echoChannel, DistanceUnit units) -{ - m_allocatedChannels = false; - m_pingChannel = &pingChannel; - m_echoChannel = &echoChannel; - m_units = units; - Initialize(); +Ultrasonic::Ultrasonic(DigitalOutput &pingChannel, DigitalInput &echoChannel, + DistanceUnit units) { + m_allocatedChannels = false; + m_pingChannel = &pingChannel; + m_echoChannel = &echoChannel; + m_units = units; + Initialize(); } /** * Destructor for the ultrasonic sensor. - * Delete the instance of the ultrasonic sensor by freeing the allocated digital channels. - * If the system was in automatic mode (round robin), then it is stopped, then started again + * Delete the instance of the ultrasonic sensor by freeing the allocated digital + * channels. + * If the system was in automatic mode (round robin), then it is stopped, then + * started again * after this sensor is removed (provided this wasn't the last sensor). */ -Ultrasonic::~Ultrasonic() -{ - bool wasAutomaticMode = m_automaticEnabled; - SetAutomaticMode(false); - if (m_allocatedChannels) - { - delete m_pingChannel; - delete m_echoChannel; - } - wpi_assert(m_firstSensor != NULL); +Ultrasonic::~Ultrasonic() { + bool wasAutomaticMode = m_automaticEnabled; + SetAutomaticMode(false); + if (m_allocatedChannels) { + delete m_pingChannel; + delete m_echoChannel; + } + wpi_assert(m_firstSensor != NULL); - takeSemaphore(m_semaphore); - { - if (this == m_firstSensor) - { - m_firstSensor = m_nextSensor; - if (m_firstSensor == NULL) - { - SetAutomaticMode(false); - } - } - else - { - wpi_assert(m_firstSensor->m_nextSensor != NULL); - for (Ultrasonic *s = m_firstSensor; s != NULL; s = s->m_nextSensor) - { - if (this == s->m_nextSensor) - { - s->m_nextSensor = s->m_nextSensor->m_nextSensor; - break; - } - } - } - } - giveSemaphore(m_semaphore); - if (m_firstSensor != NULL && wasAutomaticMode) - SetAutomaticMode(true); + takeSemaphore(m_semaphore); + { + if (this == m_firstSensor) { + m_firstSensor = m_nextSensor; + if (m_firstSensor == NULL) { + SetAutomaticMode(false); + } + } else { + wpi_assert(m_firstSensor->m_nextSensor != NULL); + for (Ultrasonic *s = m_firstSensor; s != NULL; s = s->m_nextSensor) { + if (this == s->m_nextSensor) { + s->m_nextSensor = s->m_nextSensor->m_nextSensor; + break; + } + } + } + } + giveSemaphore(m_semaphore); + if (m_firstSensor != NULL && wasAutomaticMode) SetAutomaticMode(true); } /** * Turn Automatic mode on/off. * When in Automatic mode, all sensors will fire in round robin, waiting a set * time between each sensor. - * @param enabling Set to true if round robin scheduling should start for all the ultrasonic sensors. This - * scheduling method assures that the sensors are non-interfering because no two sensors fire at the same time. - * If another scheduling algorithm is preffered, it can be implemented by pinging the sensors manually and waiting + * @param enabling Set to true if round robin scheduling should start for all + * the ultrasonic sensors. This + * scheduling method assures that the sensors are non-interfering because no two + * sensors fire at the same time. + * If another scheduling algorithm is preffered, it can be implemented by + * pinging the sensors manually and waiting * for the results to come back. */ -void Ultrasonic::SetAutomaticMode(bool enabling) -{ - if (enabling == m_automaticEnabled) - return; // ignore the case of no change +void Ultrasonic::SetAutomaticMode(bool enabling) { + if (enabling == m_automaticEnabled) return; // ignore the case of no change - m_automaticEnabled = enabling; - if (enabling) - { - // enabling automatic mode. - // Clear all the counters so no data is valid - for (Ultrasonic *u = m_firstSensor; u != NULL; u = u->m_nextSensor) - { - u->m_counter->Reset(); - } - // Start round robin task - wpi_assert(m_task.Verify() == false); // should be false since was previously disabled - m_task.Start(); - } - else - { - // disabling automatic mode. Wait for background task to stop running. - while (m_task.Verify()) - Wait(0.15); // just a little longer than the ping time for round-robin to stop + m_automaticEnabled = enabling; + if (enabling) { + // enabling automatic mode. + // Clear all the counters so no data is valid + for (Ultrasonic *u = m_firstSensor; u != NULL; u = u->m_nextSensor) { + u->m_counter->Reset(); + } + // Start round robin task + wpi_assert(m_task.Verify() == + false); // should be false since was previously disabled + m_task.Start(); + } else { + // disabling automatic mode. Wait for background task to stop running. + while (m_task.Verify()) + Wait(0.15); // just a little longer than the ping time for round-robin to + // stop - // clear all the counters (data now invalid) since automatic mode is stopped - for (Ultrasonic *u = m_firstSensor; u != NULL; u = u->m_nextSensor) - { - u->m_counter->Reset(); - } - m_task.Stop(); - } + // clear all the counters (data now invalid) since automatic mode is stopped + for (Ultrasonic *u = m_firstSensor; u != NULL; u = u->m_nextSensor) { + u->m_counter->Reset(); + } + m_task.Stop(); + } } /** * Single ping to ultrasonic sensor. - * Send out a single ping to the ultrasonic sensor. This only works if automatic (round robin) - * mode is disabled. A single ping is sent out, and the counter should count the semi-period + * Send out a single ping to the ultrasonic sensor. This only works if automatic + * (round robin) + * mode is disabled. A single ping is sent out, and the counter should count the + * semi-period * when it comes in. The counter is reset to make the current value invalid. */ -void Ultrasonic::Ping() -{ - wpi_assert(!m_automaticEnabled); - m_counter->Reset(); // reset the counter to zero (invalid data now) - m_pingChannel->Pulse(kPingTime); // do the ping to start getting a single range +void Ultrasonic::Ping() { + wpi_assert(!m_automaticEnabled); + m_counter->Reset(); // reset the counter to zero (invalid data now) + m_pingChannel->Pulse( + kPingTime); // do the ping to start getting a single range } /** * Check if there is a valid range measurement. - * The ranges are accumulated in a counter that will increment on each edge of the echo (return) - * signal. If the count is not at least 2, then the range has not yet been measured, and is invalid. + * The ranges are accumulated in a counter that will increment on each edge of + * the echo (return) + * signal. If the count is not at least 2, then the range has not yet been + * measured, and is invalid. */ -bool Ultrasonic::IsRangeValid() const -{ - return m_counter->Get() > 1; -} +bool Ultrasonic::IsRangeValid() const { return m_counter->Get() > 1; } /** * Get the range in inches from the ultrasonic sensor. - * @return double Range in inches of the target returned from the ultrasonic sensor. If there is - * no valid value yet, i.e. at least one measurement hasn't completed, then return 0. + * @return double Range in inches of the target returned from the ultrasonic + * sensor. If there is + * no valid value yet, i.e. at least one measurement hasn't completed, then + * return 0. */ -double Ultrasonic::GetRangeInches() const -{ - if (IsRangeValid()) - return m_counter->GetPeriod() * kSpeedOfSoundInchesPerSec / 2.0; - else - return 0; +double Ultrasonic::GetRangeInches() const { + if (IsRangeValid()) + return m_counter->GetPeriod() * kSpeedOfSoundInchesPerSec / 2.0; + else + return 0; } /** * Get the range in millimeters from the ultrasonic sensor. - * @return double Range in millimeters of the target returned by the ultrasonic sensor. - * If there is no valid value yet, i.e. at least one measurement hasn't complted, then return 0. + * @return double Range in millimeters of the target returned by the ultrasonic + * sensor. + * If there is no valid value yet, i.e. at least one measurement hasn't + * complted, then return 0. */ -double Ultrasonic::GetRangeMM() const -{ - return GetRangeInches() * 25.4; -} +double Ultrasonic::GetRangeMM() const { return GetRangeInches() * 25.4; } /** * Get the range in the current DistanceUnit for the PIDSource base object. * * @return The range in DistanceUnit */ -double Ultrasonic::PIDGet() const -{ - switch(m_units) - { - case Ultrasonic::kInches: - return GetRangeInches(); - case Ultrasonic::kMilliMeters: - return GetRangeMM(); - default: - return 0.0; - } +double Ultrasonic::PIDGet() const { + switch (m_units) { + case Ultrasonic::kInches: + return GetRangeInches(); + case Ultrasonic::kMilliMeters: + return GetRangeMM(); + default: + return 0.0; + } } /** - * Set the current DistanceUnit that should be used for the PIDSource base object. + * Set the current DistanceUnit that should be used for the PIDSource base + * object. * * @param units The DistanceUnit that should be used. */ -void Ultrasonic::SetDistanceUnits(DistanceUnit units) -{ - m_units = units; -} +void Ultrasonic::SetDistanceUnits(DistanceUnit units) { m_units = units; } /** * Get the current DistanceUnit that is used for the PIDSource base object. * * @return The type of DistanceUnit that is being used. */ -Ultrasonic::DistanceUnit Ultrasonic::GetDistanceUnits() const -{ - return m_units; +Ultrasonic::DistanceUnit Ultrasonic::GetDistanceUnits() const { + return m_units; } void Ultrasonic::UpdateTable() { - if (m_table != NULL) { - m_table->PutNumber("Value", GetRangeInches()); - } + if (m_table != NULL) { + m_table->PutNumber("Value", GetRangeInches()); + } } -void Ultrasonic::StartLiveWindowMode() { +void Ultrasonic::StartLiveWindowMode() {} -} +void Ultrasonic::StopLiveWindowMode() {} -void Ultrasonic::StopLiveWindowMode() { - -} - -std::string Ultrasonic::GetSmartDashboardType() const { - return "Ultrasonic"; -} +std::string Ultrasonic::GetSmartDashboardType() const { return "Ultrasonic"; } void Ultrasonic::InitTable(ITable *subTable) { - m_table = subTable; - UpdateTable(); + m_table = subTable; + UpdateTable(); } -ITable * Ultrasonic::GetTable() const { - return m_table; -} +ITable *Ultrasonic::GetTable() const { return m_table; } diff --git a/wpilibc/wpilibC++Devices/src/Utility.cpp b/wpilibc/wpilibC++Devices/src/Utility.cpp index d94472b7b8..ee8b5e6ad4 100644 --- a/wpilibc/wpilibC++Devices/src/Utility.cpp +++ b/wpilibc/wpilibC++Devices/src/Utility.cpp @@ -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. */ /*----------------------------------------------------------------------------*/ @@ -23,154 +24,130 @@ static bool suspendOnAssertEnabled = false; /** * Enable suspend on assert. * If enabled, the user task will be suspended whenever an assert fails. This - * will allow the user to attach to the task with the debugger and examine variables + * will allow the user to attach to the task with the debugger and examine + * variables * around the failure. */ -void wpi_suspendOnAssertEnabled(bool enabled) -{ - suspendOnAssertEnabled = enabled; +void wpi_suspendOnAssertEnabled(bool enabled) { + suspendOnAssertEnabled = enabled; } /** * Assert implementation. * This allows breakpoints to be set on an assert. - * The users don't call this, but instead use the wpi_assert macros in Utility.h. + * The users don't call this, but instead use the wpi_assert macros in + * Utility.h. */ -bool wpi_assert_impl(bool conditionValue, - const char *conditionText, - const char *message, - const char *fileName, - uint32_t lineNumber, - const char *funcName) -{ - if(!conditionValue) - { - std::stringstream errorStream; +bool wpi_assert_impl(bool conditionValue, const char *conditionText, + const char *message, const char *fileName, + uint32_t lineNumber, const char *funcName) { + if (!conditionValue) { + std::stringstream errorStream; - errorStream << "Assertion \"" << conditionText << "\" "; - errorStream << "on line " << lineNumber << " "; - errorStream << "of "<< basename(fileName) << " "; + errorStream << "Assertion \"" << conditionText << "\" "; + errorStream << "on line " << lineNumber << " "; + errorStream << "of " << basename(fileName) << " "; - if(message) - { - errorStream << "failed: " << message << std::endl; - } - else - { - errorStream << "failed." << std::endl; - } + if (message) { + errorStream << "failed: " << message << std::endl; + } else { + errorStream << "failed." << std::endl; + } - errorStream << GetStackTrace(2); + errorStream << GetStackTrace(2); - std::string error = errorStream.str(); + std::string error = errorStream.str(); - // Print the error and send it to the DriverStation - std::cout << error << std::endl; - HALSetErrorData(error.c_str(), error.size(), 100); + // Print the error and send it to the DriverStation + std::cout << error << std::endl; + HALSetErrorData(error.c_str(), error.size(), 100); - if (suspendOnAssertEnabled) suspendTask(0); - } + if (suspendOnAssertEnabled) suspendTask(0); + } - return conditionValue; + return conditionValue; } /** * Common error routines for wpi_assertEqual_impl and wpi_assertNotEqual_impl - * This should not be called directly; it should only be used by wpi_assertEqual_impl + * This should not be called directly; it should only be used by + * wpi_assertEqual_impl * and wpi_assertNotEqual_impl. */ -void wpi_assertEqual_common_impl(const char *valueA, - const char *valueB, - const char *equalityType, - const char *message, - const char *fileName, - uint32_t lineNumber, - const char *funcName) -{ - std::stringstream errorStream; +void wpi_assertEqual_common_impl(const char *valueA, const char *valueB, + const char *equalityType, const char *message, + const char *fileName, uint32_t lineNumber, + const char *funcName) { + std::stringstream errorStream; - errorStream << "Assertion \"" << valueA << " " << equalityType << " " << valueB << "\" "; - errorStream << "on line " << lineNumber << " "; - errorStream << "of "<< basename(fileName) << " "; + errorStream << "Assertion \"" << valueA << " " << equalityType << " " + << valueB << "\" "; + errorStream << "on line " << lineNumber << " "; + errorStream << "of " << basename(fileName) << " "; - if(message) - { - errorStream << "failed: " << message << std::endl; - } - else - { - errorStream << "failed." << std::endl; - } + if (message) { + errorStream << "failed: " << message << std::endl; + } else { + errorStream << "failed." << std::endl; + } - errorStream << GetStackTrace(3); + errorStream << GetStackTrace(3); - std::string error = errorStream.str(); + std::string error = errorStream.str(); - // Print the error and send it to the DriverStation - std::cout << error << std::endl; - HALSetErrorData(error.c_str(), error.size(), 100); + // Print the error and send it to the DriverStation + std::cout << error << std::endl; + HALSetErrorData(error.c_str(), error.size(), 100); - if (suspendOnAssertEnabled) suspendTask(0); + if (suspendOnAssertEnabled) suspendTask(0); } /** * Assert equal implementation. * This determines whether the two given integers are equal. If not, * the value of each is printed along with an optional message string. - * The users don't call this, but instead use the wpi_assertEqual macros in Utility.h. + * The users don't call this, but instead use the wpi_assertEqual macros in + * Utility.h. */ -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) -{ - if(!(valueA == valueB)) - { - wpi_assertEqual_common_impl(valueAString, valueBString, - "==", message, fileName, lineNumber, funcName); - } - return valueA == valueB; +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) { + if (!(valueA == valueB)) { + wpi_assertEqual_common_impl(valueAString, valueBString, "==", message, + fileName, lineNumber, funcName); + } + return valueA == valueB; } /** * Assert not equal implementation. * This determines whether the two given integers are equal. If so, * the value of each is printed along with an optional message string. - * The users don't call this, but instead use the wpi_assertNotEqual macros in Utility.h. + * The users don't call this, but instead use the wpi_assertNotEqual macros in + * Utility.h. */ -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) -{ - if(!(valueA != valueB)) - { - wpi_assertEqual_common_impl(valueAString, valueBString, - "!=", message, fileName, lineNumber, funcName); - } - return valueA != valueB; +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) { + if (!(valueA != valueB)) { + wpi_assertEqual_common_impl(valueAString, valueBString, "!=", message, + fileName, lineNumber, funcName); + } + return valueA != valueB; } - /** * Return the FPGA Version number. * For now, expect this to be competition year. * @return FPGA Version number. */ -uint16_t GetFPGAVersion() -{ - int32_t status = 0; - uint16_t version = getFPGAVersion(&status); - wpi_setGlobalErrorWithContext(status, getHALErrorMessage(status)); - return version; +uint16_t GetFPGAVersion() { + int32_t status = 0; + uint16_t version = getFPGAVersion(&status); + wpi_setGlobalErrorWithContext(status, getHALErrorMessage(status)); + return version; } /** @@ -181,91 +158,80 @@ uint16_t GetFPGAVersion() * The 12 least significant bits are the Build Number. * @return FPGA Revision number. */ -uint32_t GetFPGARevision() -{ - int32_t status = 0; - uint32_t revision = getFPGARevision(&status); - wpi_setGlobalErrorWithContext(status, getHALErrorMessage(status)); - return revision; +uint32_t GetFPGARevision() { + int32_t status = 0; + uint32_t revision = getFPGARevision(&status); + wpi_setGlobalErrorWithContext(status, getHALErrorMessage(status)); + return revision; } /** * Read the microsecond-resolution timer on the FPGA. * - * @return The current time in microseconds according to the FPGA (since FPGA reset). + * @return The current time in microseconds according to the FPGA (since FPGA + * reset). */ -uint32_t GetFPGATime() -{ - int32_t status = 0; - uint32_t time = getFPGATime(&status); - wpi_setGlobalErrorWithContext(status, getHALErrorMessage(status)); - return time; +uint32_t GetFPGATime() { + int32_t status = 0; + uint32_t time = getFPGATime(&status); + wpi_setGlobalErrorWithContext(status, getHALErrorMessage(status)); + return time; } /** * Get the state of the "USER" button on the RoboRIO * @return True if the button is currently pressed down */ -bool GetUserButton() -{ - int32_t status = 0; +bool GetUserButton() { + int32_t status = 0; - bool value = getFPGAButton(&status); - wpi_setGlobalError(status); + bool value = getFPGAButton(&status); + wpi_setGlobalError(status); - return value; + return value; } /** * Demangle a C++ symbol, used for printing stack traces. */ -static std::string demangle(char const *mangledSymbol) -{ - char buffer[256]; - size_t length; - int status; +static std::string demangle(char const *mangledSymbol) { + char buffer[256]; + size_t length; + int status; + if (sscanf(mangledSymbol, "%*[^(]%*[(]%255[^)+]", buffer)) { + char *symbol = abi::__cxa_demangle(buffer, NULL, &length, &status); + if (status == 0) { + return symbol; + } else { + // If the symbol couldn't be demangled, it's probably a C function, + // so just return it as-is. + return buffer; + } + } - if(sscanf(mangledSymbol, "%*[^(]%*[(]%255[^)+]", buffer)) - { - char *symbol = abi::__cxa_demangle(buffer, NULL, &length, &status); - if(status == 0) - { - return symbol; - } - else - { - // If the symbol couldn't be demangled, it's probably a C function, - // so just return it as-is. - return buffer; - } - } - - // If everything else failed, just return the mangled symbol - return mangledSymbol; + // If everything else failed, just return the mangled symbol + return mangledSymbol; } /** * Get a stack trace, ignoring the first "offset" symbols. * @param offset The number of symbols at the top of the stack to ignore */ -std::string GetStackTrace(uint32_t offset) -{ - void *stackTrace[128]; - int stackSize = backtrace(stackTrace, 128); - char **mangledSymbols = backtrace_symbols(stackTrace, stackSize); - std::stringstream trace; +std::string GetStackTrace(uint32_t offset) { + void *stackTrace[128]; + int stackSize = backtrace(stackTrace, 128); + char **mangledSymbols = backtrace_symbols(stackTrace, stackSize); + std::stringstream trace; - for(int i = offset; i < stackSize; i++) - { - // Only print recursive functions once in a row. - if(i == 0 ||stackTrace[i] != stackTrace[i - 1]) - { - trace << "\tat " << demangle(mangledSymbols[i]) << std::endl; - } - } + for (int i = offset; i < stackSize; i++) { + // Only print recursive functions once in a row. + if (i == 0 || stackTrace[i] != stackTrace[i - 1]) { + trace << "\tat " << demangle(mangledSymbols[i]) << std::endl; + } + } - free(mangledSymbols); + free(mangledSymbols); - return trace.str(); + return trace.str(); } diff --git a/wpilibc/wpilibC++Devices/src/Victor.cpp b/wpilibc/wpilibC++Devices/src/Victor.cpp index 997783168d..63b6c8b30c 100644 --- a/wpilibc/wpilibC++Devices/src/Victor.cpp +++ b/wpilibc/wpilibC++Devices/src/Victor.cpp @@ -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,11 +13,16 @@ /** * Common initialization code called by all constructors. * - * Note that the Victor uses the following bounds for PWM values. These values were determined - * empirically and optimized for the Victor 888. These values should work reasonably well for - * Victor 884 controllers as well but if users experience issues such as asymmetric behaviour around - * the deadband or inability to saturate the controller in either direction, calibration is recommended. - * The calibration procedure can be found in the Victor 884 User Manual available from IFI. + * Note that the Victor uses the following bounds for PWM values. These values + * were determined + * empirically and optimized for the Victor 888. These values should work + * reasonably well for + * Victor 884 controllers as well but if users experience issues such as + * asymmetric behaviour around + * the deadband or inability to saturate the controller in either direction, + * calibration is recommended. + * The calibration procedure can be found in the Victor 884 User Manual + * available from IFI. * * 2.027ms = full "forward" * 1.525ms = the "high end" of the deadband range @@ -25,29 +31,25 @@ * 1.026ms = full "reverse" */ void Victor::InitVictor() { - SetBounds(2.027, 1.525, 1.507, 1.49, 1.026); + SetBounds(2.027, 1.525, 1.507, 1.49, 1.026); - SetPeriodMultiplier(kPeriodMultiplier_2X); - SetRaw(m_centerPwm); - SetZeroLatch(); + SetPeriodMultiplier(kPeriodMultiplier_2X); + SetRaw(m_centerPwm); + SetZeroLatch(); - LiveWindow::GetInstance()->AddActuator("Victor", GetChannel(), this); - HALReport(HALUsageReporting::kResourceType_Victor, GetChannel()); - m_isInverted = false; + LiveWindow::GetInstance()->AddActuator("Victor", GetChannel(), this); + HALReport(HALUsageReporting::kResourceType_Victor, GetChannel()); + m_isInverted = false; } /** * Constructor for a Victor - * @param channel The PWM channel number that the Victor is attached to. 0-9 are on-board, 10-19 are on the MXP port + * @param channel The PWM channel number that the Victor is attached to. 0-9 are + * on-board, 10-19 are on the MXP port */ -Victor::Victor(uint32_t channel) : SafePWM(channel) -{ - InitVictor(); -} +Victor::Victor(uint32_t channel) : SafePWM(channel) { InitVictor(); } -Victor::~Victor() -{ -} +Victor::~Victor() {} /** * Set the PWM value. @@ -58,9 +60,8 @@ Victor::~Victor() * @param speed The speed value between -1.0 and 1.0 to set. * @param syncGroup Unused interface. */ -void Victor::Set(float speed, uint8_t syncGroup) -{ - SetSpeed(m_isInverted ? -speed: speed); +void Victor::Set(float speed, uint8_t syncGroup) { + SetSpeed(m_isInverted ? -speed : speed); } /** @@ -68,25 +69,17 @@ void Victor::Set(float speed, uint8_t syncGroup) * * @return The most recently set value for the PWM between -1.0 and 1.0. */ -float Victor::Get() const -{ - return GetSpeed(); -} +float Victor::Get() const { return GetSpeed(); } /** * Common interface for disabling a motor. */ -void Victor::Disable() -{ - SetRaw(kPwmDisabled); -} +void Victor::Disable() { SetRaw(kPwmDisabled); } /** * Common interface for inverting direction of a speed controller. * @param isInverted The state of inversion, true is inverted. */ -void Victor::SetInverted(bool isInverted){ -m_isInverted = isInverted; -} +void Victor::SetInverted(bool isInverted) { m_isInverted = isInverted; } /** * Common interface for the inverting direction of a speed controller. @@ -94,16 +87,11 @@ m_isInverted = isInverted; * @return isInverted The state of inversion, true is inverted. * */ -bool Victor::GetInverted() const { - return m_isInverted; -} +bool Victor::GetInverted() const { return m_isInverted; } /** * Write out the PID value as seen in the PIDOutput base object. * * @param output Write out the PWM value as was found in the PIDController */ -void Victor::PIDWrite(float output) -{ - Set(output); -} +void Victor::PIDWrite(float output) { Set(output); } diff --git a/wpilibc/wpilibC++Devices/src/VictorSP.cpp b/wpilibc/wpilibC++Devices/src/VictorSP.cpp index 9d4d764ebf..0416061a2d 100644 --- a/wpilibc/wpilibC++Devices/src/VictorSP.cpp +++ b/wpilibc/wpilibC++Devices/src/VictorSP.cpp @@ -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,10 +13,14 @@ /** * Common initialization code called by all constructors. * - * Note that the VictorSP uses the following bounds for PWM values. These values should work reasonably well for - * most controllers, but if users experience issues such as asymmetric behavior around - * the deadband or inability to saturate the controller in either direction, calibration is recommended. - * The calibration procedure can be found in the VictorSP User Manual available from Vex. + * Note that the VictorSP uses the following bounds for PWM values. These values + * should work reasonably well for + * most controllers, but if users experience issues such as asymmetric behavior + * around + * the deadband or inability to saturate the controller in either direction, + * calibration is recommended. + * The calibration procedure can be found in the VictorSP User Manual available + * from Vex. * * 2.004ms = full "forward" * 1.52ms = the "high end" of the deadband range @@ -24,28 +29,24 @@ * 0.997ms = full "reverse" */ void VictorSP::InitVictorSP() { - SetBounds(2.004, 1.52, 1.50, 1.48, .997); - SetPeriodMultiplier(kPeriodMultiplier_1X); - SetRaw(m_centerPwm); - SetZeroLatch(); + SetBounds(2.004, 1.52, 1.50, 1.48, .997); + SetPeriodMultiplier(kPeriodMultiplier_1X); + SetRaw(m_centerPwm); + SetZeroLatch(); - HALReport(HALUsageReporting::kResourceType_VictorSP, GetChannel()); - LiveWindow::GetInstance()->AddActuator("VictorSP", GetChannel(), this); - m_isInverted = false; + HALReport(HALUsageReporting::kResourceType_VictorSP, GetChannel()); + LiveWindow::GetInstance()->AddActuator("VictorSP", GetChannel(), this); + m_isInverted = false; } /** * Constructor for a VictorSP - * @param channel The PWM channel that the VictorSP is attached to. 0-9 are on-board, 10-19 are on the MXP port + * @param channel The PWM channel that the VictorSP is attached to. 0-9 are + * on-board, 10-19 are on the MXP port */ -VictorSP::VictorSP(uint32_t channel) : SafePWM(channel) -{ - InitVictorSP(); -} +VictorSP::VictorSP(uint32_t channel) : SafePWM(channel) { InitVictorSP(); } -VictorSP::~VictorSP() -{ -} +VictorSP::~VictorSP() {} /** * Set the PWM value. @@ -56,9 +57,8 @@ VictorSP::~VictorSP() * @param speed The speed value between -1.0 and 1.0 to set. * @param syncGroup Unused interface. */ -void VictorSP::Set(float speed, uint8_t syncGroup) -{ - SetSpeed(m_isInverted ? -speed: speed); +void VictorSP::Set(float speed, uint8_t syncGroup) { + SetSpeed(m_isInverted ? -speed : speed); } /** @@ -66,18 +66,13 @@ void VictorSP::Set(float speed, uint8_t syncGroup) * * @return The most recently set value for the PWM between -1.0 and 1.0. */ -float VictorSP::Get() const -{ - return GetSpeed(); -} +float VictorSP::Get() const { return GetSpeed(); } /** * Common interface for inverting direction of a speed controller. * @param isInverted The state of inversion, true is inverted. */ -void VictorSP::SetInverted(bool isInverted){ -m_isInverted = isInverted; -} +void VictorSP::SetInverted(bool isInverted) { m_isInverted = isInverted; } /** * Common interface for the inverting direction of a speed controller. @@ -85,24 +80,16 @@ m_isInverted = isInverted; * @return isInverted The state of inversion, true is inverted. * */ -bool VictorSP::GetInverted() const { - return m_isInverted; -} +bool VictorSP::GetInverted() const { return m_isInverted; } /** * Common interface for disabling a motor. */ -void VictorSP::Disable() -{ - SetRaw(kPwmDisabled); -} +void VictorSP::Disable() { SetRaw(kPwmDisabled); } /** * Write out the PID value as seen in the PIDOutput base object. * * @param output Write out the PWM value as was found in the PIDController */ -void VictorSP::PIDWrite(float output) -{ - Set(output); -} +void VictorSP::PIDWrite(float output) { Set(output); } diff --git a/wpilibc/wpilibC++Devices/src/Vision/AxisCamera.cpp b/wpilibc/wpilibC++Devices/src/Vision/AxisCamera.cpp index 47658d0eee..babeeadd55 100644 --- a/wpilibc/wpilibC++Devices/src/Vision/AxisCamera.cpp +++ b/wpilibc/wpilibC++Devices/src/Vision/AxisCamera.cpp @@ -21,223 +21,213 @@ static const unsigned int kMaxPacketSize = 1536; static const unsigned int kImageBufferAllocationIncrement = 1000; -static const std::string kWhiteBalanceStrings[] = -{ "auto", "hold", "fixed_outdoor1", "fixed_outdoor2", "fixed_indoor", - "fixed_fluor1", "fixed_fluor2", }; +static const std::string kWhiteBalanceStrings[] = { + "auto", "hold", "fixed_outdoor1", "fixed_outdoor2", + "fixed_indoor", "fixed_fluor1", "fixed_fluor2", +}; -static const std::string kExposureControlStrings[] = -{ "auto", "hold", "flickerfree50", "flickerfree60", }; +static const std::string kExposureControlStrings[] = { + "auto", "hold", "flickerfree50", "flickerfree60", +}; -static const std::string kResolutionStrings[] = -{ "640x480", "480x360", "320x240", "240x180", "176x144", "160x120", }; +static const std::string kResolutionStrings[] = { + "640x480", "480x360", "320x240", "240x180", "176x144", "160x120", +}; -static const std::string kRotationStrings[] = -{ "0", "180", }; +static const std::string kRotationStrings[] = { + "0", "180", +}; /** * AxisCamera constructor * @param cameraHost The host to find the camera at, typically an IP address */ -AxisCamera::AxisCamera(std::string const& cameraHost) - : m_cameraHost(cameraHost) - , m_cameraSocket(-1) - , m_freshImage(false) - , m_brightness(50) - , m_whiteBalance(kWhiteBalance_Automatic) - , m_colorLevel(50) - , m_exposureControl(kExposureControl_Automatic) - , m_exposurePriority(50) - , m_maxFPS(0) - , m_resolution(kResolution_640x480) - , m_compression(50) - , m_rotation(kRotation_0) - , m_parametersDirty(true) - , m_streamDirty(true) - , m_done(false) -{ - m_captureThread = std::thread(&AxisCamera::Capture, this); +AxisCamera::AxisCamera(std::string const &cameraHost) + : m_cameraHost(cameraHost), + m_cameraSocket(-1), + m_freshImage(false), + m_brightness(50), + m_whiteBalance(kWhiteBalance_Automatic), + m_colorLevel(50), + m_exposureControl(kExposureControl_Automatic), + m_exposurePriority(50), + m_maxFPS(0), + m_resolution(kResolution_640x480), + m_compression(50), + m_rotation(kRotation_0), + m_parametersDirty(true), + m_streamDirty(true), + m_done(false) { + m_captureThread = std::thread(&AxisCamera::Capture, this); } -AxisCamera::~AxisCamera() -{ - m_done = true; - m_captureThread.join(); +AxisCamera::~AxisCamera() { + m_done = true; + m_captureThread.join(); } /* - * Return true if the latest image from the camera has not been retrieved by calling GetImage() yet. + * Return true if the latest image from the camera has not been retrieved by + * calling GetImage() yet. * @return true if the image has not been retrieved yet. */ -bool AxisCamera::IsFreshImage() const -{ - return m_freshImage; +bool AxisCamera::IsFreshImage() const { return m_freshImage; } + +/** + * Get an image from the camera and store it in the provided image. + * @param image The imaq image to store the result in. This must be an HSL or + * RGB image. + * @return 1 upon success, zero on a failure + */ +int AxisCamera::GetImage(Image *image) { + if (m_imageData.size() == 0) { + return 0; + } + + std::lock_guard lock(m_imageDataMutex); + + Priv_ReadJPEGString_C(image, m_imageData.data(), m_imageData.size()); + + m_freshImage = false; + + return 1; } /** * Get an image from the camera and store it in the provided image. - * @param image The imaq image to store the result in. This must be an HSL or RGB image. + * @param image The image to store the result in. This must be an HSL or RGB + * image * @return 1 upon success, zero on a failure */ -int AxisCamera::GetImage(Image *image) -{ - if (m_imageData.size() == 0) - { - return 0; - } - - std::lock_guard lock(m_imageDataMutex); - - Priv_ReadJPEGString_C(image, m_imageData.data(), m_imageData.size()); - - m_freshImage = false; - - return 1; +int AxisCamera::GetImage(ColorImage *image) { + return GetImage(image->GetImaqImage()); } /** - * Get an image from the camera and store it in the provided image. - * @param image The image to store the result in. This must be an HSL or RGB image - * @return 1 upon success, zero on a failure - */ -int AxisCamera::GetImage(ColorImage *image) -{ - return GetImage(image->GetImaqImage()); -} - -/** - * Instantiate a new image object and fill it with the latest image from the camera. + * Instantiate a new image object and fill it with the latest image from the + * camera. * - * The returned pointer is owned by the caller and is their responsibility to delete. + * The returned pointer is owned by the caller and is their responsibility to + * delete. * @return a pointer to an HSLImage object */ -HSLImage *AxisCamera::GetImage() -{ - HSLImage *image = new HSLImage(); - GetImage(image); - return image; +HSLImage *AxisCamera::GetImage() { + HSLImage *image = new HSLImage(); + GetImage(image); + return image; } /** * Copy an image into an existing buffer. * This copies an image into an existing buffer rather than creating a new image - * in memory. That way a new image is only allocated when the image being copied is + * in memory. That way a new image is only allocated when the image being copied + * is * larger than the destination. * This method is called by the PCVideoServer class. * @param imageData The destination image. * @param numBytes The size of the destination image. * @return 0 if failed (no source image or no memory), 1 if success. */ -int AxisCamera::CopyJPEG(char **destImage, unsigned int &destImageSize, unsigned int &destImageBufferSize) -{ - std::lock_guard lock(m_imageDataMutex); - if (destImage == NULL) - wpi_setWPIErrorWithContext(NullParameter, "destImage must not be NULL"); +int AxisCamera::CopyJPEG(char **destImage, unsigned int &destImageSize, + unsigned int &destImageBufferSize) { + std::lock_guard lock(m_imageDataMutex); + if (destImage == NULL) + wpi_setWPIErrorWithContext(NullParameter, "destImage must not be NULL"); - if (m_imageData.size() == 0) - return 0; // if no source image + if (m_imageData.size() == 0) return 0; // if no source image - if (destImageBufferSize < m_imageData.size()) // if current destination buffer too small - { - if (*destImage != NULL) delete [] *destImage; - destImageBufferSize = m_imageData.size() + kImageBufferAllocationIncrement; - *destImage = new char[destImageBufferSize]; - if (*destImage == NULL) return 0; - } - // copy this image into destination buffer - if (*destImage == NULL) - { - wpi_setWPIErrorWithContext(NullParameter, "*destImage must not be NULL"); - } - - std::copy(m_imageData.begin(), m_imageData.end(), *destImage); - destImageSize = m_imageData.size();; - return 1; + if (destImageBufferSize < + m_imageData.size()) // if current destination buffer too small + { + if (*destImage != NULL) delete[] * destImage; + destImageBufferSize = m_imageData.size() + kImageBufferAllocationIncrement; + *destImage = new char[destImageBufferSize]; + if (*destImage == NULL) return 0; + } + // copy this image into destination buffer + if (*destImage == NULL) { + wpi_setWPIErrorWithContext(NullParameter, "*destImage must not be NULL"); + } + + std::copy(m_imageData.begin(), m_imageData.end(), *destImage); + destImageSize = m_imageData.size(); + ; + return 1; } /** * Request a change in the brightness of the camera images. * @param brightness valid values 0 .. 100 */ -void AxisCamera::WriteBrightness(int brightness) -{ - if (brightness < 0 || brightness > 100) - { - wpi_setWPIErrorWithContext(ParameterOutOfRange, - "Brightness must be from 0 to 100"); - return; - } +void AxisCamera::WriteBrightness(int brightness) { + if (brightness < 0 || brightness > 100) { + wpi_setWPIErrorWithContext(ParameterOutOfRange, + "Brightness must be from 0 to 100"); + return; + } - std::lock_guard lock(m_parametersMutex); + std::lock_guard lock(m_parametersMutex); - if (m_brightness != brightness) - { - m_brightness = brightness; - m_parametersDirty = true; - } + if (m_brightness != brightness) { + m_brightness = brightness; + m_parametersDirty = true; + } } /** * @return The configured brightness of the camera images */ -int AxisCamera::GetBrightness() -{ - std::lock_guard lock(m_parametersMutex); - return m_brightness; +int AxisCamera::GetBrightness() { + std::lock_guard lock(m_parametersMutex); + return m_brightness; } /** * Request a change in the white balance on the camera. * @param whiteBalance Valid values from the WhiteBalance enum. */ -void AxisCamera::WriteWhiteBalance(AxisCamera::WhiteBalance whiteBalance) -{ - std::lock_guard lock(m_parametersMutex); +void AxisCamera::WriteWhiteBalance(AxisCamera::WhiteBalance whiteBalance) { + std::lock_guard lock(m_parametersMutex); - if (m_whiteBalance != whiteBalance) - { - m_whiteBalance = whiteBalance; - m_parametersDirty = true; - } + if (m_whiteBalance != whiteBalance) { + m_whiteBalance = whiteBalance; + m_parametersDirty = true; + } } /** * @return The configured white balances of the camera images */ -AxisCamera::WhiteBalance AxisCamera::GetWhiteBalance() -{ - std::lock_guard lock(m_parametersMutex); - return m_whiteBalance; +AxisCamera::WhiteBalance AxisCamera::GetWhiteBalance() { + std::lock_guard lock(m_parametersMutex); + return m_whiteBalance; } /** * Request a change in the color level of the camera images. * @param colorLevel valid values are 0 .. 100 */ -void AxisCamera::WriteColorLevel(int colorLevel) -{ - if (colorLevel < 0 || colorLevel > 100) - { - wpi_setWPIErrorWithContext(ParameterOutOfRange, - "Color level must be from 0 to 100"); - return; - } +void AxisCamera::WriteColorLevel(int colorLevel) { + if (colorLevel < 0 || colorLevel > 100) { + wpi_setWPIErrorWithContext(ParameterOutOfRange, + "Color level must be from 0 to 100"); + return; + } - std::lock_guard lock(m_parametersMutex); + std::lock_guard lock(m_parametersMutex); - if (m_colorLevel != colorLevel) - { - m_colorLevel = colorLevel; - m_parametersDirty = true; - } + if (m_colorLevel != colorLevel) { + m_colorLevel = colorLevel; + m_parametersDirty = true; + } } /** * @return The configured color level of the camera images */ -int AxisCamera::GetColorLevel() -{ - std::lock_guard lock(m_parametersMutex); - return m_colorLevel; +int AxisCamera::GetColorLevel() { + std::lock_guard lock(m_parametersMutex); + return m_colorLevel; } /** @@ -245,24 +235,21 @@ int AxisCamera::GetColorLevel() * @param exposureControl A mode to write in the Exposure enum. */ void AxisCamera::WriteExposureControl( - AxisCamera::ExposureControl exposureControl) -{ - std::lock_guard lock(m_parametersMutex); + AxisCamera::ExposureControl exposureControl) { + std::lock_guard lock(m_parametersMutex); - if (m_exposureControl != exposureControl) - { - m_exposureControl = exposureControl; - m_parametersDirty = true; - } + if (m_exposureControl != exposureControl) { + m_exposureControl = exposureControl; + m_parametersDirty = true; + } } /** * @return The configured exposure control mode of the camera */ -AxisCamera::ExposureControl AxisCamera::GetExposureControl() -{ - std::lock_guard lock(m_parametersMutex); - return m_exposureControl; +AxisCamera::ExposureControl AxisCamera::GetExposureControl() { + std::lock_guard lock(m_parametersMutex); + return m_exposureControl; } /** @@ -272,270 +259,241 @@ AxisCamera::ExposureControl AxisCamera::GetExposureControl() * 50 = None * 100 = Prioritize frame rate */ -void AxisCamera::WriteExposurePriority(int exposurePriority) -{ - if (exposurePriority != 0 && exposurePriority != 50 - && exposurePriority != 100) - { - wpi_setWPIErrorWithContext(ParameterOutOfRange, - "Exposure priority must be from 0, 50, or 100"); - return; - } +void AxisCamera::WriteExposurePriority(int exposurePriority) { + if (exposurePriority != 0 && exposurePriority != 50 && + exposurePriority != 100) { + wpi_setWPIErrorWithContext(ParameterOutOfRange, + "Exposure priority must be from 0, 50, or 100"); + return; + } - std::lock_guard lock(m_parametersMutex); + std::lock_guard lock(m_parametersMutex); - if (m_exposurePriority != exposurePriority) - { - m_exposurePriority = exposurePriority; - m_parametersDirty = true; - } + if (m_exposurePriority != exposurePriority) { + m_exposurePriority = exposurePriority; + m_parametersDirty = true; + } } /** * @return The configured exposure priority of the camera */ -int AxisCamera::GetExposurePriority() -{ - std::lock_guard lock(m_parametersMutex); - return m_exposurePriority; +int AxisCamera::GetExposurePriority() { + std::lock_guard lock(m_parametersMutex); + return m_exposurePriority; } /** * Write the maximum frames per second that the camera should send * Write 0 to send as many as possible. - * @param maxFPS The number of frames the camera should send in a second, exposure permitting. + * @param maxFPS The number of frames the camera should send in a second, + * exposure permitting. */ -void AxisCamera::WriteMaxFPS(int maxFPS) -{ - std::lock_guard lock(m_parametersMutex); +void AxisCamera::WriteMaxFPS(int maxFPS) { + std::lock_guard lock(m_parametersMutex); - if (m_maxFPS != maxFPS) - { - m_maxFPS = maxFPS; - m_parametersDirty = true; - m_streamDirty = true; - } + if (m_maxFPS != maxFPS) { + m_maxFPS = maxFPS; + m_parametersDirty = true; + m_streamDirty = true; + } } /** * @return The configured maximum FPS of the camera */ -int AxisCamera::GetMaxFPS() -{ - std::lock_guard lock(m_parametersMutex); - return m_maxFPS; +int AxisCamera::GetMaxFPS() { + std::lock_guard lock(m_parametersMutex); + return m_maxFPS; } /** * Write resolution value to camera. * @param resolution The camera resolution value to write to the camera. */ -void AxisCamera::WriteResolution(AxisCamera::Resolution resolution) -{ - std::lock_guard lock(m_parametersMutex); +void AxisCamera::WriteResolution(AxisCamera::Resolution resolution) { + std::lock_guard lock(m_parametersMutex); - if (m_resolution != resolution) - { - m_resolution = resolution; - m_parametersDirty = true; - m_streamDirty = true; - } + if (m_resolution != resolution) { + m_resolution = resolution; + m_parametersDirty = true; + m_streamDirty = true; + } } /** * @return The configured resolution of the camera (not necessarily the same * resolution as the most recent image, if it was changed recently.) */ -AxisCamera::Resolution AxisCamera::GetResolution() -{ - std::lock_guard lock(m_parametersMutex); - return m_resolution; +AxisCamera::Resolution AxisCamera::GetResolution() { + std::lock_guard lock(m_parametersMutex); + return m_resolution; } /** * Write the rotation value to the camera. * If you mount your camera upside down, use this to adjust the image for you. - * @param rotation The angle to rotate the camera (AxisCamera::Rotation::k0 + * @param rotation The angle to rotate the camera + * (AxisCamera::Rotation::k0 * or AxisCamera::Rotation::k180) */ -void AxisCamera::WriteRotation(AxisCamera::Rotation rotation) -{ - std::lock_guard lock(m_parametersMutex); +void AxisCamera::WriteRotation(AxisCamera::Rotation rotation) { + std::lock_guard lock(m_parametersMutex); - if (m_rotation != rotation) - { - m_rotation = rotation; - m_parametersDirty = true; - m_streamDirty = true; - } + if (m_rotation != rotation) { + m_rotation = rotation; + m_parametersDirty = true; + m_streamDirty = true; + } } /** * @return The configured rotation mode of the camera */ -AxisCamera::Rotation AxisCamera::GetRotation() -{ - std::lock_guard lock(m_parametersMutex); - return m_rotation; +AxisCamera::Rotation AxisCamera::GetRotation() { + std::lock_guard lock(m_parametersMutex); + return m_rotation; } /** * Write the compression value to the camera. * @param compression Values between 0 and 100. */ -void AxisCamera::WriteCompression(int compression) -{ - if (compression < 0 || compression > 100) - { - wpi_setWPIErrorWithContext(ParameterOutOfRange, - "Compression must be from 0 to 100"); - return; - } +void AxisCamera::WriteCompression(int compression) { + if (compression < 0 || compression > 100) { + wpi_setWPIErrorWithContext(ParameterOutOfRange, + "Compression must be from 0 to 100"); + return; + } - std::lock_guard lock(m_parametersMutex); + std::lock_guard lock(m_parametersMutex); - if (m_compression != compression) - { - m_compression = compression; - m_parametersDirty = true; - m_streamDirty = true; - } + if (m_compression != compression) { + m_compression = compression; + m_parametersDirty = true; + m_streamDirty = true; + } } /** * @return The configured compression level of the camera */ -int AxisCamera::GetCompression() -{ - std::lock_guard lock(m_parametersMutex); - return m_compression; +int AxisCamera::GetCompression() { + std::lock_guard lock(m_parametersMutex); + return m_compression; } /** * Method called in the capture thread to receive images from the camera */ -void AxisCamera::Capture() -{ - int consecutiveErrors = 0; +void AxisCamera::Capture() { + int consecutiveErrors = 0; - // Loop on trying to setup the camera connection. This happens in a background - // thread so it shouldn't effect the operation of user programs. - while (!m_done) - { - std::string requestString = "GET /mjpg/video.mjpg HTTP/1.1\n" - "User-Agent: HTTPStreamClient\n" - "Connection: Keep-Alive\n" - "Cache-Control: no-cache\n" - "Authorization: Basic RlJDOkZSQw==\n\n"; - m_captureMutex.lock(); - m_cameraSocket = CreateCameraSocket(requestString, consecutiveErrors > 5); - if (m_cameraSocket != -1) - { - ReadImagesFromCamera(); - consecutiveErrors = 0; - } - else - { - consecutiveErrors++; - } - m_captureMutex.unlock(); - Wait(0.5); - } + // Loop on trying to setup the camera connection. This happens in a background + // thread so it shouldn't effect the operation of user programs. + while (!m_done) { + std::string requestString = + "GET /mjpg/video.mjpg HTTP/1.1\n" + "User-Agent: HTTPStreamClient\n" + "Connection: Keep-Alive\n" + "Cache-Control: no-cache\n" + "Authorization: Basic RlJDOkZSQw==\n\n"; + m_captureMutex.lock(); + m_cameraSocket = CreateCameraSocket(requestString, consecutiveErrors > 5); + if (m_cameraSocket != -1) { + ReadImagesFromCamera(); + consecutiveErrors = 0; + } else { + consecutiveErrors++; + } + m_captureMutex.unlock(); + Wait(0.5); + } } /** * This function actually reads the images from the camera. */ -void AxisCamera::ReadImagesFromCamera() -{ - char *imgBuffer = NULL; - int imgBufferLength = 0; +void AxisCamera::ReadImagesFromCamera() { + char *imgBuffer = NULL; + int imgBufferLength = 0; - // TODO: these recv calls must be non-blocking. Otherwise if the camera - // fails during a read, the code hangs and never retries when the camera comes - // back up. + // TODO: these recv calls must be non-blocking. Otherwise if the camera + // fails during a read, the code hangs and never retries when the camera comes + // back up. - int counter = 2; - while (!m_done) - { - char initialReadBuffer[kMaxPacketSize] = ""; - char intermediateBuffer[1]; - char *trailingPtr = initialReadBuffer; - int trailingCounter = 0; - while (counter) - { - // TODO: fix me... this cannot be the most efficient way to approach this, reading one byte at a time. - if (recv(m_cameraSocket, intermediateBuffer, 1, 0) == -1) - { - wpi_setErrnoErrorWithContext("Failed to read image header"); - close(m_cameraSocket); - return; - } - strncat(initialReadBuffer, intermediateBuffer, 1); - // trailingCounter ensures that we start looking for the 4 byte string after - // there is at least 4 bytes total. Kind of obscure. - // look for 2 blank lines (\r\n) - if (NULL != strstr(trailingPtr, "\r\n\r\n")) - { - --counter; - } - if (++trailingCounter >= 4) - { - trailingPtr++; - } - } - counter = 1; - char *contentLength = strstr(initialReadBuffer, "Content-Length: "); - if (contentLength == NULL) - { - wpi_setWPIErrorWithContext(IncompatibleMode, - "No content-length token found in packet"); - close(m_cameraSocket); - return; - } - contentLength = contentLength + 16; // skip past "content length" - int readLength = atol(contentLength); // get the image byte count + int counter = 2; + while (!m_done) { + char initialReadBuffer[kMaxPacketSize] = ""; + char intermediateBuffer[1]; + char *trailingPtr = initialReadBuffer; + int trailingCounter = 0; + while (counter) { + // TODO: fix me... this cannot be the most efficient way to approach this, + // reading one byte at a time. + if (recv(m_cameraSocket, intermediateBuffer, 1, 0) == -1) { + wpi_setErrnoErrorWithContext("Failed to read image header"); + close(m_cameraSocket); + return; + } + strncat(initialReadBuffer, intermediateBuffer, 1); + // trailingCounter ensures that we start looking for the 4 byte string + // after + // there is at least 4 bytes total. Kind of obscure. + // look for 2 blank lines (\r\n) + if (NULL != strstr(trailingPtr, "\r\n\r\n")) { + --counter; + } + if (++trailingCounter >= 4) { + trailingPtr++; + } + } + counter = 1; + char *contentLength = strstr(initialReadBuffer, "Content-Length: "); + if (contentLength == NULL) { + wpi_setWPIErrorWithContext(IncompatibleMode, + "No content-length token found in packet"); + close(m_cameraSocket); + return; + } + contentLength = contentLength + 16; // skip past "content length" + int readLength = atol(contentLength); // get the image byte count - // Make sure buffer is large enough - if (imgBufferLength < readLength) - { - if (imgBuffer) - delete[] imgBuffer; - imgBufferLength = readLength + kImageBufferAllocationIncrement; - imgBuffer = new char[imgBufferLength]; - if (imgBuffer == NULL) - { - imgBufferLength = 0; - continue; - } - } + // Make sure buffer is large enough + if (imgBufferLength < readLength) { + if (imgBuffer) delete[] imgBuffer; + imgBufferLength = readLength + kImageBufferAllocationIncrement; + imgBuffer = new char[imgBufferLength]; + if (imgBuffer == NULL) { + imgBufferLength = 0; + continue; + } + } - // Read the image data for "Content-Length" bytes - int bytesRead = 0; - int remaining = readLength; - while (bytesRead < readLength) - { - int bytesThisRecv = recv(m_cameraSocket, &imgBuffer[bytesRead], - remaining, 0); - bytesRead += bytesThisRecv; - remaining -= bytesThisRecv; - } + // Read the image data for "Content-Length" bytes + int bytesRead = 0; + int remaining = readLength; + while (bytesRead < readLength) { + int bytesThisRecv = + recv(m_cameraSocket, &imgBuffer[bytesRead], remaining, 0); + bytesRead += bytesThisRecv; + remaining -= bytesThisRecv; + } - // Update image - { - std::lock_guard lock(m_imageDataMutex); + // Update image + { + std::lock_guard lock(m_imageDataMutex); - m_imageData.assign(imgBuffer, imgBuffer + imgBufferLength); - m_freshImage = true; - } + m_imageData.assign(imgBuffer, imgBuffer + imgBufferLength); + m_freshImage = true; + } - if (WriteParameters()) - { - break; - } - } + if (WriteParameters()) { + break; + } + } - close(m_cameraSocket); + close(m_cameraSocket); } /** @@ -550,96 +508,96 @@ void AxisCamera::ReadImagesFromCamera() * @return true if the stream should be restarted due to a * parameter changing. */ -bool AxisCamera::WriteParameters() -{ - if (m_parametersDirty) - { - std::stringstream request; - request << "GET /axis-cgi/admin/param.cgi?action=update"; +bool AxisCamera::WriteParameters() { + if (m_parametersDirty) { + std::stringstream request; + request << "GET /axis-cgi/admin/param.cgi?action=update"; - m_parametersMutex.lock(); - request << "&ImageSource.I0.Sensor.Brightness=" << m_brightness; - request << "&ImageSource.I0.Sensor.WhiteBalance=" << kWhiteBalanceStrings[m_whiteBalance]; - request << "&ImageSource.I0.Sensor.ColorLevel=" << m_colorLevel; - request << "&ImageSource.I0.Sensor.Exposure=" << kExposureControlStrings[m_exposureControl]; - request << "&ImageSource.I0.Sensor.ExposurePriority=" << m_exposurePriority; - request << "&Image.I0.Stream.FPS=" << m_maxFPS; - request << "&Image.I0.Appearance.Resolution=" << kResolutionStrings[m_resolution]; - request << "&Image.I0.Appearance.Compression=" << m_compression; - request << "&Image.I0.Appearance.Rotation=" << kRotationStrings[m_rotation]; - m_parametersMutex.unlock(); + m_parametersMutex.lock(); + request << "&ImageSource.I0.Sensor.Brightness=" << m_brightness; + request << "&ImageSource.I0.Sensor.WhiteBalance=" + << kWhiteBalanceStrings[m_whiteBalance]; + request << "&ImageSource.I0.Sensor.ColorLevel=" << m_colorLevel; + request << "&ImageSource.I0.Sensor.Exposure=" + << kExposureControlStrings[m_exposureControl]; + request << "&ImageSource.I0.Sensor.ExposurePriority=" << m_exposurePriority; + request << "&Image.I0.Stream.FPS=" << m_maxFPS; + request << "&Image.I0.Appearance.Resolution=" + << kResolutionStrings[m_resolution]; + request << "&Image.I0.Appearance.Compression=" << m_compression; + request << "&Image.I0.Appearance.Rotation=" << kRotationStrings[m_rotation]; + m_parametersMutex.unlock(); - request << " HTTP/1.1" << std::endl; - request << "User-Agent: HTTPStreamClient" << std::endl; - request << "Connection: Keep-Alive" << std::endl; - request << "Cache-Control: no-cache" << std::endl; - request << "Authorization: Basic RlJDOkZSQw==" << std::endl; - request << std::endl; + request << " HTTP/1.1" << std::endl; + request << "User-Agent: HTTPStreamClient" << std::endl; + request << "Connection: Keep-Alive" << std::endl; + request << "Cache-Control: no-cache" << std::endl; + request << "Authorization: Basic RlJDOkZSQw==" << std::endl; + request << std::endl; - int socket = CreateCameraSocket(request.str(), false); - if (socket == -1) - { - wpi_setErrnoErrorWithContext("Error setting camera parameters"); - } - else - { - close(socket); - m_parametersDirty = false; + int socket = CreateCameraSocket(request.str(), false); + if (socket == -1) { + wpi_setErrnoErrorWithContext("Error setting camera parameters"); + } else { + close(socket); + m_parametersDirty = false; - if (m_streamDirty) - { - m_streamDirty = false; - return true; - } - } - } + if (m_streamDirty) { + m_streamDirty = false; + return true; + } + } + } - return false; + return false; } /** * Create a socket connected to camera - * Used to create a connection to the camera for both capturing images and setting parameters. - * @param requestString The initial request string to send upon successful connection. - * @param setError If true, rais an error if there's a problem creating the connection. - * This is only enabled after several unsucessful connections, so a single one doesn't + * Used to create a connection to the camera for both capturing images and + * setting parameters. + * @param requestString The initial request string to send upon successful + * connection. + * @param setError If true, rais an error if there's a problem creating the + * connection. + * This is only enabled after several unsucessful connections, so a single one + * doesn't * cause an error message to be printed if it immediately recovers. * @return -1 if failed, socket handle if successful. */ -int AxisCamera::CreateCameraSocket(std::string const& requestString, bool setError) -{ - struct addrinfo *address = 0; - int camSocket; +int AxisCamera::CreateCameraSocket(std::string const &requestString, + bool setError) { + struct addrinfo *address = 0; + int camSocket; - /* create socket */ - if ((camSocket = socket(AF_INET, SOCK_STREAM, 0)) == -1) - { - if (setError) wpi_setErrnoErrorWithContext("Failed to create the camera socket"); - return -1; - } + /* create socket */ + if ((camSocket = socket(AF_INET, SOCK_STREAM, 0)) == -1) { + if (setError) + wpi_setErrnoErrorWithContext("Failed to create the camera socket"); + return -1; + } - if (getaddrinfo(m_cameraHost.c_str(), "80", 0, &address) == -1) - { - if (setError) wpi_setErrnoErrorWithContext("Failed to create the camera socket"); - return -1; - } + if (getaddrinfo(m_cameraHost.c_str(), "80", 0, &address) == -1) { + if (setError) + wpi_setErrnoErrorWithContext("Failed to create the camera socket"); + return -1; + } - /* connect to server */ - if (connect(camSocket, address->ai_addr, address->ai_addrlen) == -1) - { - if (setError) wpi_setErrnoErrorWithContext("Failed to connect to the camera"); - close(camSocket); - return -1; - } + /* connect to server */ + if (connect(camSocket, address->ai_addr, address->ai_addrlen) == -1) { + if (setError) + wpi_setErrnoErrorWithContext("Failed to connect to the camera"); + close(camSocket); + return -1; + } - int sent = send(camSocket, requestString.c_str(), requestString.size(), 0); - if (sent == -1) - { - if (setError) wpi_setErrnoErrorWithContext("Failed to send a request to the camera"); - close(camSocket); - return -1; - } + int sent = send(camSocket, requestString.c_str(), requestString.size(), 0); + if (sent == -1) { + if (setError) + wpi_setErrnoErrorWithContext("Failed to send a request to the camera"); + close(camSocket); + return -1; + } - return camSocket; + return camSocket; } - diff --git a/wpilibc/wpilibC++Devices/src/Vision/BaeUtilities.cpp b/wpilibc/wpilibC++Devices/src/Vision/BaeUtilities.cpp index 278fa5913b..fe2944a7ed 100644 --- a/wpilibc/wpilibC++Devices/src/Vision/BaeUtilities.cpp +++ b/wpilibc/wpilibC++Devices/src/Vision/BaeUtilities.cpp @@ -1,5 +1,6 @@ /*----------------------------------------------------------------------------*/ -/* Copyright (c) FIRST 2014. All Rights Reserved. */ +/* Copyright (c) FIRST 2014. 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,145 +10,147 @@ #include #include #include -#include -#include - +#include +#include + #include "Vision/BaeUtilities.h" #include "Servo.h" #include "Timer.h" /** @file - * Utility functions + * Utility functions */ /** * debug output flag options: - * DEBUG_OFF, DEBUG_MOSTLY_OFF, DEBUG_SCREEN_ONLY, DEBUG_FILE_ONLY, DEBUG_SCREEN_AND_FILE + * DEBUG_OFF, DEBUG_MOSTLY_OFF, DEBUG_SCREEN_ONLY, DEBUG_FILE_ONLY, + * DEBUG_SCREEN_AND_FILE */ -static DebugOutputType dprintfFlag = DEBUG_OFF; +static DebugOutputType dprintfFlag = DEBUG_OFF; /** * Set the debug flag to print to screen, file on cRIO, both or neither * @param tempString The format string. */ -void SetDebugFlag ( DebugOutputType flag ) -{ dprintfFlag = flag; } +void SetDebugFlag(DebugOutputType flag) { dprintfFlag = flag; } /** * Debug print to a file and/or a terminal window. * Call like you would call printf. - * Set functionName in the function if you want the correct function name to print out. + * Set functionName in the function if you want the correct function name to + * print out. * The file line number will also be printed. * @param tempString The format string. */ -void dprintf ( const char * tempString, ... ) /* Variable argument list */ +void dprintf(const char *tempString, ...) /* Variable argument list */ { - va_list args; /* Input argument list */ - int line_number; /* Line number passed in argument */ - int type; - const char *functionName; /* Format passed in argument */ - const char *fmt; /* Format passed in argument */ - char text[512]; /* Text string */ - char outtext[512]; /* Text string */ - FILE *outfile_fd; /* Output file pointer */ - char filepath[128]; /* Text string */ - int fatalFlag=0; - const char *filename; - int index; - int tempStringLen; + va_list args; /* Input argument list */ + int line_number; /* Line number passed in argument */ + int type; + const char *functionName; /* Format passed in argument */ + const char *fmt; /* Format passed in argument */ + char text[512]; /* Text string */ + char outtext[512]; /* Text string */ + FILE *outfile_fd; /* Output file pointer */ + char filepath[128]; /* Text string */ + int fatalFlag = 0; + const char *filename; + int index; + int tempStringLen; + + if (dprintfFlag == DEBUG_OFF) { + return; + } + + va_start(args, tempString); - if (dprintfFlag == DEBUG_OFF) { return; } - - va_start (args, tempString); - tempStringLen = strlen(tempString); filename = tempString; - for (index=0;indexSet( newServoPosition ); - //ShowActivity ("pan x: normalized %f newServoPosition = %f" , - // normalizedSinPosition, newServoPosition ); +void panForTarget(Servo *panServo, double sinStart) { + float normalizedSinPosition = (float)SinPosition(NULL, sinStart); + float newServoPosition = NormalizeToRange(normalizedSinPosition); + panServo->Set(newServoPosition); + // ShowActivity ("pan x: normalized %f newServoPosition = %f" , + // normalizedSinPosition, newServoPosition ); } - -/** @brief Read a file and return non-comment output string +/** @brief Read a file and return non-comment output string Call the first time with 0 lineNumber to get the number of lines to read Then call with each lineNumber to get one camera parameter. There should @@ -286,100 +288,84 @@ be one property=value entry on each line, i.e. "exposure=auto" * @param lineNumber if 0, return number of lines; else return that line number * @return int number of lines or -1 if error **/ -int processFile(char *inputFile, char *outputString, int lineNumber) -{ - FILE *infile; - int stringSize = 80; // max size of one line in file - char inputStr[stringSize]; - int lineCount=0; - - if (lineNumber < 0) - return (-1); +int processFile(char *inputFile, char *outputString, int lineNumber) { + FILE *infile; + int stringSize = 80; // max size of one line in file + char inputStr[stringSize]; + int lineCount = 0; - if ((infile = fopen (inputFile, "r")) == NULL) { - printf ("Fatal error opening file %s\n",inputFile); - return (0); - } + if (lineNumber < 0) return (-1); + + if ((infile = fopen(inputFile, "r")) == NULL) { + printf("Fatal error opening file %s\n", inputFile); + return (0); + } while (!feof(infile)) { - if (fgets (inputStr, stringSize, infile) != NULL) { + if (fgets(inputStr, stringSize, infile) != NULL) { // Skip empty lines - if (emptyString(inputStr)) - continue; + if (emptyString(inputStr)) continue; // Skip comment lines - if (inputStr[0] == '#' || inputStr[0] == '!') - continue; + if (inputStr[0] == '#' || inputStr[0] == '!') continue; lineCount++; if (lineNumber == 0) continue; - else - { - if (lineCount == lineNumber) - break; + else { + if (lineCount == lineNumber) break; } } } - // close file - fclose (infile); + // close file + fclose(infile); // if number lines requested return the count - if (lineNumber == 0) - return (lineCount); + if (lineNumber == 0) return (lineCount); // check for input out of range - if (lineNumber > lineCount) - return (-1); + if (lineNumber > lineCount) return (-1); // return the line selected if (lineCount) { stripString(inputStr); strcpy(outputString, inputStr); - return(lineCount); - } - else { - return(-1); + return (lineCount); + } else { + return (-1); } } -/** Ignore empty string +/** Ignore empty string * @param string to check if empty **/ -int emptyString(char *string) -{ - int i,len; +int emptyString(char *string) { + int i, len; - if(string == NULL) - return(1); + if (string == NULL) return (1); len = strlen(string); - for(i=0; iimageWidth, &par->imageHeight); - wpi_setImaqErrorWithContext(success, "Error getting image size"); - if (StatusIsFatal()) - return; + success = imaqGetImageSize(m_imaqImage, &par->imageWidth, &par->imageHeight); + wpi_setImaqErrorWithContext(success, "Error getting image size"); + if (StatusIsFatal()) return; - success = imaqCountParticles(m_imaqImage, 1, &numParticles); - wpi_setImaqErrorWithContext(success, "Error counting particles"); - if (StatusIsFatal()) - return; + success = imaqCountParticles(m_imaqImage, 1, &numParticles); + wpi_setImaqErrorWithContext(success, "Error counting particles"); + if (StatusIsFatal()) return; - if (particleNumber >= numParticles) - { - wpi_setWPIErrorWithContext(ParameterOutOfRange, "particleNumber"); - return; - } + if (particleNumber >= numParticles) { + wpi_setWPIErrorWithContext(ParameterOutOfRange, "particleNumber"); + return; + } - par->particleIndex = particleNumber; - // Don't bother measuring the rest of the particle if one fails - bool good = ParticleMeasurement(particleNumber, IMAQ_MT_CENTER_OF_MASS_X, &par->center_mass_x); - good = good && ParticleMeasurement(particleNumber, IMAQ_MT_CENTER_OF_MASS_Y, &par->center_mass_y); - good = good && ParticleMeasurement(particleNumber, IMAQ_MT_AREA, &par->particleArea); - good = good && ParticleMeasurement(particleNumber, IMAQ_MT_BOUNDING_RECT_TOP, &par->boundingRect.top); - good = good && ParticleMeasurement(particleNumber, IMAQ_MT_BOUNDING_RECT_LEFT, &par->boundingRect.left); - good = good && ParticleMeasurement(particleNumber, IMAQ_MT_BOUNDING_RECT_HEIGHT, &par->boundingRect.height); - good = good && ParticleMeasurement(particleNumber, IMAQ_MT_BOUNDING_RECT_WIDTH, &par->boundingRect.width); - good = good && ParticleMeasurement(particleNumber, IMAQ_MT_AREA_BY_IMAGE_AREA, &par->particleToImagePercent); - good = good && ParticleMeasurement(particleNumber, IMAQ_MT_AREA_BY_PARTICLE_AND_HOLES_AREA, &par->particleQuality); + par->particleIndex = particleNumber; + // Don't bother measuring the rest of the particle if one fails + bool good = ParticleMeasurement(particleNumber, IMAQ_MT_CENTER_OF_MASS_X, + &par->center_mass_x); + good = good && ParticleMeasurement(particleNumber, IMAQ_MT_CENTER_OF_MASS_Y, + &par->center_mass_y); + good = good && + ParticleMeasurement(particleNumber, IMAQ_MT_AREA, &par->particleArea); + good = good && ParticleMeasurement(particleNumber, IMAQ_MT_BOUNDING_RECT_TOP, + &par->boundingRect.top); + good = good && ParticleMeasurement(particleNumber, IMAQ_MT_BOUNDING_RECT_LEFT, + &par->boundingRect.left); + good = + good && ParticleMeasurement(particleNumber, IMAQ_MT_BOUNDING_RECT_HEIGHT, + &par->boundingRect.height); + good = + good && ParticleMeasurement(particleNumber, IMAQ_MT_BOUNDING_RECT_WIDTH, + &par->boundingRect.width); + good = good && ParticleMeasurement(particleNumber, IMAQ_MT_AREA_BY_IMAGE_AREA, + &par->particleToImagePercent); + good = good && ParticleMeasurement(particleNumber, + IMAQ_MT_AREA_BY_PARTICLE_AND_HOLES_AREA, + &par->particleQuality); - if (good) - { - /* normalized position (-1 to 1) */ - par->center_mass_x_normalized = NormalizeFromRange(par->center_mass_x, par->imageWidth); - par->center_mass_y_normalized = NormalizeFromRange(par->center_mass_y, par->imageHeight); - } + if (good) { + /* normalized position (-1 to 1) */ + par->center_mass_x_normalized = + NormalizeFromRange(par->center_mass_x, par->imageWidth); + par->center_mass_y_normalized = + NormalizeFromRange(par->center_mass_y, par->imageHeight); + } } - /** * Get an ordered vector of particles for the image. * Create a vector of particle analysis reports sorted by size for an image. * The vector contains the actual report structures. - * @returns a pointer to the vector of particle analysis reports. The caller must delete the + * @returns a pointer to the vector of particle analysis reports. The caller + * must delete the * vector when finished using it. */ -vector* BinaryImage::GetOrderedParticleAnalysisReports() -{ - vector* particles = new vector; - int particleCount = GetNumberParticles(); - for(int particleIndex = 0; particleIndex < particleCount; particleIndex++) - { - particles->push_back(GetParticleAnalysisReport(particleIndex)); - } - // TODO: This is pretty inefficient since each compare in the sort copies - // both reports being compared... do it manually instead... while we're - // at it, we should provide a version that allows a preallocated buffer of - // ParticleAnalysisReport structures - sort(particles->begin(), particles->end(), CompareParticleSizes); - return particles; +vector * +BinaryImage::GetOrderedParticleAnalysisReports() { + vector *particles = + new vector; + int particleCount = GetNumberParticles(); + for (int particleIndex = 0; particleIndex < particleCount; particleIndex++) { + particles->push_back(GetParticleAnalysisReport(particleIndex)); + } + // TODO: This is pretty inefficient since each compare in the sort copies + // both reports being compared... do it manually instead... while we're + // at it, we should provide a version that allows a preallocated buffer of + // ParticleAnalysisReport structures + sort(particles->begin(), particles->end(), CompareParticleSizes); + return particles; } /** @@ -121,102 +126,108 @@ vector* BinaryImage::GetOrderedParticleAnalysisReports() * Writes the binary image to flash on the cRIO for later inspection. * @param fileName the name of the image file written to the flash. */ -void BinaryImage::Write(const char *fileName) -{ - RGBValue colorTable[256]; - memset(colorTable, 0, sizeof(colorTable)); - colorTable[0].R = 0; - colorTable[1].R = 255; - colorTable[0].G = colorTable[1].G = 0; - colorTable[0].B = colorTable[1].B = 0; - colorTable[0].alpha = colorTable[1].alpha = 0; - imaqWriteFile(m_imaqImage, fileName, colorTable); +void BinaryImage::Write(const char *fileName) { + RGBValue colorTable[256]; + memset(colorTable, 0, sizeof(colorTable)); + colorTable[0].R = 0; + colorTable[1].R = 255; + colorTable[0].G = colorTable[1].G = 0; + colorTable[0].B = colorTable[1].B = 0; + colorTable[0].alpha = colorTable[1].alpha = 0; + imaqWriteFile(m_imaqImage, fileName, colorTable); } /** * Measure a single parameter for an image. - * Get the measurement for a single parameter about an image by calling the imaqMeasureParticle + * Get the measurement for a single parameter about an image by calling the + * imaqMeasureParticle * function for the selected parameter. * @param particleNumber which particle in the set of particles * @param whatToMeasure the imaq MeasurementType (what to measure) * @param result the value of the measurement * @returns false on failure, true on success */ -bool BinaryImage::ParticleMeasurement(int particleNumber, MeasurementType whatToMeasure, int *result) -{ - double resultDouble; - bool success = ParticleMeasurement(particleNumber, whatToMeasure, &resultDouble); - *result = (int)resultDouble; - return success; +bool BinaryImage::ParticleMeasurement(int particleNumber, + MeasurementType whatToMeasure, + int *result) { + double resultDouble; + bool success = + ParticleMeasurement(particleNumber, whatToMeasure, &resultDouble); + *result = (int)resultDouble; + return success; } /** * Measure a single parameter for an image. - * Get the measurement for a single parameter about an image by calling the imaqMeasureParticle + * Get the measurement for a single parameter about an image by calling the + * imaqMeasureParticle * function for the selected parameter. * @param particleNumber which particle in the set of particles * @param whatToMeasure the imaq MeasurementType (what to measure) * @param result the value of the measurement * @returns true on failure, false on success */ -bool BinaryImage::ParticleMeasurement(int particleNumber, MeasurementType whatToMeasure, double *result) -{ - int success; - success = imaqMeasureParticle(m_imaqImage, particleNumber, 0, whatToMeasure, result); - wpi_setImaqErrorWithContext(success, "Error measuring particle"); - return !StatusIsFatal(); +bool BinaryImage::ParticleMeasurement(int particleNumber, + MeasurementType whatToMeasure, + double *result) { + int success; + success = imaqMeasureParticle(m_imaqImage, particleNumber, 0, whatToMeasure, + result); + wpi_setImaqErrorWithContext(success, "Error measuring particle"); + return !StatusIsFatal(); } -//Normalizes to [-1,1] -double BinaryImage::NormalizeFromRange(double position, int range) -{ - return (position * 2.0 / (double)range) - 1.0; +// Normalizes to [-1,1] +double BinaryImage::NormalizeFromRange(double position, int range) { + return (position * 2.0 / (double)range) - 1.0; } /** * The compare helper function for sort. - * This function compares two particle analysis reports as a helper for the sort function. + * This function compares two particle analysis reports as a helper for the sort + * function. * @param particle1 The first particle to compare * @param particle2 the second particle to compare * @returns true if particle1 is greater than particle2 */ -bool BinaryImage::CompareParticleSizes(ParticleAnalysisReport particle1, ParticleAnalysisReport particle2) -{ - //we want descending sort order - return particle1.particleToImagePercent > particle2.particleToImagePercent; +bool BinaryImage::CompareParticleSizes(ParticleAnalysisReport particle1, + ParticleAnalysisReport particle2) { + // we want descending sort order + return particle1.particleToImagePercent > particle2.particleToImagePercent; } -BinaryImage *BinaryImage::RemoveSmallObjects(bool connectivity8, int erosions) -{ - BinaryImage *result = new BinaryImage(); - int success = imaqSizeFilter(result->GetImaqImage(), m_imaqImage, connectivity8, erosions, IMAQ_KEEP_LARGE, NULL); - wpi_setImaqErrorWithContext(success, "Error in RemoveSmallObjects"); - return result; +BinaryImage *BinaryImage::RemoveSmallObjects(bool connectivity8, int erosions) { + BinaryImage *result = new BinaryImage(); + int success = imaqSizeFilter(result->GetImaqImage(), m_imaqImage, + connectivity8, erosions, IMAQ_KEEP_LARGE, NULL); + wpi_setImaqErrorWithContext(success, "Error in RemoveSmallObjects"); + return result; } -BinaryImage *BinaryImage::RemoveLargeObjects(bool connectivity8, int erosions) -{ - BinaryImage *result = new BinaryImage(); - int success = imaqSizeFilter(result->GetImaqImage(), m_imaqImage, connectivity8, erosions, IMAQ_KEEP_SMALL, NULL); - wpi_setImaqErrorWithContext(success, "Error in RemoveLargeObjects"); - return result; +BinaryImage *BinaryImage::RemoveLargeObjects(bool connectivity8, int erosions) { + BinaryImage *result = new BinaryImage(); + int success = imaqSizeFilter(result->GetImaqImage(), m_imaqImage, + connectivity8, erosions, IMAQ_KEEP_SMALL, NULL); + wpi_setImaqErrorWithContext(success, "Error in RemoveLargeObjects"); + return result; } -BinaryImage *BinaryImage::ConvexHull(bool connectivity8) -{ - BinaryImage *result = new BinaryImage(); - int success = imaqConvexHull(result->GetImaqImage(), m_imaqImage, connectivity8); - wpi_setImaqErrorWithContext(success, "Error in convex hull operation"); - return result; +BinaryImage *BinaryImage::ConvexHull(bool connectivity8) { + BinaryImage *result = new BinaryImage(); + int success = + imaqConvexHull(result->GetImaqImage(), m_imaqImage, connectivity8); + wpi_setImaqErrorWithContext(success, "Error in convex hull operation"); + return result; } -BinaryImage *BinaryImage::ParticleFilter(ParticleFilterCriteria2 *criteria, int criteriaCount) -{ - BinaryImage *result = new BinaryImage(); - int numParticles; - ParticleFilterOptions2 filterOptions = {0, 0, 0, 1}; - int success = imaqParticleFilter4(result->GetImaqImage(), m_imaqImage, criteria, criteriaCount, &filterOptions, NULL, &numParticles); - wpi_setImaqErrorWithContext(success, "Error in particle filter operation"); - return result; +BinaryImage *BinaryImage::ParticleFilter(ParticleFilterCriteria2 *criteria, + int criteriaCount) { + BinaryImage *result = new BinaryImage(); + int numParticles; + ParticleFilterOptions2 filterOptions = {0, 0, 0, 1}; + int success = + imaqParticleFilter4(result->GetImaqImage(), m_imaqImage, criteria, + criteriaCount, &filterOptions, NULL, &numParticles); + wpi_setImaqErrorWithContext(success, "Error in particle filter operation"); + return result; } - diff --git a/wpilibc/wpilibC++Devices/src/Vision/ColorImage.cpp b/wpilibc/wpilibC++Devices/src/Vision/ColorImage.cpp index aa72da31c7..3a52337a78 100644 --- a/wpilibc/wpilibC++Devices/src/Vision/ColorImage.cpp +++ b/wpilibc/wpilibC++Devices/src/Vision/ColorImage.cpp @@ -8,13 +8,9 @@ #include "WPIErrors.h" -ColorImage::ColorImage(ImageType type) : ImageBase(type) -{ -} +ColorImage::ColorImage(ImageType type) : ImageBase(type) {} -ColorImage::~ColorImage() -{ -} +ColorImage::~ColorImage() {} /** * Perform a threshold operation on a ColorImage. @@ -23,19 +19,16 @@ ColorImage::~ColorImage() * @param colorMode The type of colorspace this operation should be performed in * @returns a pointer to a binary image */ -BinaryImage *ColorImage::ComputeThreshold(ColorMode colorMode, - int low1, int high1, - int low2, int high2, - int low3, int high3) -{ - BinaryImage *result = new BinaryImage(); - Range range1 = {low1, high1}, - range2 = {low2, high2}, - range3 = {low3, high3}; - - int success = imaqColorThreshold(result->GetImaqImage(), m_imaqImage, 1, colorMode, &range1, &range2, &range3); - wpi_setImaqErrorWithContext(success, "ImaqThreshold error"); - return result; +BinaryImage *ColorImage::ComputeThreshold(ColorMode colorMode, int low1, + int high1, int low2, int high2, + int low3, int high3) { + BinaryImage *result = new BinaryImage(); + Range range1 = {low1, high1}, range2 = {low2, high2}, range3 = {low3, high3}; + + int success = imaqColorThreshold(result->GetImaqImage(), m_imaqImage, 1, + colorMode, &range1, &range2, &range3); + wpi_setImaqErrorWithContext(success, "ImaqThreshold error"); + return result; } /** @@ -46,23 +39,25 @@ BinaryImage *ColorImage::ComputeThreshold(ColorMode colorMode, * @param greenHigh Green high value * @param blueLow Blue low value * @param blueHigh Blue high value - * @returns A pointer to a BinaryImage that represents the result of the threshold operation. + * @returns A pointer to a BinaryImage that represents the result of the + * threshold operation. */ -BinaryImage *ColorImage::ThresholdRGB(int redLow, int redHigh, int greenLow, int greenHigh, int blueLow, int blueHigh) -{ - return ComputeThreshold(IMAQ_RGB, redLow, redHigh, greenLow, greenHigh, blueLow, blueHigh); +BinaryImage *ColorImage::ThresholdRGB(int redLow, int redHigh, int greenLow, + int greenHigh, int blueLow, + int blueHigh) { + return ComputeThreshold(IMAQ_RGB, redLow, redHigh, greenLow, greenHigh, + blueLow, blueHigh); } /** * Perform a threshold in RGB space. * @param threshold a reference to the Threshold object to use. - * @returns A pointer to a BinaryImage that represents the result of the threshold operation. + * @returns A pointer to a BinaryImage that represents the result of the + * threshold operation. */ -BinaryImage *ColorImage::ThresholdRGB(Threshold &t) -{ - return ComputeThreshold(IMAQ_RGB, t.plane1Low, t.plane1High, - t.plane2Low, t.plane2High, - t.plane3Low, t.plane3High); +BinaryImage *ColorImage::ThresholdRGB(Threshold &t) { + return ComputeThreshold(IMAQ_RGB, t.plane1Low, t.plane1High, t.plane2Low, + t.plane2High, t.plane3Low, t.plane3High); } /** @@ -73,23 +68,25 @@ BinaryImage *ColorImage::ThresholdRGB(Threshold &t) * @param saturationHigh High value for saturation * @param luminenceLow Low value for luminence * @param luminenceHigh High value for luminence - * @returns a pointer to a BinaryImage that represents the result of the threshold operation. + * @returns a pointer to a BinaryImage that represents the result of the + * threshold operation. */ -BinaryImage *ColorImage::ThresholdHSL(int hueLow, int hueHigh, int saturationLow, int saturationHigh, int luminenceLow, int luminenceHigh) -{ - return ComputeThreshold(IMAQ_HSL, hueLow, hueHigh, saturationLow, saturationHigh, luminenceLow, luminenceHigh); +BinaryImage *ColorImage::ThresholdHSL(int hueLow, int hueHigh, + int saturationLow, int saturationHigh, + int luminenceLow, int luminenceHigh) { + return ComputeThreshold(IMAQ_HSL, hueLow, hueHigh, saturationLow, + saturationHigh, luminenceLow, luminenceHigh); } /** * Perform a threshold in HSL space. * @param threshold a reference to the Threshold object to use. - * @returns A pointer to a BinaryImage that represents the result of the threshold operation. + * @returns A pointer to a BinaryImage that represents the result of the + * threshold operation. */ -BinaryImage *ColorImage::ThresholdHSL(Threshold &t) -{ - return ComputeThreshold(IMAQ_HSL, t.plane1Low, t.plane1High, - t.plane2Low, t.plane2High, - t.plane3Low, t.plane3High); +BinaryImage *ColorImage::ThresholdHSL(Threshold &t) { + return ComputeThreshold(IMAQ_HSL, t.plane1Low, t.plane1High, t.plane2Low, + t.plane2High, t.plane3Low, t.plane3High); } /** @@ -100,23 +97,25 @@ BinaryImage *ColorImage::ThresholdHSL(Threshold &t) * @param saturationHigh High value for saturation * @param valueLow Low value * @param valueHigh High value - * @returns a pointer to a BinaryImage that represents the result of the threshold operation. + * @returns a pointer to a BinaryImage that represents the result of the + * threshold operation. */ -BinaryImage *ColorImage::ThresholdHSV(int hueLow, int hueHigh, int saturationLow, int saturationHigh, int valueLow, int valueHigh) -{ - return ComputeThreshold(IMAQ_HSV, hueLow, hueHigh, saturationLow, saturationHigh, valueLow, valueHigh); +BinaryImage *ColorImage::ThresholdHSV(int hueLow, int hueHigh, + int saturationLow, int saturationHigh, + int valueLow, int valueHigh) { + return ComputeThreshold(IMAQ_HSV, hueLow, hueHigh, saturationLow, + saturationHigh, valueLow, valueHigh); } /** * Perform a threshold in HSV space. * @param threshold a reference to the Threshold object to use. - * @returns A pointer to a BinaryImage that represents the result of the threshold operation. + * @returns A pointer to a BinaryImage that represents the result of the + * threshold operation. */ -BinaryImage *ColorImage::ThresholdHSV(Threshold &t) -{ - return ComputeThreshold(IMAQ_HSV, t.plane1Low, t.plane1High, - t.plane2Low, t.plane2High, - t.plane3Low, t.plane3High); +BinaryImage *ColorImage::ThresholdHSV(Threshold &t) { + return ComputeThreshold(IMAQ_HSV, t.plane1Low, t.plane1High, t.plane2Low, + t.plane2High, t.plane3Low, t.plane3High); } /** @@ -127,23 +126,25 @@ BinaryImage *ColorImage::ThresholdHSV(Threshold &t) * @param saturationHigh High value for saturation * @param valueLow Low intensity * @param valueHigh High intensity - * @returns a pointer to a BinaryImage that represents the result of the threshold operation. + * @returns a pointer to a BinaryImage that represents the result of the + * threshold operation. */ -BinaryImage *ColorImage::ThresholdHSI(int hueLow, int hueHigh, int saturationLow, int saturationHigh, int intensityLow, int intensityHigh) -{ - return ComputeThreshold(IMAQ_HSI, hueLow, hueHigh, saturationLow, saturationHigh, intensityLow, intensityHigh); +BinaryImage *ColorImage::ThresholdHSI(int hueLow, int hueHigh, + int saturationLow, int saturationHigh, + int intensityLow, int intensityHigh) { + return ComputeThreshold(IMAQ_HSI, hueLow, hueHigh, saturationLow, + saturationHigh, intensityLow, intensityHigh); } /** * Perform a threshold in HSI space. * @param threshold a reference to the Threshold object to use. - * @returns A pointer to a BinaryImage that represents the result of the threshold operation. + * @returns A pointer to a BinaryImage that represents the result of the + * threshold operation. */ -BinaryImage *ColorImage::ThresholdHSI(Threshold &t) -{ - return ComputeThreshold(IMAQ_HSI, t.plane1Low, t.plane1High, - t.plane2Low, t.plane2High, - t.plane3Low, t.plane3High); +BinaryImage *ColorImage::ThresholdHSI(Threshold &t) { + return ComputeThreshold(IMAQ_HSI, t.plane1Low, t.plane1High, t.plane2Low, + t.plane2High, t.plane3Low, t.plane3High); } /** @@ -152,18 +153,15 @@ BinaryImage *ColorImage::ThresholdHSI(Threshold &t) * @param planeNumber Which plane is to be extracted * @returns A pointer to a MonoImage that represents the extracted plane. */ -MonoImage *ColorImage::ExtractColorPlane(ColorMode mode, int planeNumber) -{ - MonoImage *result = new MonoImage(); - if (m_imaqImage == NULL) - wpi_setWPIError(NullParameter); - int success = imaqExtractColorPlanes(m_imaqImage, - mode, - (planeNumber == 1) ? result->GetImaqImage() : NULL, - (planeNumber == 2) ? result->GetImaqImage() : NULL, - (planeNumber == 3) ? result->GetImaqImage() : NULL); - wpi_setImaqErrorWithContext(success, "Imaq ExtractColorPlanes failed"); - return result; +MonoImage *ColorImage::ExtractColorPlane(ColorMode mode, int planeNumber) { + MonoImage *result = new MonoImage(); + if (m_imaqImage == NULL) wpi_setWPIError(NullParameter); + int success = imaqExtractColorPlanes( + m_imaqImage, mode, (planeNumber == 1) ? result->GetImaqImage() : NULL, + (planeNumber == 2) ? result->GetImaqImage() : NULL, + (planeNumber == 3) ? result->GetImaqImage() : NULL); + wpi_setImaqErrorWithContext(success, "Imaq ExtractColorPlanes failed"); + return result; } /* @@ -171,9 +169,8 @@ MonoImage *ColorImage::ExtractColorPlane(ColorMode mode, int planeNumber) * @param mode The color mode in which to operate * @returns a pointer to a MonoImage that is the extracted plane. */ -MonoImage *ColorImage::ExtractFirstColorPlane(ColorMode mode) -{ - return ExtractColorPlane(mode, 1); +MonoImage *ColorImage::ExtractFirstColorPlane(ColorMode mode) { + return ExtractColorPlane(mode, 1); } /* @@ -181,9 +178,8 @@ MonoImage *ColorImage::ExtractFirstColorPlane(ColorMode mode) * @param mode The color mode in which to operate * @returns a pointer to a MonoImage that is the extracted plane. */ -MonoImage *ColorImage::ExtractSecondColorPlane(ColorMode mode) -{ - return ExtractColorPlane(mode, 2); +MonoImage *ColorImage::ExtractSecondColorPlane(ColorMode mode) { + return ExtractColorPlane(mode, 2); } /* @@ -191,90 +187,80 @@ MonoImage *ColorImage::ExtractSecondColorPlane(ColorMode mode) * @param mode The color mode in which to operate * @returns a pointer to a MonoImage that is the extracted plane. */ -MonoImage *ColorImage::ExtractThirdColorPlane(ColorMode mode) -{ - return ExtractColorPlane(mode, 3); +MonoImage *ColorImage::ExtractThirdColorPlane(ColorMode mode) { + return ExtractColorPlane(mode, 3); } /* * Extract the red plane from an RGB image. * @returns a pointer to a MonoImage that is the extraced plane. */ -MonoImage *ColorImage::GetRedPlane() -{ - return ExtractFirstColorPlane(IMAQ_RGB); +MonoImage *ColorImage::GetRedPlane() { + return ExtractFirstColorPlane(IMAQ_RGB); } /* * Extract the green plane from an RGB image. * @returns a pointer to a MonoImage that is the extraced plane. */ -MonoImage *ColorImage::GetGreenPlane() -{ - return ExtractSecondColorPlane(IMAQ_RGB); +MonoImage *ColorImage::GetGreenPlane() { + return ExtractSecondColorPlane(IMAQ_RGB); } /* * Extract the blue plane from an RGB image. * @returns a pointer to a MonoImage that is the extraced plane. */ -MonoImage *ColorImage::GetBluePlane() -{ - return ExtractThirdColorPlane(IMAQ_RGB); +MonoImage *ColorImage::GetBluePlane() { + return ExtractThirdColorPlane(IMAQ_RGB); } /* * Extract the Hue plane from an HSL image. * @returns a pointer to a MonoImage that is the extraced plane. */ -MonoImage *ColorImage::GetHSLHuePlane() -{ - return ExtractFirstColorPlane(IMAQ_HSL); +MonoImage *ColorImage::GetHSLHuePlane() { + return ExtractFirstColorPlane(IMAQ_HSL); } /* * Extract the Hue plane from an HSV image. * @returns a pointer to a MonoImage that is the extraced plane. */ -MonoImage *ColorImage::GetHSVHuePlane() -{ - return ExtractFirstColorPlane(IMAQ_HSV); +MonoImage *ColorImage::GetHSVHuePlane() { + return ExtractFirstColorPlane(IMAQ_HSV); } /* * Extract the Hue plane from an HSI image. * @returns a pointer to a MonoImage that is the extraced plane. */ -MonoImage *ColorImage::GetHSIHuePlane() -{ - return ExtractFirstColorPlane(IMAQ_HSI); +MonoImage *ColorImage::GetHSIHuePlane() { + return ExtractFirstColorPlane(IMAQ_HSI); } /* * Extract the Luminance plane from an HSL image. * @returns a pointer to a MonoImage that is the extraced plane. */ -MonoImage *ColorImage::GetLuminancePlane() -{ - return ExtractThirdColorPlane(IMAQ_HSL); +MonoImage *ColorImage::GetLuminancePlane() { + return ExtractThirdColorPlane(IMAQ_HSL); } /* * Extract the Value plane from an HSV image. * @returns a pointer to a MonoImage that is the extraced plane. */ -MonoImage *ColorImage::GetValuePlane() -{ - return ExtractThirdColorPlane(IMAQ_HSV); +MonoImage *ColorImage::GetValuePlane() { + return ExtractThirdColorPlane(IMAQ_HSV); } /* * Extract the Intensity plane from an HSI image. * @returns a pointer to a MonoImage that is the extraced plane. */ -MonoImage *ColorImage::GetIntensityPlane() -{ - return ExtractThirdColorPlane(IMAQ_HSI); +MonoImage *ColorImage::GetIntensityPlane() { + return ExtractThirdColorPlane(IMAQ_HSI); } /** @@ -284,182 +270,177 @@ MonoImage *ColorImage::GetIntensityPlane() * @param plane The pointer to the replacement plane as a MonoImage * @param planeNumber The plane number (1, 2, 3) to replace */ -void ColorImage::ReplacePlane(ColorMode mode, MonoImage *plane, int planeNumber) { - int success = imaqReplaceColorPlanes(m_imaqImage, - (const Image*) m_imaqImage, - mode, - (planeNumber == 1) ? plane->GetImaqImage() : NULL, - (planeNumber == 2) ? plane->GetImaqImage() : NULL, - (planeNumber == 3) ? plane->GetImaqImage() : NULL); - wpi_setImaqErrorWithContext(success, "Imaq ReplaceColorPlanes failed"); +void ColorImage::ReplacePlane(ColorMode mode, MonoImage *plane, + int planeNumber) { + int success = + imaqReplaceColorPlanes(m_imaqImage, (const Image *)m_imaqImage, mode, + (planeNumber == 1) ? plane->GetImaqImage() : NULL, + (planeNumber == 2) ? plane->GetImaqImage() : NULL, + (planeNumber == 3) ? plane->GetImaqImage() : NULL); + wpi_setImaqErrorWithContext(success, "Imaq ReplaceColorPlanes failed"); } /** * Replace the first color plane with a MonoImage. * @param mode The color mode in which to operate. - * @param plane A pointer to a MonoImage that will replace the specified color plane. + * @param plane A pointer to a MonoImage that will replace the specified color + * plane. */ -void ColorImage::ReplaceFirstColorPlane(ColorMode mode, MonoImage *plane) -{ - ReplacePlane(mode, plane, 1); +void ColorImage::ReplaceFirstColorPlane(ColorMode mode, MonoImage *plane) { + ReplacePlane(mode, plane, 1); } /** * Replace the second color plane with a MonoImage. * @param mode The color mode in which to operate. - * @param plane A pointer to a MonoImage that will replace the specified color plane. + * @param plane A pointer to a MonoImage that will replace the specified color + * plane. */ -void ColorImage::ReplaceSecondColorPlane(ColorMode mode, MonoImage *plane) -{ - ReplacePlane(mode, plane, 2); +void ColorImage::ReplaceSecondColorPlane(ColorMode mode, MonoImage *plane) { + ReplacePlane(mode, plane, 2); } /** * Replace the third color plane with a MonoImage. * @param mode The color mode in which to operate. - * @param plane A pointer to a MonoImage that will replace the specified color plane. + * @param plane A pointer to a MonoImage that will replace the specified color + * plane. */ -void ColorImage::ReplaceThirdColorPlane(ColorMode mode, MonoImage *plane) -{ - ReplacePlane(mode, plane, 3); +void ColorImage::ReplaceThirdColorPlane(ColorMode mode, MonoImage *plane) { + ReplacePlane(mode, plane, 3); } /** * Replace the red color plane with a MonoImage. * @param mode The color mode in which to operate. - * @param plane A pointer to a MonoImage that will replace the specified color plane. + * @param plane A pointer to a MonoImage that will replace the specified color + * plane. */ -void ColorImage::ReplaceRedPlane(MonoImage *plane) -{ - ReplaceFirstColorPlane(IMAQ_RGB, plane); +void ColorImage::ReplaceRedPlane(MonoImage *plane) { + ReplaceFirstColorPlane(IMAQ_RGB, plane); } /** * Replace the green color plane with a MonoImage. * @param mode The color mode in which to operate. - * @param plane A pointer to a MonoImage that will replace the specified color plane. + * @param plane A pointer to a MonoImage that will replace the specified color + * plane. */ -void ColorImage::ReplaceGreenPlane(MonoImage *plane) -{ - ReplaceSecondColorPlane(IMAQ_RGB, plane); +void ColorImage::ReplaceGreenPlane(MonoImage *plane) { + ReplaceSecondColorPlane(IMAQ_RGB, plane); } /** * Replace the blue color plane with a MonoImage. * @param mode The color mode in which to operate. - * @param plane A pointer to a MonoImage that will replace the specified color plane. + * @param plane A pointer to a MonoImage that will replace the specified color + * plane. */ -void ColorImage::ReplaceBluePlane(MonoImage *plane) -{ - ReplaceThirdColorPlane(IMAQ_RGB, plane); +void ColorImage::ReplaceBluePlane(MonoImage *plane) { + ReplaceThirdColorPlane(IMAQ_RGB, plane); } - /** * Replace the Hue color plane in a HSL image with a MonoImage. * @param mode The color mode in which to operate. - * @param plane A pointer to a MonoImage that will replace the specified color plane. + * @param plane A pointer to a MonoImage that will replace the specified color + * plane. */ -void ColorImage::ReplaceHSLHuePlane(MonoImage *plane) -{ - return ReplaceFirstColorPlane(IMAQ_HSL, plane); +void ColorImage::ReplaceHSLHuePlane(MonoImage *plane) { + return ReplaceFirstColorPlane(IMAQ_HSL, plane); } /** * Replace the Hue color plane in a HSV image with a MonoImage. * @param mode The color mode in which to operate. - * @param plane A pointer to a MonoImage that will replace the specified color plane. + * @param plane A pointer to a MonoImage that will replace the specified color + * plane. */ -void ColorImage::ReplaceHSVHuePlane(MonoImage *plane) -{ - return ReplaceFirstColorPlane(IMAQ_HSV, plane); +void ColorImage::ReplaceHSVHuePlane(MonoImage *plane) { + return ReplaceFirstColorPlane(IMAQ_HSV, plane); } /** * Replace the first Hue plane in a HSI image with a MonoImage. * @param mode The color mode in which to operate. - * @param plane A pointer to a MonoImage that will replace the specified color plane. + * @param plane A pointer to a MonoImage that will replace the specified color + * plane. */ -void ColorImage::ReplaceHSIHuePlane(MonoImage *plane) -{ - return ReplaceFirstColorPlane(IMAQ_HSI, plane); +void ColorImage::ReplaceHSIHuePlane(MonoImage *plane) { + return ReplaceFirstColorPlane(IMAQ_HSI, plane); } /** * Replace the Saturation color plane in an HSL image with a MonoImage. * @param mode The color mode in which to operate. - * @param plane A pointer to a MonoImage that will replace the specified color plane. + * @param plane A pointer to a MonoImage that will replace the specified color + * plane. */ -void ColorImage::ReplaceHSLSaturationPlane(MonoImage *plane) -{ - return ReplaceSecondColorPlane(IMAQ_HSL, plane); +void ColorImage::ReplaceHSLSaturationPlane(MonoImage *plane) { + return ReplaceSecondColorPlane(IMAQ_HSL, plane); } /** * Replace the Saturation color plane in a HSV image with a MonoImage. * @param mode The color mode in which to operate. - * @param plane A pointer to a MonoImage that will replace the specified color plane. + * @param plane A pointer to a MonoImage that will replace the specified color + * plane. */ -void ColorImage::ReplaceHSVSaturationPlane(MonoImage *plane) -{ - return ReplaceSecondColorPlane(IMAQ_HSV, plane); +void ColorImage::ReplaceHSVSaturationPlane(MonoImage *plane) { + return ReplaceSecondColorPlane(IMAQ_HSV, plane); } /** * Replace the Saturation color plane in a HSI image with a MonoImage. * @param mode The color mode in which to operate. - * @param plane A pointer to a MonoImage that will replace the specified color plane. + * @param plane A pointer to a MonoImage that will replace the specified color + * plane. */ -void ColorImage::ReplaceHSISaturationPlane(MonoImage *plane) -{ - return ReplaceSecondColorPlane(IMAQ_HSI, plane); +void ColorImage::ReplaceHSISaturationPlane(MonoImage *plane) { + return ReplaceSecondColorPlane(IMAQ_HSI, plane); } /** * Replace the Luminance color plane in an HSL image with a MonoImage. * @param mode The color mode in which to operate. - * @param plane A pointer to a MonoImage that will replace the specified color plane. + * @param plane A pointer to a MonoImage that will replace the specified color + * plane. */ -void ColorImage::ReplaceLuminancePlane(MonoImage *plane) -{ - return ReplaceThirdColorPlane(IMAQ_HSL, plane); +void ColorImage::ReplaceLuminancePlane(MonoImage *plane) { + return ReplaceThirdColorPlane(IMAQ_HSL, plane); } /** * Replace the Value color plane in an HSV with a MonoImage. * @param mode The color mode in which to operate. - * @param plane A pointer to a MonoImage that will replace the specified color plane. + * @param plane A pointer to a MonoImage that will replace the specified color + * plane. */ -void ColorImage::ReplaceValuePlane(MonoImage *plane) -{ - return ReplaceThirdColorPlane(IMAQ_HSV, plane); +void ColorImage::ReplaceValuePlane(MonoImage *plane) { + return ReplaceThirdColorPlane(IMAQ_HSV, plane); } /** * Replace the Intensity color plane in a HSI image with a MonoImage. * @param mode The color mode in which to operate. - * @param plane A pointer to a MonoImage that will replace the specified color plane. + * @param plane A pointer to a MonoImage that will replace the specified color + * plane. */ -void ColorImage::ReplaceIntensityPlane(MonoImage *plane) -{ - return ReplaceThirdColorPlane(IMAQ_HSI, plane); +void ColorImage::ReplaceIntensityPlane(MonoImage *plane) { + return ReplaceThirdColorPlane(IMAQ_HSI, plane); } -//TODO: frcColorEqualize(Image* dest, const Image* source, int colorEqualization) needs to be modified -//The colorEqualization parameter is discarded and is set to TRUE in the call to imaqColorEqualize. -void ColorImage::Equalize(bool allPlanes) -{ - // Note that this call uses NI-defined TRUE and FALSE - int success = imaqColorEqualize(m_imaqImage, (const Image*) m_imaqImage, (allPlanes) ? TRUE : FALSE); - wpi_setImaqErrorWithContext(success, "Imaq ColorEqualize error"); +// TODO: frcColorEqualize(Image* dest, const Image* source, int +// colorEqualization) needs to be modified +// The colorEqualization parameter is discarded and is set to TRUE in the call +// to imaqColorEqualize. +void ColorImage::Equalize(bool allPlanes) { + // Note that this call uses NI-defined TRUE and FALSE + int success = imaqColorEqualize(m_imaqImage, (const Image *)m_imaqImage, + (allPlanes) ? TRUE : FALSE); + wpi_setImaqErrorWithContext(success, "Imaq ColorEqualize error"); } -void ColorImage::ColorEqualize() -{ - Equalize(true); -} +void ColorImage::ColorEqualize() { Equalize(true); } -void ColorImage::LuminanceEqualize() -{ - Equalize(false); -} +void ColorImage::LuminanceEqualize() { Equalize(false); } diff --git a/wpilibc/wpilibC++Devices/src/Vision/FrcError.cpp b/wpilibc/wpilibC++Devices/src/Vision/FrcError.cpp index 109dea6db3..7cd1fbf512 100644 --- a/wpilibc/wpilibC++Devices/src/Vision/FrcError.cpp +++ b/wpilibc/wpilibC++Devices/src/Vision/FrcError.cpp @@ -3,22 +3,21 @@ /* 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 "nivision.h" -#include "Vision/FrcError.h" + +#include "nivision.h" +#include "Vision/FrcError.h" /** * Get the error code returned from the NI Vision library * @return The last error code. */ -int GetLastVisionError() -{ - //int errorCode = imaqGetLastVisionError(); // error code: 0 = no error - //char* errorText = GetVisionErrorText(errorCode); - //dprintf (LOG_DEBUG, "Error = %i %s ", errorCode, errorText); - return imaqGetLastError(); +int GetLastVisionError() { + // int errorCode = imaqGetLastVisionError(); // error code: 0 = no error + // char* errorText = GetVisionErrorText(errorCode); + // dprintf (LOG_DEBUG, "Error = %i %s ", errorCode, errorText); + return imaqGetLastError(); } - + /** * Get the error text for an NI Vision error code. * Note: imaqGetErrorText() is not supported on real time system, so @@ -27,1201 +26,2378 @@ int GetLastVisionError() * @param errorCode The error code to find the text for. * @return The error text */ -const char* GetVisionErrorText(int errorCode) -{ - const char* errorText; +const char* GetVisionErrorText(int errorCode) { + const char* errorText; - switch (errorCode) - { - default: - { errorText = "UNKNOWN_ERROR";break;} - case -1074395138: - { errorText = "ERR_OCR_REGION_TOO_SMALL";break;} - case -1074395139: - { errorText = "ERR_IMAQ_QR_DIMENSION_INVALID";break;} - case -1074395140: - { errorText = "ERR_OCR_CHAR_REPORT_CORRUPTED";break;} - case -1074395141: - { errorText = "ERR_OCR_NO_TEXT_FOUND";break;} - case -1074395142: - { errorText = "ERR_QR_DETECTION_MODELTYPE";break;} - case -1074395143: - { errorText = "ERR_QR_DETECTION_MODE";break;} - case -1074395144: - { errorText = "ERR_QR_INVALID_BARCODE";break;} - case -1074395145: - { errorText = "ERR_QR_INVALID_READ";break;} - case -1074395146: - { errorText = "ERR_QR_DETECTION_VERSION";break;} - case -1074395147: - { errorText = "ERR_BARCODE_RSSLIMITED";break;} - case -1074395148: - { errorText = "ERR_OVERLAY_GROUP_NOT_FOUND";break;} - case -1074395149: - { errorText = "ERR_DUPLICATE_TRANSFORM_TYPE";break;} - case -1074395151: - { errorText = "ERR_OCR_CORRECTION_FAILED";break;} - case -1074395155: - { errorText = "ERR_OCR_ORIENT_DETECT_FAILED";break;} - case -1074395156: - { errorText = "ERR_OCR_SKEW_DETECT_FAILED";break;} - case -1074395158: - { errorText = "ERR_OCR_INVALID_CONTRASTMODE";break;} - case -1074395159: - { errorText = "ERR_OCR_INVALID_TOLERANCE";break;} - case -1074395160: - { errorText = "ERR_OCR_INVALID_MAXPOINTSIZE";break;} - case -1074395161: - { errorText = "ERR_OCR_INVALID_CORRECTIONLEVEL";break;} - case -1074395162: - { errorText = "ERR_OCR_INVALID_CORRECTIONMODE";break;} - case -1074395163: - { errorText = "ERR_OCR_INVALID_CHARACTERPREFERENCE";break;} - case -1074395164: - { errorText = "ERR_OCR_ADD_WORD_FAILED";break;} - case -1074395165: - { errorText = "ERR_OCR_WTS_DIR_NOT_FOUND";break;} - case -1074395166: - { errorText = "ERR_OCR_BIN_DIR_NOT_FOUND";break;} - case -1074395167: - { errorText = "ERR_OCR_INVALID_OUTPUTDELIMITER";break;} - case -1074395168: - { errorText = "ERR_OCR_INVALID_AUTOCORRECTIONMODE";break;} - case -1074395169: - { errorText = "ERR_OCR_INVALID_RECOGNITIONMODE";break;} - case -1074395170: - { errorText = "ERR_OCR_INVALID_CHARACTERTYPE";break;} - case -1074395171: - { errorText = "ERR_OCR_INI_FILE_NOT_FOUND";break;} - case -1074395172: - { errorText = "ERR_OCR_INVALID_CHARACTERSET";break;} - case -1074395173: - { errorText = "ERR_OCR_INVALID_LANGUAGE";break;} - case -1074395174: - { errorText = "ERR_OCR_INVALID_AUTOORIENTMODE";break;} - case -1074395175: - { errorText = "ERR_OCR_BAD_USER_DICTIONARY";break;} - case -1074395178: - { errorText = "ERR_OCR_RECOGNITION_FAILED";break;} - case -1074395179: - { errorText = "ERR_OCR_PREPROCESSING_FAILED";break;} - case -1074395200: - { errorText = "ERR_OCR_INVALID_PARAMETER";break;} - case -1074395201: - { errorText = "ERR_OCR_LOAD_LIBRARY";break;} - case -1074395203: - { errorText = "ERR_OCR_LIB_INIT";break;} - case -1074395210: - { errorText = "ERR_OCR_CANNOT_MATCH_TEXT_TEMPLATE";break;} - case -1074395211: - { errorText = "ERR_OCR_BAD_TEXT_TEMPLATE";break;} - case -1074395212: - { errorText = "ERR_OCR_TEMPLATE_WRONG_SIZE";break;} - case -1074395233: - { errorText = "ERR_TEMPLATE_IMAGE_TOO_LARGE";break;} - case -1074395234: - { errorText = "ERR_TEMPLATE_IMAGE_TOO_SMALL";break;} - case -1074395235: - { errorText = "ERR_TEMPLATE_IMAGE_CONTRAST_TOO_LOW";break;} - case -1074395237: - { errorText = "ERR_TEMPLATE_DESCRIPTOR_SHIFT_1";break;} - case -1074395238: - { errorText = "ERR_TEMPLATE_DESCRIPTOR_NOSHIFT";break;} - case -1074395239: - { errorText = "ERR_TEMPLATE_DESCRIPTOR_SHIFT";break;} - case -1074395240: - { errorText = "ERR_TEMPLATE_DESCRIPTOR_ROTATION_1";break;} - case -1074395241: - { errorText = "ERR_TEMPLATE_DESCRIPTOR_NOROTATION";break;} - case -1074395242: - { errorText = "ERR_TEMPLATE_DESCRIPTOR_ROTATION";break;} - case -1074395243: - { errorText = "ERR_TEMPLATE_DESCRIPTOR_4";break;} - case -1074395244: - { errorText = "ERR_TEMPLATE_DESCRIPTOR_3";break;} - case -1074395245: - { errorText = "ERR_TEMPLATE_DESCRIPTOR_2";break;} - case -1074395246: - { errorText = "ERR_TEMPLATE_DESCRIPTOR_1";break;} - case -1074395247: - { errorText = "ERR_TEMPLATE_DESCRIPTOR";break;} - case -1074395248: - { errorText = "ERR_TOO_MANY_ROTATION_ANGLE_RANGES";break;} - case -1074395249: - { errorText = "ERR_ROTATION_ANGLE_RANGE_TOO_LARGE";break;} - case -1074395250: - { errorText = "ERR_MATCH_SETUP_DATA";break;} - case -1074395251: - { errorText = "ERR_INVALID_MATCH_MODE";break;} - case -1074395252: - { errorText = "ERR_LEARN_SETUP_DATA";break;} - case -1074395253: - { errorText = "ERR_INVALID_LEARN_MODE";break;} - case -1074395256: - { errorText = "ERR_EVEN_WINDOW_SIZE";break;} - case -1074395257: - { errorText = "ERR_INVALID_EDGE_DIR";break;} - case -1074395258: - { errorText = "ERR_BAD_FILTER_WIDTH";break;} - case -1074395260: - { errorText = "ERR_HEAP_TRASHED";break;} - case -1074395261: - { errorText = "ERR_GIP_RANGE";break;} - case -1074395262: - { errorText = "ERR_LCD_BAD_MATCH";break;} - case -1074395263: - { errorText = "ERR_LCD_NO_SEGMENTS";break;} - case -1074395265: - { errorText = "ERR_BARCODE";break;} - case -1074395267: - { errorText = "ERR_COMPLEX_ROOT";break;} - case -1074395268: - { errorText = "ERR_LINEAR_COEFF";break;} - case -1074395269: - { errorText = "ERR_NULL_POINTER";break;} - case -1074395270: - { errorText = "ERR_DIV_BY_ZERO";break;} - case -1074395275: - { errorText = "ERR_INVALID_BROWSER_IMAGE";break;} - case -1074395276: - { errorText = "ERR_LINES_PARALLEL";break;} - case -1074395277: - { errorText = "ERR_BARCODE_CHECKSUM";break;} - case -1074395278: - { errorText = "ERR_LCD_NOT_NUMERIC";break;} - case -1074395279: - { errorText = "ERR_ROI_NOT_POLYGON";break;} - case -1074395280: - { errorText = "ERR_ROI_NOT_RECT";break;} - case -1074395281: - { errorText = "ERR_IMAGE_SMALLER_THAN_BORDER";break;} - case -1074395282: - { errorText = "ERR_CANT_DRAW_INTO_VIEWER";break;} - case -1074395283: - { errorText = "ERR_INVALID_RAKE_DIRECTION";break;} - case -1074395284: - { errorText = "ERR_INVALID_EDGE_PROCESS";break;} - case -1074395285: - { errorText = "ERR_INVALID_SPOKE_DIRECTION";break;} - case -1074395286: - { errorText = "ERR_INVALID_CONCENTRIC_RAKE_DIRECTION";break;} - case -1074395287: - { errorText = "ERR_INVALID_LINE";break;} - case -1074395290: - { errorText = "ERR_SHAPEMATCH_BADTEMPLATE";break;} - case -1074395291: - { errorText = "ERR_SHAPEMATCH_BADIMAGEDATA";break;} - case -1074395292: - { errorText = "ERR_POINTS_ARE_COLLINEAR";break;} - case -1074395293: - { errorText = "ERR_CONTOURID_NOT_FOUND";break;} - case -1074395294: - { errorText = "ERR_CONTOUR_INDEX_OUT_OF_RANGE";break;} - case -1074395295: - { errorText = "ERR_INVALID_INTERPOLATIONMETHOD_INTERPOLATEPOINTS";break;} - case -1074395296: - { errorText = "ERR_INVALID_BARCODETYPE";break;} - case -1074395297: - { errorText = "ERR_INVALID_PARTICLEINFOMODE";break;} - case -1074395298: - { errorText = "ERR_COMPLEXPLANE_NOT_REAL_OR_IMAGINARY";break;} - case -1074395299: - { errorText = "ERR_INVALID_COMPLEXPLANE";break;} - case -1074395300: - { errorText = "ERR_INVALID_METERARCMODE";break;} - case -1074395301: - { errorText = "ERR_ROI_NOT_2_LINES";break;} - case -1074395302: - { errorText = "ERR_INVALID_THRESHOLDMETHOD";break;} - case -1074395303: - { errorText = "ERR_INVALID_NUM_OF_CLASSES";break;} - case -1074395304: - { errorText = "ERR_INVALID_MATHTRANSFORMMETHOD";break;} - case -1074395305: - { errorText = "ERR_INVALID_REFERENCEMODE";break;} - case -1074395306: - { errorText = "ERR_INVALID_TOOL";break;} - case -1074395307: - { errorText = "ERR_PRECISION_NOT_GTR_THAN_0";break;} - case -1074395308: - { errorText = "ERR_INVALID_COLORSENSITIVITY";break;} - case -1074395309: - { errorText = "ERR_INVALID_WINDOW_THREAD_POLICY";break;} - case -1074395310: - { errorText = "ERR_INVALID_PALETTE_TYPE";break;} - case -1074395311: - { errorText = "ERR_INVALID_COLOR_SPECTRUM";break;} - case -1074395312: - { errorText = "ERR_LCD_CALIBRATE";break;} - case -1074395313: - { errorText = "ERR_WRITE_FILE_NOT_SUPPORTED";break;} - case -1074395316: - { errorText = "ERR_INVALID_KERNEL_CODE";break;} - case -1074395317: - { errorText = "ERR_UNDEF_POINT";break;} - case -1074395318: - { errorText = "ERR_INSF_POINTS";break;} - case -1074395319: - { errorText = "ERR_INVALID_SUBPIX_TYPE";break;} - case -1074395320: - { errorText = "ERR_TEMPLATE_EMPTY";break;} - case -1074395321: - { errorText = "ERR_INVALID_MORPHOLOGYMETHOD";break;} - case -1074395322: - { errorText = "ERR_INVALID_TEXTALIGNMENT";break;} - case -1074395323: - { errorText = "ERR_INVALID_FONTCOLOR";break;} - case -1074395324: - { errorText = "ERR_INVALID_SHAPEMODE";break;} - case -1074395325: - { errorText = "ERR_INVALID_DRAWMODE";break;} - case -1074395326: - { errorText = "ERR_INVALID_DRAWMODE_FOR_LINE";break;} - case -1074395327: - { errorText = "ERR_INVALID_SCALINGMODE";break;} - case -1074395328: - { errorText = "ERR_INVALID_INTERPOLATIONMETHOD";break;} - case -1074395329: - { errorText = "ERR_INVALID_OUTLINEMETHOD";break;} - case -1074395330: - { errorText = "ERR_INVALID_BORDER_SIZE";break;} - case -1074395331: - { errorText = "ERR_INVALID_BORDERMETHOD";break;} - case -1074395332: - { errorText = "ERR_INVALID_COMPAREFUNCTION";break;} - case -1074395333: - { errorText = "ERR_INVALID_VERTICAL_TEXT_ALIGNMENT";break;} - case -1074395334: - { errorText = "ERR_INVALID_CONVERSIONSTYLE";break;} - case -1074395335: - { errorText = "ERR_DISPATCH_STATUS_CONFLICT";break;} - case -1074395336: - { errorText = "ERR_UNKNOWN_ALGORITHM";break;} - case -1074395340: - { errorText = "ERR_INVALID_SIZETYPE";break;} - case -1074395343: - { errorText = "ERR_FILE_FILENAME_NULL";break;} - case -1074395345: - { errorText = "ERR_INVALID_FLIPAXIS";break;} - case -1074395346: - { errorText = "ERR_INVALID_INTERPOLATIONMETHOD_FOR_ROTATE";break;} - case -1074395347: - { errorText = "ERR_INVALID_3DDIRECTION";break;} - case -1074395348: - { errorText = "ERR_INVALID_3DPLANE";break;} - case -1074395349: - { errorText = "ERR_INVALID_SKELETONMETHOD";break;} - case -1074395350: - { errorText = "ERR_INVALID_VISION_INFO";break;} - case -1074395351: - { errorText = "ERR_INVALID_RECT";break;} - case -1074395352: - { errorText = "ERR_INVALID_FEATURE_MODE";break;} - case -1074395353: - { errorText = "ERR_INVALID_SEARCH_STRATEGY";break;} - case -1074395354: - { errorText = "ERR_INVALID_COLOR_WEIGHT";break;} - case -1074395355: - { errorText = "ERR_INVALID_NUM_MATCHES_REQUESTED";break;} - case -1074395356: - { errorText = "ERR_INVALID_MIN_MATCH_SCORE";break;} - case -1074395357: - { errorText = "ERR_INVALID_COLOR_IGNORE_MODE";break;} - case -1074395360: - { errorText = "ERR_COMPLEX_PLANE";break;} - case -1074395361: - { errorText = "ERR_INVALID_STEEPNESS";break;} - case -1074395362: - { errorText = "ERR_INVALID_WIDTH";break;} - case -1074395363: - { errorText = "ERR_INVALID_SUBSAMPLING_RATIO";break;} - case -1074395364: - { errorText = "ERR_IGNORE_COLOR_SPECTRUM_SET";break;} - case -1074395365: - { errorText = "ERR_COLOR_TEMPLATE_DESCRIPTOR_NOSPECTRUM";break;} - case -1074395366: - { errorText = "ERR_COLOR_TEMPLATE_DESCRIPTOR_NOSHAPE";break;} - case -1074395367: - { errorText = "ERR_COLOR_TEMPLATE_DESCRIPTOR_ROTATION_5";break;} - case -1074395368: - { errorText = "ERR_COLOR_TEMPLATE_DESCRIPTOR_ROTATION_4";break;} - case -1074395369: - { errorText = "ERR_COLOR_TEMPLATE_DESCRIPTOR_ROTATION_3";break;} - case -1074395370: - { errorText = "ERR_COLOR_TEMPLATE_DESCRIPTOR_ROTATION_2";break;} - case -1074395371: - { errorText = "ERR_COLOR_TEMPLATE_DESCRIPTOR_ROTATION_1";break;} - case -1074395372: - { errorText = "ERR_COLOR_TEMPLATE_DESCRIPTOR_NOROTATION";break;} - case -1074395373: - { errorText = "ERR_COLOR_TEMPLATE_DESCRIPTOR_ROTATION";break;} - case -1074395374: - { errorText = "ERR_COLOR_TEMPLATE_DESCRIPTOR_SHIFT_2";break;} - case -1074395375: - { errorText = "ERR_COLOR_TEMPLATE_DESCRIPTOR_SHIFT_1";break;} - case -1074395376: - { errorText = "ERR_COLOR_TEMPLATE_DESCRIPTOR_NOSHIFT";break;} - case -1074395377: - { errorText = "ERR_COLOR_TEMPLATE_DESCRIPTOR_SHIFT";break;} - case -1074395378: - { errorText = "ERR_COLOR_TEMPLATE_DESCRIPTOR_6";break;} - case -1074395379: - { errorText = "ERR_COLOR_TEMPLATE_DESCRIPTOR_5";break;} - case -1074395380: - { errorText = "ERR_COLOR_TEMPLATE_DESCRIPTOR_4";break;} - case -1074395381: - { errorText = "ERR_COLOR_TEMPLATE_DESCRIPTOR_3";break;} - case -1074395382: - { errorText = "ERR_COLOR_TEMPLATE_DESCRIPTOR_2";break;} - case -1074395383: - { errorText = "ERR_COLOR_TEMPLATE_DESCRIPTOR_1";break;} - case -1074395384: - { errorText = "ERR_COLOR_TEMPLATE_DESCRIPTOR";break;} - case -1074395385: - { errorText = "ERR_COLOR_ROTATION_REQUIRES_SHAPE_FEATURE";break;} - case -1074395386: - { errorText = "ERR_COLOR_MATCH_SETUP_DATA_SHAPE";break;} - case -1074395387: - { errorText = "ERR_COLOR_MATCH_SETUP_DATA";break;} - case -1074395388: - { errorText = "ERR_COLOR_LEARN_SETUP_DATA_SHAPE";break;} - case -1074395389: - { errorText = "ERR_COLOR_LEARN_SETUP_DATA";break;} - case -1074395390: - { errorText = "ERR_COLOR_TEMPLATE_IMAGE_LUMINANCE_CONTRAST_TOO_LOW";break;} - case -1074395391: - { errorText = "ERR_COLOR_TEMPLATE_IMAGE_HUE_CONTRAST_TOO_LOW";break;} - case -1074395392: - { errorText = "ERR_COLOR_TEMPLATE_IMAGE_TOO_LARGE";break;} - case -1074395393: - { errorText = "ERR_COLOR_TEMPLATE_IMAGE_TOO_SMALL";break;} - case -1074395394: - { errorText = "ERR_COLOR_SPECTRUM_MASK";break;} - case -1074395395: - { errorText = "ERR_COLOR_IMAGE_REQUIRED";break;} - case -1074395397: - { errorText = "ERR_COMPLEX_IMAGE_REQUIRED";break;} - case -1074395399: - { errorText = "ERR_MULTICORE_INVALID_ARGUMENT";break;} - case -1074395400: - { errorText = "ERR_MULTICORE_OPERATION";break;} - case -1074395401: - { errorText = "ERR_INVALID_MATCHFACTOR";break;} - case -1074395402: - { errorText = "ERR_INVALID_MAXPOINTS";break;} - case -1074395403: - { errorText = "ERR_EXTRAINFO_VERSION";break;} - case -1074395404: - { errorText = "ERR_INVALID_INTERPOLATIONMETHOD_FOR_UNWRAP";break;} - case -1074395405: - { errorText = "ERR_INVALID_TEXTORIENTATION";break;} - case -1074395406: - { errorText = "ERR_COORDSYS_NOT_FOUND";break;} - case -1074395407: - { errorText = "ERR_INVALID_CONTRAST";break;} - case -1074395408: - { errorText = "ERR_INVALID_DETECTION_MODE";break;} - case -1074395409: - { errorText = "ERR_INVALID_SUBPIXEL_DIVISIONS";break;} - case -1074395410: - { errorText = "ERR_INVALID_ICONS_PER_LINE";break;} - case -1074395549: - { errorText = "ERR_NIOCR_INVALID_NUMBER_OF_OBJECTS_TO_VERIFY";break;} - case -1074395550: - { errorText = "ERR_NIOCR_INVALID_CHARACTER_VALUE";break;} - case -1074395551: - { errorText = "ERR_NIOCR_RENAME_REFCHAR";break;} - case -1074395552: - { errorText = "ERR_NIOCR_NOT_A_VALID_CHARACTER_SET";break;} - case -1074395553: - { errorText = "ERR_NIOCR_INVALID_MIN_BOUNDING_RECT_HEIGHT";break;} - case -1074395554: - { errorText = "ERR_NIOCR_INVALID_READ_RESOLUTION";break;} - case -1074395555: - { errorText = "ERR_NIOCR_INVALID_SPACING_RANGE";break;} - case -1074395556: - { errorText = "ERR_NIOCR_INVALID_BOUNDING_RECT_HEIGHT_RANGE";break;} - case -1074395557: - { errorText = "ERR_NIOCR_INVALID_BOUNDING_RECT_WIDTH_RANGE";break;} - case -1074395558: - { errorText = "ERR_NIOCR_INVALID_CHARACTER_SIZE_RANGE";break;} - case -1074395559: - { errorText = "ERR_NIOCR_INVALID_READ_OPTION";break;} - case -1074395560: - { errorText = "ERR_NIOCR_INVALID_OBJECT_INDEX";break;} - case -1074395561: - { errorText = "ERR_NIOCR_INVALID_NUMBER_OF_CHARACTERS";break;} - case -1074395562: - { errorText = "ERR_NIOCR_BOOLEAN_VALUE_FOR_STRING_ATTRIBUTE";break;} - case -1074395563: - { errorText = "ERR_NIOCR_UNLICENSED";break;} - case -1074395564: - { errorText = "ERR_NIOCR_INVALID_PREDEFINED_CHARACTER";break;} - case -1074395565: - { errorText = "ERR_NIOCR_MUST_BE_SINGLE_CHARACTER";break;} - case -1074395566: - { errorText = "ERR_NIOCR_BOOLEAN_VALUE_FOR_INTEGER_ATTRIBUTE";break;} - case -1074395567: - { errorText = "ERR_NIOCR_STRING_VALUE_FOR_BOOLEAN_ATTRIBUTE";break;} - case -1074395568: - { errorText = "ERR_NIOCR_STRING_VALUE_FOR_INTEGER_ATTRIBUTE";break;} - case -1074395569: - { errorText = "ERR_NIOCR_INVALID_ATTRIBUTE";break;} - case -1074395570: - { errorText = "ERR_NIOCR_INTEGER_VALUE_FOR_BOOLEAN_ATTRIBUTE";break;} - case -1074395571: - { errorText = "ERR_NIOCR_GET_ONLY_ATTRIBUTE";break;} - case -1074395572: - { errorText = "ERR_NIOCR_INTEGER_VALUE_FOR_STRING_ATTRIBUTE";break;} - case -1074395573: - { errorText = "ERR_NIOCR_INVALID_CHARACTER_SET_FILE_VERSION";break;} - case -1074395574: - { errorText = "ERR_NIOCR_CHARACTER_SET_DESCRIPTION_TOO_LONG";break;} - case -1074395575: - { errorText = "ERR_NIOCR_INVALID_NUMBER_OF_EROSIONS";break;} - case -1074395576: - { errorText = "ERR_NIOCR_CHARACTER_VALUE_TOO_LONG";break;} - case -1074395577: - { errorText = "ERR_NIOCR_CHARACTER_VALUE_CANNOT_BE_EMPTYSTRING";break;} - case -1074395578: - { errorText = "ERR_NIOCR_INVALID_CHARACTER_SET_FILE";break;} - case -1074395579: - { errorText = "ERR_NIOCR_INVALID_ASPECT_RATIO";break;} - case -1074395580: - { errorText = "ERR_NIOCR_INVALID_MIN_BOUNDING_RECT_WIDTH";break;} - case -1074395581: - { errorText = "ERR_NIOCR_INVALID_MAX_VERT_ELEMENT_SPACING";break;} - case -1074395582: - { errorText = "ERR_NIOCR_INVALID_MAX_HORIZ_ELEMENT_SPACING";break;} - case -1074395583: - { errorText = "ERR_NIOCR_INVALID_MIN_CHAR_SPACING";break;} - case -1074395584: - { errorText = "ERR_NIOCR_INVALID_THRESHOLD_LIMITS";break;} - case -1074395585: - { errorText = "ERR_NIOCR_INVALID_UPPER_THRESHOLD_LIMIT";break;} - case -1074395586: - { errorText = "ERR_NIOCR_INVALID_LOWER_THRESHOLD_LIMIT";break;} - case -1074395587: - { errorText = "ERR_NIOCR_INVALID_THRESHOLD_RANGE";break;} - case -1074395588: - { errorText = "ERR_NIOCR_INVALID_HIGH_THRESHOLD_VALUE";break;} - case -1074395589: - { errorText = "ERR_NIOCR_INVALID_LOW_THRESHOLD_VALUE";break;} - case -1074395590: - { errorText = "ERR_NIOCR_INVALID_NUMBER_OF_VALID_CHARACTER_POSITIONS";break;} - case -1074395591: - { errorText = "ERR_NIOCR_INVALID_CHARACTER_INDEX";break;} - case -1074395592: - { errorText = "ERR_NIOCR_INVALID_READ_STRATEGY";break;} - case -1074395593: - { errorText = "ERR_NIOCR_INVALID_NUMBER_OF_BLOCKS";break;} - case -1074395594: - { errorText = "ERR_NIOCR_INVALID_SUBSTITUTION_CHARACTER";break;} - case -1074395595: - { errorText = "ERR_NIOCR_INVALID_THRESHOLD_MODE";break;} - case -1074395596: - { errorText = "ERR_NIOCR_INVALID_CHARACTER_SIZE";break;} - case -1074395597: - { errorText = "ERR_NIOCR_NOT_A_VALID_SESSION";break;} - case -1074395598: - { errorText = "ERR_NIOCR_INVALID_ACCEPTANCE_LEVEL";break;} - case -1074395600: - { errorText = "ERR_INFO_NOT_FOUND";break;} - case -1074395601: - { errorText = "ERR_INVALID_EDGE_THRESHOLD";break;} - case -1074395602: - { errorText = "ERR_INVALID_MINIMUM_CURVE_LENGTH";break;} - case -1074395603: - { errorText = "ERR_INVALID_ROW_STEP";break;} - case -1074395604: - { errorText = "ERR_INVALID_COLUMN_STEP";break;} - case -1074395605: - { errorText = "ERR_INVALID_MAXIMUM_END_POINT_GAP";break;} - case -1074395606: - { errorText = "ERR_INVALID_MINIMUM_FEATURES_TO_MATCH";break;} - case -1074395607: - { errorText = "ERR_INVALID_MAXIMUM_FEATURES_PER_MATCH";break;} - case -1074395608: - { errorText = "ERR_INVALID_SUBPIXEL_ITERATIONS";break;} - case -1074395609: - { errorText = "ERR_INVALID_SUBPIXEL_TOLERANCE";break;} - case -1074395610: - { errorText = "ERR_INVALID_INITIAL_MATCH_LIST_LENGTH";break;} - case -1074395611: - { errorText = "ERR_INVALID_MINIMUM_RECTANGLE_DIMENSION";break;} - case -1074395612: - { errorText = "ERR_INVALID_MINIMUM_FEATURE_RADIUS";break;} - case -1074395613: - { errorText = "ERR_INVALID_MINIMUM_FEATURE_LENGTH";break;} - case -1074395614: - { errorText = "ERR_INVALID_MINIMUM_FEATURE_ASPECT_RATIO";break;} - case -1074395615: - { errorText = "ERR_INVALID_MINIMUM_FEATURE_STRENGTH";break;} - case -1074395616: - { errorText = "ERR_INVALID_EDGE_FILTER_SIZE";break;} - case -1074395617: - { errorText = "ERR_INVALID_NUMBER_OF_FEATURES_RANGE";break;} - case -1074395618: - { errorText = "ERR_TOO_MANY_SCALE_RANGES";break;} - case -1074395619: - { errorText = "ERR_TOO_MANY_OCCLUSION_RANGES";break;} - case -1074395620: - { errorText = "ERR_INVALID_CURVE_EXTRACTION_MODE";break;} - case -1074395621: - { errorText = "ERR_INVALID_LEARN_GEOMETRIC_PATTERN_SETUP_DATA";break;} - case -1074395622: - { errorText = "ERR_INVALID_MATCH_GEOMETRIC_PATTERN_SETUP_DATA";break;} - case -1074395623: - { errorText = "ERR_INVALID_SCALE_RANGE";break;} - case -1074395624: - { errorText = "ERR_INVALID_OCCLUSION_RANGE";break;} - case -1074395625: - { errorText = "ERR_INVALID_MATCH_CONSTRAINT_TYPE";break;} - case -1074395626: - { errorText = "ERR_NOT_ENOUGH_TEMPLATE_FEATURES";break;} - case -1074395627: - { errorText = "ERR_NOT_ENOUGH_TEMPLATE_FEATURES_1";break;} - case -1074395628: - { errorText = "ERR_INVALID_GEOMETRIC_MATCHING_TEMPLATE";break;} - case -1074395629: - { errorText = "ERR_INVALID_MAXIMUM_PIXEL_DISTANCE_FROM_LINE";break;} - case -1074395630: - { errorText = "ERR_INVALID_MAXIMUM_FEATURES_LEARNED";break;} - case -1074395631: - { errorText = "ERR_INVALID_MIN_MATCH_SEPARATION_DISTANCE";break;} - case -1074395632: - { errorText = "ERR_INVALID_MIN_MATCH_SEPARATION_ANGLE";break;} - case -1074395633: - { errorText = "ERR_INVALID_MIN_MATCH_SEPARATION_SCALE";break;} - case -1074395634: - { errorText = "ERR_INVALID_MAX_MATCH_OVERLAP";break;} - case -1074395635: - { errorText = "ERR_INVALID_SHAPE_DESCRIPTOR";break;} - case -1074395636: - { errorText = "ERR_DIRECTX_NOT_FOUND";break;} - case -1074395637: - { errorText = "ERR_HARDWARE_DOESNT_SUPPORT_NONTEARING";break;} - case -1074395638: - { errorText = "ERR_INVALID_FILL_STYLE";break;} - case -1074395639: - { errorText = "ERR_INVALID_HATCH_STYLE";break;} - case -1074395640: - { errorText = "ERR_TOO_MANY_ZONES";break;} - case -1074395641: - { errorText = "ERR_DUPLICATE_LABEL";break;} - case -1074395642: - { errorText = "ERR_LABEL_NOT_FOUND";break;} - case -1074395643: - { errorText = "ERR_INVALID_NUMBER_OF_MATCH_OPTIONS";break;} - case -1074395644: - { errorText = "ERR_LABEL_TOO_LONG";break;} - case -1074395645: - { errorText = "ERR_INVALID_NUMBER_OF_LABELS";break;} - case -1074395646: - { errorText = "ERR_NO_TEMPLATE_TO_LEARN";break;} - case -1074395647: - { errorText = "ERR_INVALID_MULTIPLE_GEOMETRIC_TEMPLATE";break;} - case -1074395648: - { errorText = "ERR_TEMPLATE_NOT_LEARNED";break;} - case -1074395649: - { errorText = "ERR_INVALID_GEOMETRIC_FEATURE_TYPE";break;} - case -1074395650: - { errorText = "ERR_CURVE_EXTRACTION_MODE_MUST_BE_SAME";break;} - case -1074395651: - { errorText = "ERR_EDGE_FILTER_SIZE_MUST_BE_SAME";break;} - case -1074395652: - { errorText = "ERR_OPENING_NEWER_GEOMETRIC_MATCHING_TEMPLATE";break;} - case -1074395653: - { errorText = "ERR_OPENING_NEWER_MULTIPLE_GEOMETRIC_TEMPLATE";break;} - case -1074395654: - { errorText = "ERR_GRADING_INFORMATION_NOT_FOUND";break;} - case -1074395655: - { errorText = "ERR_ENABLE_CALIBRATION_SUPPORT_MUST_BE_SAME";break;} - case -1074395656: - { errorText = "ERR_SMOOTH_CONTOURS_MUST_BE_SAME";break;} - case -1074395700: - { errorText = "ERR_REQUIRES_WIN2000_OR_NEWER";break;} - case -1074395701: - { errorText = "ERR_INVALID_MATRIX_SIZE_RANGE";break;} - case -1074395702: - { errorText = "ERR_INVALID_LENGTH";break;} - case -1074395703: - { errorText = "ERR_INVALID_TYPE_OF_FLATTEN";break;} - case -1074395704: - { errorText = "ERR_INVALID_COMPRESSION_TYPE";break;} - case -1074395705: - { errorText = "ERR_DATA_CORRUPTED";break;} - case -1074395706: - { errorText = "ERR_AVI_SESSION_ALREADY_OPEN";break;} - case -1074395707: - { errorText = "ERR_AVI_WRITE_SESSION_REQUIRED";break;} - case -1074395708: - { errorText = "ERR_AVI_READ_SESSION_REQUIRED";break;} - case -1074395709: - { errorText = "ERR_AVI_UNOPENED_SESSION";break;} - case -1074395710: - { errorText = "ERR_TOO_MANY_PARTICLES";break;} - case -1074395711: - { errorText = "ERR_NOT_ENOUGH_REGIONS";break;} - case -1074395712: - { errorText = "ERR_WRONG_REGION_TYPE";break;} - case -1074395713: - { errorText = "ERR_VALUE_NOT_IN_ENUM";break;} - case -1074395714: - { errorText = "ERR_INVALID_AXIS_ORIENTATION";break;} - case -1074395715: - { errorText = "ERR_INVALID_CALIBRATION_UNIT";break;} - case -1074395716: - { errorText = "ERR_INVALID_SCALING_METHOD";break;} - case -1074395717: - { errorText = "ERR_INVALID_RANGE";break;} - case -1074395718: - { errorText = "ERR_LAB_VERSION";break;} - case -1074395719: - { errorText = "ERR_BAD_ROI_BOX";break;} - case -1074395720: - { errorText = "ERR_BAD_ROI";break;} - case -1074395721: - { errorText = "ERR_INVALID_BIT_DEPTH";break;} - case -1074395722: - { errorText = "ERR_CLASSIFIER_CLASSIFY_IMAGE_WITH_CUSTOM_SESSION";break;} - case -1074395723: - { errorText = "ERR_CUSTOMDATA_KEY_NOT_FOUND";break;} - case -1074395724: - { errorText = "ERR_CUSTOMDATA_INVALID_SIZE";break;} - case -1074395725: - { errorText = "ERR_DATA_VERSION";break;} - case -1074395726: - { errorText = "ERR_MATCHFACTOR_OBSOLETE";break;} - case -1074395727: - { errorText = "ERR_UNSUPPORTED_2D_BARCODE_SEARCH_MODE";break;} - case -1074395728: - { errorText = "ERR_INVALID_2D_BARCODE_SEARCH_MODE";break;} - case -1074395754: - { errorText = "ERR_TRIG_TIMEOUT";break;} - case -1074395756: - { errorText = "ERR_DLL_FUNCTION_NOT_FOUND";break;} - case -1074395757: - { errorText = "ERR_DLL_NOT_FOUND";break;} - case -1074395758: - { errorText = "ERR_BOARD_NOT_OPEN";break;} - case -1074395760: - { errorText = "ERR_BOARD_NOT_FOUND";break;} - case -1074395762: - { errorText = "ERR_INVALID_NIBLACK_DEVIATION_FACTOR";break;} - case -1074395763: - { errorText = "ERR_INVALID_NORMALIZATION_METHOD";break;} - case -1074395766: - { errorText = "ERR_DEPRECATED_FUNCTION";break;} - case -1074395767: - { errorText = "ERR_INVALID_ALIGNMENT";break;} - case -1074395768: - { errorText = "ERR_INVALID_SCALE";break;} - case -1074395769: - { errorText = "ERR_INVALID_EDGE_THICKNESS";break;} - case -1074395770: - { errorText = "ERR_INVALID_INSPECTION_TEMPLATE";break;} - case -1074395771: - { errorText = "ERR_OPENING_NEWER_INSPECTION_TEMPLATE";break;} - case -1074395772: - { errorText = "ERR_INVALID_REGISTRATION_METHOD";break;} - case -1074395773: - { errorText = "ERR_NO_DEST_IMAGE";break;} - case -1074395774: - { errorText = "ERR_NO_LABEL";break;} - case -1074395775: - { errorText = "ERR_ROI_HAS_OPEN_CONTOURS";break;} - case -1074395776: - { errorText = "ERR_INVALID_USE_OF_COMPACT_SESSION_FILE";break;} - case -1074395777: - { errorText = "ERR_INCOMPATIBLE_CLASSIFIER_TYPES";break;} - case -1074395778: - { errorText = "ERR_INVALID_KERNEL_SIZE";break;} - case -1074395779: - { errorText = "ERR_CANNOT_COMPACT_UNTRAINED";break;} - case -1074395780: - { errorText = "ERR_INVALID_PARTICLE_TYPE";break;} - case -1074395781: - { errorText = "ERR_CLASSIFIER_INVALID_ENGINE_TYPE";break;} - case -1074395782: - { errorText = "ERR_DESCRIPTION_TOO_LONG";break;} - case -1074395783: - { errorText = "ERR_BAD_SAMPLE_INDEX";break;} - case -1074395784: - { errorText = "ERR_INVALID_LIMITS";break;} - case -1074395785: - { errorText = "ERR_NO_PARTICLE";break;} - case -1074395786: - { errorText = "ERR_INVALID_PARTICLE_OPTIONS";break;} - case -1074395787: - { errorText = "ERR_INVALID_CLASSIFIER_TYPE";break;} - case -1074395788: - { errorText = "ERR_NO_SAMPLES";break;} - case -1074395789: - { errorText = "ERR_OPENING_NEWER_CLASSIFIER_SESSION";break;} - case -1074395790: - { errorText = "ERR_INVALID_DISTANCE_METRIC";break;} - case -1074395791: - { errorText = "ERR_CLASSIFIER_INVALID_SESSION_TYPE";break;} - case -1074395792: - { errorText = "ERR_CLASSIFIER_SESSION_NOT_TRAINED";break;} - case -1074395793: - { errorText = "ERR_INVALID_OPERATION_ON_COMPACT_SESSION_ATTEMPTED";break;} - case -1074395794: - { errorText = "ERR_K_TOO_HIGH";break;} - case -1074395795: - { errorText = "ERR_K_TOO_LOW";break;} - case -1074395796: - { errorText = "ERR_INVALID_KNN_METHOD";break;} - case -1074395797: - { errorText = "ERR_INVALID_CLASSIFIER_SESSION";break;} - case -1074395798: - { errorText = "ERR_INVALID_CUSTOM_SAMPLE";break;} - case -1074395799: - { errorText = "ERR_INTERNAL";break;} - case -1074395800: - { errorText = "ERR_PROTECTION";break;} - case -1074395801: - { errorText = "ERR_TOO_MANY_CONTOURS";break;} - case -1074395837: - { errorText = "ERR_INVALID_COMPRESSION_RATIO";break;} - case -1074395840: - { errorText = "ERR_BAD_INDEX";break;} - case -1074395875: - { errorText = "ERR_BARCODE_PHARMACODE";break;} - case -1074395876: - { errorText = "ERR_UNSUPPORTED_COLOR_MODE";break;} - case -1074395877: - { errorText = "ERR_COLORMODE_REQUIRES_CHANGECOLORSPACE2";break;} - case -1074395878: - { errorText = "ERR_PROP_NODE_WRITE_NOT_SUPPORTED";break;} - case -1074395879: - { errorText = "ERR_BAD_MEASURE";break;} - case -1074395880: - { errorText = "ERR_PARTICLE";break;} - case -1074395920: - { errorText = "ERR_NUMBER_CLASS";break;} - case -1074395953: - { errorText = "ERR_INVALID_WAVELET_TRANSFORM_MODE";break;} - case -1074395954: - { errorText = "ERR_INVALID_QUANTIZATION_STEP_SIZE";break;} - case -1074395955: - { errorText = "ERR_INVALID_MAX_WAVELET_TRANSFORM_LEVEL";break;} - case -1074395956: - { errorText = "ERR_INVALID_QUALITY";break;} - case -1074395957: - { errorText = "ERR_ARRAY_SIZE_MISMATCH";break;} - case -1074395958: - { errorText = "ERR_WINDOW_ID";break;} - case -1074395959: - { errorText = "ERR_CREATE_WINDOW";break;} - case -1074395960: - { errorText = "ERR_INIT";break;} - case -1074395971: - { errorText = "ERR_INVALID_OFFSET";break;} - case -1074395972: - { errorText = "ERR_DIRECTX_ENUMERATE_FILTERS";break;} - case -1074395973: - { errorText = "ERR_JPEG2000_UNSUPPORTED_MULTIPLE_LAYERS";break;} - case -1074395974: - { errorText = "ERR_UNSUPPORTED_JPEG2000_COLORSPACE_METHOD";break;} - case -1074395975: - { errorText = "ERR_AVI_TIMEOUT";break;} - case -1074395976: - { errorText = "ERR_NUMBER_OF_PALETTE_COLORS";break;} - case -1074395977: - { errorText = "ERR_AVI_VERSION";break;} - case -1074395978: - { errorText = "ERR_INVALID_PARTICLE_NUMBER";break;} - case -1074395979: - { errorText = "ERR_INVALID_PARTICLE_INFO";break;} - case -1074395980: - { errorText = "ERR_COM_INITIALIZE";break;} - case -1074395981: - { errorText = "ERR_INSUFFICIENT_BUFFER_SIZE";break;} - case -1074395982: - { errorText = "ERR_INVALID_FRAMES_PER_SECOND";break;} - case -1074395983: - { errorText = "ERR_FILE_NO_SPACE";break;} - case -1074395984: - { errorText = "ERR_FILE_INVALID_DATA_TYPE";break;} - case -1074395985: - { errorText = "ERR_FILE_OPERATION";break;} - case -1074395986: - { errorText = "ERR_FILE_FORMAT";break;} - case -1074395987: - { errorText = "ERR_FILE_EOF";break;} - case -1074395988: - { errorText = "ERR_FILE_WRITE";break;} - case -1074395989: - { errorText = "ERR_FILE_READ";break;} - case -1074395990: - { errorText = "ERR_FILE_GET_INFO";break;} - case -1074395991: - { errorText = "ERR_FILE_INVALID_TYPE";break;} - case -1074395992: - { errorText = "ERR_FILE_PERMISSION";break;} - case -1074395993: - { errorText = "ERR_FILE_IO_ERR";break;} - case -1074395994: - { errorText = "ERR_FILE_TOO_MANY_OPEN";break;} - case -1074395995: - { errorText = "ERR_FILE_NOT_FOUND";break;} - case -1074395996: - { errorText = "ERR_FILE_OPEN";break;} - case -1074395997: - { errorText = "ERR_FILE_ARGERR";break;} - case -1074395998: - { errorText = "ERR_FILE_COLOR_TABLE";break;} - case -1074395999: - { errorText = "ERR_FILE_FILE_TYPE";break;} - case -1074396000: - { errorText = "ERR_FILE_FILE_HEADER";break;} - case -1074396001: - { errorText = "ERR_TOO_MANY_AVI_SESSIONS";break;} - case -1074396002: - { errorText = "ERR_INVALID_LINEGAUGEMETHOD";break;} - case -1074396003: - { errorText = "ERR_AVI_DATA_EXCEEDS_BUFFER_SIZE";break;} - case -1074396004: - { errorText = "ERR_DIRECTX_CERTIFICATION_FAILURE";break;} - case -1074396005: - { errorText = "ERR_INVALID_AVI_SESSION";break;} - case -1074396006: - { errorText = "ERR_DIRECTX_UNKNOWN_COMPRESSION_FILTER";break;} - case -1074396007: - { errorText = "ERR_DIRECTX_INCOMPATIBLE_COMPRESSION_FILTER";break;} - case -1074396008: - { errorText = "ERR_DIRECTX_NO_FILTER";break;} - case -1074396009: - { errorText = "ERR_DIRECTX";break;} - case -1074396010: - { errorText = "ERR_INVALID_FRAME_NUMBER";break;} - case -1074396011: - { errorText = "ERR_RPC_BIND";break;} - case -1074396012: - { errorText = "ERR_RPC_EXECUTE";break;} - case -1074396013: - { errorText = "ERR_INVALID_VIDEO_MODE";break;} - case -1074396014: - { errorText = "ERR_INVALID_VIDEO_BLIT";break;} - case -1074396015: - { errorText = "ERR_RPC_EXECUTE_IVB";break;} - case -1074396016: - { errorText = "ERR_NO_VIDEO_DRIVER";break;} - case -1074396017: - { errorText = "ERR_OPENING_NEWER_AIM_GRADING_DATA";break;} - case -1074396018: - { errorText = "ERR_INVALID_EDGE_POLARITY_SEARCH_MODE";break;} - case -1074396019: - { errorText = "ERR_INVALID_THRESHOLD_PERCENTAGE";break;} - case -1074396020: - { errorText = "ERR_INVALID_GRADING_MODE";break;} - case -1074396021: - { errorText = "ERR_INVALID_KERNEL_SIZE_FOR_EDGE_DETECTION";break;} - case -1074396022: - { errorText = "ERR_INVALID_SEARCH_MODE_FOR_STRAIGHT_EDGE";break;} - case -1074396023: - { errorText = "ERR_INVALID_ANGLE_TOL_FOR_STRAIGHT_EDGE";break;} - case -1074396024: - { errorText = "ERR_INVALID_MIN_COVERAGE_FOR_STRAIGHT_EDGE";break;} - case -1074396025: - { errorText = "ERR_INVALID_ANGLE_RANGE_FOR_STRAIGHT_EDGE";break;} - case -1074396026: - { errorText = "ERR_INVALID_PROCESS_TYPE_FOR_EDGE_DETECTION";break;} - case -1074396032: - { errorText = "ERR_TEMPLATEDESCRIPTOR_ROTATION_SEARCHSTRATEGY";break;} - case -1074396033: - { errorText = "ERR_TEMPLATEDESCRIPTOR_LEARNSETUPDATA";break;} - case -1074396034: - { errorText = "ERR_TEMPLATEIMAGE_EDGEINFO";break;} - case -1074396035: - { errorText = "ERR_TEMPLATEIMAGE_NOCIRCLE";break;} - case -1074396036: - { errorText = "ERR_INVALID_SKELETONMODE";break;} - case -1074396037: - { errorText = "ERR_TIMEOUT";break;} - case -1074396038: - { errorText = "ERR_FIND_COORDSYS_MORE_THAN_ONE_EDGE";break;} - case -1074396039: - { errorText = "ERR_IO_ERROR";break;} - case -1074396040: - { errorText = "ERR_DRIVER";break;} - case -1074396041: - { errorText = "ERR_INVALID_2D_BARCODE_TYPE";break;} - case -1074396042: - { errorText = "ERR_INVALID_2D_BARCODE_CONTRAST";break;} - case -1074396043: - { errorText = "ERR_INVALID_2D_BARCODE_CELL_SHAPE";break;} - case -1074396044: - { errorText = "ERR_INVALID_2D_BARCODE_SHAPE";break;} - case -1074396045: - { errorText = "ERR_INVALID_2D_BARCODE_SUBTYPE";break;} - case -1074396046: - { errorText = "ERR_INVALID_2D_BARCODE_CONTRAST_FOR_ROI";break;} - case -1074396047: - { errorText = "ERR_INVALID_LINEAR_AVERAGE_MODE";break;} - case -1074396048: - { errorText = "ERR_INVALID_CELL_SAMPLE_SIZE";break;} - case -1074396049: - { errorText = "ERR_INVALID_MATRIX_POLARITY";break;} - case -1074396050: - { errorText = "ERR_INVALID_ECC_TYPE";break;} - case -1074396051: - { errorText = "ERR_INVALID_CELL_FILTER_MODE";break;} - case -1074396052: - { errorText = "ERR_INVALID_DEMODULATION_MODE";break;} - case -1074396053: - { errorText = "ERR_INVALID_BORDER_INTEGRITY";break;} - case -1074396054: - { errorText = "ERR_INVALID_CELL_FILL_TYPE";break;} - case -1074396055: - { errorText = "ERR_INVALID_ASPECT_RATIO";break;} - case -1074396056: - { errorText = "ERR_INVALID_MATRIX_MIRROR_MODE";break;} - case -1074396057: - { errorText = "ERR_INVALID_SEARCH_VECTOR_WIDTH";break;} - case -1074396058: - { errorText = "ERR_INVALID_ROTATION_MODE";break;} - case -1074396059: - { errorText = "ERR_INVALID_MAX_ITERATIONS";break;} - case -1074396060: - { errorText = "ERR_JPEG2000_LOSSLESS_WITH_FLOATING_POINT";break;} - case -1074396061: - { errorText = "ERR_INVALID_WINDOW_SIZE";break;} - case -1074396062: - { errorText = "ERR_INVALID_TOLERANCE";break;} - case -1074396063: - { errorText = "ERR_EXTERNAL_ALIGNMENT";break;} - case -1074396064: - { errorText = "ERR_EXTERNAL_NOT_SUPPORTED";break;} - case -1074396065: - { errorText = "ERR_CANT_RESIZE_EXTERNAL";break;} - case -1074396066: - { errorText = "ERR_INVALID_POINTSYMBOL";break;} - case -1074396067: - { errorText = "ERR_IMAGES_NOT_DIFF";break;} - case -1074396068: - { errorText = "ERR_INVALID_ACTION";break;} - case -1074396069: - { errorText = "ERR_INVALID_COLOR_MODE";break;} - case -1074396070: - { errorText = "ERR_INVALID_FUNCTION";break;} - case -1074396071: - { errorText = "ERR_INVALID_SCAN_DIRECTION";break;} - case -1074396072: - { errorText = "ERR_INVALID_BORDER";break;} - case -1074396073: - { errorText = "ERR_MASK_OUTSIDE_IMAGE";break;} - case -1074396074: - { errorText = "ERR_INCOMP_SIZE";break;} - case -1074396075: - { errorText = "ERR_COORD_SYS_SECOND_AXIS";break;} - case -1074396076: - { errorText = "ERR_COORD_SYS_FIRST_AXIS";break;} - case -1074396077: - { errorText = "ERR_INCOMP_TYPE";break;} - case -1074396079: - { errorText = "ERR_INVALID_METAFILE_HANDLE";break;} - case -1074396080: - { errorText = "ERR_INVALID_IMAGE_TYPE";break;} - case -1074396081: - { errorText = "ERR_BAD_PASSWORD";break;} - case -1074396082: - { errorText = "ERR_PALETTE_NOT_SUPPORTED";break;} - case -1074396083: - { errorText = "ERR_ROLLBACK_TIMEOUT";break;} - case -1074396084: - { errorText = "ERR_ROLLBACK_DELETE_TIMER";break;} - case -1074396085: - { errorText = "ERR_ROLLBACK_INIT_TIMER";break;} - case -1074396086: - { errorText = "ERR_ROLLBACK_START_TIMER";break;} - case -1074396087: - { errorText = "ERR_ROLLBACK_STOP_TIMER";break;} - case -1074396088: - { errorText = "ERR_ROLLBACK_RESIZE";break;} - case -1074396089: - { errorText = "ERR_ROLLBACK_RESOURCE_REINITIALIZE";break;} - case -1074396090: - { errorText = "ERR_ROLLBACK_RESOURCE_ENABLED";break;} - case -1074396091: - { errorText = "ERR_ROLLBACK_RESOURCE_UNINITIALIZED_ENABLE";break;} - case -1074396092: - { errorText = "ERR_ROLLBACK_RESOURCE_NON_EMPTY_INITIALIZE";break;} - case -1074396093: - { errorText = "ERR_ROLLBACK_RESOURCE_LOCKED";break;} - case -1074396094: - { errorText = "ERR_ROLLBACK_RESOURCE_CANNOT_UNLOCK";break;} - case -1074396095: - { errorText = "ERR_CALIBRATION_DUPLICATE_REFERENCE_POINT";break;} - case -1074396096: - { errorText = "ERR_NOT_AN_OBJECT";break;} - case -1074396097: - { errorText = "ERR_INVALID_PARTICLE_PARAMETER_VALUE";break;} - case -1074396098: - { errorText = "ERR_RESERVED_MUST_BE_NULL";break;} - case -1074396099: - { errorText = "ERR_CALIBRATION_INFO_SIMPLE_TRANSFORM";break;} - case -1074396100: - { errorText = "ERR_CALIBRATION_INFO_PERSPECTIVE_PROJECTION";break;} - case -1074396101: - { errorText = "ERR_CALIBRATION_INFO_MICRO_PLANE";break;} - case -1074396102: - { errorText = "ERR_CALIBRATION_INFO_6";break;} - case -1074396103: - { errorText = "ERR_CALIBRATION_INFO_5";break;} - case -1074396104: - { errorText = "ERR_CALIBRATION_INFO_4";break;} - case -1074396105: - { errorText = "ERR_CALIBRATION_INFO_3";break;} - case -1074396106: - { errorText = "ERR_CALIBRATION_INFO_2";break;} - case -1074396107: - { errorText = "ERR_CALIBRATION_INFO_1";break;} - case -1074396108: - { errorText = "ERR_CALIBRATION_ERRORMAP";break;} - case -1074396109: - { errorText = "ERR_CALIBRATION_INVALID_SCALING_FACTOR";break;} - case -1074396110: - { errorText = "ERR_CALIBRATION_INFO_VERSION";break;} - case -1074396111: - { errorText = "ERR_CALIBRATION_FAILED_TO_FIND_GRID";break;} - case -1074396112: - { errorText = "ERR_INCOMP_MATRIX_SIZE";break;} - case -1074396113: - { errorText = "ERR_CALIBRATION_IMAGE_UNCALIBRATED";break;} - case -1074396114: - { errorText = "ERR_CALIBRATION_INVALID_ROI";break;} - case -1074396115: - { errorText = "ERR_CALIBRATION_IMAGE_CORRECTED";break;} - case -1074396116: - { errorText = "ERR_CALIBRATION_INSF_POINTS";break;} - case -1074396117: - { errorText = "ERR_MATRIX_SIZE";break;} - case -1074396118: - { errorText = "ERR_INVALID_STEP_SIZE";break;} - case -1074396119: - { errorText = "ERR_CUSTOMDATA_INVALID_KEY";break;} - case -1074396120: - { errorText = "ERR_NOT_IMAGE";break;} - case -1074396121: - { errorText = "ERR_SATURATION_THRESHOLD_OUT_OF_RANGE";break;} - case -1074396122: - { errorText = "ERR_DRAWTEXT_COLOR_MUST_BE_GRAYSCALE";break;} - case -1074396123: - { errorText = "ERR_INVALID_CALIBRATION_MODE";break;} - case -1074396124: - { errorText = "ERR_INVALID_CALIBRATION_ROI_MODE";break;} - case -1074396125: - { errorText = "ERR_INVALID_CONTRAST_THRESHOLD";break;} - case -1074396126: - { errorText = "ERR_ROLLBACK_RESOURCE_CONFLICT_1";break;} - case -1074396127: - { errorText = "ERR_ROLLBACK_RESOURCE_CONFLICT_2";break;} - case -1074396128: - { errorText = "ERR_ROLLBACK_RESOURCE_CONFLICT_3";break;} - case -1074396129: - { errorText = "ERR_ROLLBACK_UNBOUNDED_INTERFACE";break;} - case -1074396130: - { errorText = "ERR_NOT_RECT_OR_ROTATED_RECT";break;} - case -1074396132: - { errorText = "ERR_MASK_NOT_TEMPLATE_SIZE";break;} - case -1074396133: - { errorText = "ERR_THREAD_COULD_NOT_INITIALIZE";break;} - case -1074396134: - { errorText = "ERR_THREAD_INITIALIZING";break;} - case -1074396135: - { errorText = "ERR_INVALID_BUTTON_LABEL";break;} - case -1074396136: - { errorText = "ERR_DIRECTX_INVALID_FILTER_QUALITY";break;} - case -1074396137: - { errorText = "ERR_DIRECTX_DLL_NOT_FOUND";break;} - case -1074396138: - { errorText = "ERR_ROLLBACK_NOT_SUPPORTED";break;} - case -1074396139: - { errorText = "ERR_ROLLBACK_RESOURCE_OUT_OF_MEMORY";break;} - case -1074396140: - { errorText = "ERR_BARCODE_CODE128_SET";break;} - case -1074396141: - { errorText = "ERR_BARCODE_CODE128_FNC";break;} - case -1074396142: - { errorText = "ERR_BARCODE_INVALID";break;} - case -1074396143: - { errorText = "ERR_BARCODE_TYPE";break;} - case -1074396144: - { errorText = "ERR_BARCODE_CODE93_SHIFT";break;} - case -1074396145: - { errorText = "ERR_BARCODE_UPCA";break;} - case -1074396146: - { errorText = "ERR_BARCODE_MSI";break;} - case -1074396147: - { errorText = "ERR_BARCODE_I25";break;} - case -1074396148: - { errorText = "ERR_BARCODE_EAN13";break;} - case -1074396149: - { errorText = "ERR_BARCODE_EAN8";break;} - case -1074396150: - { errorText = "ERR_BARCODE_CODE128";break;} - case -1074396151: - { errorText = "ERR_BARCODE_CODE93";break;} - case -1074396152: - { errorText = "ERR_BARCODE_CODE39";break;} - case -1074396153: - { errorText = "ERR_BARCODE_CODABAR";break;} - case -1074396154: - { errorText = "ERR_IMAGE_TOO_SMALL";break;} - case -1074396155: - { errorText = "ERR_UNINIT";break;} - case -1074396156: - { errorText = "ERR_NEED_FULL_VERSION";break;} - case -1074396157: - { errorText = "ERR_UNREGISTERED";break;} - case -1074396158: - { errorText = "ERR_MEMORY_ERROR";break;} - case -1074396159: - { errorText = "ERR_OUT_OF_MEMORY";break;} - case -1074396160: - { errorText = "ERR_SYSTEM_ERROR";break;} - case 0: - { errorText = "ERR_SUCCESS";break;} - // end National Instruments defined errors - - // begin BAE defined errors - case ERR_VISION_GENERAL_ERROR: - { errorText = "ERR_VISION_GENERAL_ERROR";break;} - case ERR_COLOR_NOT_FOUND: - { errorText = "ERR_COLOR_NOT_FOUND";break;} - case ERR_PARTICLE_TOO_SMALL: - { errorText = "ERR_PARTICLE_TOO_SMALL";break;} - case ERR_CAMERA_FAILURE: - { errorText = "ERR_CAMERA_FAILURE";break;} - case ERR_CAMERA_SOCKET_CREATE_FAILED: - { errorText = "ERR_CAMERA_SOCKET_CREATE_FAILED";break;} - case ERR_CAMERA_CONNECT_FAILED: - { errorText = "ERR_CAMERA_CONNECT_FAILED";break;} - case ERR_CAMERA_STALE_IMAGE: - { errorText = "ERR_CAMERA_STALE_IMAGE";break;} - case ERR_CAMERA_NOT_INITIALIZED: - { errorText = "ERR_CAMERA_NOT_INITIALIZED";break;} - case ERR_CAMERA_NO_BUFFER_AVAILABLE: - { errorText = "ERR_CAMERA_NO_BUFFER_AVAILABLE";break;} - case ERR_CAMERA_HEADER_ERROR: - { errorText = "ERR_CAMERA_HEADER_ERROR";break;} - case ERR_CAMERA_BLOCKING_TIMEOUT: - { errorText = "ERR_CAMERA_BLOCKING_TIMEOUT";break;} - case ERR_CAMERA_AUTHORIZATION_FAILED: - { errorText = "ERR_CAMERA_AUTHORIZATION_FAILED";break;} - case ERR_CAMERA_TASK_SPAWN_FAILED: - { errorText = "ERR_CAMERA_TASK_SPAWN_FAILED";break;} - case ERR_CAMERA_TASK_INPUT_OUT_OF_RANGE: - { errorText = "ERR_CAMERA_TASK_INPUT_OUT_OF_RANGE";break;} - case ERR_CAMERA_COMMAND_FAILURE: - { errorText = "ERR_CAMERA_COMMAND_FAILURE";break;} - } - - return errorText; + switch (errorCode) { + default: { + errorText = "UNKNOWN_ERROR"; + break; + } + case -1074395138: { + errorText = "ERR_OCR_REGION_TOO_SMALL"; + break; + } + case -1074395139: { + errorText = "ERR_IMAQ_QR_DIMENSION_INVALID"; + break; + } + case -1074395140: { + errorText = "ERR_OCR_CHAR_REPORT_CORRUPTED"; + break; + } + case -1074395141: { + errorText = "ERR_OCR_NO_TEXT_FOUND"; + break; + } + case -1074395142: { + errorText = "ERR_QR_DETECTION_MODELTYPE"; + break; + } + case -1074395143: { + errorText = "ERR_QR_DETECTION_MODE"; + break; + } + case -1074395144: { + errorText = "ERR_QR_INVALID_BARCODE"; + break; + } + case -1074395145: { + errorText = "ERR_QR_INVALID_READ"; + break; + } + case -1074395146: { + errorText = "ERR_QR_DETECTION_VERSION"; + break; + } + case -1074395147: { + errorText = "ERR_BARCODE_RSSLIMITED"; + break; + } + case -1074395148: { + errorText = "ERR_OVERLAY_GROUP_NOT_FOUND"; + break; + } + case -1074395149: { + errorText = "ERR_DUPLICATE_TRANSFORM_TYPE"; + break; + } + case -1074395151: { + errorText = "ERR_OCR_CORRECTION_FAILED"; + break; + } + case -1074395155: { + errorText = "ERR_OCR_ORIENT_DETECT_FAILED"; + break; + } + case -1074395156: { + errorText = "ERR_OCR_SKEW_DETECT_FAILED"; + break; + } + case -1074395158: { + errorText = "ERR_OCR_INVALID_CONTRASTMODE"; + break; + } + case -1074395159: { + errorText = "ERR_OCR_INVALID_TOLERANCE"; + break; + } + case -1074395160: { + errorText = "ERR_OCR_INVALID_MAXPOINTSIZE"; + break; + } + case -1074395161: { + errorText = "ERR_OCR_INVALID_CORRECTIONLEVEL"; + break; + } + case -1074395162: { + errorText = "ERR_OCR_INVALID_CORRECTIONMODE"; + break; + } + case -1074395163: { + errorText = "ERR_OCR_INVALID_CHARACTERPREFERENCE"; + break; + } + case -1074395164: { + errorText = "ERR_OCR_ADD_WORD_FAILED"; + break; + } + case -1074395165: { + errorText = "ERR_OCR_WTS_DIR_NOT_FOUND"; + break; + } + case -1074395166: { + errorText = "ERR_OCR_BIN_DIR_NOT_FOUND"; + break; + } + case -1074395167: { + errorText = "ERR_OCR_INVALID_OUTPUTDELIMITER"; + break; + } + case -1074395168: { + errorText = "ERR_OCR_INVALID_AUTOCORRECTIONMODE"; + break; + } + case -1074395169: { + errorText = "ERR_OCR_INVALID_RECOGNITIONMODE"; + break; + } + case -1074395170: { + errorText = "ERR_OCR_INVALID_CHARACTERTYPE"; + break; + } + case -1074395171: { + errorText = "ERR_OCR_INI_FILE_NOT_FOUND"; + break; + } + case -1074395172: { + errorText = "ERR_OCR_INVALID_CHARACTERSET"; + break; + } + case -1074395173: { + errorText = "ERR_OCR_INVALID_LANGUAGE"; + break; + } + case -1074395174: { + errorText = "ERR_OCR_INVALID_AUTOORIENTMODE"; + break; + } + case -1074395175: { + errorText = "ERR_OCR_BAD_USER_DICTIONARY"; + break; + } + case -1074395178: { + errorText = "ERR_OCR_RECOGNITION_FAILED"; + break; + } + case -1074395179: { + errorText = "ERR_OCR_PREPROCESSING_FAILED"; + break; + } + case -1074395200: { + errorText = "ERR_OCR_INVALID_PARAMETER"; + break; + } + case -1074395201: { + errorText = "ERR_OCR_LOAD_LIBRARY"; + break; + } + case -1074395203: { + errorText = "ERR_OCR_LIB_INIT"; + break; + } + case -1074395210: { + errorText = "ERR_OCR_CANNOT_MATCH_TEXT_TEMPLATE"; + break; + } + case -1074395211: { + errorText = "ERR_OCR_BAD_TEXT_TEMPLATE"; + break; + } + case -1074395212: { + errorText = "ERR_OCR_TEMPLATE_WRONG_SIZE"; + break; + } + case -1074395233: { + errorText = "ERR_TEMPLATE_IMAGE_TOO_LARGE"; + break; + } + case -1074395234: { + errorText = "ERR_TEMPLATE_IMAGE_TOO_SMALL"; + break; + } + case -1074395235: { + errorText = "ERR_TEMPLATE_IMAGE_CONTRAST_TOO_LOW"; + break; + } + case -1074395237: { + errorText = "ERR_TEMPLATE_DESCRIPTOR_SHIFT_1"; + break; + } + case -1074395238: { + errorText = "ERR_TEMPLATE_DESCRIPTOR_NOSHIFT"; + break; + } + case -1074395239: { + errorText = "ERR_TEMPLATE_DESCRIPTOR_SHIFT"; + break; + } + case -1074395240: { + errorText = "ERR_TEMPLATE_DESCRIPTOR_ROTATION_1"; + break; + } + case -1074395241: { + errorText = "ERR_TEMPLATE_DESCRIPTOR_NOROTATION"; + break; + } + case -1074395242: { + errorText = "ERR_TEMPLATE_DESCRIPTOR_ROTATION"; + break; + } + case -1074395243: { + errorText = "ERR_TEMPLATE_DESCRIPTOR_4"; + break; + } + case -1074395244: { + errorText = "ERR_TEMPLATE_DESCRIPTOR_3"; + break; + } + case -1074395245: { + errorText = "ERR_TEMPLATE_DESCRIPTOR_2"; + break; + } + case -1074395246: { + errorText = "ERR_TEMPLATE_DESCRIPTOR_1"; + break; + } + case -1074395247: { + errorText = "ERR_TEMPLATE_DESCRIPTOR"; + break; + } + case -1074395248: { + errorText = "ERR_TOO_MANY_ROTATION_ANGLE_RANGES"; + break; + } + case -1074395249: { + errorText = "ERR_ROTATION_ANGLE_RANGE_TOO_LARGE"; + break; + } + case -1074395250: { + errorText = "ERR_MATCH_SETUP_DATA"; + break; + } + case -1074395251: { + errorText = "ERR_INVALID_MATCH_MODE"; + break; + } + case -1074395252: { + errorText = "ERR_LEARN_SETUP_DATA"; + break; + } + case -1074395253: { + errorText = "ERR_INVALID_LEARN_MODE"; + break; + } + case -1074395256: { + errorText = "ERR_EVEN_WINDOW_SIZE"; + break; + } + case -1074395257: { + errorText = "ERR_INVALID_EDGE_DIR"; + break; + } + case -1074395258: { + errorText = "ERR_BAD_FILTER_WIDTH"; + break; + } + case -1074395260: { + errorText = "ERR_HEAP_TRASHED"; + break; + } + case -1074395261: { + errorText = "ERR_GIP_RANGE"; + break; + } + case -1074395262: { + errorText = "ERR_LCD_BAD_MATCH"; + break; + } + case -1074395263: { + errorText = "ERR_LCD_NO_SEGMENTS"; + break; + } + case -1074395265: { + errorText = "ERR_BARCODE"; + break; + } + case -1074395267: { + errorText = "ERR_COMPLEX_ROOT"; + break; + } + case -1074395268: { + errorText = "ERR_LINEAR_COEFF"; + break; + } + case -1074395269: { + errorText = "ERR_NULL_POINTER"; + break; + } + case -1074395270: { + errorText = "ERR_DIV_BY_ZERO"; + break; + } + case -1074395275: { + errorText = "ERR_INVALID_BROWSER_IMAGE"; + break; + } + case -1074395276: { + errorText = "ERR_LINES_PARALLEL"; + break; + } + case -1074395277: { + errorText = "ERR_BARCODE_CHECKSUM"; + break; + } + case -1074395278: { + errorText = "ERR_LCD_NOT_NUMERIC"; + break; + } + case -1074395279: { + errorText = "ERR_ROI_NOT_POLYGON"; + break; + } + case -1074395280: { + errorText = "ERR_ROI_NOT_RECT"; + break; + } + case -1074395281: { + errorText = "ERR_IMAGE_SMALLER_THAN_BORDER"; + break; + } + case -1074395282: { + errorText = "ERR_CANT_DRAW_INTO_VIEWER"; + break; + } + case -1074395283: { + errorText = "ERR_INVALID_RAKE_DIRECTION"; + break; + } + case -1074395284: { + errorText = "ERR_INVALID_EDGE_PROCESS"; + break; + } + case -1074395285: { + errorText = "ERR_INVALID_SPOKE_DIRECTION"; + break; + } + case -1074395286: { + errorText = "ERR_INVALID_CONCENTRIC_RAKE_DIRECTION"; + break; + } + case -1074395287: { + errorText = "ERR_INVALID_LINE"; + break; + } + case -1074395290: { + errorText = "ERR_SHAPEMATCH_BADTEMPLATE"; + break; + } + case -1074395291: { + errorText = "ERR_SHAPEMATCH_BADIMAGEDATA"; + break; + } + case -1074395292: { + errorText = "ERR_POINTS_ARE_COLLINEAR"; + break; + } + case -1074395293: { + errorText = "ERR_CONTOURID_NOT_FOUND"; + break; + } + case -1074395294: { + errorText = "ERR_CONTOUR_INDEX_OUT_OF_RANGE"; + break; + } + case -1074395295: { + errorText = "ERR_INVALID_INTERPOLATIONMETHOD_INTERPOLATEPOINTS"; + break; + } + case -1074395296: { + errorText = "ERR_INVALID_BARCODETYPE"; + break; + } + case -1074395297: { + errorText = "ERR_INVALID_PARTICLEINFOMODE"; + break; + } + case -1074395298: { + errorText = "ERR_COMPLEXPLANE_NOT_REAL_OR_IMAGINARY"; + break; + } + case -1074395299: { + errorText = "ERR_INVALID_COMPLEXPLANE"; + break; + } + case -1074395300: { + errorText = "ERR_INVALID_METERARCMODE"; + break; + } + case -1074395301: { + errorText = "ERR_ROI_NOT_2_LINES"; + break; + } + case -1074395302: { + errorText = "ERR_INVALID_THRESHOLDMETHOD"; + break; + } + case -1074395303: { + errorText = "ERR_INVALID_NUM_OF_CLASSES"; + break; + } + case -1074395304: { + errorText = "ERR_INVALID_MATHTRANSFORMMETHOD"; + break; + } + case -1074395305: { + errorText = "ERR_INVALID_REFERENCEMODE"; + break; + } + case -1074395306: { + errorText = "ERR_INVALID_TOOL"; + break; + } + case -1074395307: { + errorText = "ERR_PRECISION_NOT_GTR_THAN_0"; + break; + } + case -1074395308: { + errorText = "ERR_INVALID_COLORSENSITIVITY"; + break; + } + case -1074395309: { + errorText = "ERR_INVALID_WINDOW_THREAD_POLICY"; + break; + } + case -1074395310: { + errorText = "ERR_INVALID_PALETTE_TYPE"; + break; + } + case -1074395311: { + errorText = "ERR_INVALID_COLOR_SPECTRUM"; + break; + } + case -1074395312: { + errorText = "ERR_LCD_CALIBRATE"; + break; + } + case -1074395313: { + errorText = "ERR_WRITE_FILE_NOT_SUPPORTED"; + break; + } + case -1074395316: { + errorText = "ERR_INVALID_KERNEL_CODE"; + break; + } + case -1074395317: { + errorText = "ERR_UNDEF_POINT"; + break; + } + case -1074395318: { + errorText = "ERR_INSF_POINTS"; + break; + } + case -1074395319: { + errorText = "ERR_INVALID_SUBPIX_TYPE"; + break; + } + case -1074395320: { + errorText = "ERR_TEMPLATE_EMPTY"; + break; + } + case -1074395321: { + errorText = "ERR_INVALID_MORPHOLOGYMETHOD"; + break; + } + case -1074395322: { + errorText = "ERR_INVALID_TEXTALIGNMENT"; + break; + } + case -1074395323: { + errorText = "ERR_INVALID_FONTCOLOR"; + break; + } + case -1074395324: { + errorText = "ERR_INVALID_SHAPEMODE"; + break; + } + case -1074395325: { + errorText = "ERR_INVALID_DRAWMODE"; + break; + } + case -1074395326: { + errorText = "ERR_INVALID_DRAWMODE_FOR_LINE"; + break; + } + case -1074395327: { + errorText = "ERR_INVALID_SCALINGMODE"; + break; + } + case -1074395328: { + errorText = "ERR_INVALID_INTERPOLATIONMETHOD"; + break; + } + case -1074395329: { + errorText = "ERR_INVALID_OUTLINEMETHOD"; + break; + } + case -1074395330: { + errorText = "ERR_INVALID_BORDER_SIZE"; + break; + } + case -1074395331: { + errorText = "ERR_INVALID_BORDERMETHOD"; + break; + } + case -1074395332: { + errorText = "ERR_INVALID_COMPAREFUNCTION"; + break; + } + case -1074395333: { + errorText = "ERR_INVALID_VERTICAL_TEXT_ALIGNMENT"; + break; + } + case -1074395334: { + errorText = "ERR_INVALID_CONVERSIONSTYLE"; + break; + } + case -1074395335: { + errorText = "ERR_DISPATCH_STATUS_CONFLICT"; + break; + } + case -1074395336: { + errorText = "ERR_UNKNOWN_ALGORITHM"; + break; + } + case -1074395340: { + errorText = "ERR_INVALID_SIZETYPE"; + break; + } + case -1074395343: { + errorText = "ERR_FILE_FILENAME_NULL"; + break; + } + case -1074395345: { + errorText = "ERR_INVALID_FLIPAXIS"; + break; + } + case -1074395346: { + errorText = "ERR_INVALID_INTERPOLATIONMETHOD_FOR_ROTATE"; + break; + } + case -1074395347: { + errorText = "ERR_INVALID_3DDIRECTION"; + break; + } + case -1074395348: { + errorText = "ERR_INVALID_3DPLANE"; + break; + } + case -1074395349: { + errorText = "ERR_INVALID_SKELETONMETHOD"; + break; + } + case -1074395350: { + errorText = "ERR_INVALID_VISION_INFO"; + break; + } + case -1074395351: { + errorText = "ERR_INVALID_RECT"; + break; + } + case -1074395352: { + errorText = "ERR_INVALID_FEATURE_MODE"; + break; + } + case -1074395353: { + errorText = "ERR_INVALID_SEARCH_STRATEGY"; + break; + } + case -1074395354: { + errorText = "ERR_INVALID_COLOR_WEIGHT"; + break; + } + case -1074395355: { + errorText = "ERR_INVALID_NUM_MATCHES_REQUESTED"; + break; + } + case -1074395356: { + errorText = "ERR_INVALID_MIN_MATCH_SCORE"; + break; + } + case -1074395357: { + errorText = "ERR_INVALID_COLOR_IGNORE_MODE"; + break; + } + case -1074395360: { + errorText = "ERR_COMPLEX_PLANE"; + break; + } + case -1074395361: { + errorText = "ERR_INVALID_STEEPNESS"; + break; + } + case -1074395362: { + errorText = "ERR_INVALID_WIDTH"; + break; + } + case -1074395363: { + errorText = "ERR_INVALID_SUBSAMPLING_RATIO"; + break; + } + case -1074395364: { + errorText = "ERR_IGNORE_COLOR_SPECTRUM_SET"; + break; + } + case -1074395365: { + errorText = "ERR_COLOR_TEMPLATE_DESCRIPTOR_NOSPECTRUM"; + break; + } + case -1074395366: { + errorText = "ERR_COLOR_TEMPLATE_DESCRIPTOR_NOSHAPE"; + break; + } + case -1074395367: { + errorText = "ERR_COLOR_TEMPLATE_DESCRIPTOR_ROTATION_5"; + break; + } + case -1074395368: { + errorText = "ERR_COLOR_TEMPLATE_DESCRIPTOR_ROTATION_4"; + break; + } + case -1074395369: { + errorText = "ERR_COLOR_TEMPLATE_DESCRIPTOR_ROTATION_3"; + break; + } + case -1074395370: { + errorText = "ERR_COLOR_TEMPLATE_DESCRIPTOR_ROTATION_2"; + break; + } + case -1074395371: { + errorText = "ERR_COLOR_TEMPLATE_DESCRIPTOR_ROTATION_1"; + break; + } + case -1074395372: { + errorText = "ERR_COLOR_TEMPLATE_DESCRIPTOR_NOROTATION"; + break; + } + case -1074395373: { + errorText = "ERR_COLOR_TEMPLATE_DESCRIPTOR_ROTATION"; + break; + } + case -1074395374: { + errorText = "ERR_COLOR_TEMPLATE_DESCRIPTOR_SHIFT_2"; + break; + } + case -1074395375: { + errorText = "ERR_COLOR_TEMPLATE_DESCRIPTOR_SHIFT_1"; + break; + } + case -1074395376: { + errorText = "ERR_COLOR_TEMPLATE_DESCRIPTOR_NOSHIFT"; + break; + } + case -1074395377: { + errorText = "ERR_COLOR_TEMPLATE_DESCRIPTOR_SHIFT"; + break; + } + case -1074395378: { + errorText = "ERR_COLOR_TEMPLATE_DESCRIPTOR_6"; + break; + } + case -1074395379: { + errorText = "ERR_COLOR_TEMPLATE_DESCRIPTOR_5"; + break; + } + case -1074395380: { + errorText = "ERR_COLOR_TEMPLATE_DESCRIPTOR_4"; + break; + } + case -1074395381: { + errorText = "ERR_COLOR_TEMPLATE_DESCRIPTOR_3"; + break; + } + case -1074395382: { + errorText = "ERR_COLOR_TEMPLATE_DESCRIPTOR_2"; + break; + } + case -1074395383: { + errorText = "ERR_COLOR_TEMPLATE_DESCRIPTOR_1"; + break; + } + case -1074395384: { + errorText = "ERR_COLOR_TEMPLATE_DESCRIPTOR"; + break; + } + case -1074395385: { + errorText = "ERR_COLOR_ROTATION_REQUIRES_SHAPE_FEATURE"; + break; + } + case -1074395386: { + errorText = "ERR_COLOR_MATCH_SETUP_DATA_SHAPE"; + break; + } + case -1074395387: { + errorText = "ERR_COLOR_MATCH_SETUP_DATA"; + break; + } + case -1074395388: { + errorText = "ERR_COLOR_LEARN_SETUP_DATA_SHAPE"; + break; + } + case -1074395389: { + errorText = "ERR_COLOR_LEARN_SETUP_DATA"; + break; + } + case -1074395390: { + errorText = "ERR_COLOR_TEMPLATE_IMAGE_LUMINANCE_CONTRAST_TOO_LOW"; + break; + } + case -1074395391: { + errorText = "ERR_COLOR_TEMPLATE_IMAGE_HUE_CONTRAST_TOO_LOW"; + break; + } + case -1074395392: { + errorText = "ERR_COLOR_TEMPLATE_IMAGE_TOO_LARGE"; + break; + } + case -1074395393: { + errorText = "ERR_COLOR_TEMPLATE_IMAGE_TOO_SMALL"; + break; + } + case -1074395394: { + errorText = "ERR_COLOR_SPECTRUM_MASK"; + break; + } + case -1074395395: { + errorText = "ERR_COLOR_IMAGE_REQUIRED"; + break; + } + case -1074395397: { + errorText = "ERR_COMPLEX_IMAGE_REQUIRED"; + break; + } + case -1074395399: { + errorText = "ERR_MULTICORE_INVALID_ARGUMENT"; + break; + } + case -1074395400: { + errorText = "ERR_MULTICORE_OPERATION"; + break; + } + case -1074395401: { + errorText = "ERR_INVALID_MATCHFACTOR"; + break; + } + case -1074395402: { + errorText = "ERR_INVALID_MAXPOINTS"; + break; + } + case -1074395403: { + errorText = "ERR_EXTRAINFO_VERSION"; + break; + } + case -1074395404: { + errorText = "ERR_INVALID_INTERPOLATIONMETHOD_FOR_UNWRAP"; + break; + } + case -1074395405: { + errorText = "ERR_INVALID_TEXTORIENTATION"; + break; + } + case -1074395406: { + errorText = "ERR_COORDSYS_NOT_FOUND"; + break; + } + case -1074395407: { + errorText = "ERR_INVALID_CONTRAST"; + break; + } + case -1074395408: { + errorText = "ERR_INVALID_DETECTION_MODE"; + break; + } + case -1074395409: { + errorText = "ERR_INVALID_SUBPIXEL_DIVISIONS"; + break; + } + case -1074395410: { + errorText = "ERR_INVALID_ICONS_PER_LINE"; + break; + } + case -1074395549: { + errorText = "ERR_NIOCR_INVALID_NUMBER_OF_OBJECTS_TO_VERIFY"; + break; + } + case -1074395550: { + errorText = "ERR_NIOCR_INVALID_CHARACTER_VALUE"; + break; + } + case -1074395551: { + errorText = "ERR_NIOCR_RENAME_REFCHAR"; + break; + } + case -1074395552: { + errorText = "ERR_NIOCR_NOT_A_VALID_CHARACTER_SET"; + break; + } + case -1074395553: { + errorText = "ERR_NIOCR_INVALID_MIN_BOUNDING_RECT_HEIGHT"; + break; + } + case -1074395554: { + errorText = "ERR_NIOCR_INVALID_READ_RESOLUTION"; + break; + } + case -1074395555: { + errorText = "ERR_NIOCR_INVALID_SPACING_RANGE"; + break; + } + case -1074395556: { + errorText = "ERR_NIOCR_INVALID_BOUNDING_RECT_HEIGHT_RANGE"; + break; + } + case -1074395557: { + errorText = "ERR_NIOCR_INVALID_BOUNDING_RECT_WIDTH_RANGE"; + break; + } + case -1074395558: { + errorText = "ERR_NIOCR_INVALID_CHARACTER_SIZE_RANGE"; + break; + } + case -1074395559: { + errorText = "ERR_NIOCR_INVALID_READ_OPTION"; + break; + } + case -1074395560: { + errorText = "ERR_NIOCR_INVALID_OBJECT_INDEX"; + break; + } + case -1074395561: { + errorText = "ERR_NIOCR_INVALID_NUMBER_OF_CHARACTERS"; + break; + } + case -1074395562: { + errorText = "ERR_NIOCR_BOOLEAN_VALUE_FOR_STRING_ATTRIBUTE"; + break; + } + case -1074395563: { + errorText = "ERR_NIOCR_UNLICENSED"; + break; + } + case -1074395564: { + errorText = "ERR_NIOCR_INVALID_PREDEFINED_CHARACTER"; + break; + } + case -1074395565: { + errorText = "ERR_NIOCR_MUST_BE_SINGLE_CHARACTER"; + break; + } + case -1074395566: { + errorText = "ERR_NIOCR_BOOLEAN_VALUE_FOR_INTEGER_ATTRIBUTE"; + break; + } + case -1074395567: { + errorText = "ERR_NIOCR_STRING_VALUE_FOR_BOOLEAN_ATTRIBUTE"; + break; + } + case -1074395568: { + errorText = "ERR_NIOCR_STRING_VALUE_FOR_INTEGER_ATTRIBUTE"; + break; + } + case -1074395569: { + errorText = "ERR_NIOCR_INVALID_ATTRIBUTE"; + break; + } + case -1074395570: { + errorText = "ERR_NIOCR_INTEGER_VALUE_FOR_BOOLEAN_ATTRIBUTE"; + break; + } + case -1074395571: { + errorText = "ERR_NIOCR_GET_ONLY_ATTRIBUTE"; + break; + } + case -1074395572: { + errorText = "ERR_NIOCR_INTEGER_VALUE_FOR_STRING_ATTRIBUTE"; + break; + } + case -1074395573: { + errorText = "ERR_NIOCR_INVALID_CHARACTER_SET_FILE_VERSION"; + break; + } + case -1074395574: { + errorText = "ERR_NIOCR_CHARACTER_SET_DESCRIPTION_TOO_LONG"; + break; + } + case -1074395575: { + errorText = "ERR_NIOCR_INVALID_NUMBER_OF_EROSIONS"; + break; + } + case -1074395576: { + errorText = "ERR_NIOCR_CHARACTER_VALUE_TOO_LONG"; + break; + } + case -1074395577: { + errorText = "ERR_NIOCR_CHARACTER_VALUE_CANNOT_BE_EMPTYSTRING"; + break; + } + case -1074395578: { + errorText = "ERR_NIOCR_INVALID_CHARACTER_SET_FILE"; + break; + } + case -1074395579: { + errorText = "ERR_NIOCR_INVALID_ASPECT_RATIO"; + break; + } + case -1074395580: { + errorText = "ERR_NIOCR_INVALID_MIN_BOUNDING_RECT_WIDTH"; + break; + } + case -1074395581: { + errorText = "ERR_NIOCR_INVALID_MAX_VERT_ELEMENT_SPACING"; + break; + } + case -1074395582: { + errorText = "ERR_NIOCR_INVALID_MAX_HORIZ_ELEMENT_SPACING"; + break; + } + case -1074395583: { + errorText = "ERR_NIOCR_INVALID_MIN_CHAR_SPACING"; + break; + } + case -1074395584: { + errorText = "ERR_NIOCR_INVALID_THRESHOLD_LIMITS"; + break; + } + case -1074395585: { + errorText = "ERR_NIOCR_INVALID_UPPER_THRESHOLD_LIMIT"; + break; + } + case -1074395586: { + errorText = "ERR_NIOCR_INVALID_LOWER_THRESHOLD_LIMIT"; + break; + } + case -1074395587: { + errorText = "ERR_NIOCR_INVALID_THRESHOLD_RANGE"; + break; + } + case -1074395588: { + errorText = "ERR_NIOCR_INVALID_HIGH_THRESHOLD_VALUE"; + break; + } + case -1074395589: { + errorText = "ERR_NIOCR_INVALID_LOW_THRESHOLD_VALUE"; + break; + } + case -1074395590: { + errorText = "ERR_NIOCR_INVALID_NUMBER_OF_VALID_CHARACTER_POSITIONS"; + break; + } + case -1074395591: { + errorText = "ERR_NIOCR_INVALID_CHARACTER_INDEX"; + break; + } + case -1074395592: { + errorText = "ERR_NIOCR_INVALID_READ_STRATEGY"; + break; + } + case -1074395593: { + errorText = "ERR_NIOCR_INVALID_NUMBER_OF_BLOCKS"; + break; + } + case -1074395594: { + errorText = "ERR_NIOCR_INVALID_SUBSTITUTION_CHARACTER"; + break; + } + case -1074395595: { + errorText = "ERR_NIOCR_INVALID_THRESHOLD_MODE"; + break; + } + case -1074395596: { + errorText = "ERR_NIOCR_INVALID_CHARACTER_SIZE"; + break; + } + case -1074395597: { + errorText = "ERR_NIOCR_NOT_A_VALID_SESSION"; + break; + } + case -1074395598: { + errorText = "ERR_NIOCR_INVALID_ACCEPTANCE_LEVEL"; + break; + } + case -1074395600: { + errorText = "ERR_INFO_NOT_FOUND"; + break; + } + case -1074395601: { + errorText = "ERR_INVALID_EDGE_THRESHOLD"; + break; + } + case -1074395602: { + errorText = "ERR_INVALID_MINIMUM_CURVE_LENGTH"; + break; + } + case -1074395603: { + errorText = "ERR_INVALID_ROW_STEP"; + break; + } + case -1074395604: { + errorText = "ERR_INVALID_COLUMN_STEP"; + break; + } + case -1074395605: { + errorText = "ERR_INVALID_MAXIMUM_END_POINT_GAP"; + break; + } + case -1074395606: { + errorText = "ERR_INVALID_MINIMUM_FEATURES_TO_MATCH"; + break; + } + case -1074395607: { + errorText = "ERR_INVALID_MAXIMUM_FEATURES_PER_MATCH"; + break; + } + case -1074395608: { + errorText = "ERR_INVALID_SUBPIXEL_ITERATIONS"; + break; + } + case -1074395609: { + errorText = "ERR_INVALID_SUBPIXEL_TOLERANCE"; + break; + } + case -1074395610: { + errorText = "ERR_INVALID_INITIAL_MATCH_LIST_LENGTH"; + break; + } + case -1074395611: { + errorText = "ERR_INVALID_MINIMUM_RECTANGLE_DIMENSION"; + break; + } + case -1074395612: { + errorText = "ERR_INVALID_MINIMUM_FEATURE_RADIUS"; + break; + } + case -1074395613: { + errorText = "ERR_INVALID_MINIMUM_FEATURE_LENGTH"; + break; + } + case -1074395614: { + errorText = "ERR_INVALID_MINIMUM_FEATURE_ASPECT_RATIO"; + break; + } + case -1074395615: { + errorText = "ERR_INVALID_MINIMUM_FEATURE_STRENGTH"; + break; + } + case -1074395616: { + errorText = "ERR_INVALID_EDGE_FILTER_SIZE"; + break; + } + case -1074395617: { + errorText = "ERR_INVALID_NUMBER_OF_FEATURES_RANGE"; + break; + } + case -1074395618: { + errorText = "ERR_TOO_MANY_SCALE_RANGES"; + break; + } + case -1074395619: { + errorText = "ERR_TOO_MANY_OCCLUSION_RANGES"; + break; + } + case -1074395620: { + errorText = "ERR_INVALID_CURVE_EXTRACTION_MODE"; + break; + } + case -1074395621: { + errorText = "ERR_INVALID_LEARN_GEOMETRIC_PATTERN_SETUP_DATA"; + break; + } + case -1074395622: { + errorText = "ERR_INVALID_MATCH_GEOMETRIC_PATTERN_SETUP_DATA"; + break; + } + case -1074395623: { + errorText = "ERR_INVALID_SCALE_RANGE"; + break; + } + case -1074395624: { + errorText = "ERR_INVALID_OCCLUSION_RANGE"; + break; + } + case -1074395625: { + errorText = "ERR_INVALID_MATCH_CONSTRAINT_TYPE"; + break; + } + case -1074395626: { + errorText = "ERR_NOT_ENOUGH_TEMPLATE_FEATURES"; + break; + } + case -1074395627: { + errorText = "ERR_NOT_ENOUGH_TEMPLATE_FEATURES_1"; + break; + } + case -1074395628: { + errorText = "ERR_INVALID_GEOMETRIC_MATCHING_TEMPLATE"; + break; + } + case -1074395629: { + errorText = "ERR_INVALID_MAXIMUM_PIXEL_DISTANCE_FROM_LINE"; + break; + } + case -1074395630: { + errorText = "ERR_INVALID_MAXIMUM_FEATURES_LEARNED"; + break; + } + case -1074395631: { + errorText = "ERR_INVALID_MIN_MATCH_SEPARATION_DISTANCE"; + break; + } + case -1074395632: { + errorText = "ERR_INVALID_MIN_MATCH_SEPARATION_ANGLE"; + break; + } + case -1074395633: { + errorText = "ERR_INVALID_MIN_MATCH_SEPARATION_SCALE"; + break; + } + case -1074395634: { + errorText = "ERR_INVALID_MAX_MATCH_OVERLAP"; + break; + } + case -1074395635: { + errorText = "ERR_INVALID_SHAPE_DESCRIPTOR"; + break; + } + case -1074395636: { + errorText = "ERR_DIRECTX_NOT_FOUND"; + break; + } + case -1074395637: { + errorText = "ERR_HARDWARE_DOESNT_SUPPORT_NONTEARING"; + break; + } + case -1074395638: { + errorText = "ERR_INVALID_FILL_STYLE"; + break; + } + case -1074395639: { + errorText = "ERR_INVALID_HATCH_STYLE"; + break; + } + case -1074395640: { + errorText = "ERR_TOO_MANY_ZONES"; + break; + } + case -1074395641: { + errorText = "ERR_DUPLICATE_LABEL"; + break; + } + case -1074395642: { + errorText = "ERR_LABEL_NOT_FOUND"; + break; + } + case -1074395643: { + errorText = "ERR_INVALID_NUMBER_OF_MATCH_OPTIONS"; + break; + } + case -1074395644: { + errorText = "ERR_LABEL_TOO_LONG"; + break; + } + case -1074395645: { + errorText = "ERR_INVALID_NUMBER_OF_LABELS"; + break; + } + case -1074395646: { + errorText = "ERR_NO_TEMPLATE_TO_LEARN"; + break; + } + case -1074395647: { + errorText = "ERR_INVALID_MULTIPLE_GEOMETRIC_TEMPLATE"; + break; + } + case -1074395648: { + errorText = "ERR_TEMPLATE_NOT_LEARNED"; + break; + } + case -1074395649: { + errorText = "ERR_INVALID_GEOMETRIC_FEATURE_TYPE"; + break; + } + case -1074395650: { + errorText = "ERR_CURVE_EXTRACTION_MODE_MUST_BE_SAME"; + break; + } + case -1074395651: { + errorText = "ERR_EDGE_FILTER_SIZE_MUST_BE_SAME"; + break; + } + case -1074395652: { + errorText = "ERR_OPENING_NEWER_GEOMETRIC_MATCHING_TEMPLATE"; + break; + } + case -1074395653: { + errorText = "ERR_OPENING_NEWER_MULTIPLE_GEOMETRIC_TEMPLATE"; + break; + } + case -1074395654: { + errorText = "ERR_GRADING_INFORMATION_NOT_FOUND"; + break; + } + case -1074395655: { + errorText = "ERR_ENABLE_CALIBRATION_SUPPORT_MUST_BE_SAME"; + break; + } + case -1074395656: { + errorText = "ERR_SMOOTH_CONTOURS_MUST_BE_SAME"; + break; + } + case -1074395700: { + errorText = "ERR_REQUIRES_WIN2000_OR_NEWER"; + break; + } + case -1074395701: { + errorText = "ERR_INVALID_MATRIX_SIZE_RANGE"; + break; + } + case -1074395702: { + errorText = "ERR_INVALID_LENGTH"; + break; + } + case -1074395703: { + errorText = "ERR_INVALID_TYPE_OF_FLATTEN"; + break; + } + case -1074395704: { + errorText = "ERR_INVALID_COMPRESSION_TYPE"; + break; + } + case -1074395705: { + errorText = "ERR_DATA_CORRUPTED"; + break; + } + case -1074395706: { + errorText = "ERR_AVI_SESSION_ALREADY_OPEN"; + break; + } + case -1074395707: { + errorText = "ERR_AVI_WRITE_SESSION_REQUIRED"; + break; + } + case -1074395708: { + errorText = "ERR_AVI_READ_SESSION_REQUIRED"; + break; + } + case -1074395709: { + errorText = "ERR_AVI_UNOPENED_SESSION"; + break; + } + case -1074395710: { + errorText = "ERR_TOO_MANY_PARTICLES"; + break; + } + case -1074395711: { + errorText = "ERR_NOT_ENOUGH_REGIONS"; + break; + } + case -1074395712: { + errorText = "ERR_WRONG_REGION_TYPE"; + break; + } + case -1074395713: { + errorText = "ERR_VALUE_NOT_IN_ENUM"; + break; + } + case -1074395714: { + errorText = "ERR_INVALID_AXIS_ORIENTATION"; + break; + } + case -1074395715: { + errorText = "ERR_INVALID_CALIBRATION_UNIT"; + break; + } + case -1074395716: { + errorText = "ERR_INVALID_SCALING_METHOD"; + break; + } + case -1074395717: { + errorText = "ERR_INVALID_RANGE"; + break; + } + case -1074395718: { + errorText = "ERR_LAB_VERSION"; + break; + } + case -1074395719: { + errorText = "ERR_BAD_ROI_BOX"; + break; + } + case -1074395720: { + errorText = "ERR_BAD_ROI"; + break; + } + case -1074395721: { + errorText = "ERR_INVALID_BIT_DEPTH"; + break; + } + case -1074395722: { + errorText = "ERR_CLASSIFIER_CLASSIFY_IMAGE_WITH_CUSTOM_SESSION"; + break; + } + case -1074395723: { + errorText = "ERR_CUSTOMDATA_KEY_NOT_FOUND"; + break; + } + case -1074395724: { + errorText = "ERR_CUSTOMDATA_INVALID_SIZE"; + break; + } + case -1074395725: { + errorText = "ERR_DATA_VERSION"; + break; + } + case -1074395726: { + errorText = "ERR_MATCHFACTOR_OBSOLETE"; + break; + } + case -1074395727: { + errorText = "ERR_UNSUPPORTED_2D_BARCODE_SEARCH_MODE"; + break; + } + case -1074395728: { + errorText = "ERR_INVALID_2D_BARCODE_SEARCH_MODE"; + break; + } + case -1074395754: { + errorText = "ERR_TRIG_TIMEOUT"; + break; + } + case -1074395756: { + errorText = "ERR_DLL_FUNCTION_NOT_FOUND"; + break; + } + case -1074395757: { + errorText = "ERR_DLL_NOT_FOUND"; + break; + } + case -1074395758: { + errorText = "ERR_BOARD_NOT_OPEN"; + break; + } + case -1074395760: { + errorText = "ERR_BOARD_NOT_FOUND"; + break; + } + case -1074395762: { + errorText = "ERR_INVALID_NIBLACK_DEVIATION_FACTOR"; + break; + } + case -1074395763: { + errorText = "ERR_INVALID_NORMALIZATION_METHOD"; + break; + } + case -1074395766: { + errorText = "ERR_DEPRECATED_FUNCTION"; + break; + } + case -1074395767: { + errorText = "ERR_INVALID_ALIGNMENT"; + break; + } + case -1074395768: { + errorText = "ERR_INVALID_SCALE"; + break; + } + case -1074395769: { + errorText = "ERR_INVALID_EDGE_THICKNESS"; + break; + } + case -1074395770: { + errorText = "ERR_INVALID_INSPECTION_TEMPLATE"; + break; + } + case -1074395771: { + errorText = "ERR_OPENING_NEWER_INSPECTION_TEMPLATE"; + break; + } + case -1074395772: { + errorText = "ERR_INVALID_REGISTRATION_METHOD"; + break; + } + case -1074395773: { + errorText = "ERR_NO_DEST_IMAGE"; + break; + } + case -1074395774: { + errorText = "ERR_NO_LABEL"; + break; + } + case -1074395775: { + errorText = "ERR_ROI_HAS_OPEN_CONTOURS"; + break; + } + case -1074395776: { + errorText = "ERR_INVALID_USE_OF_COMPACT_SESSION_FILE"; + break; + } + case -1074395777: { + errorText = "ERR_INCOMPATIBLE_CLASSIFIER_TYPES"; + break; + } + case -1074395778: { + errorText = "ERR_INVALID_KERNEL_SIZE"; + break; + } + case -1074395779: { + errorText = "ERR_CANNOT_COMPACT_UNTRAINED"; + break; + } + case -1074395780: { + errorText = "ERR_INVALID_PARTICLE_TYPE"; + break; + } + case -1074395781: { + errorText = "ERR_CLASSIFIER_INVALID_ENGINE_TYPE"; + break; + } + case -1074395782: { + errorText = "ERR_DESCRIPTION_TOO_LONG"; + break; + } + case -1074395783: { + errorText = "ERR_BAD_SAMPLE_INDEX"; + break; + } + case -1074395784: { + errorText = "ERR_INVALID_LIMITS"; + break; + } + case -1074395785: { + errorText = "ERR_NO_PARTICLE"; + break; + } + case -1074395786: { + errorText = "ERR_INVALID_PARTICLE_OPTIONS"; + break; + } + case -1074395787: { + errorText = "ERR_INVALID_CLASSIFIER_TYPE"; + break; + } + case -1074395788: { + errorText = "ERR_NO_SAMPLES"; + break; + } + case -1074395789: { + errorText = "ERR_OPENING_NEWER_CLASSIFIER_SESSION"; + break; + } + case -1074395790: { + errorText = "ERR_INVALID_DISTANCE_METRIC"; + break; + } + case -1074395791: { + errorText = "ERR_CLASSIFIER_INVALID_SESSION_TYPE"; + break; + } + case -1074395792: { + errorText = "ERR_CLASSIFIER_SESSION_NOT_TRAINED"; + break; + } + case -1074395793: { + errorText = "ERR_INVALID_OPERATION_ON_COMPACT_SESSION_ATTEMPTED"; + break; + } + case -1074395794: { + errorText = "ERR_K_TOO_HIGH"; + break; + } + case -1074395795: { + errorText = "ERR_K_TOO_LOW"; + break; + } + case -1074395796: { + errorText = "ERR_INVALID_KNN_METHOD"; + break; + } + case -1074395797: { + errorText = "ERR_INVALID_CLASSIFIER_SESSION"; + break; + } + case -1074395798: { + errorText = "ERR_INVALID_CUSTOM_SAMPLE"; + break; + } + case -1074395799: { + errorText = "ERR_INTERNAL"; + break; + } + case -1074395800: { + errorText = "ERR_PROTECTION"; + break; + } + case -1074395801: { + errorText = "ERR_TOO_MANY_CONTOURS"; + break; + } + case -1074395837: { + errorText = "ERR_INVALID_COMPRESSION_RATIO"; + break; + } + case -1074395840: { + errorText = "ERR_BAD_INDEX"; + break; + } + case -1074395875: { + errorText = "ERR_BARCODE_PHARMACODE"; + break; + } + case -1074395876: { + errorText = "ERR_UNSUPPORTED_COLOR_MODE"; + break; + } + case -1074395877: { + errorText = "ERR_COLORMODE_REQUIRES_CHANGECOLORSPACE2"; + break; + } + case -1074395878: { + errorText = "ERR_PROP_NODE_WRITE_NOT_SUPPORTED"; + break; + } + case -1074395879: { + errorText = "ERR_BAD_MEASURE"; + break; + } + case -1074395880: { + errorText = "ERR_PARTICLE"; + break; + } + case -1074395920: { + errorText = "ERR_NUMBER_CLASS"; + break; + } + case -1074395953: { + errorText = "ERR_INVALID_WAVELET_TRANSFORM_MODE"; + break; + } + case -1074395954: { + errorText = "ERR_INVALID_QUANTIZATION_STEP_SIZE"; + break; + } + case -1074395955: { + errorText = "ERR_INVALID_MAX_WAVELET_TRANSFORM_LEVEL"; + break; + } + case -1074395956: { + errorText = "ERR_INVALID_QUALITY"; + break; + } + case -1074395957: { + errorText = "ERR_ARRAY_SIZE_MISMATCH"; + break; + } + case -1074395958: { + errorText = "ERR_WINDOW_ID"; + break; + } + case -1074395959: { + errorText = "ERR_CREATE_WINDOW"; + break; + } + case -1074395960: { + errorText = "ERR_INIT"; + break; + } + case -1074395971: { + errorText = "ERR_INVALID_OFFSET"; + break; + } + case -1074395972: { + errorText = "ERR_DIRECTX_ENUMERATE_FILTERS"; + break; + } + case -1074395973: { + errorText = "ERR_JPEG2000_UNSUPPORTED_MULTIPLE_LAYERS"; + break; + } + case -1074395974: { + errorText = "ERR_UNSUPPORTED_JPEG2000_COLORSPACE_METHOD"; + break; + } + case -1074395975: { + errorText = "ERR_AVI_TIMEOUT"; + break; + } + case -1074395976: { + errorText = "ERR_NUMBER_OF_PALETTE_COLORS"; + break; + } + case -1074395977: { + errorText = "ERR_AVI_VERSION"; + break; + } + case -1074395978: { + errorText = "ERR_INVALID_PARTICLE_NUMBER"; + break; + } + case -1074395979: { + errorText = "ERR_INVALID_PARTICLE_INFO"; + break; + } + case -1074395980: { + errorText = "ERR_COM_INITIALIZE"; + break; + } + case -1074395981: { + errorText = "ERR_INSUFFICIENT_BUFFER_SIZE"; + break; + } + case -1074395982: { + errorText = "ERR_INVALID_FRAMES_PER_SECOND"; + break; + } + case -1074395983: { + errorText = "ERR_FILE_NO_SPACE"; + break; + } + case -1074395984: { + errorText = "ERR_FILE_INVALID_DATA_TYPE"; + break; + } + case -1074395985: { + errorText = "ERR_FILE_OPERATION"; + break; + } + case -1074395986: { + errorText = "ERR_FILE_FORMAT"; + break; + } + case -1074395987: { + errorText = "ERR_FILE_EOF"; + break; + } + case -1074395988: { + errorText = "ERR_FILE_WRITE"; + break; + } + case -1074395989: { + errorText = "ERR_FILE_READ"; + break; + } + case -1074395990: { + errorText = "ERR_FILE_GET_INFO"; + break; + } + case -1074395991: { + errorText = "ERR_FILE_INVALID_TYPE"; + break; + } + case -1074395992: { + errorText = "ERR_FILE_PERMISSION"; + break; + } + case -1074395993: { + errorText = "ERR_FILE_IO_ERR"; + break; + } + case -1074395994: { + errorText = "ERR_FILE_TOO_MANY_OPEN"; + break; + } + case -1074395995: { + errorText = "ERR_FILE_NOT_FOUND"; + break; + } + case -1074395996: { + errorText = "ERR_FILE_OPEN"; + break; + } + case -1074395997: { + errorText = "ERR_FILE_ARGERR"; + break; + } + case -1074395998: { + errorText = "ERR_FILE_COLOR_TABLE"; + break; + } + case -1074395999: { + errorText = "ERR_FILE_FILE_TYPE"; + break; + } + case -1074396000: { + errorText = "ERR_FILE_FILE_HEADER"; + break; + } + case -1074396001: { + errorText = "ERR_TOO_MANY_AVI_SESSIONS"; + break; + } + case -1074396002: { + errorText = "ERR_INVALID_LINEGAUGEMETHOD"; + break; + } + case -1074396003: { + errorText = "ERR_AVI_DATA_EXCEEDS_BUFFER_SIZE"; + break; + } + case -1074396004: { + errorText = "ERR_DIRECTX_CERTIFICATION_FAILURE"; + break; + } + case -1074396005: { + errorText = "ERR_INVALID_AVI_SESSION"; + break; + } + case -1074396006: { + errorText = "ERR_DIRECTX_UNKNOWN_COMPRESSION_FILTER"; + break; + } + case -1074396007: { + errorText = "ERR_DIRECTX_INCOMPATIBLE_COMPRESSION_FILTER"; + break; + } + case -1074396008: { + errorText = "ERR_DIRECTX_NO_FILTER"; + break; + } + case -1074396009: { + errorText = "ERR_DIRECTX"; + break; + } + case -1074396010: { + errorText = "ERR_INVALID_FRAME_NUMBER"; + break; + } + case -1074396011: { + errorText = "ERR_RPC_BIND"; + break; + } + case -1074396012: { + errorText = "ERR_RPC_EXECUTE"; + break; + } + case -1074396013: { + errorText = "ERR_INVALID_VIDEO_MODE"; + break; + } + case -1074396014: { + errorText = "ERR_INVALID_VIDEO_BLIT"; + break; + } + case -1074396015: { + errorText = "ERR_RPC_EXECUTE_IVB"; + break; + } + case -1074396016: { + errorText = "ERR_NO_VIDEO_DRIVER"; + break; + } + case -1074396017: { + errorText = "ERR_OPENING_NEWER_AIM_GRADING_DATA"; + break; + } + case -1074396018: { + errorText = "ERR_INVALID_EDGE_POLARITY_SEARCH_MODE"; + break; + } + case -1074396019: { + errorText = "ERR_INVALID_THRESHOLD_PERCENTAGE"; + break; + } + case -1074396020: { + errorText = "ERR_INVALID_GRADING_MODE"; + break; + } + case -1074396021: { + errorText = "ERR_INVALID_KERNEL_SIZE_FOR_EDGE_DETECTION"; + break; + } + case -1074396022: { + errorText = "ERR_INVALID_SEARCH_MODE_FOR_STRAIGHT_EDGE"; + break; + } + case -1074396023: { + errorText = "ERR_INVALID_ANGLE_TOL_FOR_STRAIGHT_EDGE"; + break; + } + case -1074396024: { + errorText = "ERR_INVALID_MIN_COVERAGE_FOR_STRAIGHT_EDGE"; + break; + } + case -1074396025: { + errorText = "ERR_INVALID_ANGLE_RANGE_FOR_STRAIGHT_EDGE"; + break; + } + case -1074396026: { + errorText = "ERR_INVALID_PROCESS_TYPE_FOR_EDGE_DETECTION"; + break; + } + case -1074396032: { + errorText = "ERR_TEMPLATEDESCRIPTOR_ROTATION_SEARCHSTRATEGY"; + break; + } + case -1074396033: { + errorText = "ERR_TEMPLATEDESCRIPTOR_LEARNSETUPDATA"; + break; + } + case -1074396034: { + errorText = "ERR_TEMPLATEIMAGE_EDGEINFO"; + break; + } + case -1074396035: { + errorText = "ERR_TEMPLATEIMAGE_NOCIRCLE"; + break; + } + case -1074396036: { + errorText = "ERR_INVALID_SKELETONMODE"; + break; + } + case -1074396037: { + errorText = "ERR_TIMEOUT"; + break; + } + case -1074396038: { + errorText = "ERR_FIND_COORDSYS_MORE_THAN_ONE_EDGE"; + break; + } + case -1074396039: { + errorText = "ERR_IO_ERROR"; + break; + } + case -1074396040: { + errorText = "ERR_DRIVER"; + break; + } + case -1074396041: { + errorText = "ERR_INVALID_2D_BARCODE_TYPE"; + break; + } + case -1074396042: { + errorText = "ERR_INVALID_2D_BARCODE_CONTRAST"; + break; + } + case -1074396043: { + errorText = "ERR_INVALID_2D_BARCODE_CELL_SHAPE"; + break; + } + case -1074396044: { + errorText = "ERR_INVALID_2D_BARCODE_SHAPE"; + break; + } + case -1074396045: { + errorText = "ERR_INVALID_2D_BARCODE_SUBTYPE"; + break; + } + case -1074396046: { + errorText = "ERR_INVALID_2D_BARCODE_CONTRAST_FOR_ROI"; + break; + } + case -1074396047: { + errorText = "ERR_INVALID_LINEAR_AVERAGE_MODE"; + break; + } + case -1074396048: { + errorText = "ERR_INVALID_CELL_SAMPLE_SIZE"; + break; + } + case -1074396049: { + errorText = "ERR_INVALID_MATRIX_POLARITY"; + break; + } + case -1074396050: { + errorText = "ERR_INVALID_ECC_TYPE"; + break; + } + case -1074396051: { + errorText = "ERR_INVALID_CELL_FILTER_MODE"; + break; + } + case -1074396052: { + errorText = "ERR_INVALID_DEMODULATION_MODE"; + break; + } + case -1074396053: { + errorText = "ERR_INVALID_BORDER_INTEGRITY"; + break; + } + case -1074396054: { + errorText = "ERR_INVALID_CELL_FILL_TYPE"; + break; + } + case -1074396055: { + errorText = "ERR_INVALID_ASPECT_RATIO"; + break; + } + case -1074396056: { + errorText = "ERR_INVALID_MATRIX_MIRROR_MODE"; + break; + } + case -1074396057: { + errorText = "ERR_INVALID_SEARCH_VECTOR_WIDTH"; + break; + } + case -1074396058: { + errorText = "ERR_INVALID_ROTATION_MODE"; + break; + } + case -1074396059: { + errorText = "ERR_INVALID_MAX_ITERATIONS"; + break; + } + case -1074396060: { + errorText = "ERR_JPEG2000_LOSSLESS_WITH_FLOATING_POINT"; + break; + } + case -1074396061: { + errorText = "ERR_INVALID_WINDOW_SIZE"; + break; + } + case -1074396062: { + errorText = "ERR_INVALID_TOLERANCE"; + break; + } + case -1074396063: { + errorText = "ERR_EXTERNAL_ALIGNMENT"; + break; + } + case -1074396064: { + errorText = "ERR_EXTERNAL_NOT_SUPPORTED"; + break; + } + case -1074396065: { + errorText = "ERR_CANT_RESIZE_EXTERNAL"; + break; + } + case -1074396066: { + errorText = "ERR_INVALID_POINTSYMBOL"; + break; + } + case -1074396067: { + errorText = "ERR_IMAGES_NOT_DIFF"; + break; + } + case -1074396068: { + errorText = "ERR_INVALID_ACTION"; + break; + } + case -1074396069: { + errorText = "ERR_INVALID_COLOR_MODE"; + break; + } + case -1074396070: { + errorText = "ERR_INVALID_FUNCTION"; + break; + } + case -1074396071: { + errorText = "ERR_INVALID_SCAN_DIRECTION"; + break; + } + case -1074396072: { + errorText = "ERR_INVALID_BORDER"; + break; + } + case -1074396073: { + errorText = "ERR_MASK_OUTSIDE_IMAGE"; + break; + } + case -1074396074: { + errorText = "ERR_INCOMP_SIZE"; + break; + } + case -1074396075: { + errorText = "ERR_COORD_SYS_SECOND_AXIS"; + break; + } + case -1074396076: { + errorText = "ERR_COORD_SYS_FIRST_AXIS"; + break; + } + case -1074396077: { + errorText = "ERR_INCOMP_TYPE"; + break; + } + case -1074396079: { + errorText = "ERR_INVALID_METAFILE_HANDLE"; + break; + } + case -1074396080: { + errorText = "ERR_INVALID_IMAGE_TYPE"; + break; + } + case -1074396081: { + errorText = "ERR_BAD_PASSWORD"; + break; + } + case -1074396082: { + errorText = "ERR_PALETTE_NOT_SUPPORTED"; + break; + } + case -1074396083: { + errorText = "ERR_ROLLBACK_TIMEOUT"; + break; + } + case -1074396084: { + errorText = "ERR_ROLLBACK_DELETE_TIMER"; + break; + } + case -1074396085: { + errorText = "ERR_ROLLBACK_INIT_TIMER"; + break; + } + case -1074396086: { + errorText = "ERR_ROLLBACK_START_TIMER"; + break; + } + case -1074396087: { + errorText = "ERR_ROLLBACK_STOP_TIMER"; + break; + } + case -1074396088: { + errorText = "ERR_ROLLBACK_RESIZE"; + break; + } + case -1074396089: { + errorText = "ERR_ROLLBACK_RESOURCE_REINITIALIZE"; + break; + } + case -1074396090: { + errorText = "ERR_ROLLBACK_RESOURCE_ENABLED"; + break; + } + case -1074396091: { + errorText = "ERR_ROLLBACK_RESOURCE_UNINITIALIZED_ENABLE"; + break; + } + case -1074396092: { + errorText = "ERR_ROLLBACK_RESOURCE_NON_EMPTY_INITIALIZE"; + break; + } + case -1074396093: { + errorText = "ERR_ROLLBACK_RESOURCE_LOCKED"; + break; + } + case -1074396094: { + errorText = "ERR_ROLLBACK_RESOURCE_CANNOT_UNLOCK"; + break; + } + case -1074396095: { + errorText = "ERR_CALIBRATION_DUPLICATE_REFERENCE_POINT"; + break; + } + case -1074396096: { + errorText = "ERR_NOT_AN_OBJECT"; + break; + } + case -1074396097: { + errorText = "ERR_INVALID_PARTICLE_PARAMETER_VALUE"; + break; + } + case -1074396098: { + errorText = "ERR_RESERVED_MUST_BE_NULL"; + break; + } + case -1074396099: { + errorText = "ERR_CALIBRATION_INFO_SIMPLE_TRANSFORM"; + break; + } + case -1074396100: { + errorText = "ERR_CALIBRATION_INFO_PERSPECTIVE_PROJECTION"; + break; + } + case -1074396101: { + errorText = "ERR_CALIBRATION_INFO_MICRO_PLANE"; + break; + } + case -1074396102: { + errorText = "ERR_CALIBRATION_INFO_6"; + break; + } + case -1074396103: { + errorText = "ERR_CALIBRATION_INFO_5"; + break; + } + case -1074396104: { + errorText = "ERR_CALIBRATION_INFO_4"; + break; + } + case -1074396105: { + errorText = "ERR_CALIBRATION_INFO_3"; + break; + } + case -1074396106: { + errorText = "ERR_CALIBRATION_INFO_2"; + break; + } + case -1074396107: { + errorText = "ERR_CALIBRATION_INFO_1"; + break; + } + case -1074396108: { + errorText = "ERR_CALIBRATION_ERRORMAP"; + break; + } + case -1074396109: { + errorText = "ERR_CALIBRATION_INVALID_SCALING_FACTOR"; + break; + } + case -1074396110: { + errorText = "ERR_CALIBRATION_INFO_VERSION"; + break; + } + case -1074396111: { + errorText = "ERR_CALIBRATION_FAILED_TO_FIND_GRID"; + break; + } + case -1074396112: { + errorText = "ERR_INCOMP_MATRIX_SIZE"; + break; + } + case -1074396113: { + errorText = "ERR_CALIBRATION_IMAGE_UNCALIBRATED"; + break; + } + case -1074396114: { + errorText = "ERR_CALIBRATION_INVALID_ROI"; + break; + } + case -1074396115: { + errorText = "ERR_CALIBRATION_IMAGE_CORRECTED"; + break; + } + case -1074396116: { + errorText = "ERR_CALIBRATION_INSF_POINTS"; + break; + } + case -1074396117: { + errorText = "ERR_MATRIX_SIZE"; + break; + } + case -1074396118: { + errorText = "ERR_INVALID_STEP_SIZE"; + break; + } + case -1074396119: { + errorText = "ERR_CUSTOMDATA_INVALID_KEY"; + break; + } + case -1074396120: { + errorText = "ERR_NOT_IMAGE"; + break; + } + case -1074396121: { + errorText = "ERR_SATURATION_THRESHOLD_OUT_OF_RANGE"; + break; + } + case -1074396122: { + errorText = "ERR_DRAWTEXT_COLOR_MUST_BE_GRAYSCALE"; + break; + } + case -1074396123: { + errorText = "ERR_INVALID_CALIBRATION_MODE"; + break; + } + case -1074396124: { + errorText = "ERR_INVALID_CALIBRATION_ROI_MODE"; + break; + } + case -1074396125: { + errorText = "ERR_INVALID_CONTRAST_THRESHOLD"; + break; + } + case -1074396126: { + errorText = "ERR_ROLLBACK_RESOURCE_CONFLICT_1"; + break; + } + case -1074396127: { + errorText = "ERR_ROLLBACK_RESOURCE_CONFLICT_2"; + break; + } + case -1074396128: { + errorText = "ERR_ROLLBACK_RESOURCE_CONFLICT_3"; + break; + } + case -1074396129: { + errorText = "ERR_ROLLBACK_UNBOUNDED_INTERFACE"; + break; + } + case -1074396130: { + errorText = "ERR_NOT_RECT_OR_ROTATED_RECT"; + break; + } + case -1074396132: { + errorText = "ERR_MASK_NOT_TEMPLATE_SIZE"; + break; + } + case -1074396133: { + errorText = "ERR_THREAD_COULD_NOT_INITIALIZE"; + break; + } + case -1074396134: { + errorText = "ERR_THREAD_INITIALIZING"; + break; + } + case -1074396135: { + errorText = "ERR_INVALID_BUTTON_LABEL"; + break; + } + case -1074396136: { + errorText = "ERR_DIRECTX_INVALID_FILTER_QUALITY"; + break; + } + case -1074396137: { + errorText = "ERR_DIRECTX_DLL_NOT_FOUND"; + break; + } + case -1074396138: { + errorText = "ERR_ROLLBACK_NOT_SUPPORTED"; + break; + } + case -1074396139: { + errorText = "ERR_ROLLBACK_RESOURCE_OUT_OF_MEMORY"; + break; + } + case -1074396140: { + errorText = "ERR_BARCODE_CODE128_SET"; + break; + } + case -1074396141: { + errorText = "ERR_BARCODE_CODE128_FNC"; + break; + } + case -1074396142: { + errorText = "ERR_BARCODE_INVALID"; + break; + } + case -1074396143: { + errorText = "ERR_BARCODE_TYPE"; + break; + } + case -1074396144: { + errorText = "ERR_BARCODE_CODE93_SHIFT"; + break; + } + case -1074396145: { + errorText = "ERR_BARCODE_UPCA"; + break; + } + case -1074396146: { + errorText = "ERR_BARCODE_MSI"; + break; + } + case -1074396147: { + errorText = "ERR_BARCODE_I25"; + break; + } + case -1074396148: { + errorText = "ERR_BARCODE_EAN13"; + break; + } + case -1074396149: { + errorText = "ERR_BARCODE_EAN8"; + break; + } + case -1074396150: { + errorText = "ERR_BARCODE_CODE128"; + break; + } + case -1074396151: { + errorText = "ERR_BARCODE_CODE93"; + break; + } + case -1074396152: { + errorText = "ERR_BARCODE_CODE39"; + break; + } + case -1074396153: { + errorText = "ERR_BARCODE_CODABAR"; + break; + } + case -1074396154: { + errorText = "ERR_IMAGE_TOO_SMALL"; + break; + } + case -1074396155: { + errorText = "ERR_UNINIT"; + break; + } + case -1074396156: { + errorText = "ERR_NEED_FULL_VERSION"; + break; + } + case -1074396157: { + errorText = "ERR_UNREGISTERED"; + break; + } + case -1074396158: { + errorText = "ERR_MEMORY_ERROR"; + break; + } + case -1074396159: { + errorText = "ERR_OUT_OF_MEMORY"; + break; + } + case -1074396160: { + errorText = "ERR_SYSTEM_ERROR"; + break; + } + case 0: { + errorText = "ERR_SUCCESS"; + break; + } + // end National Instruments defined errors + + // begin BAE defined errors + case ERR_VISION_GENERAL_ERROR: { + errorText = "ERR_VISION_GENERAL_ERROR"; + break; + } + case ERR_COLOR_NOT_FOUND: { + errorText = "ERR_COLOR_NOT_FOUND"; + break; + } + case ERR_PARTICLE_TOO_SMALL: { + errorText = "ERR_PARTICLE_TOO_SMALL"; + break; + } + case ERR_CAMERA_FAILURE: { + errorText = "ERR_CAMERA_FAILURE"; + break; + } + case ERR_CAMERA_SOCKET_CREATE_FAILED: { + errorText = "ERR_CAMERA_SOCKET_CREATE_FAILED"; + break; + } + case ERR_CAMERA_CONNECT_FAILED: { + errorText = "ERR_CAMERA_CONNECT_FAILED"; + break; + } + case ERR_CAMERA_STALE_IMAGE: { + errorText = "ERR_CAMERA_STALE_IMAGE"; + break; + } + case ERR_CAMERA_NOT_INITIALIZED: { + errorText = "ERR_CAMERA_NOT_INITIALIZED"; + break; + } + case ERR_CAMERA_NO_BUFFER_AVAILABLE: { + errorText = "ERR_CAMERA_NO_BUFFER_AVAILABLE"; + break; + } + case ERR_CAMERA_HEADER_ERROR: { + errorText = "ERR_CAMERA_HEADER_ERROR"; + break; + } + case ERR_CAMERA_BLOCKING_TIMEOUT: { + errorText = "ERR_CAMERA_BLOCKING_TIMEOUT"; + break; + } + case ERR_CAMERA_AUTHORIZATION_FAILED: { + errorText = "ERR_CAMERA_AUTHORIZATION_FAILED"; + break; + } + case ERR_CAMERA_TASK_SPAWN_FAILED: { + errorText = "ERR_CAMERA_TASK_SPAWN_FAILED"; + break; + } + case ERR_CAMERA_TASK_INPUT_OUT_OF_RANGE: { + errorText = "ERR_CAMERA_TASK_INPUT_OUT_OF_RANGE"; + break; + } + case ERR_CAMERA_COMMAND_FAILURE: { + errorText = "ERR_CAMERA_COMMAND_FAILURE"; + break; + } + } + + return errorText; } - - - diff --git a/wpilibc/wpilibC++Devices/src/Vision/HSLImage.cpp b/wpilibc/wpilibC++Devices/src/Vision/HSLImage.cpp index 1a6694901b..11670a8325 100644 --- a/wpilibc/wpilibC++Devices/src/Vision/HSLImage.cpp +++ b/wpilibc/wpilibC++Devices/src/Vision/HSLImage.cpp @@ -9,20 +9,15 @@ /** * Create a new image that uses the Hue, Saturation, and Luminance planes. */ -HSLImage::HSLImage() : ColorImage(IMAQ_IMAGE_HSL) -{ -} +HSLImage::HSLImage() : ColorImage(IMAQ_IMAGE_HSL) {} /** * Create a new image by loading a file. * @param fileName The path of the file to load. */ -HSLImage::HSLImage(const char *fileName) : ColorImage(IMAQ_IMAGE_HSL) -{ - int success = imaqReadFile(m_imaqImage, fileName, NULL, NULL); - wpi_setImaqErrorWithContext(success, "Imaq ReadFile error"); +HSLImage::HSLImage(const char *fileName) : ColorImage(IMAQ_IMAGE_HSL) { + int success = imaqReadFile(m_imaqImage, fileName, NULL, NULL); + wpi_setImaqErrorWithContext(success, "Imaq ReadFile error"); } -HSLImage::~HSLImage() -{ -} +HSLImage::~HSLImage() {} diff --git a/wpilibc/wpilibC++Devices/src/Vision/ImageBase.cpp b/wpilibc/wpilibC++Devices/src/Vision/ImageBase.cpp index ba549b6e0a..8b6adaf195 100644 --- a/wpilibc/wpilibC++Devices/src/Vision/ImageBase.cpp +++ b/wpilibc/wpilibC++Devices/src/Vision/ImageBase.cpp @@ -13,19 +13,16 @@ * creates any type of image and stores the pointer to it in the class. * @param type The type of image to create */ -ImageBase::ImageBase(ImageType type) -{ - m_imaqImage = imaqCreateImage(type, DEFAULT_BORDER_SIZE); +ImageBase::ImageBase(ImageType type) { + m_imaqImage = imaqCreateImage(type, DEFAULT_BORDER_SIZE); } /** * Frees memory associated with an ImageBase. * Destructor frees the imaq image allocated with the class. */ -ImageBase::~ImageBase() -{ - if(m_imaqImage) - imaqDispose(m_imaqImage); +ImageBase::~ImageBase() { + if (m_imaqImage) imaqDispose(m_imaqImage); } /** @@ -33,41 +30,34 @@ ImageBase::~ImageBase() * Write the image to a file in the flash on the cRIO. * @param fileName The name of the file to write */ -void ImageBase::Write(const char *fileName) -{ - int success = imaqWriteFile(m_imaqImage, fileName, NULL); - wpi_setImaqErrorWithContext(success, "Imaq Image writeFile error"); +void ImageBase::Write(const char *fileName) { + int success = imaqWriteFile(m_imaqImage, fileName, NULL); + wpi_setImaqErrorWithContext(success, "Imaq Image writeFile error"); } /** * Gets the height of an image. * @return The height of the image in pixels. */ -int ImageBase::GetHeight() -{ - int height; - imaqGetImageSize(m_imaqImage, NULL, &height); - return height; +int ImageBase::GetHeight() { + int height; + imaqGetImageSize(m_imaqImage, NULL, &height); + return height; } /** * Gets the width of an image. * @return The width of the image in pixels. */ -int ImageBase::GetWidth() -{ - int width; - imaqGetImageSize(m_imaqImage, &width, NULL); - return width; +int ImageBase::GetWidth() { + int width; + imaqGetImageSize(m_imaqImage, &width, NULL); + return width; } /** * Access the internal IMAQ Image data structure. - * + * * @return A pointer to the internal IMAQ Image data structure. */ -Image *ImageBase::GetImaqImage() -{ - return m_imaqImage; -} - +Image *ImageBase::GetImaqImage() { return m_imaqImage; } diff --git a/wpilibc/wpilibC++Devices/src/Vision/MonoImage.cpp b/wpilibc/wpilibC++Devices/src/Vision/MonoImage.cpp index 17efe2012e..1351939cba 100644 --- a/wpilibc/wpilibC++Devices/src/Vision/MonoImage.cpp +++ b/wpilibc/wpilibC++Devices/src/Vision/MonoImage.cpp @@ -9,13 +9,9 @@ using namespace std; -MonoImage::MonoImage() : ImageBase(IMAQ_IMAGE_U8) -{ -} +MonoImage::MonoImage() : ImageBase(IMAQ_IMAGE_U8) {} -MonoImage::~MonoImage() -{ -} +MonoImage::~MonoImage() {} /** * Look for ellipses in an image. @@ -26,30 +22,27 @@ MonoImage::~MonoImage() * @param roi Region of Interest * @returns a vector of EllipseMatch structures (0 length vector on no match) */ -vector * MonoImage::DetectEllipses( - EllipseDescriptor *ellipseDescriptor, CurveOptions *curveOptions, - ShapeDetectionOptions *shapeDetectionOptions, ROI *roi) -{ - int numberOfMatches; - EllipseMatch *e = imaqDetectEllipses(m_imaqImage, ellipseDescriptor, - curveOptions, shapeDetectionOptions, roi, &numberOfMatches); - vector *ellipses = new vector; - if (e == NULL) - { - return ellipses; - } - for (int i = 0; i < numberOfMatches; i++) - { - ellipses->push_back(e[i]); - } - imaqDispose(e); - return ellipses; +vector *MonoImage::DetectEllipses( + EllipseDescriptor *ellipseDescriptor, CurveOptions *curveOptions, + ShapeDetectionOptions *shapeDetectionOptions, ROI *roi) { + int numberOfMatches; + EllipseMatch *e = + imaqDetectEllipses(m_imaqImage, ellipseDescriptor, curveOptions, + shapeDetectionOptions, roi, &numberOfMatches); + vector *ellipses = new vector; + if (e == NULL) { + return ellipses; + } + for (int i = 0; i < numberOfMatches; i++) { + ellipses->push_back(e[i]); + } + imaqDispose(e); + return ellipses; } -vector * MonoImage::DetectEllipses( - EllipseDescriptor *ellipseDescriptor) -{ - vector *ellipses = DetectEllipses(ellipseDescriptor, NULL, - NULL, NULL); - return ellipses; +vector *MonoImage::DetectEllipses( + EllipseDescriptor *ellipseDescriptor) { + vector *ellipses = + DetectEllipses(ellipseDescriptor, NULL, NULL, NULL); + return ellipses; } diff --git a/wpilibc/wpilibC++Devices/src/Vision/RGBImage.cpp b/wpilibc/wpilibC++Devices/src/Vision/RGBImage.cpp index a34212e686..ef2dffe1ad 100644 --- a/wpilibc/wpilibC++Devices/src/Vision/RGBImage.cpp +++ b/wpilibc/wpilibC++Devices/src/Vision/RGBImage.cpp @@ -9,20 +9,15 @@ /** * Create a new image that uses Red, Green, and Blue planes. */ -RGBImage::RGBImage() : ColorImage(IMAQ_IMAGE_RGB) -{ -} +RGBImage::RGBImage() : ColorImage(IMAQ_IMAGE_RGB) {} /** * Create a new image by loading a file. * @param fileName The path of the file to load. */ -RGBImage::RGBImage(const char *fileName) : ColorImage(IMAQ_IMAGE_RGB) -{ - int success = imaqReadFile(m_imaqImage, fileName, NULL, NULL); - wpi_setImaqErrorWithContext(success, "Imaq ReadFile error"); +RGBImage::RGBImage(const char *fileName) : ColorImage(IMAQ_IMAGE_RGB) { + int success = imaqReadFile(m_imaqImage, fileName, NULL, NULL); + wpi_setImaqErrorWithContext(success, "Imaq ReadFile error"); } -RGBImage::~RGBImage() -{ -} +RGBImage::~RGBImage() {} diff --git a/wpilibc/wpilibC++Devices/src/Vision/Threshold.cpp b/wpilibc/wpilibC++Devices/src/Vision/Threshold.cpp index 1d81b388ea..2e172437c1 100644 --- a/wpilibc/wpilibC++Devices/src/Vision/Threshold.cpp +++ b/wpilibc/wpilibC++Devices/src/Vision/Threshold.cpp @@ -7,12 +7,12 @@ #include "Vision/Threshold.h" Threshold::Threshold(int new_plane1Low, int new_plane1High, int new_plane2Low, - int new_plane2High, int new_plane3Low, int new_plane3High) -{ - plane1Low = new_plane1Low; - plane1High = new_plane1High; - plane2Low = new_plane2Low; - plane2High = new_plane2High; - plane3Low = new_plane3Low; - plane3High = new_plane3High; + int new_plane2High, int new_plane3Low, + int new_plane3High) { + plane1Low = new_plane1Low; + plane1High = new_plane1High; + plane2Low = new_plane2Low; + plane2High = new_plane2High; + plane3Low = new_plane3Low; + plane3High = new_plane3High; } diff --git a/wpilibc/wpilibC++Devices/src/Vision/VisionAPI.cpp b/wpilibc/wpilibC++Devices/src/Vision/VisionAPI.cpp index c72b3211ae..6e0b7ada3a 100644 --- a/wpilibc/wpilibC++Devices/src/Vision/VisionAPI.cpp +++ b/wpilibc/wpilibC++Devices/src/Vision/VisionAPI.cpp @@ -4,15 +4,16 @@ /* must be accompanied by the FIRST BSD license file in $(WIND_BASE)/WPILib. */ /*----------------------------------------------------------------------------*/ -#include -#include +#include +#include #include "Vision/BaeUtilities.h" #include "Vision/FrcError.h" -#include "Vision/VisionAPI.h" +#include "Vision/VisionAPI.h" int VisionAPI_debugFlag = 1; -#define DPRINTF if(VisionAPI_debugFlag)dprintf +#define DPRINTF \ + if (VisionAPI_debugFlag) dprintf /** @file * Image Management functions @@ -20,648 +21,800 @@ int VisionAPI_debugFlag = 1; /** * @brief Create an image object -* Supports IMAQ_IMAGE_U8, IMAQ_IMAGE_I16, IMAQ_IMAGE_SGL, IMAQ_IMAGE_COMPLEX, IMAQ_IMAGE_RGB, IMAQ_IMAGE_HSL, IMAQ_IMAGE_RGB_U64 -* The border size is defaulted to 3 so that convolutional algorithms work at the edges. -* When you are finished with the created image, dispose of it by calling frcDispose(). -* To get extended error information, call GetLastError(). -* +* Supports IMAQ_IMAGE_U8, IMAQ_IMAGE_I16, IMAQ_IMAGE_SGL, IMAQ_IMAGE_COMPLEX, +* IMAQ_IMAGE_RGB, IMAQ_IMAGE_HSL, IMAQ_IMAGE_RGB_U64 +* The border size is defaulted to 3 so that convolutional algorithms work at the +* edges. +* When you are finished with the created image, dispose of it by calling +* frcDispose(). +* To get extended error information, call GetLastError(). +* * @param type Type of image to create -* @return Image* On success, this function returns the created image. On failure, it returns NULL. +* @return Image* On success, this function returns the created image. On +* failure, it returns NULL. */ -Image* frcCreateImage(ImageType type) { return imaqCreateImage(type, DEFAULT_BORDER_SIZE); } +Image* frcCreateImage(ImageType type) { + return imaqCreateImage(type, DEFAULT_BORDER_SIZE); +} /** * @brief Dispose of one object. Supports any object created on the heap. -* +* * @param object object to dispose of -* @return On success: 1. On failure: 0. To get extended error information, call GetLastError(). +* @return On success: 1. On failure: 0. To get extended error information, call +* GetLastError(). */ -int frcDispose(void* object) { return imaqDispose(object); } +int frcDispose(void* object) { return imaqDispose(object); } /** * @brief Dispose of a list of objects. Supports any object created on the heap. -* +* * @param functionName The name of the function -* @param ... A list of pointers to structures that need to be disposed of. +* @param ... A list of pointers to structures that need to be disposed of. * The last pointer in the list should always be set to NULL. -* -* @return On success: 1. On failure: 0. To get extended error information, call GetLastError(). +* +* @return On success: 1. On failure: 0. To get extended error information, call +* GetLastError(). */ -int frcDispose( const char* functionName, ... ) /* Variable argument list */ +int frcDispose(const char* functionName, ...) /* Variable argument list */ { - va_list disposalPtrList; /* Input argument list */ - void* disposalPtr; /* For iteration */ - int success, returnValue = 1; - - va_start( disposalPtrList, functionName ); /* start of variable list */ - disposalPtr = va_arg( disposalPtrList, void* ); - while( disposalPtr != NULL ) { - success = imaqDispose(disposalPtr); - if (!success) {returnValue = 0;} - disposalPtr = va_arg( disposalPtrList, void* ); + va_list disposalPtrList; /* Input argument list */ + void* disposalPtr; /* For iteration */ + int success, returnValue = 1; + + va_start(disposalPtrList, functionName); /* start of variable list */ + disposalPtr = va_arg(disposalPtrList, void*); + while (disposalPtr != NULL) { + success = imaqDispose(disposalPtr); + if (!success) { + returnValue = 0; } - return returnValue; + disposalPtr = va_arg(disposalPtrList, void*); + } + return returnValue; } /** -* @brief Copy an image object. -* Supports IMAQ_IMAGE_U8, IMAQ_IMAGE_I16, IMAQ_IMAGE_SGL, IMAQ_IMAGE_RGB, IMAQ_IMAGE_HSL. -* -* @param dest Copy of image. On failure, dest is NULL. Must have already been created using frcCreateImage(). -* When you are finished with the created image, dispose of it by calling frcDispose(). -* @param source Image to copy -* -* @return On success: 1. On failure: 0. To get extended error information, call GetLastError(). +* @brief Copy an image object. +* Supports IMAQ_IMAGE_U8, IMAQ_IMAGE_I16, IMAQ_IMAGE_SGL, IMAQ_IMAGE_RGB, +* IMAQ_IMAGE_HSL. +* +* @param dest Copy of image. On failure, dest is NULL. Must have already been +* created using frcCreateImage(). +* When you are finished with the created image, dispose of it by calling +* frcDispose(). +* @param source Image to copy +* +* @return On success: 1. On failure: 0. To get extended error information, call +* GetLastError(). */ -int frcCopyImage(Image* dest, const Image* source) { return imaqDuplicate(dest, source); } +int frcCopyImage(Image* dest, const Image* source) { + return imaqDuplicate(dest, source); +} /** -* @brief Crop image without changing the scale. -* Supports IMAQ_IMAGE_U8, IMAQ_IMAGE_I16, IMAQ_IMAGE_SGL, IMAQ_IMAGE_RGB, IMAQ_IMAGE_HSL. -* +* @brief Crop image without changing the scale. +* Supports IMAQ_IMAGE_U8, IMAQ_IMAGE_I16, IMAQ_IMAGE_SGL, IMAQ_IMAGE_RGB, +* IMAQ_IMAGE_HSL. +* * @param dest Modified image * @param source Image to crop * @param rect region to process, or IMAQ_NO_RECT -* -* @return On success: 1. On failure: 0. To get extended error information, call GetLastError(). +* +* @return On success: 1. On failure: 0. To get extended error information, call +* GetLastError(). */ -int frcCrop(Image* dest, const Image* source, Rect rect) -{ - return imaqScale(dest, source, 1, 1, IMAQ_SCALE_LARGER, rect); +int frcCrop(Image* dest, const Image* source, Rect rect) { + return imaqScale(dest, source, 1, 1, IMAQ_SCALE_LARGER, rect); } - /** -* @brief Scales the entire image larger or smaller. -* Supports IMAQ_IMAGE_U8, IMAQ_IMAGE_I16, IMAQ_IMAGE_SGL, IMAQ_IMAGE_RGB, IMAQ_IMAGE_HSL. -* +* @brief Scales the entire image larger or smaller. +* Supports IMAQ_IMAGE_U8, IMAQ_IMAGE_I16, IMAQ_IMAGE_SGL, IMAQ_IMAGE_RGB, +* IMAQ_IMAGE_HSL. +* * @param dest Modified image * @param source Image to scale * @param xScale the horizontal reduction ratio -* @param yScale the vertical reduction ratio -* @param scaleMode IMAQ_SCALE_LARGER or IMAQ_SCALE_SMALLER -* -* @return On success: 1. On failure: 0. To get extended error information, call GetLastError(). +* @param yScale the vertical reduction ratio +* @param scaleMode IMAQ_SCALE_LARGER or IMAQ_SCALE_SMALLER +* +* @return On success: 1. On failure: 0. To get extended error information, call +* GetLastError(). */ -int frcScale(Image* dest, const Image* source, int xScale, int yScale, ScalingMode scaleMode) -{ - Rect rect = IMAQ_NO_RECT; - return imaqScale(dest, source, xScale, yScale, scaleMode, rect); +int frcScale(Image* dest, const Image* source, int xScale, int yScale, + ScalingMode scaleMode) { + Rect rect = IMAQ_NO_RECT; + return imaqScale(dest, source, xScale, yScale, scaleMode, rect); } - + /** - * @brief Creates image object from the information in a file. The file can be in one of the following formats: - * PNG, JPEG, JPEG2000, TIFF, AIPD, or BMP. - * Supports IMAQ_IMAGE_U8, IMAQ_IMAGE_I16, IMAQ_IMAGE_SGL, IMAQ_IMAGE_COMPLEX, IMAQ_IMAGE_RGB, IMAQ_IMAGE_HSL, IMAQ_IMAGE_RGB_U64. - * + * @brief Creates image object from the information in a file. The file can be + * in one of the following formats: + * PNG, JPEG, JPEG2000, TIFF, AIPD, or BMP. + * Supports IMAQ_IMAGE_U8, IMAQ_IMAGE_I16, IMAQ_IMAGE_SGL, IMAQ_IMAGE_COMPLEX, + * IMAQ_IMAGE_RGB, IMAQ_IMAGE_HSL, IMAQ_IMAGE_RGB_U64. + * * @param image Image read in * @param fileName File to read. Cannot be NULL - * - * @return On success: 1. On failure: 0. To get extended error information, call GetLastError(). - */ - int frcReadImage(Image* image, const char* fileName) - { - return imaqReadFile(image, fileName, NULL, NULL); - } - - - /** - * @brief Write image to a file. - * Supports IMAQ_IMAGE_U8, IMAQ_IMAGE_I16, IMAQ_IMAGE_SGL, IMAQ_IMAGE_COMPLEX, IMAQ_IMAGE_RGB, IMAQ_IMAGE_HSL, IMAQ_IMAGE_RGB_U64. - * - * The file type is determined by the extension, as follows: * - * Extension File Type - * aipd or .apd AIPD - * .bmp BMP - * .jpg or .jpeg JPEG - * .jp2 JPEG2000 - * .png PNG - * .tif or .tiff TIFF - * - * - *The following are the supported image types for each file type: - * - * File Types Image Types - * AIPD all image types - * BMP, JPEG 8-bit, RGB - * PNG, TIFF, JPEG2000 8-bit, 16-bit, RGB, RGBU64 - * - * @param image Image to write - * @param fileName File to read. Cannot be NULL. The extension determines the file format that is written. - * - * @return On success: 1. On failure: 0. To get extended error information, call GetLastError(). + * @return On success: 1. On failure: 0. To get extended error information, call + * GetLastError(). */ -int frcWriteImage(const Image* image, const char* fileName) -{ - RGBValue* colorTable = NULL; - return imaqWriteFile(image, fileName, colorTable); +int frcReadImage(Image* image, const char* fileName) { + return imaqReadFile(image, fileName, NULL, NULL); } +/** +* @brief Write image to a file. +* Supports IMAQ_IMAGE_U8, IMAQ_IMAGE_I16, IMAQ_IMAGE_SGL, IMAQ_IMAGE_COMPLEX, +* IMAQ_IMAGE_RGB, IMAQ_IMAGE_HSL, IMAQ_IMAGE_RGB_U64. +* +* The file type is determined by the extension, as follows: +* +* Extension File Type +* aipd or .apd AIPD +* .bmp BMP +* .jpg or .jpeg JPEG +* .jp2 JPEG2000 +* .png PNG +* .tif or .tiff TIFF +* +* +* The following are the supported image types for each file type: +* +* File Types Image Types +* AIPD all image types +* BMP, JPEG 8-bit, RGB +* PNG, TIFF, JPEG2000 8-bit, 16-bit, RGB, RGBU64 +* +* @param image Image to write +* @param fileName File to read. Cannot be NULL. The extension determines the +* file format that is written. +* +* @return On success: 1. On failure: 0. To get extended error information, call +* GetLastError(). +*/ +int frcWriteImage(const Image* image, const char* fileName) { + RGBValue* colorTable = NULL; + return imaqWriteFile(image, fileName, colorTable); +} /* Measure Intensity functions */ /** -* @brief Measures the pixel intensities in a rectangle of an image. -* Outputs intensity based statistics about an image such as Max, Min, Mean and Std Dev of pixel value. +* @brief Measures the pixel intensities in a rectangle of an image. +* Outputs intensity based statistics about an image such as Max, Min, Mean and +* Std Dev of pixel value. * Supports IMAQ_IMAGE_U8, IMAQ_IMAGE_I16, IMAQ_IMAGE_SGL. * -* Parameter Discussion : -* Relevant parameters of the HistogramReport include: -* min, max, mean and stdDev -* min/max —Setting both min and max to 0 causes the function to set min to 0 -* and the max to 255 for 8-bit images and to the actual minimum value and +* Parameter Discussion : +* Relevant parameters of the HistogramReport include: +* min, max, mean and stdDev +* min/max —Setting both min and max to 0 causes the function to set +* min to 0 +* and the max to 255 for 8-bit images and to the actual +* minimum value and * maximum value of the image for all other image types. -* max—Setting both min and max to 0 causes the function to set max to 255 -* for 8-bit images and to the actual maximum value of the image for +* max—Setting both min and max to 0 causes the function to set max +* to 255 +* for 8-bit images and to the actual maximum value of the +* image for * all other image types. * * @param image Image whose histogram the function calculates. -* @param numClasses The number of classes into which the function separates the pixels. +* @param numClasses The number of classes into which the function separates the +* pixels. * Determines the number of elements in the histogram array returned -* @param min The minimum pixel value to consider for the histogram. +* @param min The minimum pixel value to consider for the histogram. * The function does not count pixels with values less than min. -* @param max The maximum pixel value to consider for the histogram. +* @param max The maximum pixel value to consider for the histogram. * The function does not count pixels with values greater than max. -* @param rect Region of interest in the image. If not included, the entire image is used. -* @return On success, this function returns a report describing the pixel value classification. -* When you are finished with the report, dispose of it by calling frcDispose(). -* On failure, this function returns NULL. To get extended error information, call GetLastError(). -* +* @param rect Region of interest in the image. If not included, the entire image +* is used. +* @return On success, this function returns a report describing the pixel value +* classification. +* When you are finished with the report, dispose of it by calling frcDispose(). +* On failure, this function returns NULL. To get extended error information, +* call GetLastError(). +* */ -HistogramReport* frcHistogram(const Image* image, int numClasses, float min, float max) -{ - Rect rect = IMAQ_NO_RECT; - return frcHistogram(image, numClasses, min, max, rect); +HistogramReport* frcHistogram(const Image* image, int numClasses, float min, + float max) { + Rect rect = IMAQ_NO_RECT; + return frcHistogram(image, numClasses, min, max, rect); } -HistogramReport* frcHistogram(const Image* image, int numClasses, float min, float max, Rect rect) -{ - int success; - int fillValue = 1; - - /* create the region of interest */ - ROI* pRoi = imaqCreateROI(); - success = imaqAddRectContour(pRoi, rect); - if ( !success ) { GetLastVisionError(); return NULL; } +HistogramReport* frcHistogram(const Image* image, int numClasses, float min, + float max, Rect rect) { + int success; + int fillValue = 1; - /* make a mask from the ROI */ - Image* pMask = frcCreateImage(IMAQ_IMAGE_U8); - success = imaqROIToMask(pMask, pRoi, fillValue, NULL, NULL); - if ( !success ) { - GetLastVisionError(); - frcDispose(__FUNCTION__, pRoi, NULL); - return NULL; - } - - /* get a histogram report */ - HistogramReport* pHr = NULL; - pHr = imaqHistogram(image, numClasses, min, max, pMask); - - /* clean up */ - frcDispose(__FUNCTION__, pRoi, pMask, NULL); - - return pHr; + /* create the region of interest */ + ROI* pRoi = imaqCreateROI(); + success = imaqAddRectContour(pRoi, rect); + if (!success) { + GetLastVisionError(); + return NULL; + } + + /* make a mask from the ROI */ + Image* pMask = frcCreateImage(IMAQ_IMAGE_U8); + success = imaqROIToMask(pMask, pRoi, fillValue, NULL, NULL); + if (!success) { + GetLastVisionError(); + frcDispose(__FUNCTION__, pRoi, NULL); + return NULL; + } + + /* get a histogram report */ + HistogramReport* pHr = NULL; + pHr = imaqHistogram(image, numClasses, min, max, pMask); + + /* clean up */ + frcDispose(__FUNCTION__, pRoi, pMask, NULL); + + return pHr; } /** -* @brief Calculates the histogram, or pixel distribution, of a color image. +* @brief Calculates the histogram, or pixel distribution, of a color image. * Supports IMAQ_IMAGE_RGB, IMAQ_IMAGE_HSL. -* +* * @param image Image whose histogram the function calculates. -* @param numClasses The number of classes into which the function separates the pixels. +* @param numClasses The number of classes into which the function separates the +* pixels. * Determines the number of elements in the histogram array returned -* @param mode The color space in which to perform the histogram. Possible values include IMAQ_RGB and IMAQ_HSL. -* @param mask An optional mask image. This image must be an IMAQ_IMAGE_U8 image. -* The function calculates the histogram using only those pixels in the image whose -* corresponding pixels in the mask are non-zero. Set this parameter to NULL to calculate +* @param mode The color space in which to perform the histogram. Possible values +* include IMAQ_RGB and IMAQ_HSL. +* @param mask An optional mask image. This image must be an IMAQ_IMAGE_U8 image. +* The function calculates the histogram using only those pixels in the image +* whose +* corresponding pixels in the mask are non-zero. Set this parameter to NULL to +* calculate * the histogram of the entire image, or use the simplified call. -* -* @return On success, this function returns a report describing the classification -* of each plane in a HistogramReport. -* When you are finished with the report, dispose of it by calling frcDispose(). -* On failure, this function returns NULL. -* To get extended error information, call imaqGetLastError(). +* +* @return On success, this function returns a report describing the +* classification +* of each plane in a HistogramReport. +* When you are finished with the report, dispose of it by calling frcDispose(). +* On failure, this function returns NULL. +* To get extended error information, call imaqGetLastError(). */ -ColorHistogramReport* frcColorHistogram(const Image* image, int numClasses, ColorMode mode) -{ - return frcColorHistogram(image, numClasses, mode, NULL); +ColorHistogramReport* frcColorHistogram(const Image* image, int numClasses, + ColorMode mode) { + return frcColorHistogram(image, numClasses, mode, NULL); } -ColorHistogramReport* frcColorHistogram(const Image* image, int numClasses, ColorMode mode, Image* mask) -{ - return imaqColorHistogram2((Image*)image, numClasses, mode, NULL, mask); +ColorHistogramReport* frcColorHistogram(const Image* image, int numClasses, + ColorMode mode, Image* mask) { + return imaqColorHistogram2((Image*)image, numClasses, mode, NULL, mask); } - /** -* @brief Measures the pixel intensities in a rectangle of an image. -* Outputs intensity based statistics about an image such as Max, Min, Mean and Std Dev of pixel value. -* Supports IMAQ_IMAGE_U8 (grayscale) IMAQ_IMAGE_RGB (color) IMAQ_IMAGE_HSL (color-HSL). -* +* @brief Measures the pixel intensities in a rectangle of an image. +* Outputs intensity based statistics about an image such as Max, Min, Mean and +* Std Dev of pixel value. +* Supports IMAQ_IMAGE_U8 (grayscale) IMAQ_IMAGE_RGB (color) IMAQ_IMAGE_HSL +* (color-HSL). +* * @param image The image whose pixel value the function queries * @param pixel The coordinates of the pixel that the function queries -* @param value On return, the value of the specified image pixel. This parameter cannot be NULL. -* This data structure contains either grayscale, RGB, HSL, Complex or RGBU64Value depending on the type of image. -* @return On success: 1. On failure: 0. To get extended error information, call GetLastError(). +* @param value On return, the value of the specified image pixel. This parameter +* cannot be NULL. +* This data structure contains either grayscale, RGB, HSL, Complex or +* RGBU64Value depending on the type of image. +* @return On success: 1. On failure: 0. To get extended error information, call +* GetLastError(). */ -int frcGetPixelValue(const Image* image, Point pixel, PixelValue* value) -{ - return imaqGetPixel(image, pixel, value); +int frcGetPixelValue(const Image* image, Point pixel, PixelValue* value) { + return imaqGetPixel(image, pixel, value); } - /* Particle Analysis functions */ /** -* @brief Filters particles out of an image based on their measurements. +* @brief Filters particles out of an image based on their measurements. * Supports IMAQ_IMAGE_U8, IMAQ_IMAGE_I16, IMAQ_IMAGE_SGL. -* -* @param dest The destination image. If dest is used, it must be the same size as the Source image. It will contain only the filtered particles. -* @param source The image containing the particles to filter. -* @param criteria An array of criteria to apply to the particles in the source image. This array cannot be NULL. -* See the NIVisionCVI.chm help file for definitions of criteria. +* +* @param dest The destination image. If dest is used, it must be the same size +* as the Source image. It will contain only the filtered particles. +* @param source The image containing the particles to filter. +* @param criteria An array of criteria to apply to the particles in the source +* image. This array cannot be NULL. +* See the NIVisionCVI.chm help file for definitions of criteria. * @param criteriaCount The number of elements in the criteria array. -* @param options Binary filter options, including rejectMatches, rejectBorder, and connectivity8. +* @param options Binary filter options, including rejectMatches, rejectBorder, +* and connectivity8. * @param rect Area of image to filter. If omitted, the default is entire image. * @param numParticles On return, the number of particles left in the image -* @return On success: 1. On failure: 0. To get extended error information, call GetLastError(). +* @return On success: 1. On failure: 0. To get extended error information, call +* GetLastError(). */ -int frcParticleFilter(Image* dest, Image* source, const ParticleFilterCriteria2* criteria, - int criteriaCount, const ParticleFilterOptions* options, int* numParticles) -{ - Rect rect = IMAQ_NO_RECT; - return frcParticleFilter(dest, source, criteria, criteriaCount, options, rect, numParticles); +int frcParticleFilter(Image* dest, Image* source, + const ParticleFilterCriteria2* criteria, + int criteriaCount, const ParticleFilterOptions* options, + int* numParticles) { + Rect rect = IMAQ_NO_RECT; + return frcParticleFilter(dest, source, criteria, criteriaCount, options, rect, + numParticles); } -int frcParticleFilter(Image* dest, Image* source, const ParticleFilterCriteria2* criteria, - int criteriaCount, const ParticleFilterOptions* options, Rect rect, int* numParticles) -{ - ROI* roi = imaqCreateROI(); - imaqAddRectContour(roi, rect); - return imaqParticleFilter3(dest, source, criteria, criteriaCount, options, roi, numParticles); +int frcParticleFilter(Image* dest, Image* source, + const ParticleFilterCriteria2* criteria, + int criteriaCount, const ParticleFilterOptions* options, + Rect rect, int* numParticles) { + ROI* roi = imaqCreateROI(); + imaqAddRectContour(roi, rect); + return imaqParticleFilter3(dest, source, criteria, criteriaCount, options, + roi, numParticles); } - /** -* @brief Performs morphological transformations on binary images. -* Supports IMAQ_IMAGE_U8. +* @brief Performs morphological transformations on binary images. +* Supports IMAQ_IMAGE_U8. * -* @param dest The destination image. The border size of the destination image is not important. -* @param source The image on which the function performs the morphological operations. The calculation -* modifies the border of the source image. The border must be at least half as large as the larger -* dimension of the structuring element. The connected source image for a morphological transformation -* must have been created with a border capable of supporting the size of the structuring element. -* A 3 by 3 structuring element requires a minimal border of 1, a 5 by 5 structuring element requires a minimal border of 2, and so on. -* @param method The morphological transform to apply. -* @param structuringElement The structuring element used in the operation. Omit this parameter if you do not want a custom structuring element. -* @return On success: 1. On failure: 0. To get extended error information, call GetLastError(). +* @param dest The destination image. The border size of the destination image is +* not important. +* @param source The image on which the function performs the morphological +* operations. The calculation +* modifies the border of the source image. The border must be at least half as +* large as the larger +* dimension of the structuring element. The connected source image for a +* morphological transformation +* must have been created with a border capable of supporting the size of the +* structuring element. +* A 3 by 3 structuring element requires a minimal border of 1, a 5 by 5 +* structuring element requires a minimal border of 2, and so on. +* @param method The morphological transform to apply. +* @param structuringElement The structuring element used in the operation. Omit +* this parameter if you do not want a custom structuring element. +* @return On success: 1. On failure: 0. To get extended error information, call +* GetLastError(). */ -int frcMorphology(Image* dest, Image* source, MorphologyMethod method) -{ - return imaqMorphology(dest, source, method, NULL); +int frcMorphology(Image* dest, Image* source, MorphologyMethod method) { + return imaqMorphology(dest, source, method, NULL); } -int frcMorphology(Image* dest, Image* source, MorphologyMethod method, const StructuringElement* structuringElement) -{ - return imaqMorphology(dest, source, method, structuringElement); +int frcMorphology(Image* dest, Image* source, MorphologyMethod method, + const StructuringElement* structuringElement) { + return imaqMorphology(dest, source, method, structuringElement); } /** -* @brief Eliminates particles that touch the border of the image. +* @brief Eliminates particles that touch the border of the image. * Supports IMAQ_IMAGE_U8. * * @param dest The destination image. -* @param source The source image. If the image has a border, the function sets all border pixel values to 0. -* @param connectivity8 specifies the type of connectivity used by the algorithm for particle detection. -* The connectivity mode directly determines whether an adjacent pixel belongs to the same particle or a -* different particle. Set to TRUE to use connectivity-8 to determine whether particles are touching -* Set to FALSE to use connectivity-4 to determine whether particles are touching. +* @param source The source image. If the image has a border, the function sets +* all border pixel values to 0. +* @param connectivity8 specifies the type of connectivity used by the algorithm +* for particle detection. +* The connectivity mode directly determines whether an adjacent pixel belongs to +* the same particle or a +* different particle. Set to TRUE to use connectivity-8 to determine whether +* particles are touching +* Set to FALSE to use connectivity-4 to determine whether particles are +* touching. * The default setting for the simplified call is TRUE -* @return On success: 1. On failure: 0. To get extended error information, call GetLastError(). +* @return On success: 1. On failure: 0. To get extended error information, call +* GetLastError(). */ -int frcRejectBorder(Image* dest, Image* source) -{ return imaqRejectBorder(dest, source, TRUE); } - -int frcRejectBorder(Image* dest, Image* source, int connectivity8) -{ - return imaqRejectBorder(dest, source, connectivity8); +int frcRejectBorder(Image* dest, Image* source) { + return imaqRejectBorder(dest, source, TRUE); } +int frcRejectBorder(Image* dest, Image* source, int connectivity8) { + return imaqRejectBorder(dest, source, connectivity8); +} /** -* @brief Counts the number of particles in a binary image. +* @brief Counts the number of particles in a binary image. * Supports IMAQ_IMAGE_U8, IMAQ_IMAGE_I16, IMAQ_IMAGE_SGL. -* @param image binary (thresholded) image +* @param image binary (thresholded) image * @param numParticles On return, the number of particles. -* @return On success: 1. On failure: 0. To get extended error information, call GetLastError(). +* @return On success: 1. On failure: 0. To get extended error information, call +* GetLastError(). */ -int frcCountParticles(Image* image, int* numParticles) -{ - return imaqCountParticles(image, 1, numParticles); +int frcCountParticles(Image* image, int* numParticles) { + return imaqCountParticles(image, 1, numParticles); } - /** -* @brief Conduct measurements for a single particle in an images. +* @brief Conduct measurements for a single particle in an images. * Supports IMAQ_IMAGE_U8, IMAQ_IMAGE_I16, IMAQ_IMAGE_SGL. -* -* @param image image with the particle to analyze. This function modifies the source image. -* If you need the original image, create a copy of the image using frcCopy() before using this function. +* +* @param image image with the particle to analyze. This function modifies the +* source image. +* If you need the original image, create a copy of the image using frcCopy() +* before using this function. * @param particleNumber The number of the particle to get information on -* @param par on return, a particle analysis report containing information about the particle. This structure must be created by the caller. -* @return On success: 1. On failure: 0. To get extended error information, call GetLastError(). +* @param par on return, a particle analysis report containing information about +* the particle. This structure must be created by the caller. +* @return On success: 1. On failure: 0. To get extended error information, call +* GetLastError(). */ -int frcParticleAnalysis(Image* image, int particleNumber, ParticleAnalysisReport* par) -{ - int success = 0; +int frcParticleAnalysis(Image* image, int particleNumber, + ParticleAnalysisReport* par) { + int success = 0; - /* image information */ - int height, width; - if ( ! imaqGetImageSize(image, &width, &height) ) { return success; } - par->imageWidth = width; - par->imageHeight = height; - par->particleIndex = particleNumber; + /* image information */ + int height, width; + if (!imaqGetImageSize(image, &width, &height)) { + return success; + } + par->imageWidth = width; + par->imageHeight = height; + par->particleIndex = particleNumber; - /* center of mass point of the largest particle */ - double returnDouble; - success = imaqMeasureParticle(image, particleNumber, 0, IMAQ_MT_CENTER_OF_MASS_X, &returnDouble); - if ( !success ) { return success; } - par->center_mass_x = (int)returnDouble; // pixel + /* center of mass point of the largest particle */ + double returnDouble; + success = imaqMeasureParticle(image, particleNumber, 0, + IMAQ_MT_CENTER_OF_MASS_X, &returnDouble); + if (!success) { + return success; + } + par->center_mass_x = (int)returnDouble; // pixel - success = imaqMeasureParticle(image, particleNumber, 0, IMAQ_MT_CENTER_OF_MASS_Y, &returnDouble); - if ( !success ) { return success; } - par->center_mass_y = (int)returnDouble; // pixel - - /* particle size statistics */ - success = imaqMeasureParticle(image, particleNumber, 0, IMAQ_MT_AREA, &returnDouble); - if ( !success ) { return success; } - par->particleArea = returnDouble; - - success = imaqMeasureParticle(image, particleNumber, 0, IMAQ_MT_BOUNDING_RECT_TOP, &returnDouble); - if ( !success ) { return success; } - par->boundingRect.top = (int)returnDouble; - - success = imaqMeasureParticle(image, particleNumber, 0, IMAQ_MT_BOUNDING_RECT_LEFT, &returnDouble); - if ( !success ) { return success; } - par->boundingRect.left = (int)returnDouble; - - success = imaqMeasureParticle(image, particleNumber, 0, IMAQ_MT_BOUNDING_RECT_HEIGHT, &returnDouble); - if ( !success ) { return success; } - par->boundingRect.height = (int)returnDouble; + success = imaqMeasureParticle(image, particleNumber, 0, + IMAQ_MT_CENTER_OF_MASS_Y, &returnDouble); + if (!success) { + return success; + } + par->center_mass_y = (int)returnDouble; // pixel - success = imaqMeasureParticle(image, particleNumber, 0, IMAQ_MT_BOUNDING_RECT_WIDTH, &returnDouble); - if ( !success ) { return success; } - par->boundingRect.width = (int)returnDouble; - - /* particle quality statistics */ - success = imaqMeasureParticle(image, particleNumber, 0, IMAQ_MT_AREA_BY_IMAGE_AREA, &returnDouble); - if ( !success ) { return success; } - par->particleToImagePercent = returnDouble; + /* particle size statistics */ + success = imaqMeasureParticle(image, particleNumber, 0, IMAQ_MT_AREA, + &returnDouble); + if (!success) { + return success; + } + par->particleArea = returnDouble; - success = imaqMeasureParticle(image, particleNumber, 0, IMAQ_MT_AREA_BY_PARTICLE_AND_HOLES_AREA, &returnDouble); - if ( !success ) { return success; } - par->particleQuality = returnDouble; - - /* normalized position (-1 to 1) */ - par->center_mass_x_normalized = RangeToNormalized(par->center_mass_x, width); - par->center_mass_y_normalized = RangeToNormalized(par->center_mass_y, height); - - return success; + success = imaqMeasureParticle(image, particleNumber, 0, + IMAQ_MT_BOUNDING_RECT_TOP, &returnDouble); + if (!success) { + return success; + } + par->boundingRect.top = (int)returnDouble; + + success = imaqMeasureParticle(image, particleNumber, 0, + IMAQ_MT_BOUNDING_RECT_LEFT, &returnDouble); + if (!success) { + return success; + } + par->boundingRect.left = (int)returnDouble; + + success = imaqMeasureParticle(image, particleNumber, 0, + IMAQ_MT_BOUNDING_RECT_HEIGHT, &returnDouble); + if (!success) { + return success; + } + par->boundingRect.height = (int)returnDouble; + + success = imaqMeasureParticle(image, particleNumber, 0, + IMAQ_MT_BOUNDING_RECT_WIDTH, &returnDouble); + if (!success) { + return success; + } + par->boundingRect.width = (int)returnDouble; + + /* particle quality statistics */ + success = imaqMeasureParticle(image, particleNumber, 0, + IMAQ_MT_AREA_BY_IMAGE_AREA, &returnDouble); + if (!success) { + return success; + } + par->particleToImagePercent = returnDouble; + + success = imaqMeasureParticle(image, particleNumber, 0, + IMAQ_MT_AREA_BY_PARTICLE_AND_HOLES_AREA, + &returnDouble); + if (!success) { + return success; + } + par->particleQuality = returnDouble; + + /* normalized position (-1 to 1) */ + par->center_mass_x_normalized = RangeToNormalized(par->center_mass_x, width); + par->center_mass_y_normalized = RangeToNormalized(par->center_mass_y, height); + + return success; } - /* Image Enhancement functions */ /** -* @brief Improves contrast on a grayscale image. +* @brief Improves contrast on a grayscale image. * Supports IMAQ_IMAGE_U8, IMAQ_IMAGE_I16. * @param dest The destination image. -* @param source The image to equalize -* @param min the smallest value used for processing. After processing, all pixel values that are less than or equal to the Minimum in the original image are set to 0 for an 8-bit image. In 16-bit and floating-point images, these pixel values are set to the smallest pixel value found in the original image. -* @param max the largest value used for processing. After processing, all pixel values that are greater than or equal to the Maximum in the original image are set to 255 for an 8-bit image. In 16-bit and floating-point images, these pixel values are set to the largest pixel value found in the original image. -* @param mask an 8-bit image that specifies the region of the small image that will be copied. Only those pixels in the Image Src (Small) image that correspond to an equivalent non-zero pixel in the mask image are copied. All other pixels keep their original values. The entire image is processed if Image Mask is NULL or this parameter is omitted. -* @return On success: 1. On failure: 0. To get extended error information, call GetLastError(). +* @param source The image to equalize +* @param min the smallest value used for processing. After processing, all pixel +* values that are less than or equal to the Minimum in the original image are set +* to 0 for an 8-bit image. In 16-bit and floating-point images, these pixel +* values are set to the smallest pixel value found in the original image. +* @param max the largest value used for processing. After processing, all pixel +* values that are greater than or equal to the Maximum in the original image are +* set to 255 for an 8-bit image. In 16-bit and floating-point images, these pixel +* values are set to the largest pixel value found in the original image. +* @param mask an 8-bit image that specifies the region of the small image that +* will be copied. Only those pixels in the Image Src (Small) image that +* correspond to an equivalent non-zero pixel in the mask image are copied. All +* other pixels keep their original values. The entire image is processed if Image +* Mask is NULL or this parameter is omitted. +* @return On success: 1. On failure: 0. To get extended error information, call +* GetLastError(). * * option defaults: * searchRect = IMAQ_NO_RECT -* minMatchScore = DEFAULT_MINMAX_SCORE (800) +* minMatchScore = DEFAULT_MINMAX_SCORE (800) */ -int frcEqualize(Image* dest, const Image* source, float min, float max) -{ return frcEqualize(dest, source, min, max, NULL); } +int frcEqualize(Image* dest, const Image* source, float min, float max) { + return frcEqualize(dest, source, min, max, NULL); +} -int frcEqualize(Image* dest, const Image* source, float min, float max, const Image* mask) -{ - return imaqEqualize(dest, source, min, max, mask); +int frcEqualize(Image* dest, const Image* source, float min, float max, + const Image* mask) { + return imaqEqualize(dest, source, min, max, mask); } /** -* @brief Improves contrast on a color image. +* @brief Improves contrast on a color image. * Supports IMAQ_IMAGE_RGB, IMAQ_IMAGE_HSL -* -* option defaults: colorEqualization = TRUE to equalize all three planes of the image -* @return On success: 1. On failure: 0. To get extended error information, call GetLastError(). +* +* option defaults: colorEqualization = TRUE to equalize all three planes of the +* image +* @return On success: 1. On failure: 0. To get extended error information, call +* GetLastError(). * @param dest The destination image. -* @param source The image to equalize -* @param colorEqualization Set this parameter to TRUE to equalize all three planes of the image (the default). Set this parameter to FALSE to equalize only the luminance plane. +* @param source The image to equalize +* @param colorEqualization Set this parameter to TRUE to equalize all three +* planes of the image (the default). Set this parameter to FALSE to equalize only +* the luminance plane. */ -int frcColorEqualize(Image* dest, const Image* source) -{ - return imaqColorEqualize(dest, source, TRUE); +int frcColorEqualize(Image* dest, const Image* source) { + return imaqColorEqualize(dest, source, TRUE); } -int frcColorEqualize(Image* dest, const Image* source, int colorEqualization) -{ - return imaqColorEqualize(dest, source, TRUE); +int frcColorEqualize(Image* dest, const Image* source, int colorEqualization) { + return imaqColorEqualize(dest, source, TRUE); } /* Image Conversion functions */ /** -* @brief Automatically thresholds a grayscale image into a binary image for Particle Analysis based on a smart threshold. +* @brief Automatically thresholds a grayscale image into a binary image for +* Particle Analysis based on a smart threshold. * Supports IMAQ_IMAGE_RGB, IMAQ_IMAGE_I16 * @param dest The destination image. -* @param source The image to threshold -* @param windowWidth The width of the rectangular window around the pixel on which the function -* performs the local threshold. This number must be at least 3 and cannot be larger than the width of source -* @param windowHeight The height of the rectangular window around the pixel on which the function -* performs the local threshold. This number must be at least 3 and cannot be larger than the height of source -* @param method Specifies the local thresholding method the function uses. Value can be IMAQ_NIBLACK -* (which computes thresholds for each pixel based on its local statistics using the Niblack local thresholding -* algorithm.), or IMAQ_BACKGROUND_CORRECTION (which does background correction first to eliminate non-uniform -* lighting effects, then performs thresholding using the Otsu thresholding algorithm) -* @param deviationWeight Specifies the k constant used in the Niblack local thresholding algorithm, which -* determines the weight applied to the variance calculation. Valid k constants range from 0 to 1. Setting -* this value to 0 will increase the performance of the function because the function will not calculate the -* variance for any of the pixels. The function ignores this value if method is not set to IMAQ_NIBLACK -* @param type Specifies the type of objects for which you want to look. Values can be IMAQ_BRIGHT_OBJECTS +* @param source The image to threshold +* @param windowWidth The width of the rectangular window around the pixel on +* which the function +* performs the local threshold. This number must be at least 3 and cannot be +* larger than the width of source +* @param windowHeight The height of the rectangular window around the pixel on +* which the function +* performs the local threshold. This number must be at least 3 and cannot be +* larger than the height of source +* @param method Specifies the local thresholding method the function uses. Value +* can be IMAQ_NIBLACK +* (which computes thresholds for each pixel based on its local statistics using +* the Niblack local thresholding +* algorithm.), or IMAQ_BACKGROUND_CORRECTION (which does background correction +* first to eliminate non-uniform +* lighting effects, then performs thresholding using the Otsu thresholding +* algorithm) +* @param deviationWeight Specifies the k constant used in the Niblack local +* thresholding algorithm, which +* determines the weight applied to the variance calculation. Valid k constants +* range from 0 to 1. Setting +* this value to 0 will increase the performance of the function because the +* function will not calculate the +* variance for any of the pixels. The function ignores this value if method is +* not set to IMAQ_NIBLACK +* @param type Specifies the type of objects for which you want to look. Values +* can be IMAQ_BRIGHT_OBJECTS * or IMAQ_DARK_OBJECTS. -* @param replaceValue Specifies the replacement value the function uses for the pixels of the kept objects +* @param replaceValue Specifies the replacement value the function uses for the +* pixels of the kept objects * in the destination image. -* @return On success: 1. On failure: 0. To get extended error information, call GetLastError(). +* @return On success: 1. On failure: 0. To get extended error information, call +* GetLastError(). */ -int frcSmartThreshold(Image* dest, const Image* source, - unsigned int windowWidth, unsigned int windowHeight, LocalThresholdMethod method, - double deviationWeight, ObjectType type) -{ - float replaceValue = 1.0; - return imaqLocalThreshold(dest, source, windowWidth, windowHeight, method, - deviationWeight, type, replaceValue); +int frcSmartThreshold(Image* dest, const Image* source, + unsigned int windowWidth, unsigned int windowHeight, + LocalThresholdMethod method, double deviationWeight, + ObjectType type) { + float replaceValue = 1.0; + return imaqLocalThreshold(dest, source, windowWidth, windowHeight, method, + deviationWeight, type, replaceValue); } -int frcSmartThreshold(Image* dest, const Image* source, - unsigned int windowWidth, unsigned int windowHeight, LocalThresholdMethod method, - double deviationWeight, ObjectType type, float replaceValue) -{ - return imaqLocalThreshold(dest, source, windowWidth, windowHeight, method, - deviationWeight, type, replaceValue); +int frcSmartThreshold(Image* dest, const Image* source, + unsigned int windowWidth, unsigned int windowHeight, + LocalThresholdMethod method, double deviationWeight, + ObjectType type, float replaceValue) { + return imaqLocalThreshold(dest, source, windowWidth, windowHeight, method, + deviationWeight, type, replaceValue); } /** -* @brief Converts a grayscale image to a binary image for Particle Analysis based on a fixed threshold. -* The function sets pixels values outside of the given range to 0. The function sets pixel values -* within the range to a given value or leaves the values unchanged. +* @brief Converts a grayscale image to a binary image for Particle Analysis +* based on a fixed threshold. +* The function sets pixels values outside of the given range to 0. The function +* sets pixel values +* within the range to a given value or leaves the values unchanged. * Use the simplified call to leave pixel values unchanged. * Supports IMAQ_IMAGE_RGB, IMAQ_IMAGE_I16. -* +* * @param dest The destination image. -* @param source The image to threshold +* @param source The image to threshold * @param rangeMin The lower boundary of the range of pixel values to keep * @param rangeMax The upper boundary of the range of pixel values to keep. -* -* @return int - error code: 0 = error. To get extended error information, call GetLastError(). +* +* @return int - error code: 0 = error. To get extended error information, call +* GetLastError(). */ -int frcSimpleThreshold(Image* dest, const Image* source, float rangeMin, float rangeMax) -{ - int newValue = 255; - return frcSimpleThreshold(dest, source, rangeMin, rangeMax, newValue); +int frcSimpleThreshold(Image* dest, const Image* source, float rangeMin, + float rangeMax) { + int newValue = 255; + return frcSimpleThreshold(dest, source, rangeMin, rangeMax, newValue); } /** -* @brief Converts a grayscale image to a binary image for Particle Analysis based on a fixed threshold. -* The function sets pixels values outside of the given range to 0. The function sets -* pixel values within the range to the given value. +* @brief Converts a grayscale image to a binary image for Particle Analysis +* based on a fixed threshold. +* The function sets pixels values outside of the given range to 0. The function +* sets +* pixel values within the range to the given value. * Supports IMAQ_IMAGE_RGB, IMAQ_IMAGE_I16. -* +* * @param dest The destination image. -* @param source The image to threshold +* @param source The image to threshold * @param rangeMin The lower boundary of the range of pixel values to keep * @param rangeMax The upper boundary of the range of pixel values to keep. -* @param newValue The replacement value for pixels within the range. Use the simplified call to leave the pixel values unchanged -* -* @return int - error code: 0 = error. To get extended error information, call GetLastError(). +* @param newValue The replacement value for pixels within the range. Use the +* simplified call to leave the pixel values unchanged +* +* @return int - error code: 0 = error. To get extended error information, call +* GetLastError(). */ -int frcSimpleThreshold(Image* dest, const Image* source, float rangeMin, float rangeMax, float newValue) -{ - int useNewValue = TRUE; - return imaqThreshold(dest, source, rangeMin, rangeMax, useNewValue, newValue); +int frcSimpleThreshold(Image* dest, const Image* source, float rangeMin, + float rangeMax, float newValue) { + int useNewValue = TRUE; + return imaqThreshold(dest, source, rangeMin, rangeMax, useNewValue, newValue); } /** -* @brief Applies a threshold to the Red, Green, and Blue values of a RGB image or the Hue, -* Saturation, Luminance values for a HSL image. +* @brief Applies a threshold to the Red, Green, and Blue values of a RGB image +* or the Hue, +* Saturation, Luminance values for a HSL image. * Supports IMAQ_IMAGE_RGB, IMAQ_IMAGE_HSL. * This simpler version filters based on a hue range in the HSL mode. -* +* * @param dest The destination image. This must be a IMAQ_IMAGE_U8 image. -* @param source The image to threshold -* @param mode The color space to perform the threshold in. valid values are: IMAQ_RGB, IMAQ_HSL. -* @param plane1Range The selection range for the first plane of the image. Set this parameter to NULL to use a selection range from 0 to 255. -* @param plane2Range The selection range for the second plane of the image. Set this parameter to NULL to use a selection range from 0 to 255. -* @param plane3Range The selection range for the third plane of the image. Set this parameter to NULL to use a selection range from 0 to 255. -* -* @return On success: 1. On failure: 0. To get extended error information, call GetLastError(). +* @param source The image to threshold +* @param mode The color space to perform the threshold in. valid values are: +* IMAQ_RGB, IMAQ_HSL. +* @param plane1Range The selection range for the first plane of the image. Set +* this parameter to NULL to use a selection range from 0 to 255. +* @param plane2Range The selection range for the second plane of the image. Set +* this parameter to NULL to use a selection range from 0 to 255. +* @param plane3Range The selection range for the third plane of the image. Set +* this parameter to NULL to use a selection range from 0 to 255. +* +* @return On success: 1. On failure: 0. To get extended error information, call +* GetLastError(). * */ -int frcColorThreshold(Image* dest, const Image* source, ColorMode mode, - const Range* plane1Range, const Range* plane2Range, const Range* plane3Range) -{ - int replaceValue = 1; - return imaqColorThreshold(dest, source, replaceValue, mode, plane1Range, plane2Range, plane3Range); +int frcColorThreshold(Image* dest, const Image* source, ColorMode mode, + const Range* plane1Range, const Range* plane2Range, + const Range* plane3Range) { + int replaceValue = 1; + return imaqColorThreshold(dest, source, replaceValue, mode, plane1Range, + plane2Range, plane3Range); } /** -* @brief Applies a threshold to the Red, Green, and Blue values of a RGB image or the Hue, -* Saturation, Luminance values for a HSL image. +* @brief Applies a threshold to the Red, Green, and Blue values of a RGB image +* or the Hue, +* Saturation, Luminance values for a HSL image. * Supports IMAQ_IMAGE_RGB, IMAQ_IMAGE_HSL. * The simpler version filters based on a hue range in the HSL mode. -* -* @param dest The destination image. This must be a IMAQ_IMAGE_U8 image. -* @param source The image to threshold -* @param replaceValue Value to assign to selected pixels. Defaults to 1 if simplified call is used. -* @param mode The color space to perform the threshold in. valid values are: IMAQ_RGB, IMAQ_HSL. -* @param plane1Range The selection range for the first plane of the image. Set this parameter to NULL to use a selection range from 0 to 255. -* @param plane2Range The selection range for the second plane of the image. Set this parameter to NULL to use a selection range from 0 to 255. -* @param plane3Range The selection range for the third plane of the image. Set this parameter to NULL to use a selection range from 0 to 255. -* -* @return On success: 1. On failure: 0. To get extended error information, call GetLastError(). -*/ -int frcColorThreshold(Image* dest, const Image* source, int replaceValue, ColorMode mode, - const Range* plane1Range, const Range* plane2Range, const Range* plane3Range) -{ return imaqColorThreshold(dest, source, replaceValue, mode, plane1Range, plane2Range, plane3Range);} - - -/** -* @brief A simpler version of ColorThreshold that thresholds hue range in the HSL mode. Supports IMAQ_IMAGE_RGB, IMAQ_IMAGE_HSL. -* @param dest The destination image. -* @param source The image to threshold -* @param hueRange The selection range for the hue (color). -* @param minSaturation The minimum saturation value (1-255). If not used, DEFAULT_SATURATION_THRESHOLD is the default. -* -* @return On success: 1. On failure: 0. To get extended error information, call GetLastError(). -*/ -int frcHueThreshold(Image* dest, const Image* source, const Range* hueRange) -{ return frcHueThreshold(dest, source, hueRange, DEFAULT_SATURATION_THRESHOLD); } - -int frcHueThreshold(Image* dest, const Image* source, const Range* hueRange, int minSaturation) -{ - // assume HSL mode - ColorMode mode = IMAQ_HSL; - // Set saturation 100 - 255 - Range satRange; satRange.minValue = minSaturation; satRange.maxValue = 255; - // Set luminance 100 - 255 - Range lumRange; lumRange.minValue = 100; lumRange.maxValue = 255; - // Replace pixels with 1 if pass threshold filter - int replaceValue = 1; - return imaqColorThreshold(dest, source, replaceValue, mode, hueRange, &satRange, &lumRange); -} - -/** -* @brief Extracts the Red, Green, Blue, or Hue, Saturation or Luminance information from a color image. -* Supports IMAQ_IMAGE_RGB, IMAQ_IMAGE_HSL, IMAQ_IMAGE_RGB_U64. -* -* @param image The source image that the function extracts the planes from. -* @param mode The color space that the function extracts the planes from. Valid values are IMAQ_RGB, IMAQ_HSL, IMAQ_HSV, IMAQ_HSI. -* @param plane1 On return, the first extracted plane. Set this parameter to NULL if you do not need this information. RGB-Red, HSL/HSV/HSI-Hue. -* @param plane2 On return, the second extracted plane. Set this parameter to NULL if you do not need this information. RGB-Green, HSL/HSV/HSI-Saturation. -* @param plane3 On return, the third extracted plane. Set this parameter to NULL if you do not need this information. RGB-Blue, HSL-Luminance, HSV-Value, HSI-Intensity. * -* @return error code: 0 = error. To get extended error information, call GetLastError(). +* @param dest The destination image. This must be a IMAQ_IMAGE_U8 image. +* @param source The image to threshold +* @param replaceValue Value to assign to selected pixels. Defaults to 1 if +* simplified call is used. +* @param mode The color space to perform the threshold in. valid values are: +* IMAQ_RGB, IMAQ_HSL. +* @param plane1Range The selection range for the first plane of the image. Set +* this parameter to NULL to use a selection range from 0 to 255. +* @param plane2Range The selection range for the second plane of the image. Set +* this parameter to NULL to use a selection range from 0 to 255. +* @param plane3Range The selection range for the third plane of the image. Set +* this parameter to NULL to use a selection range from 0 to 255. +* +* @return On success: 1. On failure: 0. To get extended error information, call +* GetLastError(). */ -int frcExtractColorPlanes(const Image* image, ColorMode mode, - Image* plane1, Image* plane2, Image* plane3) -{ return imaqExtractColorPlanes(image, mode, plane1, plane2, plane3); } +int frcColorThreshold(Image* dest, const Image* source, int replaceValue, + ColorMode mode, const Range* plane1Range, + const Range* plane2Range, const Range* plane3Range) { + return imaqColorThreshold(dest, source, replaceValue, mode, plane1Range, + plane2Range, plane3Range); +} /** -* @brief Extracts the Hue information from a color image. Supports IMAQ_IMAGE_RGB, IMAQ_IMAGE_HSL, IMAQ_IMAGE_RGB_U64 -* -* @param image The source image that the function extracts the plane from. -* @param huePlane On return, the extracted hue plane. -* @param minSaturation the minimum saturation level required 0-255 (try 50) -* -* @return On success: 1. On failure: 0. To get extended error information, call GetLastError(). +* @brief A simpler version of ColorThreshold that thresholds hue range in the +* HSL mode. Supports IMAQ_IMAGE_RGB, IMAQ_IMAGE_HSL. +* @param dest The destination image. +* @param source The image to threshold +* @param hueRange The selection range for the hue (color). +* @param minSaturation The minimum saturation value (1-255). If not used, +* DEFAULT_SATURATION_THRESHOLD is the default. +* +* @return On success: 1. On failure: 0. To get extended error information, call +* GetLastError(). */ -int frcExtractHuePlane(const Image* image, Image* huePlane) -{ - return frcExtractHuePlane(image, huePlane, DEFAULT_SATURATION_THRESHOLD); +int frcHueThreshold(Image* dest, const Image* source, const Range* hueRange) { + return frcHueThreshold(dest, source, hueRange, DEFAULT_SATURATION_THRESHOLD); } -int frcExtractHuePlane(const Image* image, Image* huePlane, int minSaturation) -{ - return frcExtractColorPlanes(image, IMAQ_HSL, huePlane, NULL, NULL); +int frcHueThreshold(Image* dest, const Image* source, const Range* hueRange, + int minSaturation) { + // assume HSL mode + ColorMode mode = IMAQ_HSL; + // Set saturation 100 - 255 + Range satRange; + satRange.minValue = minSaturation; + satRange.maxValue = 255; + // Set luminance 100 - 255 + Range lumRange; + lumRange.minValue = 100; + lumRange.maxValue = 255; + // Replace pixels with 1 if pass threshold filter + int replaceValue = 1; + return imaqColorThreshold(dest, source, replaceValue, mode, hueRange, + &satRange, &lumRange); } +/** +* @brief Extracts the Red, Green, Blue, or Hue, Saturation or Luminance +* information from a color image. +* Supports IMAQ_IMAGE_RGB, IMAQ_IMAGE_HSL, IMAQ_IMAGE_RGB_U64. +* +* @param image The source image that the function extracts the planes from. +* @param mode The color space that the function extracts the planes from. Valid +* values are IMAQ_RGB, IMAQ_HSL, IMAQ_HSV, IMAQ_HSI. +* @param plane1 On return, the first extracted plane. Set this parameter to NULL +* if you do not need this information. RGB-Red, HSL/HSV/HSI-Hue. +* @param plane2 On return, the second extracted plane. Set this parameter to +* NULL if you do not need this information. RGB-Green, HSL/HSV/HSI-Saturation. +* @param plane3 On return, the third extracted plane. Set this parameter to NULL +* if you do not need this information. RGB-Blue, HSL-Luminance, HSV-Value, +* HSI-Intensity. +* +* @return error code: 0 = error. To get extended error information, call +* GetLastError(). +*/ +int frcExtractColorPlanes(const Image* image, ColorMode mode, Image* plane1, + Image* plane2, Image* plane3) { + return imaqExtractColorPlanes(image, mode, plane1, plane2, plane3); +} +/** +* @brief Extracts the Hue information from a color image. Supports +* IMAQ_IMAGE_RGB, IMAQ_IMAGE_HSL, IMAQ_IMAGE_RGB_U64 +* +* @param image The source image that the function extracts the plane from. +* @param huePlane On return, the extracted hue plane. +* @param minSaturation the minimum saturation level required 0-255 (try 50) +* +* @return On success: 1. On failure: 0. To get extended error information, call +* GetLastError(). +*/ +int frcExtractHuePlane(const Image* image, Image* huePlane) { + return frcExtractHuePlane(image, huePlane, DEFAULT_SATURATION_THRESHOLD); +} - - - - - +int frcExtractHuePlane(const Image* image, Image* huePlane, int minSaturation) { + return frcExtractColorPlanes(image, IMAQ_HSL, huePlane, NULL, NULL); +} diff --git a/wpilibc/wpilibC++IntegrationTests/include/TestBench.h b/wpilibc/wpilibC++IntegrationTests/include/TestBench.h index 935dedbba4..a09f887a03 100644 --- a/wpilibc/wpilibC++IntegrationTests/include/TestBench.h +++ b/wpilibc/wpilibC++IntegrationTests/include/TestBench.h @@ -10,57 +10,57 @@ #include "WPILib.h" class TestBench { -public: - /* Analog input channels */ - static const uint32_t kCameraGyroChannel = 0; - static const uint32_t kFakeCompressorChannel = 1; - static const uint32_t kFakeAnalogOutputChannel = 2; + public: + /* Analog input channels */ + static const uint32_t kCameraGyroChannel = 0; + static const uint32_t kFakeCompressorChannel = 1; + static const uint32_t kFakeAnalogOutputChannel = 2; - /* Analog output channels */ - static const uint32_t kAnalogOutputChannel = 0; - static const uint32_t kFakeJaguarPotentiometer = 1; + /* Analog output channels */ + static const uint32_t kAnalogOutputChannel = 0; + static const uint32_t kFakeJaguarPotentiometer = 1; - /* DIO channels */ - static const uint32_t kTalonEncoderChannelA = 0; - static const uint32_t kTalonEncoderChannelB = 1; - static const uint32_t kVictorEncoderChannelA = 2; - static const uint32_t kVictorEncoderChannelB = 3; - static const uint32_t kJaguarEncoderChannelA = 4; - static const uint32_t kJaguarEncoderChannelB = 5; - static const uint32_t kLoop1OutputChannel = 6; - static const uint32_t kLoop1InputChannel = 7; - static const uint32_t kLoop2OutputChannel = 8; - static const uint32_t kLoop2InputChannel = 9; + /* DIO channels */ + static const uint32_t kTalonEncoderChannelA = 0; + static const uint32_t kTalonEncoderChannelB = 1; + static const uint32_t kVictorEncoderChannelA = 2; + static const uint32_t kVictorEncoderChannelB = 3; + static const uint32_t kJaguarEncoderChannelA = 4; + static const uint32_t kJaguarEncoderChannelB = 5; + static const uint32_t kLoop1OutputChannel = 6; + static const uint32_t kLoop1InputChannel = 7; + static const uint32_t kLoop2OutputChannel = 8; + static const uint32_t kLoop2InputChannel = 9; - /* PWM channels */ - static const uint32_t kVictorChannel = 1; - static const uint32_t kJaguarChannel = 2; - static const uint32_t kCameraPanChannel = 8; - static const uint32_t kCameraTiltChannel = 9; + /* PWM channels */ + static const uint32_t kVictorChannel = 1; + static const uint32_t kJaguarChannel = 2; + static const uint32_t kCameraPanChannel = 8; + static const uint32_t kCameraTiltChannel = 9; - /* MXP digital channels */ - static const uint32_t kTalonChannel = 10; - static const uint32_t kFakePressureSwitchChannel = 11; - static const uint32_t kFakeSolenoid1Channel = 12; - static const uint32_t kFakeSolenoid2Channel = 13; - static const uint32_t kFakeRelayForward = 18; - static const uint32_t kFakeRelayReverse = 19; - static const uint32_t kFakeJaguarForwardLimit = 20; - static const uint32_t kFakeJaguarReverseLimit = 21; + /* MXP digital channels */ + static const uint32_t kTalonChannel = 10; + static const uint32_t kFakePressureSwitchChannel = 11; + static const uint32_t kFakeSolenoid1Channel = 12; + static const uint32_t kFakeSolenoid2Channel = 13; + static const uint32_t kFakeRelayForward = 18; + static const uint32_t kFakeRelayReverse = 19; + static const uint32_t kFakeJaguarForwardLimit = 20; + static const uint32_t kFakeJaguarReverseLimit = 21; - /* Relay channels */ - static const uint32_t kRelayChannel = 0; - static const uint32_t kCANJaguarRelayChannel = 1; + /* Relay channels */ + static const uint32_t kRelayChannel = 0; + static const uint32_t kCANJaguarRelayChannel = 1; - /* CAN IDs */ - static const uint32_t kCANJaguarID = 2; + /* CAN IDs */ + static const uint32_t kCANJaguarID = 2; - /* PDP channels */ - static const uint32_t kJaguarPDPChannel = 6; - static const uint32_t kVictorPDPChannel = 8; - static const uint32_t kTalonPDPChannel = 11; + /* PDP channels */ + static const uint32_t kJaguarPDPChannel = 6; + static const uint32_t kVictorPDPChannel = 8; + static const uint32_t kTalonPDPChannel = 11; - /* PCM channels */ - static const int32_t kSolenoidChannel1 = 0; - static const int32_t kSolenoidChannel2 = 1; + /* PCM channels */ + static const int32_t kSolenoidChannel1 = 0; + static const int32_t kSolenoidChannel2 = 1; }; diff --git a/wpilibc/wpilibC++IntegrationTests/include/command/MockCommand.h b/wpilibc/wpilibC++IntegrationTests/include/command/MockCommand.h index 25d353a07d..60f428f206 100644 --- a/wpilibc/wpilibC++IntegrationTests/include/command/MockCommand.h +++ b/wpilibc/wpilibC++IntegrationTests/include/command/MockCommand.h @@ -2,47 +2,34 @@ #include "WPILib.h" -class MockCommand : public Command -{ -private: - int m_initializeCount; - int m_executeCount; - int m_isFinishedCount; - bool m_hasFinished; - int m_endCount; - int m_interruptedCount; -protected: - virtual void Initialize(); - virtual void Execute(); - virtual bool IsFinished(); - virtual void End(); - virtual void Interrupted(); -public: - MockCommand(); - int GetInitializeCount(){ - return m_initializeCount; - } - bool HasInitialized(); +class MockCommand : public Command { + private: + int m_initializeCount; + int m_executeCount; + int m_isFinishedCount; + bool m_hasFinished; + int m_endCount; + int m_interruptedCount; - int GetExecuteCount(){ - return m_executeCount; - } - int GetIsFinishedCount(){ - return m_isFinishedCount; - } - bool IsHasFinished(){ - return m_hasFinished; - } - void SetHasFinished(bool hasFinished){ - m_hasFinished = hasFinished; - } - int GetEndCount(){ - return m_endCount; - } - bool HasEnd(); + protected: + virtual void Initialize(); + virtual void Execute(); + virtual bool IsFinished(); + virtual void End(); + virtual void Interrupted(); - int GetInterruptedCount(){ - return m_interruptedCount; - } - bool HasInterrupted(); + public: + MockCommand(); + int GetInitializeCount() { return m_initializeCount; } + bool HasInitialized(); + + int GetExecuteCount() { return m_executeCount; } + int GetIsFinishedCount() { return m_isFinishedCount; } + bool IsHasFinished() { return m_hasFinished; } + void SetHasFinished(bool hasFinished) { m_hasFinished = hasFinished; } + int GetEndCount() { return m_endCount; } + bool HasEnd(); + + int GetInterruptedCount() { return m_interruptedCount; } + bool HasInterrupted(); }; diff --git a/wpilibc/wpilibC++IntegrationTests/src/AnalogLoopTest.cpp b/wpilibc/wpilibC++IntegrationTests/src/AnalogLoopTest.cpp index 505488cc2e..d03c62dc88 100644 --- a/wpilibc/wpilibC++IntegrationTests/src/AnalogLoopTest.cpp +++ b/wpilibc/wpilibC++IntegrationTests/src/AnalogLoopTest.cpp @@ -15,19 +15,19 @@ static const double kDelayTime = 0.01; * A fixture with an analog input and an analog output wired together */ class AnalogLoopTest : public testing::Test { -protected: - AnalogInput *m_input; - AnalogOutput *m_output; + protected: + AnalogInput *m_input; + AnalogOutput *m_output; - virtual void SetUp() override { - m_input = new AnalogInput(TestBench::kFakeAnalogOutputChannel); - m_output = new AnalogOutput(TestBench::kAnalogOutputChannel); - } + virtual void SetUp() override { + m_input = new AnalogInput(TestBench::kFakeAnalogOutputChannel); + m_output = new AnalogOutput(TestBench::kAnalogOutputChannel); + } - virtual void TearDown() override { - delete m_input; - delete m_output; - } + virtual void TearDown() override { + delete m_input; + delete m_output; + } }; /** @@ -35,14 +35,14 @@ protected: * matches. */ TEST_F(AnalogLoopTest, AnalogInputWorks) { - // Set the output voltage and check if the input measures the same voltage - for(int i = 0; i < 50; i++) { - m_output->SetVoltage(i / 10.0f); + // Set the output voltage and check if the input measures the same voltage + for (int i = 0; i < 50; i++) { + m_output->SetVoltage(i / 10.0f); - Wait(kDelayTime); + Wait(kDelayTime); - EXPECT_NEAR(m_output->GetVoltage(), m_input->GetVoltage(), 0.01f); - } + EXPECT_NEAR(m_output->GetVoltage(), m_input->GetVoltage(), 0.01f); + } } /** @@ -50,26 +50,29 @@ TEST_F(AnalogLoopTest, AnalogInputWorks) { * range correctly. */ TEST_F(AnalogLoopTest, AnalogTriggerWorks) { - AnalogTrigger trigger(m_input); - trigger.SetLimitsVoltage(2.0f, 3.0f); + AnalogTrigger trigger(m_input); + trigger.SetLimitsVoltage(2.0f, 3.0f); - m_output->SetVoltage(1.0f); - Wait(kDelayTime); + m_output->SetVoltage(1.0f); + Wait(kDelayTime); - EXPECT_FALSE(trigger.GetInWindow()) << "Analog trigger is in the window (2V, 3V)"; - EXPECT_FALSE(trigger.GetTriggerState()) << "Analog trigger is on"; + EXPECT_FALSE(trigger.GetInWindow()) + << "Analog trigger is in the window (2V, 3V)"; + EXPECT_FALSE(trigger.GetTriggerState()) << "Analog trigger is on"; - m_output->SetVoltage(2.5f); - Wait(kDelayTime); + m_output->SetVoltage(2.5f); + Wait(kDelayTime); - EXPECT_TRUE(trigger.GetInWindow()) << "Analog trigger is not in the window (2V, 3V)"; - EXPECT_FALSE(trigger.GetTriggerState()) << "Analog trigger is on"; + EXPECT_TRUE(trigger.GetInWindow()) + << "Analog trigger is not in the window (2V, 3V)"; + EXPECT_FALSE(trigger.GetTriggerState()) << "Analog trigger is on"; - m_output->SetVoltage(4.0f); - Wait(kDelayTime); + m_output->SetVoltage(4.0f); + Wait(kDelayTime); - EXPECT_FALSE(trigger.GetInWindow()) << "Analog trigger is in the window (2V, 3V)"; - EXPECT_TRUE(trigger.GetTriggerState()) << "Analog trigger is not on"; + EXPECT_FALSE(trigger.GetInWindow()) + << "Analog trigger is in the window (2V, 3V)"; + EXPECT_TRUE(trigger.GetTriggerState()) << "Analog trigger is not on"; } /** @@ -77,46 +80,47 @@ TEST_F(AnalogLoopTest, AnalogTriggerWorks) { * a counter. */ TEST_F(AnalogLoopTest, AnalogTriggerCounterWorks) { - AnalogTrigger trigger(m_input); - trigger.SetLimitsVoltage(2.0f, 3.0f); + AnalogTrigger trigger(m_input); + trigger.SetLimitsVoltage(2.0f, 3.0f); - Counter counter(trigger); + Counter counter(trigger); - // Turn the analog output low and high 50 times - for(int i = 0; i < 50; i++) { - m_output->SetVoltage(1.0); - Wait(kDelayTime); - m_output->SetVoltage(4.0); - Wait(kDelayTime); - } + // Turn the analog output low and high 50 times + for (int i = 0; i < 50; i++) { + m_output->SetVoltage(1.0); + Wait(kDelayTime); + m_output->SetVoltage(4.0); + Wait(kDelayTime); + } - // The counter should be 50 - EXPECT_EQ(50, counter.Get()) << "Analog trigger counter did not count 50 ticks"; + // The counter should be 50 + EXPECT_EQ(50, counter.Get()) + << "Analog trigger counter did not count 50 ticks"; } static void InterruptHandler(uint32_t interruptAssertedMask, void *param) { - *(int *)param = 12345; + *(int *)param = 12345; } TEST_F(AnalogLoopTest, AsynchronusInterruptWorks) { - int param = 0; - AnalogTrigger trigger(m_input); - trigger.SetLimitsVoltage(2.0f, 3.0f); + int param = 0; + AnalogTrigger trigger(m_input); + trigger.SetLimitsVoltage(2.0f, 3.0f); - // Given an interrupt handler that sets an int to 12345 - AnalogTriggerOutput *triggerOutput = trigger.CreateOutput(kState); - triggerOutput->RequestInterrupts(InterruptHandler, ¶m); - triggerOutput->EnableInterrupts(); + // Given an interrupt handler that sets an int to 12345 + AnalogTriggerOutput *triggerOutput = trigger.CreateOutput(kState); + triggerOutput->RequestInterrupts(InterruptHandler, ¶m); + triggerOutput->EnableInterrupts(); - // If the analog output moves from below to above the window - m_output->SetVoltage(0.0); - Wait(kDelayTime); - m_output->SetVoltage(5.0); - triggerOutput->CancelInterrupts(); + // If the analog output moves from below to above the window + m_output->SetVoltage(0.0); + Wait(kDelayTime); + m_output->SetVoltage(5.0); + triggerOutput->CancelInterrupts(); - // Then the int should be 12345 - Wait(kDelayTime); - EXPECT_EQ(12345, param) << "The interrupt did not run."; + // Then the int should be 12345 + Wait(kDelayTime); + EXPECT_EQ(12345, param) << "The interrupt did not run."; - delete triggerOutput; + delete triggerOutput; } diff --git a/wpilibc/wpilibC++IntegrationTests/src/AnalogPotentiometerTest.cpp b/wpilibc/wpilibC++IntegrationTests/src/AnalogPotentiometerTest.cpp index d9cae8a6a3..af3d9b85b4 100644 --- a/wpilibc/wpilibC++IntegrationTests/src/AnalogPotentiometerTest.cpp +++ b/wpilibc/wpilibC++IntegrationTests/src/AnalogPotentiometerTest.cpp @@ -15,13 +15,14 @@ static const double kVoltage = 3.33; static const double kAngle = 180.0; class AnalogPotentiometerTest : public testing::Test { -protected: + protected: AnalogOutput *m_fakePot; AnalogPotentiometer *m_pot; virtual void SetUp() override { m_fakePot = new AnalogOutput(TestBench::kAnalogOutputChannel); - m_pot = new AnalogPotentiometer(TestBench::kFakeAnalogOutputChannel,kScale); + m_pot = + new AnalogPotentiometer(TestBench::kFakeAnalogOutputChannel, kScale); } virtual void TearDown() override { @@ -33,13 +34,13 @@ protected: TEST_F(AnalogPotentiometerTest, TestInitialSettings) { m_fakePot->SetVoltage(0.0); Wait(0.1); - EXPECT_NEAR(0.0,m_pot->Get(),5.0) - <<"The potentiometer did not initialize to 0."; + EXPECT_NEAR(0.0, m_pot->Get(), 5.0) + << "The potentiometer did not initialize to 0."; } -TEST_F(AnalogPotentiometerTest,TestRangeValues) { +TEST_F(AnalogPotentiometerTest, TestRangeValues) { m_fakePot->SetVoltage(kVoltage); Wait(0.1); EXPECT_NEAR(kAngle, m_pot->Get(), 2.0) - << "The potentiometer did not measure the correct angle."; + << "The potentiometer did not measure the correct angle."; } diff --git a/wpilibc/wpilibC++IntegrationTests/src/BuiltInAccelerometerTest.cpp b/wpilibc/wpilibC++IntegrationTests/src/BuiltInAccelerometerTest.cpp index c7a1079c47..0850e307ca 100644 --- a/wpilibc/wpilibC++IntegrationTests/src/BuiltInAccelerometerTest.cpp +++ b/wpilibc/wpilibC++IntegrationTests/src/BuiltInAccelerometerTest.cpp @@ -14,13 +14,13 @@ static constexpr double kAccelerationTolerance = 0.1; * but checking for gravity is probably good enough to tell that it's working. */ TEST(BuiltInAccelerometerTest, Accelerometer) { - BuiltInAccelerometer accelerometer; + BuiltInAccelerometer accelerometer; - /* The testbench sometimes shakes a little from a previous test. Give it - some time. */ - Wait(1.0); + /* The testbench sometimes shakes a little from a previous test. Give it + some time. */ + Wait(1.0); - ASSERT_NEAR(0.0, accelerometer.GetX(), kAccelerationTolerance); - ASSERT_NEAR(1.0, accelerometer.GetY(), kAccelerationTolerance); - ASSERT_NEAR(0.0, accelerometer.GetZ(), kAccelerationTolerance); + ASSERT_NEAR(0.0, accelerometer.GetX(), kAccelerationTolerance); + ASSERT_NEAR(1.0, accelerometer.GetY(), kAccelerationTolerance); + ASSERT_NEAR(0.0, accelerometer.GetZ(), kAccelerationTolerance); } diff --git a/wpilibc/wpilibC++IntegrationTests/src/CANJaguarTest.cpp b/wpilibc/wpilibC++IntegrationTests/src/CANJaguarTest.cpp index fcb9a586a5..5066375458 100644 --- a/wpilibc/wpilibC++IntegrationTests/src/CANJaguarTest.cpp +++ b/wpilibc/wpilibC++IntegrationTests/src/CANJaguarTest.cpp @@ -20,7 +20,7 @@ static constexpr double kEncoderSettlingTime = 1.0; static constexpr double kEncoderPositionTolerance = 0.1; static constexpr double kEncoderSpeedTolerance = 30.0; -static constexpr double kPotentiometerSettlingTime = 1.0; +static constexpr double kPotentiometerSettlingTime = 1.0; static constexpr double kPotentiometerPositionTolerance = 0.1; static constexpr double kCurrentTolerance = 0.1; @@ -33,84 +33,82 @@ static constexpr double kMotorPercent = 0.5; static constexpr double kMotorSpeed = 100; class CANJaguarTest : public testing::Test { -protected: - CANJaguar *m_jaguar; - DigitalOutput *m_fakeForwardLimit, *m_fakeReverseLimit; - AnalogOutput *m_fakePotentiometer; - Relay *m_spike; + protected: + CANJaguar *m_jaguar; + DigitalOutput *m_fakeForwardLimit, *m_fakeReverseLimit; + AnalogOutput *m_fakePotentiometer; + Relay *m_spike; - virtual void SetUp() override { - m_spike = new Relay(TestBench::kCANJaguarRelayChannel, Relay::kForwardOnly); - m_spike->Set(Relay::kOn); - Wait(kSpikeTime); + virtual void SetUp() override { + m_spike = new Relay(TestBench::kCANJaguarRelayChannel, Relay::kForwardOnly); + m_spike->Set(Relay::kOn); + Wait(kSpikeTime); - m_jaguar = new CANJaguar(TestBench::kCANJaguarID); + m_jaguar = new CANJaguar(TestBench::kCANJaguarID); - m_fakeForwardLimit = new DigitalOutput(TestBench::kFakeJaguarForwardLimit); - m_fakeForwardLimit->Set(0); + m_fakeForwardLimit = new DigitalOutput(TestBench::kFakeJaguarForwardLimit); + m_fakeForwardLimit->Set(0); - m_fakeReverseLimit = new DigitalOutput(TestBench::kFakeJaguarReverseLimit); - m_fakeReverseLimit->Set(0); + m_fakeReverseLimit = new DigitalOutput(TestBench::kFakeJaguarReverseLimit); + m_fakeReverseLimit->Set(0); - m_fakePotentiometer = new AnalogOutput(TestBench::kFakeJaguarPotentiometer); - m_fakePotentiometer->SetVoltage(0.0f); + m_fakePotentiometer = new AnalogOutput(TestBench::kFakeJaguarPotentiometer); + m_fakePotentiometer->SetVoltage(0.0f); - /* The motor might still have momentum from the previous test. */ - Wait(kEncoderSettlingTime); - } + /* The motor might still have momentum from the previous test. */ + Wait(kEncoderSettlingTime); + } - virtual void TearDown() override { - delete m_jaguar; - delete m_fakeForwardLimit; - delete m_fakeReverseLimit; - delete m_fakePotentiometer; - delete m_spike; - } + virtual void TearDown() override { + delete m_jaguar; + delete m_fakeForwardLimit; + delete m_fakeReverseLimit; + delete m_fakePotentiometer; + delete m_spike; + } - /** - * Calls CANJaguar::Set periodically 50 times to make sure everything is - * verified. This mimics a real robot program, where Set is presumably - * called in each iteration of the main loop. - */ - void SetJaguar(float totalTime, float value = 0.0f) { - for(int i = 0; i < 50; i++) { - m_jaguar->Set(value); - Wait(totalTime / 50.0); - } - } - /** - * returns the sign of the given number - */ - int SignNum(double value){ - return -(value<0) + (value>0); - } - void InversionTest(float motorValue, float delayTime = kMotorTime){ - m_jaguar->EnableControl(); + /** + * Calls CANJaguar::Set periodically 50 times to make sure everything is + * verified. This mimics a real robot program, where Set is presumably + * called in each iteration of the main loop. + */ + void SetJaguar(float totalTime, float value = 0.0f) { + for (int i = 0; i < 50; i++) { + m_jaguar->Set(value); + Wait(totalTime / 50.0); + } + } + /** + * returns the sign of the given number + */ + int SignNum(double value) { return -(value < 0) + (value > 0); } + void InversionTest(float motorValue, float delayTime = kMotorTime) { + m_jaguar->EnableControl(); m_jaguar->SetInverted(false); - SetJaguar(delayTime,motorValue); + SetJaguar(delayTime, motorValue); double initialSpeed = m_jaguar->GetSpeed(); m_jaguar->Set(0.0); m_jaguar->SetInverted(true); - SetJaguar(delayTime,motorValue); + SetJaguar(delayTime, motorValue); double finalSpeed = m_jaguar->GetSpeed(); - //checks that the motor has changed direction + // checks that the motor has changed direction EXPECT_FALSE(SignNum(initialSpeed) == SignNum(finalSpeed)) << "CAN Jaguar did not invert direction positive. Initial speed was: " << initialSpeed << " Final displacement was: " << finalSpeed << " Sign of initial displacement was: " << SignNum(initialSpeed) << " Sign of final displacement was: " << SignNum(finalSpeed); - SetJaguar(delayTime,-motorValue); + SetJaguar(delayTime, -motorValue); initialSpeed = m_jaguar->GetSpeed(); m_jaguar->Set(0.0); m_jaguar->SetInverted(false); - SetJaguar(delayTime,-motorValue); + SetJaguar(delayTime, -motorValue); finalSpeed = m_jaguar->GetSpeed(); EXPECT_FALSE(SignNum(initialSpeed) == SignNum(finalSpeed)) << "CAN Jaguar did not invert direction negative. Initial displacement " "was: " << initialSpeed << " Final displacement was: " << finalSpeed << " Sign of initial displacement was: " << SignNum(initialSpeed) << " Sign of final displacement was: " << SignNum(finalSpeed); - } + } }; /** @@ -118,11 +116,13 @@ protected: * causes a ResourceAlreadyAllocated error. */ TEST_F(CANJaguarTest, AlreadyAllocatedError) { - std::cout << "The following errors are expected." << std::endl << std::endl; + std::cout << "The following errors are expected." << std::endl + << std::endl; - CANJaguar jaguar(TestBench::kCANJaguarID); - EXPECT_EQ(wpi_error_value_ResourceAlreadyAllocated, jaguar.GetError().GetCode()) - << "An error should have been returned"; + CANJaguar jaguar(TestBench::kCANJaguarID); + EXPECT_EQ(wpi_error_value_ResourceAlreadyAllocated, + jaguar.GetError().GetCode()) + << "An error should have been returned"; } /** @@ -130,11 +130,12 @@ TEST_F(CANJaguarTest, AlreadyAllocatedError) { * out-of-range error. */ TEST_F(CANJaguarTest, 64OutOfRangeError) { - std::cout << "The following errors are expected." << std::endl << std::endl; + std::cout << "The following errors are expected." << std::endl + << std::endl; - CANJaguar jaguar(64); - EXPECT_EQ(wpi_error_value_ChannelIndexOutOfRange, jaguar.GetError().GetCode()) - << "An error should have been returned"; + CANJaguar jaguar(64); + EXPECT_EQ(wpi_error_value_ChannelIndexOutOfRange, jaguar.GetError().GetCode()) + << "An error should have been returned"; } /** @@ -142,11 +143,12 @@ TEST_F(CANJaguarTest, 64OutOfRangeError) { * error. */ TEST_F(CANJaguarTest, 0OutOfRangeError) { - std::cout << "The following errors are expected." << std::endl << std::endl; + std::cout << "The following errors are expected." << std::endl + << std::endl; - CANJaguar jaguar(0); - EXPECT_EQ(wpi_error_value_ChannelIndexOutOfRange, jaguar.GetError().GetCode()) - << "An error should have been returned"; + CANJaguar jaguar(0); + EXPECT_EQ(wpi_error_value_ChannelIndexOutOfRange, jaguar.GetError().GetCode()) + << "An error should have been returned"; } /** @@ -154,43 +156,42 @@ TEST_F(CANJaguarTest, 0OutOfRangeError) { * really getting status data from the Jaguar. */ TEST_F(CANJaguarTest, InitialStatus) { - m_jaguar->SetPercentMode(); + m_jaguar->SetPercentMode(); - EXPECT_NEAR(m_jaguar->GetBusVoltage(), kExpectedBusVoltage, 3.0) - << "Bus voltage is not a plausible value."; + EXPECT_NEAR(m_jaguar->GetBusVoltage(), kExpectedBusVoltage, 3.0) + << "Bus voltage is not a plausible value."; - EXPECT_FLOAT_EQ(m_jaguar->GetOutputVoltage(), 0.0) - << "Output voltage is non-zero."; + EXPECT_FLOAT_EQ(m_jaguar->GetOutputVoltage(), 0.0) + << "Output voltage is non-zero."; - EXPECT_FLOAT_EQ(m_jaguar->GetOutputCurrent(), 0.0) - << "Output current is non-zero."; + EXPECT_FLOAT_EQ(m_jaguar->GetOutputCurrent(), 0.0) + << "Output current is non-zero."; - EXPECT_NEAR(m_jaguar->GetTemperature(), kExpectedTemperature, 5.0) - << "Temperature is not a plausible value."; + EXPECT_NEAR(m_jaguar->GetTemperature(), kExpectedTemperature, 5.0) + << "Temperature is not a plausible value."; - EXPECT_EQ(m_jaguar->GetFaults(), 0) - << "Jaguar has one or more fault set."; + EXPECT_EQ(m_jaguar->GetFaults(), 0) << "Jaguar has one or more fault set."; } /** * Ensure that the jaguar doesn't move when it's disabled */ TEST_F(CANJaguarTest, Disable) { - m_jaguar->SetPercentMode(CANJaguar::QuadEncoder, 360); - m_jaguar->EnableControl(); - m_jaguar->DisableControl(); + m_jaguar->SetPercentMode(CANJaguar::QuadEncoder, 360); + m_jaguar->EnableControl(); + m_jaguar->DisableControl(); - Wait(kEncoderSettlingTime); + Wait(kEncoderSettlingTime); - double initialPosition = m_jaguar->GetPosition(); + double initialPosition = m_jaguar->GetPosition(); - SetJaguar(kMotorTime, 1.0f); - m_jaguar->Set(0.0f); + SetJaguar(kMotorTime, 1.0f); + m_jaguar->Set(0.0f); - double finalPosition = m_jaguar->GetPosition(); + double finalPosition = m_jaguar->GetPosition(); - EXPECT_NEAR(initialPosition, finalPosition, kEncoderPositionTolerance) - << "Jaguar moved while disabled"; + EXPECT_NEAR(initialPosition, finalPosition, kEncoderPositionTolerance) + << "Jaguar moved while disabled"; } /** @@ -199,31 +200,31 @@ TEST_F(CANJaguarTest, Disable) { * behaves like it should in that control mode. */ TEST_F(CANJaguarTest, BrownOut) { + /* Set the jaguar to quad encoder position mode */ + m_jaguar->SetPositionMode(CANJaguar::QuadEncoder, 360, 20.0f, 0.01f, 0.0f); + m_jaguar->EnableControl(); + SetJaguar(kMotorTime, 0.0); + double setpoint = m_jaguar->GetPosition() + 1.0f; - /* Set the jaguar to quad encoder position mode */ - m_jaguar->SetPositionMode(CANJaguar::QuadEncoder, 360, 20.0f, 0.01f, 0.0f); - m_jaguar->EnableControl(); - SetJaguar(kMotorTime, 0.0); - double setpoint = m_jaguar->GetPosition() + 1.0f; + /* Turn the spike off and on again */ + m_spike->Set(Relay::kOff); + Wait(kSpikeTime); + m_spike->Set(Relay::kOn); + Wait(kSpikeTime); - /* Turn the spike off and on again */ - m_spike->Set(Relay::kOff); - Wait(kSpikeTime); - m_spike->Set(Relay::kOn); - Wait(kSpikeTime); + /* The jaguar should automatically get set to quad encoder position mode, + so it should be able to reach a setpoint in a couple seconds. */ + for (int i = 0; i < 10; i++) { + SetJaguar(1.0f, setpoint); - /* The jaguar should automatically get set to quad encoder position mode, - so it should be able to reach a setpoint in a couple seconds. */ - for(int i = 0; i < 10; i++) { - SetJaguar(1.0f, setpoint); + if (std::abs(m_jaguar->GetPosition() - setpoint) <= + kEncoderPositionTolerance) { + return; + } + } - if(std::abs(m_jaguar->GetPosition() - setpoint) <= kEncoderPositionTolerance) { - return; - } - } - - EXPECT_NEAR(setpoint, m_jaguar->GetPosition(), kEncoderPositionTolerance) - << "CAN Jaguar should have resumed PID control after power cycle"; + EXPECT_NEAR(setpoint, m_jaguar->GetPosition(), kEncoderPositionTolerance) + << "CAN Jaguar should have resumed PID control after power cycle"; } /** @@ -231,36 +232,36 @@ TEST_F(CANJaguarTest, BrownOut) { * mode and get the same values back. */ TEST_F(CANJaguarTest, SetGet) { - m_jaguar->DisableControl(); + m_jaguar->DisableControl(); - m_jaguar->SetSpeedMode(CANJaguar::QuadEncoder, 360, 1, 2, 3); - m_jaguar->Set(4); + m_jaguar->SetSpeedMode(CANJaguar::QuadEncoder, 360, 1, 2, 3); + m_jaguar->Set(4); - EXPECT_FLOAT_EQ(1, m_jaguar->GetP()); - EXPECT_FLOAT_EQ(2, m_jaguar->GetI()); - EXPECT_FLOAT_EQ(3, m_jaguar->GetD()); - EXPECT_FLOAT_EQ(4, m_jaguar->Get()); + EXPECT_FLOAT_EQ(1, m_jaguar->GetP()); + EXPECT_FLOAT_EQ(2, m_jaguar->GetI()); + EXPECT_FLOAT_EQ(3, m_jaguar->GetD()); + EXPECT_FLOAT_EQ(4, m_jaguar->Get()); } /** * Test if we can drive the motor in percentage mode and get a position back */ TEST_F(CANJaguarTest, PercentModeForwardWorks) { - m_jaguar->SetPercentMode(CANJaguar::QuadEncoder, 360); - m_jaguar->EnableControl(); + m_jaguar->SetPercentMode(CANJaguar::QuadEncoder, 360); + m_jaguar->EnableControl(); - /* The motor might still have momentum from the previous test. */ - SetJaguar(kEncoderSettlingTime, 0.0f); + /* The motor might still have momentum from the previous test. */ + SetJaguar(kEncoderSettlingTime, 0.0f); - double initialPosition = m_jaguar->GetPosition(); + double initialPosition = m_jaguar->GetPosition(); - /* Drive the speed controller briefly to move the encoder */ - SetJaguar(kMotorTime, 1.0f); - m_jaguar->Set(0.0f); + /* Drive the speed controller briefly to move the encoder */ + SetJaguar(kMotorTime, 1.0f); + m_jaguar->Set(0.0f); - /* The position should have increased */ - EXPECT_GT(m_jaguar->GetPosition(), initialPosition) - << "CAN Jaguar position should have increased after the motor moved"; + /* The position should have increased */ + EXPECT_GT(m_jaguar->GetPosition(), initialPosition) + << "CAN Jaguar position should have increased after the motor moved"; } /** @@ -268,22 +269,22 @@ TEST_F(CANJaguarTest, PercentModeForwardWorks) { * position back */ TEST_F(CANJaguarTest, PercentModeReverseWorks) { - m_jaguar->SetPercentMode(CANJaguar::QuadEncoder, 360); - m_jaguar->EnableControl(); + m_jaguar->SetPercentMode(CANJaguar::QuadEncoder, 360); + m_jaguar->EnableControl(); - /* The motor might still have momentum from the previous test. */ - SetJaguar(kEncoderSettlingTime, 0.0f); + /* The motor might still have momentum from the previous test. */ + SetJaguar(kEncoderSettlingTime, 0.0f); - double initialPosition = m_jaguar->GetPosition(); + double initialPosition = m_jaguar->GetPosition(); - /* Drive the speed controller briefly to move the encoder */ - SetJaguar(kMotorTime, -1.0f); - m_jaguar->Set(0.0f); + /* Drive the speed controller briefly to move the encoder */ + SetJaguar(kMotorTime, -1.0f); + m_jaguar->Set(0.0f); - float p = m_jaguar->GetPosition(); - /* The position should have decreased */ - EXPECT_LT(p, initialPosition) - << "CAN Jaguar position should have decreased after the motor moved"; + float p = m_jaguar->GetPosition(); + /* The position should have decreased */ + EXPECT_LT(p, initialPosition) + << "CAN Jaguar position should have decreased after the motor moved"; } /** @@ -291,17 +292,17 @@ TEST_F(CANJaguarTest, PercentModeReverseWorks) { * status. */ TEST_F(CANJaguarTest, VoltageModeWorks) { - m_jaguar->SetVoltageMode(); - m_jaguar->EnableControl(); + m_jaguar->SetVoltageMode(); + m_jaguar->EnableControl(); - float setpoints[] = { M_PI, 8.0f, -10.0f }; + float setpoints[] = {M_PI, 8.0f, -10.0f}; - for(unsigned int i = 0; i < sizeof(setpoints)/sizeof(setpoints[0]); i++) { - float setpoint = setpoints[i]; + for (unsigned int i = 0; i < sizeof(setpoints) / sizeof(setpoints[0]); i++) { + float setpoint = setpoints[i]; - SetJaguar(kMotorTime, setpoint); - EXPECT_NEAR(setpoint, m_jaguar->GetOutputVoltage(), kVoltageTolerance); - } + SetJaguar(kMotorTime, setpoint); + EXPECT_NEAR(setpoint, m_jaguar->GetOutputVoltage(), kVoltageTolerance); + } } /** @@ -309,13 +310,13 @@ TEST_F(CANJaguarTest, VoltageModeWorks) { * speed status. */ TEST_F(CANJaguarTest, SpeedModeWorks) { - m_jaguar->SetSpeedMode(CANJaguar::QuadEncoder, 360, 0.1f, 0.003f, 0.01f); - m_jaguar->EnableControl(); + m_jaguar->SetSpeedMode(CANJaguar::QuadEncoder, 360, 0.1f, 0.003f, 0.01f); + m_jaguar->EnableControl(); - constexpr float speed = 50.0f; + constexpr float speed = 50.0f; - SetJaguar(kMotorTime, speed); - EXPECT_NEAR(speed, m_jaguar->GetSpeed(), kEncoderSpeedTolerance); + SetJaguar(kMotorTime, speed); + EXPECT_NEAR(speed, m_jaguar->GetSpeed(), kEncoderSpeedTolerance); } /** @@ -323,23 +324,24 @@ TEST_F(CANJaguarTest, SpeedModeWorks) { * the Jaguar. */ TEST_F(CANJaguarTest, PositionModeWorks) { - m_jaguar->SetPositionMode(CANJaguar::QuadEncoder, 360, 15.0f, 0.02f, 0.0f); + m_jaguar->SetPositionMode(CANJaguar::QuadEncoder, 360, 15.0f, 0.02f, 0.0f); - double setpoint = m_jaguar->GetPosition() + 1.0f; + double setpoint = m_jaguar->GetPosition() + 1.0f; - m_jaguar->EnableControl(); + m_jaguar->EnableControl(); - /* It should get to the setpoint within 10 seconds */ - for(int i = 0; i < 10; i++) { - SetJaguar(1.0f, setpoint); + /* It should get to the setpoint within 10 seconds */ + for (int i = 0; i < 10; i++) { + SetJaguar(1.0f, setpoint); - if(std::abs(m_jaguar->GetPosition() - setpoint) <= kEncoderPositionTolerance) { - return; - } - } + if (std::abs(m_jaguar->GetPosition() - setpoint) <= + kEncoderPositionTolerance) { + return; + } + } - EXPECT_NEAR(setpoint, m_jaguar->GetPosition(), kEncoderPositionTolerance) - << "CAN Jaguar should have reached setpoint with PID control"; + EXPECT_NEAR(setpoint, m_jaguar->GetPosition(), kEncoderPositionTolerance) + << "CAN Jaguar should have reached setpoint with PID control"; } /** @@ -347,26 +349,28 @@ TEST_F(CANJaguarTest, PositionModeWorks) { * a corresponding output current */ TEST_F(CANJaguarTest, DISABLED_CurrentModeWorks) { - m_jaguar->SetCurrentMode(10.0, 4.0, 1.0); - m_jaguar->EnableControl(); + m_jaguar->SetCurrentMode(10.0, 4.0, 1.0); + m_jaguar->EnableControl(); - float setpoints[] = { 1.6f, 2.0f, -1.6f }; + float setpoints[] = {1.6f, 2.0f, -1.6f}; - for(unsigned int i = 0; i < sizeof(setpoints)/sizeof(setpoints[0]); i++) { - float setpoint = setpoints[i]; - float expectedCurrent = std::abs(setpoints[i]); + for (unsigned int i = 0; i < sizeof(setpoints) / sizeof(setpoints[0]); i++) { + float setpoint = setpoints[i]; + float expectedCurrent = std::abs(setpoints[i]); - /* It should get to each setpoint within 10 seconds */ - for(int j = 0; j < 10; j++) { - SetJaguar(1.0, setpoint); + /* It should get to each setpoint within 10 seconds */ + for (int j = 0; j < 10; j++) { + SetJaguar(1.0, setpoint); - if(std::abs(m_jaguar->GetOutputCurrent() - expectedCurrent) <= kCurrentTolerance) { - break; - } - } + if (std::abs(m_jaguar->GetOutputCurrent() - expectedCurrent) <= + kCurrentTolerance) { + break; + } + } - EXPECT_NEAR(expectedCurrent, m_jaguar->GetOutputCurrent(), kCurrentTolerance); - } + EXPECT_NEAR(expectedCurrent, m_jaguar->GetOutputCurrent(), + kCurrentTolerance); + } } /** @@ -374,20 +378,21 @@ TEST_F(CANJaguarTest, DISABLED_CurrentModeWorks) { * as a fake potentiometer. */ TEST_F(CANJaguarTest, FakePotentiometerPosition) { - m_jaguar->SetPercentMode(CANJaguar::Potentiometer); - m_jaguar->EnableControl(); + m_jaguar->SetPercentMode(CANJaguar::Potentiometer); + m_jaguar->EnableControl(); - // Set the analog output to 4 different voltages and check if the Jaguar - // returns corresponding positions. - for(int i = 0; i <= 3; i++) { - m_fakePotentiometer->SetVoltage(static_cast(i)); + // Set the analog output to 4 different voltages and check if the Jaguar + // returns corresponding positions. + for (int i = 0; i <= 3; i++) { + m_fakePotentiometer->SetVoltage(static_cast(i)); - SetJaguar(kPotentiometerSettlingTime); + SetJaguar(kPotentiometerSettlingTime); - EXPECT_NEAR(m_fakePotentiometer->GetVoltage() / 3.0f, m_jaguar->GetPosition(), - kPotentiometerPositionTolerance) - << "CAN Jaguar should have returned the potentiometer position set by the analog output"; - } + EXPECT_NEAR(m_fakePotentiometer->GetVoltage() / 3.0f, + m_jaguar->GetPosition(), kPotentiometerPositionTolerance) + << "CAN Jaguar should have returned the potentiometer position set by " + "the analog output"; + } } /** @@ -395,35 +400,37 @@ TEST_F(CANJaguarTest, FakePotentiometerPosition) { * limit switch. */ TEST_F(CANJaguarTest, FakeLimitSwitchForwards) { - m_jaguar->SetPercentMode(CANJaguar::QuadEncoder, 360); - m_jaguar->ConfigLimitMode(CANJaguar::kLimitMode_SwitchInputsOnly); - m_fakeForwardLimit->Set(1); - m_fakeReverseLimit->Set(0); - m_jaguar->EnableControl(); + m_jaguar->SetPercentMode(CANJaguar::QuadEncoder, 360); + m_jaguar->ConfigLimitMode(CANJaguar::kLimitMode_SwitchInputsOnly); + m_fakeForwardLimit->Set(1); + m_fakeReverseLimit->Set(0); + m_jaguar->EnableControl(); - SetJaguar(kEncoderSettlingTime); + SetJaguar(kEncoderSettlingTime); - /* Make sure the limits are recognized by the Jaguar. */ - ASSERT_FALSE(m_jaguar->GetForwardLimitOK()); - ASSERT_TRUE(m_jaguar->GetReverseLimitOK()); + /* Make sure the limits are recognized by the Jaguar. */ + ASSERT_FALSE(m_jaguar->GetForwardLimitOK()); + ASSERT_TRUE(m_jaguar->GetReverseLimitOK()); - double initialPosition = m_jaguar->GetPosition(); + double initialPosition = m_jaguar->GetPosition(); - /* Drive the speed controller briefly to move the encoder. If the limit - switch is recognized, it shouldn't actually move. */ - SetJaguar(kMotorTime, 1.0f); + /* Drive the speed controller briefly to move the encoder. If the limit + switch is recognized, it shouldn't actually move. */ + SetJaguar(kMotorTime, 1.0f); - /* The position should be the same, since the limit switch was on. */ - EXPECT_NEAR(initialPosition, m_jaguar->GetPosition(), kEncoderPositionTolerance) - << "CAN Jaguar should not have moved with the limit switch pressed"; + /* The position should be the same, since the limit switch was on. */ + EXPECT_NEAR(initialPosition, m_jaguar->GetPosition(), + kEncoderPositionTolerance) + << "CAN Jaguar should not have moved with the limit switch pressed"; - /* Drive the speed controller in the other direction. It should actually - move, since only the forward switch is activated.*/ - SetJaguar(kMotorTime, -1.0f); + /* Drive the speed controller in the other direction. It should actually + move, since only the forward switch is activated.*/ + SetJaguar(kMotorTime, -1.0f); - /* The position should have decreased */ - EXPECT_LT(m_jaguar->GetPosition(), initialPosition) - << "CAN Jaguar should have moved in reverse while the forward limit was on"; + /* The position should have decreased */ + EXPECT_LT(m_jaguar->GetPosition(), initialPosition) + << "CAN Jaguar should have moved in reverse while the forward limit was " + "on"; } /** @@ -431,58 +438,59 @@ TEST_F(CANJaguarTest, FakeLimitSwitchForwards) { * switch. */ TEST_F(CANJaguarTest, FakeLimitSwitchReverse) { - m_jaguar->SetPercentMode(CANJaguar::QuadEncoder, 360); - m_jaguar->ConfigLimitMode(CANJaguar::kLimitMode_SwitchInputsOnly); - m_fakeForwardLimit->Set(0); - m_fakeReverseLimit->Set(1); - m_jaguar->EnableControl(); + m_jaguar->SetPercentMode(CANJaguar::QuadEncoder, 360); + m_jaguar->ConfigLimitMode(CANJaguar::kLimitMode_SwitchInputsOnly); + m_fakeForwardLimit->Set(0); + m_fakeReverseLimit->Set(1); + m_jaguar->EnableControl(); - SetJaguar(kEncoderSettlingTime); + SetJaguar(kEncoderSettlingTime); - /* Make sure the limits are recognized by the Jaguar. */ - ASSERT_TRUE(m_jaguar->GetForwardLimitOK()); - ASSERT_FALSE(m_jaguar->GetReverseLimitOK()); + /* Make sure the limits are recognized by the Jaguar. */ + ASSERT_TRUE(m_jaguar->GetForwardLimitOK()); + ASSERT_FALSE(m_jaguar->GetReverseLimitOK()); - double initialPosition = m_jaguar->GetPosition(); + double initialPosition = m_jaguar->GetPosition(); - /* Drive the speed controller backwards briefly to move the encoder. If - the limit switch is recognized, it shouldn't actually move. */ - SetJaguar(kMotorTime, -1.0f); + /* Drive the speed controller backwards briefly to move the encoder. If + the limit switch is recognized, it shouldn't actually move. */ + SetJaguar(kMotorTime, -1.0f); - /* The position should be the same, since the limit switch was on. */ - EXPECT_NEAR(initialPosition, m_jaguar->GetPosition(), kEncoderPositionTolerance) - << "CAN Jaguar should not have moved with the limit switch pressed"; + /* The position should be the same, since the limit switch was on. */ + EXPECT_NEAR(initialPosition, m_jaguar->GetPosition(), + kEncoderPositionTolerance) + << "CAN Jaguar should not have moved with the limit switch pressed"; - /* Drive the speed controller in the other direction. It should actually - move, since only the reverse switch is activated.*/ - SetJaguar(kMotorTime, 1.0f); + /* Drive the speed controller in the other direction. It should actually + move, since only the reverse switch is activated.*/ + SetJaguar(kMotorTime, 1.0f); - /* The position should have increased */ - EXPECT_GT(m_jaguar->GetPosition(), initialPosition) - << "CAN Jaguar should have moved forwards while the reverse limit was on"; + /* The position should have increased */ + EXPECT_GT(m_jaguar->GetPosition(), initialPosition) + << "CAN Jaguar should have moved forwards while the reverse limit was on"; } /** -*Tests that inversion works in voltage mode +* Tests that inversion works in voltage mode */ -TEST_F(CANJaguarTest, InvertingVoltageMode){ -m_jaguar->SetVoltageMode(CANJaguar::QuadEncoder, 360); -m_jaguar->EnableControl(); -InversionTest(kMotorVoltage); +TEST_F(CANJaguarTest, InvertingVoltageMode) { + m_jaguar->SetVoltageMode(CANJaguar::QuadEncoder, 360); + m_jaguar->EnableControl(); + InversionTest(kMotorVoltage); } /** -*Tests that inversion works in percentMode +* Tests that inversion works in percentMode */ -TEST_F(CANJaguarTest, InvertingPercentMode){ -m_jaguar->SetPercentMode(CANJaguar::QuadEncoder, 360); -m_jaguar->EnableControl(); -InversionTest(kMotorPercent); +TEST_F(CANJaguarTest, InvertingPercentMode) { + m_jaguar->SetPercentMode(CANJaguar::QuadEncoder, 360); + m_jaguar->EnableControl(); + InversionTest(kMotorPercent); } /** * Tests that inversion works in SpeedMode */ -TEST_F(CANJaguarTest, InvertingSpeedMode){ -m_jaguar->SetSpeedMode(CANJaguar::QuadEncoder, 360, 0.1f, 0.005f, 0.00f); -m_jaguar->EnableControl(); -InversionTest(kMotorSpeed, kMotorTime); +TEST_F(CANJaguarTest, InvertingSpeedMode) { + m_jaguar->SetSpeedMode(CANJaguar::QuadEncoder, 360, 0.1f, 0.005f, 0.00f); + m_jaguar->EnableControl(); + InversionTest(kMotorSpeed, kMotorTime); } diff --git a/wpilibc/wpilibC++IntegrationTests/src/CANTalonTest.cpp b/wpilibc/wpilibC++IntegrationTests/src/CANTalonTest.cpp index afaf5e5e12..ca2c148835 100644 --- a/wpilibc/wpilibC++IntegrationTests/src/CANTalonTest.cpp +++ b/wpilibc/wpilibC++IntegrationTests/src/CANTalonTest.cpp @@ -13,7 +13,7 @@ const int deviceId = 0; TEST(CANTalonTest, QuickTest) { double throttle = 0.1; - CANTalon talon(deviceId); + CANTalon talon(deviceId); talon.SetControlMode(CANSpeedController::kPercentVbus); talon.EnableControl(); talon.Set(throttle); @@ -32,16 +32,17 @@ TEST(CANTalonTest, SetGetPID) { // Tests that we can actually set and get PID values as intended. CANTalon talon(deviceId); double p = 0.05, i = 0.098, d = 1.23; - talon.SetPID(p, i , d); + talon.SetPID(p, i, d); // Wait(0.03); EXPECT_NEAR(p, talon.GetP(), 1e-5); EXPECT_NEAR(i, talon.GetI(), 1e-5); EXPECT_NEAR(d, talon.GetD(), 1e-5); - // Test with new values in case the talon was already set to the previous ones. + // Test with new values in case the talon was already set to the previous + // ones. p = 0.15; i = 0.198; d = 1.03; - talon.SetPID(p, i , d); + talon.SetPID(p, i, d); // Wait(0.03); EXPECT_NEAR(p, talon.GetP(), 1e-5); EXPECT_NEAR(i, talon.GetI(), 1e-5); diff --git a/wpilibc/wpilibC++IntegrationTests/src/CounterTest.cpp b/wpilibc/wpilibC++IntegrationTests/src/CounterTest.cpp index 0b19a92f96..b268df73db 100644 --- a/wpilibc/wpilibC++IntegrationTests/src/CounterTest.cpp +++ b/wpilibc/wpilibC++IntegrationTests/src/CounterTest.cpp @@ -14,7 +14,7 @@ static const double kMotorDelay = 2.5; static const double kMaxPeriod = 2.0; class CounterTest : public testing::Test { -protected: + protected: Counter *m_talonCounter; Counter *m_victorCounter; Counter *m_jaguarCounter; @@ -38,16 +38,16 @@ protected: delete m_victor; delete m_talon; delete m_jaguar; - } + } - void Reset() { - m_talonCounter->Reset(); - m_victorCounter->Reset(); - m_jaguarCounter->Reset(); - m_talon->Set(0.0f); - m_victor->Set(0.0f); - m_jaguar->Set(0.0f); - } + void Reset() { + m_talonCounter->Reset(); + m_victorCounter->Reset(); + m_jaguarCounter->Reset(); + m_talon->Set(0.0f); + m_victor->Set(0.0f); + m_jaguar->Set(0.0f); + } }; /** @@ -59,14 +59,13 @@ TEST_F(CounterTest, CountTalon) { /* Run the motor forward and determine if the counter is counting. */ m_talon->Set(1.0f); Wait(0.5); - EXPECT_NE(0.0f, m_talonCounter->Get()) - << "The counter did not count (talon)"; + EXPECT_NE(0.0f, m_talonCounter->Get()) << "The counter did not count (talon)"; /* Set the motor to 0 and determine if the counter resets to 0. */ m_talon->Set(0.0f); Wait(0.5); m_talonCounter->Reset(); EXPECT_FLOAT_EQ(0.0f, m_talonCounter->Get()) - << "The counter did not restart to 0 (talon)"; + << "The counter did not restart to 0 (talon)"; } TEST_F(CounterTest, CountVictor) { @@ -75,13 +74,13 @@ TEST_F(CounterTest, CountVictor) { m_victor->Set(1.0f); Wait(0.5); EXPECT_NE(0.0f, m_victorCounter->Get()) - << "The counter did not count (victor)"; + << "The counter did not count (victor)"; /* Set the motor to 0 and determine if the counter resets to 0. */ m_victor->Set(0.0f); Wait(0.5); m_victorCounter->Reset(); EXPECT_FLOAT_EQ(0.0f, m_victorCounter->Get()) - << "The counter did not restart to 0 (jaguar)"; + << "The counter did not restart to 0 (jaguar)"; } TEST_F(CounterTest, CountJaguar) { @@ -90,13 +89,13 @@ TEST_F(CounterTest, CountJaguar) { m_jaguar->Set(1.0f); Wait(0.5); EXPECT_NE(0.0f, m_jaguarCounter->Get()) - << "The counter did not count (jaguar)"; + << "The counter did not count (jaguar)"; /* Set the motor to 0 and determine if the counter resets to 0. */ m_jaguar->Set(0.0f); Wait(0.5); m_jaguarCounter->Reset(); EXPECT_FLOAT_EQ(0.0f, m_jaguarCounter->Get()) - << "The counter did not restart to 0 (jaguar)"; + << "The counter did not restart to 0 (jaguar)"; } /** @@ -109,13 +108,12 @@ TEST_F(CounterTest, TalonGetStopped) { m_talonCounter->SetMaxPeriod(kMaxPeriod); m_talon->Set(1.0f); Wait(0.5); - EXPECT_FALSE(m_talonCounter->GetStopped()) - << "The counter did not count."; + EXPECT_FALSE(m_talonCounter->GetStopped()) << "The counter did not count."; /* Stop the motor and wait until the Max Period is exceeded */ m_talon->Set(0.0f); Wait(kMotorDelay); EXPECT_TRUE(m_talonCounter->GetStopped()) - << "The counter did not stop counting."; + << "The counter did not stop counting."; } TEST_F(CounterTest, VictorGetStopped) { @@ -124,13 +122,12 @@ TEST_F(CounterTest, VictorGetStopped) { m_victorCounter->SetMaxPeriod(kMaxPeriod); m_victor->Set(1.0f); Wait(0.5); - EXPECT_FALSE(m_victorCounter->GetStopped()) - << "The counter did not count."; + EXPECT_FALSE(m_victorCounter->GetStopped()) << "The counter did not count."; /* Stop the motor and wait until the Max Period is exceeded */ m_victor->Set(0.0f); Wait(kMotorDelay); EXPECT_TRUE(m_victorCounter->GetStopped()) - << "The counter did not stop counting."; + << "The counter did not stop counting."; } TEST_F(CounterTest, JaguarGetStopped) { @@ -139,11 +136,10 @@ TEST_F(CounterTest, JaguarGetStopped) { m_jaguarCounter->SetMaxPeriod(kMaxPeriod); m_jaguar->Set(1.0f); Wait(0.5); - EXPECT_FALSE(m_jaguarCounter->GetStopped()) - << "The counter did not count."; + EXPECT_FALSE(m_jaguarCounter->GetStopped()) << "The counter did not count."; /* Stop the motor and wait until the Max Period is exceeded */ m_jaguar->Set(0.0f); Wait(kMotorDelay); EXPECT_TRUE(m_jaguarCounter->GetStopped()) - << "The counter did not stop counting."; + << "The counter did not stop counting."; } diff --git a/wpilibc/wpilibC++IntegrationTests/src/DIOLoopTest.cpp b/wpilibc/wpilibC++IntegrationTests/src/DIOLoopTest.cpp index c05f005029..3a920eaf73 100644 --- a/wpilibc/wpilibC++IntegrationTests/src/DIOLoopTest.cpp +++ b/wpilibc/wpilibC++IntegrationTests/src/DIOLoopTest.cpp @@ -21,23 +21,21 @@ static const double kSynchronousInterruptTimeTolerance = 0.01; * together. */ class DIOLoopTest : public testing::Test { -protected: - DigitalInput *m_input; - DigitalOutput *m_output; + protected: + DigitalInput *m_input; + DigitalOutput *m_output; - virtual void SetUp() override { - m_input = new DigitalInput(TestBench::kLoop1InputChannel); - m_output = new DigitalOutput(TestBench::kLoop1OutputChannel); - } + virtual void SetUp() override { + m_input = new DigitalInput(TestBench::kLoop1InputChannel); + m_output = new DigitalOutput(TestBench::kLoop1OutputChannel); + } - virtual void TearDown() override { - delete m_input; - delete m_output; - } + virtual void TearDown() override { + delete m_input; + delete m_output; + } - void Reset() { - m_output->Set(false); - } + void Reset() { m_output->Set(false); } }; /** @@ -45,17 +43,17 @@ protected: * reading the input. */ TEST_F(DIOLoopTest, Loop) { - Reset(); + Reset(); - m_output->Set(false); - Wait(kDelayTime); - EXPECT_FALSE(m_input->Get()) << "The digital output was turned off, but " - << "the digital input is on."; + m_output->Set(false); + Wait(kDelayTime); + EXPECT_FALSE(m_input->Get()) << "The digital output was turned off, but " + << "the digital input is on."; - m_output->Set(true); - Wait(kDelayTime); - EXPECT_TRUE(m_input->Get()) << "The digital output was turned on, but " - << "the digital input is off."; + m_output->Set(true); + Wait(kDelayTime); + EXPECT_TRUE(m_input->Get()) << "The digital output was turned on, but " + << "the digital input is off."; } /** @@ -63,63 +61,64 @@ TEST_F(DIOLoopTest, Loop) { * Counter class works */ TEST_F(DIOLoopTest, FakeCounter) { - Reset(); + Reset(); - Counter counter(m_input); + Counter counter(m_input); - EXPECT_EQ(0, counter.Get()) << "Counter did not initialize to 0."; + EXPECT_EQ(0, counter.Get()) << "Counter did not initialize to 0."; - /* Count 100 ticks. The counter value should be 100 after this loop. */ - for(int i = 0; i < 100; i++) { - m_output->Set(true); - Wait(kCounterTime); - m_output->Set(false); - Wait(kCounterTime); - } + /* Count 100 ticks. The counter value should be 100 after this loop. */ + for (int i = 0; i < 100; i++) { + m_output->Set(true); + Wait(kCounterTime); + m_output->Set(false); + Wait(kCounterTime); + } - EXPECT_EQ(100, counter.Get()) << "Counter did not count up to 100."; + EXPECT_EQ(100, counter.Get()) << "Counter did not count up to 100."; } static void InterruptHandler(uint32_t interruptAssertedMask, void *param) { - *(int *)param = 12345; + *(int *)param = 12345; } TEST_F(DIOLoopTest, AsynchronousInterruptWorks) { - int param = 0; + int param = 0; - // Given an interrupt handler that sets an int to 12345 - m_input->RequestInterrupts(InterruptHandler, ¶m); - m_input->EnableInterrupts(); + // Given an interrupt handler that sets an int to 12345 + m_input->RequestInterrupts(InterruptHandler, ¶m); + m_input->EnableInterrupts(); - // If the voltage rises - m_output->Set(false); - m_output->Set(true); - m_input->CancelInterrupts(); + // If the voltage rises + m_output->Set(false); + m_output->Set(true); + m_input->CancelInterrupts(); - // Then the int should be 12345 - Wait(kDelayTime); - EXPECT_EQ(12345, param) << "The interrupt did not run."; + // Then the int should be 12345 + Wait(kDelayTime); + EXPECT_EQ(12345, param) << "The interrupt did not run."; } static void *InterruptTriggerer(void *data) { - DigitalOutput *output = static_cast(data); - output->Set(false); - Wait(kSynchronousInterruptTime); - output->Set(true); - return NULL; + DigitalOutput *output = static_cast(data); + output->Set(false); + Wait(kSynchronousInterruptTime); + output->Set(true); + return NULL; } TEST_F(DIOLoopTest, SynchronousInterruptWorks) { - // Given a synchronous interrupt - m_input->RequestInterrupts(); + // Given a synchronous interrupt + m_input->RequestInterrupts(); - // If we have another thread trigger the interrupt in a few seconds - pthread_t interruptTriggererLoop; - pthread_create(&interruptTriggererLoop, NULL, InterruptTriggerer, m_output); + // If we have another thread trigger the interrupt in a few seconds + pthread_t interruptTriggererLoop; + pthread_create(&interruptTriggererLoop, NULL, InterruptTriggerer, m_output); - // Then this thread should pause and resume after that number of seconds - Timer timer; - timer.Start(); - m_input->WaitForInterrupt(kSynchronousInterruptTime + 1.0); - EXPECT_NEAR(kSynchronousInterruptTime, timer.Get(), kSynchronousInterruptTimeTolerance); + // Then this thread should pause and resume after that number of seconds + Timer timer; + timer.Start(); + m_input->WaitForInterrupt(kSynchronousInterruptTime + 1.0); + EXPECT_NEAR(kSynchronousInterruptTime, timer.Get(), + kSynchronousInterruptTimeTolerance); } diff --git a/wpilibc/wpilibC++IntegrationTests/src/FakeEncoderTest.cpp b/wpilibc/wpilibC++IntegrationTests/src/FakeEncoderTest.cpp index 4b27b4e054..e6c86a684a 100644 --- a/wpilibc/wpilibC++IntegrationTests/src/FakeEncoderTest.cpp +++ b/wpilibc/wpilibC++IntegrationTests/src/FakeEncoderTest.cpp @@ -1,6 +1,7 @@ /*----------------------------------------------------------------------------*/ /* Copyright (c) FIRST 2014. All Rights Reserved. */ -/* Open Source Software - may be modified and shared by FRC teams. The code */ +/* Open Source Software - may be modified and shared by FRC teams. The code + */ /* must be accompanied by the FIRST BSD license file in the root directory of */ /* the project. */ /*----------------------------------------------------------------------------*/ @@ -12,139 +13,144 @@ static const double kDelayTime = 0.001; class FakeEncoderTest : public testing::Test { -protected: - DigitalOutput *m_outputA; - DigitalOutput *m_outputB; - AnalogOutput *m_indexOutput; + protected: + DigitalOutput *m_outputA; + DigitalOutput *m_outputB; + AnalogOutput *m_indexOutput; - Encoder *m_encoder; - AnalogTrigger *m_indexAnalogTrigger; - AnalogTriggerOutput *m_indexAnalogTriggerOutput; + Encoder *m_encoder; + AnalogTrigger *m_indexAnalogTrigger; + AnalogTriggerOutput *m_indexAnalogTriggerOutput; - virtual void SetUp() override { - m_outputA = new DigitalOutput(TestBench::kLoop2OutputChannel); - m_outputB = new DigitalOutput(TestBench::kLoop1OutputChannel); - m_indexOutput = new AnalogOutput(TestBench::kAnalogOutputChannel); - m_outputA->Set(false); - m_outputB->Set(false); - m_encoder = new Encoder(TestBench::kLoop1InputChannel, TestBench::kLoop2InputChannel); - m_indexAnalogTrigger = new AnalogTrigger(TestBench::kFakeAnalogOutputChannel); - m_indexAnalogTrigger->SetLimitsVoltage(2.0, 3.0); - m_indexAnalogTriggerOutput = m_indexAnalogTrigger->CreateOutput(AnalogTriggerType::kState); - } + virtual void SetUp() override { + m_outputA = new DigitalOutput(TestBench::kLoop2OutputChannel); + m_outputB = new DigitalOutput(TestBench::kLoop1OutputChannel); + m_indexOutput = new AnalogOutput(TestBench::kAnalogOutputChannel); + m_outputA->Set(false); + m_outputB->Set(false); + m_encoder = new Encoder(TestBench::kLoop1InputChannel, + TestBench::kLoop2InputChannel); + m_indexAnalogTrigger = + new AnalogTrigger(TestBench::kFakeAnalogOutputChannel); + m_indexAnalogTrigger->SetLimitsVoltage(2.0, 3.0); + m_indexAnalogTriggerOutput = + m_indexAnalogTrigger->CreateOutput(AnalogTriggerType::kState); + } - virtual void TearDown() override { - delete m_outputA; - delete m_outputB; - delete m_indexOutput; - delete m_encoder; - delete m_indexAnalogTrigger; - delete m_indexAnalogTriggerOutput; - } + virtual void TearDown() override { + delete m_outputA; + delete m_outputB; + delete m_indexOutput; + delete m_encoder; + delete m_indexAnalogTrigger; + delete m_indexAnalogTriggerOutput; + } - /** - * Output pulses to the encoder's input channels to simulate a change of 100 ticks - */ - void Simulate100QuadratureTicks() { - for(int i = 0; i < 100; i++) { - m_outputA->Set(true); - Wait(kDelayTime); - m_outputB->Set(true); - Wait(kDelayTime); - m_outputA->Set(false); - Wait(kDelayTime); - m_outputB->Set(false); - Wait(kDelayTime); - } - } + /** + * Output pulses to the encoder's input channels to simulate a change of 100 + * ticks + */ + void Simulate100QuadratureTicks() { + for (int i = 0; i < 100; i++) { + m_outputA->Set(true); + Wait(kDelayTime); + m_outputB->Set(true); + Wait(kDelayTime); + m_outputA->Set(false); + Wait(kDelayTime); + m_outputB->Set(false); + Wait(kDelayTime); + } + } - void SetIndexHigh() { - m_indexOutput->SetVoltage(5.0); - Wait(kDelayTime); - } + void SetIndexHigh() { + m_indexOutput->SetVoltage(5.0); + Wait(kDelayTime); + } - void SetIndexLow() { - m_indexOutput->SetVoltage(0.0); - Wait(kDelayTime); - } + void SetIndexLow() { + m_indexOutput->SetVoltage(0.0); + Wait(kDelayTime); + } }; /** * Test the encoder by reseting it to 0 and reading the value. */ TEST_F(FakeEncoderTest, TestDefaultState) { - EXPECT_FLOAT_EQ(0.0f, m_encoder->Get()) - << "The encoder did not start at 0."; + EXPECT_FLOAT_EQ(0.0f, m_encoder->Get()) << "The encoder did not start at 0."; } /** * Test the encoder by setting the digital outputs and reading the value. */ TEST_F(FakeEncoderTest, TestCountUp) { - m_encoder->Reset(); - Simulate100QuadratureTicks(); + m_encoder->Reset(); + Simulate100QuadratureTicks(); - EXPECT_FLOAT_EQ(100.0f, m_encoder->Get()) - << "Encoder did not count to 100."; + EXPECT_FLOAT_EQ(100.0f, m_encoder->Get()) << "Encoder did not count to 100."; } /** * Test that the encoder can stay reset while the index source is high */ TEST_F(FakeEncoderTest, TestResetWhileHigh) { - m_encoder->SetIndexSource(m_indexAnalogTriggerOutput, Encoder::IndexingType::kResetWhileHigh); + m_encoder->SetIndexSource(m_indexAnalogTriggerOutput, + Encoder::IndexingType::kResetWhileHigh); - SetIndexLow(); - Simulate100QuadratureTicks(); - SetIndexHigh(); - EXPECT_EQ(0, m_encoder->Get()); + SetIndexLow(); + Simulate100QuadratureTicks(); + SetIndexHigh(); + EXPECT_EQ(0, m_encoder->Get()); - Simulate100QuadratureTicks(); - EXPECT_EQ(0, m_encoder->Get()); + Simulate100QuadratureTicks(); + EXPECT_EQ(0, m_encoder->Get()); } /** * Test that the encoder can reset when the index source goes from low to high */ TEST_F(FakeEncoderTest, TestResetOnRisingEdge) { - m_encoder->SetIndexSource(m_indexAnalogTriggerOutput, Encoder::IndexingType::kResetOnRisingEdge); + m_encoder->SetIndexSource(m_indexAnalogTriggerOutput, + Encoder::IndexingType::kResetOnRisingEdge); - SetIndexLow(); - Simulate100QuadratureTicks(); - SetIndexHigh(); - EXPECT_EQ(0, m_encoder->Get()); + SetIndexLow(); + Simulate100QuadratureTicks(); + SetIndexHigh(); + EXPECT_EQ(0, m_encoder->Get()); - Simulate100QuadratureTicks(); - EXPECT_EQ(100, m_encoder->Get()); + Simulate100QuadratureTicks(); + EXPECT_EQ(100, m_encoder->Get()); } /** * Test that the encoder can stay reset while the index source is low */ TEST_F(FakeEncoderTest, TestResetWhileLow) { - m_encoder->SetIndexSource(m_indexAnalogTriggerOutput, Encoder::IndexingType::kResetWhileLow); + m_encoder->SetIndexSource(m_indexAnalogTriggerOutput, + Encoder::IndexingType::kResetWhileLow); - SetIndexHigh(); - Simulate100QuadratureTicks(); - SetIndexLow(); - EXPECT_EQ(0, m_encoder->Get()); + SetIndexHigh(); + Simulate100QuadratureTicks(); + SetIndexLow(); + EXPECT_EQ(0, m_encoder->Get()); - Simulate100QuadratureTicks(); - EXPECT_EQ(0, m_encoder->Get()); + Simulate100QuadratureTicks(); + EXPECT_EQ(0, m_encoder->Get()); } /** * Test that the encoder can reset when the index source goes from high to low */ TEST_F(FakeEncoderTest, TestResetOnFallingEdge) { - m_encoder->SetIndexSource(m_indexAnalogTriggerOutput, Encoder::IndexingType::kResetOnFallingEdge); + m_encoder->SetIndexSource(m_indexAnalogTriggerOutput, + Encoder::IndexingType::kResetOnFallingEdge); - SetIndexHigh(); - Simulate100QuadratureTicks(); - SetIndexLow(); - EXPECT_EQ(0, m_encoder->Get()); + SetIndexHigh(); + Simulate100QuadratureTicks(); + SetIndexLow(); + EXPECT_EQ(0, m_encoder->Get()); - Simulate100QuadratureTicks(); - EXPECT_EQ(100, m_encoder->Get()); + Simulate100QuadratureTicks(); + EXPECT_EQ(100, m_encoder->Get()); } - diff --git a/wpilibc/wpilibC++IntegrationTests/src/MotorEncoderTest.cpp b/wpilibc/wpilibC++IntegrationTests/src/MotorEncoderTest.cpp index c6e7833a99..e736dfc8ef 100644 --- a/wpilibc/wpilibC++IntegrationTests/src/MotorEncoderTest.cpp +++ b/wpilibc/wpilibC++IntegrationTests/src/MotorEncoderTest.cpp @@ -12,13 +12,19 @@ enum MotorEncoderTestType { TEST_VICTOR, TEST_JAGUAR, TEST_TALON }; std::ostream &operator<<(std::ostream &os, MotorEncoderTestType const &type) { - switch(type) { - case TEST_VICTOR: os << "Victor"; break; - case TEST_JAGUAR: os << "Jaguar"; break; - case TEST_TALON: os << "Talon"; break; - } + switch (type) { + case TEST_VICTOR: + os << "Victor"; + break; + case TEST_JAGUAR: + os << "Jaguar"; + break; + case TEST_TALON: + os << "Talon"; + break; + } - return os; + return os; } static constexpr double kMotorTime = 0.5; @@ -29,124 +35,121 @@ static constexpr double kMotorTime = 0.5; * @author Thomas Clark */ class MotorEncoderTest : public testing::TestWithParam { -protected: - SpeedController *m_speedController; - Encoder *m_encoder; + protected: + SpeedController *m_speedController; + Encoder *m_encoder; - virtual void SetUp() override { - switch(GetParam()) { - case TEST_VICTOR: - m_speedController = new Victor(TestBench::kVictorChannel); - m_encoder = new Encoder(TestBench::kVictorEncoderChannelA, - TestBench::kVictorEncoderChannelB); - break; + virtual void SetUp() override { + switch (GetParam()) { + case TEST_VICTOR: + m_speedController = new Victor(TestBench::kVictorChannel); + m_encoder = new Encoder(TestBench::kVictorEncoderChannelA, + TestBench::kVictorEncoderChannelB); + break; - case TEST_JAGUAR: - m_speedController = new Jaguar(TestBench::kJaguarChannel); - m_encoder = new Encoder(TestBench::kJaguarEncoderChannelA, - TestBench::kJaguarEncoderChannelB); - break; + case TEST_JAGUAR: + m_speedController = new Jaguar(TestBench::kJaguarChannel); + m_encoder = new Encoder(TestBench::kJaguarEncoderChannelA, + TestBench::kJaguarEncoderChannelB); + break; - case TEST_TALON: - m_speedController = new Talon(TestBench::kTalonChannel); - m_encoder = new Encoder(TestBench::kTalonEncoderChannelA, - TestBench::kTalonEncoderChannelB); - break; - } + case TEST_TALON: + m_speedController = new Talon(TestBench::kTalonChannel); + m_encoder = new Encoder(TestBench::kTalonEncoderChannelA, + TestBench::kTalonEncoderChannelB); + break; + } + } - } + virtual void TearDown() override { + delete m_speedController; + delete m_encoder; + } - virtual void TearDown() override { - delete m_speedController; - delete m_encoder; - } - - void Reset() { - m_speedController->Set(0.0f); - m_encoder->Reset(); - } + void Reset() { + m_speedController->Set(0.0f); + m_encoder->Reset(); + } }; - /** * Test if the encoder value increments after the motor drives forward */ TEST_P(MotorEncoderTest, Increment) { - Reset(); + Reset(); - /* Drive the speed controller briefly to move the encoder */ - m_speedController->Set(1.0); - Wait(kMotorTime); - m_speedController->Set(0.0); + /* Drive the speed controller briefly to move the encoder */ + m_speedController->Set(1.0); + Wait(kMotorTime); + m_speedController->Set(0.0); - /* The encoder should be positive now */ - EXPECT_GT(m_encoder->Get(), 0) - << "Encoder should have incremented after the motor moved"; + /* The encoder should be positive now */ + EXPECT_GT(m_encoder->Get(), 0) + << "Encoder should have incremented after the motor moved"; } - /** * Test if the encoder value decrements after the motor drives backwards */ TEST_P(MotorEncoderTest, Decrement) { - Reset(); + Reset(); - /* Drive the speed controller briefly to move the encoder */ - m_speedController->Set(-1.0f); - Wait(kMotorTime); - m_speedController->Set(0.0f); + /* Drive the speed controller briefly to move the encoder */ + m_speedController->Set(-1.0f); + Wait(kMotorTime); + m_speedController->Set(0.0f); - /* The encoder should be positive now */ - EXPECT_LT(m_encoder->Get(), 0.0f) - << "Encoder should have decremented after the motor moved"; + /* The encoder should be positive now */ + EXPECT_LT(m_encoder->Get(), 0.0f) + << "Encoder should have decremented after the motor moved"; } /** * Test if motor speeds are clamped to [-1,1] */ TEST_P(MotorEncoderTest, ClampSpeed) { - Reset(); + Reset(); - m_speedController->Set(2.0f); - Wait(kMotorTime); + m_speedController->Set(2.0f); + Wait(kMotorTime); - EXPECT_FLOAT_EQ(1.0f, m_speedController->Get()); + EXPECT_FLOAT_EQ(1.0f, m_speedController->Get()); - m_speedController->Set(-2.0f); - Wait(kMotorTime); + m_speedController->Set(-2.0f); + Wait(kMotorTime); - EXPECT_FLOAT_EQ(-1.0f, m_speedController->Get()); + EXPECT_FLOAT_EQ(-1.0f, m_speedController->Get()); } /** * Test if PID loops work */ TEST_P(MotorEncoderTest, PIDController) { - Reset(); + Reset(); - PIDController pid(0.001f, 0.0005f, 0.0f, m_encoder, m_speedController); - pid.SetAbsoluteTolerance(20.0f); - pid.SetOutputRange(-0.3f, 0.3f); - pid.SetSetpoint(2500); + PIDController pid(0.001f, 0.0005f, 0.0f, m_encoder, m_speedController); + pid.SetAbsoluteTolerance(20.0f); + pid.SetOutputRange(-0.3f, 0.3f); + pid.SetSetpoint(2500); - /* 10 seconds should be plenty time to get to the setpoint */ - pid.Enable(); - Wait(10.0); - pid.Disable(); + /* 10 seconds should be plenty time to get to the setpoint */ + pid.Enable(); + Wait(10.0); + pid.Disable(); - RecordProperty("PIDError", pid.GetError()); + RecordProperty("PIDError", pid.GetError()); - EXPECT_TRUE(pid.OnTarget()) << "PID loop did not converge within 10 seconds."; + EXPECT_TRUE(pid.OnTarget()) << "PID loop did not converge within 10 seconds."; } /** * Test resetting encoders */ TEST_P(MotorEncoderTest, Reset) { - Reset(); + Reset(); - EXPECT_EQ(0, m_encoder->Get()) << "Encoder did not reset to 0"; + EXPECT_EQ(0, m_encoder->Get()) << "Encoder did not reset to 0"; } INSTANTIATE_TEST_CASE_P(Test, MotorEncoderTest, - testing::Values(TEST_VICTOR, TEST_JAGUAR, TEST_TALON)); + testing::Values(TEST_VICTOR, TEST_JAGUAR, TEST_TALON)); diff --git a/wpilibc/wpilibC++IntegrationTests/src/MotorInvertingTest.cpp b/wpilibc/wpilibC++IntegrationTests/src/MotorInvertingTest.cpp index ba9bdb92e2..475693fc09 100644 --- a/wpilibc/wpilibC++IntegrationTests/src/MotorInvertingTest.cpp +++ b/wpilibc/wpilibC++IntegrationTests/src/MotorInvertingTest.cpp @@ -13,98 +13,108 @@ enum MotorInvertingTestType { TEST_VICTOR, TEST_JAGUAR, TEST_TALON }; static const double motorSpeed = 0.25; static const double delayTime = 0.5; std::ostream &operator<<(std::ostream &os, MotorInvertingTestType const &type) { - switch(type) { - case TEST_VICTOR: os << "Victor"; break; - case TEST_JAGUAR: os << "Jaguar"; break; - case TEST_TALON: os << "Talon"; break; - } + switch (type) { + case TEST_VICTOR: + os << "Victor"; + break; + case TEST_JAGUAR: + os << "Jaguar"; + break; + case TEST_TALON: + os << "Talon"; + break; + } - return os; + return os; } -class MotorInvertingTest : public testing::TestWithParam{ -protected: - SpeedController *m_speedController; - Encoder *m_encoder; - virtual void SetUp() { - switch(GetParam()) { - case TEST_VICTOR: - m_speedController = new Victor(TestBench::kVictorChannel); - m_encoder = new Encoder(TestBench::kVictorEncoderChannelA, - TestBench::kVictorEncoderChannelB); - break; +class MotorInvertingTest + : public testing::TestWithParam { + protected: + SpeedController *m_speedController; + Encoder *m_encoder; + virtual void SetUp() { + switch (GetParam()) { + case TEST_VICTOR: + m_speedController = new Victor(TestBench::kVictorChannel); + m_encoder = new Encoder(TestBench::kVictorEncoderChannelA, + TestBench::kVictorEncoderChannelB); + break; - case TEST_JAGUAR: - m_speedController = new Jaguar(TestBench::kJaguarChannel); - m_encoder = new Encoder(TestBench::kJaguarEncoderChannelA, - TestBench::kJaguarEncoderChannelB); - break; + case TEST_JAGUAR: + m_speedController = new Jaguar(TestBench::kJaguarChannel); + m_encoder = new Encoder(TestBench::kJaguarEncoderChannelA, + TestBench::kJaguarEncoderChannelB); + break; - case TEST_TALON: - m_speedController = new Talon(TestBench::kTalonChannel); - m_encoder = new Encoder(TestBench::kTalonEncoderChannelA, - TestBench::kTalonEncoderChannelB); - break; - } + case TEST_TALON: + m_speedController = new Talon(TestBench::kTalonChannel); + m_encoder = new Encoder(TestBench::kTalonEncoderChannelA, + TestBench::kTalonEncoderChannelB); + break; + } + } + virtual void TearDown() { + delete m_speedController; + delete m_encoder; + } - } - virtual void TearDown() { - delete m_speedController; - delete m_encoder; - } - - void Reset() { - m_speedController->SetInverted(false); - m_speedController->Set(0.0f); - m_encoder->Reset(); - } + void Reset() { + m_speedController->SetInverted(false); + m_speedController->Set(0.0f); + m_encoder->Reset(); + } }; -TEST_P(MotorInvertingTest, InvertingPositive){ - Reset(); - m_speedController->Set(motorSpeed); - Wait(delayTime); - bool initDirection = m_encoder->GetDirection(); - m_speedController->SetInverted(true); - m_speedController->Set(motorSpeed); - Wait(delayTime); - EXPECT_TRUE(m_encoder->GetDirection()!=initDirection) <<"Inverting with Positive value does not change direction"; - Reset(); +TEST_P(MotorInvertingTest, InvertingPositive) { + Reset(); + m_speedController->Set(motorSpeed); + Wait(delayTime); + bool initDirection = m_encoder->GetDirection(); + m_speedController->SetInverted(true); + m_speedController->Set(motorSpeed); + Wait(delayTime); + EXPECT_TRUE(m_encoder->GetDirection() != initDirection) + << "Inverting with Positive value does not change direction"; + Reset(); } -TEST_P(MotorInvertingTest, InvertingNegative){ - Reset(); - m_speedController->SetInverted(false); - m_speedController->Set(-motorSpeed); - Wait(delayTime); - bool initDirection = m_encoder->GetDirection(); - m_speedController->SetInverted(true); - m_speedController->Set(-motorSpeed); - Wait(delayTime); - EXPECT_TRUE(m_encoder->GetDirection()!=initDirection) <<"Inverting with Negative value does not change direction"; - Reset(); +TEST_P(MotorInvertingTest, InvertingNegative) { + Reset(); + m_speedController->SetInverted(false); + m_speedController->Set(-motorSpeed); + Wait(delayTime); + bool initDirection = m_encoder->GetDirection(); + m_speedController->SetInverted(true); + m_speedController->Set(-motorSpeed); + Wait(delayTime); + EXPECT_TRUE(m_encoder->GetDirection() != initDirection) + << "Inverting with Negative value does not change direction"; + Reset(); } -TEST_P(MotorInvertingTest, InvertingSwitchingPosToNeg){ - Reset(); - m_speedController->SetInverted(false); - m_speedController->Set(motorSpeed); - Wait(delayTime); - bool initDirection = m_encoder->GetDirection(); - m_speedController->SetInverted(true); - m_speedController->Set(-motorSpeed); - Wait(delayTime); - EXPECT_TRUE(m_encoder->GetDirection()==initDirection) <<"Inverting with Switching value does change direction"; - Reset(); +TEST_P(MotorInvertingTest, InvertingSwitchingPosToNeg) { + Reset(); + m_speedController->SetInverted(false); + m_speedController->Set(motorSpeed); + Wait(delayTime); + bool initDirection = m_encoder->GetDirection(); + m_speedController->SetInverted(true); + m_speedController->Set(-motorSpeed); + Wait(delayTime); + EXPECT_TRUE(m_encoder->GetDirection() == initDirection) + << "Inverting with Switching value does change direction"; + Reset(); } -TEST_P(MotorInvertingTest, InvertingSwitchingNegToPos){ - Reset(); - m_speedController->SetInverted(false); - m_speedController->Set(-motorSpeed); - Wait(delayTime); - bool initDirection = m_encoder->GetDirection(); - m_speedController->SetInverted(true); - m_speedController->Set(motorSpeed); - Wait(delayTime); - EXPECT_TRUE(m_encoder->GetDirection()==initDirection) <<"Inverting with Switching value does change direction"; - Reset(); +TEST_P(MotorInvertingTest, InvertingSwitchingNegToPos) { + Reset(); + m_speedController->SetInverted(false); + m_speedController->Set(-motorSpeed); + Wait(delayTime); + bool initDirection = m_encoder->GetDirection(); + m_speedController->SetInverted(true); + m_speedController->Set(motorSpeed); + Wait(delayTime); + EXPECT_TRUE(m_encoder->GetDirection() == initDirection) + << "Inverting with Switching value does change direction"; + Reset(); } INSTANTIATE_TEST_CASE_P(Test, MotorInvertingTest, - testing::Values(TEST_VICTOR, TEST_JAGUAR, TEST_TALON)); + testing::Values(TEST_VICTOR, TEST_JAGUAR, TEST_TALON)); diff --git a/wpilibc/wpilibC++IntegrationTests/src/NotifierTest.cpp b/wpilibc/wpilibC++IntegrationTests/src/NotifierTest.cpp index 87cd2a9940..8258ad1b9d 100644 --- a/wpilibc/wpilibC++IntegrationTests/src/NotifierTest.cpp +++ b/wpilibc/wpilibC++IntegrationTests/src/NotifierTest.cpp @@ -9,31 +9,29 @@ #include "gtest/gtest.h" #include "TestBench.h" - unsigned notifierCounter; -void notifierHandler(void *) -{ - notifierCounter++; -} +void notifierHandler(void *) { notifierCounter++; } /** * Test if the Wait function works */ TEST(NotifierTest, DISABLED_TestTimerNotifications) { - std::cout << "NotifierTest..." << std::endl; - notifierCounter = 0; - std::cout << "notifier(notifierHandler, NULL)..." << std::endl; - Notifier notifier(notifierHandler, NULL); - std::cout << "Start Periodic..." << std::endl; - notifier.StartPeriodic(1.0); + std::cout << "NotifierTest..." << std::endl; + notifierCounter = 0; + std::cout << "notifier(notifierHandler, NULL)..." << std::endl; + Notifier notifier(notifierHandler, NULL); + std::cout << "Start Periodic..." << std::endl; + notifier.StartPeriodic(1.0); - std::cout << "Wait..." << std::endl; - Wait(10.5); - std::cout << "...Wait" << std::endl; + std::cout << "Wait..." << std::endl; + Wait(10.5); + std::cout << "...Wait" << std::endl; - EXPECT_EQ(10u, notifierCounter) << "Received " << notifierCounter << " notifications in 10.5 seconds"; - std::cout << "Received " << notifierCounter << " notifications in 10.5 seconds"; + EXPECT_EQ(10u, notifierCounter) << "Received " << notifierCounter + << " notifications in 10.5 seconds"; + std::cout << "Received " << notifierCounter + << " notifications in 10.5 seconds"; - std::cout << "...NotifierTest" << std::endl; + std::cout << "...NotifierTest" << std::endl; } diff --git a/wpilibc/wpilibC++IntegrationTests/src/PCMTest.cpp b/wpilibc/wpilibC++IntegrationTests/src/PCMTest.cpp index 2cc25deb72..38f8d76b61 100644 --- a/wpilibc/wpilibC++IntegrationTests/src/PCMTest.cpp +++ b/wpilibc/wpilibC++IntegrationTests/src/PCMTest.cpp @@ -10,105 +10,106 @@ #include "TestBench.h" /* The PCM switches the compressor up to a couple seconds after the pressure - switch changes. */ + switch changes. */ static const double kCompressorDelayTime = 3.0; /* Solenoids should change much more quickly */ static const double kSolenoidDelayTime = 0.5; /* The voltage divider on the test bench should bring the compressor output - to around these values. */ + to around these values. */ static const double kCompressorOnVoltage = 5.00; static const double kCompressorOffVoltage = 1.68; class PCMTest : public testing::Test { -protected: - Compressor *m_compressor; + protected: + Compressor *m_compressor; - DigitalOutput *m_fakePressureSwitch; - AnalogInput *m_fakeCompressor; - DoubleSolenoid *m_doubleSolenoid; - DigitalInput *m_fakeSolenoid1, *m_fakeSolenoid2; + DigitalOutput *m_fakePressureSwitch; + AnalogInput *m_fakeCompressor; + DoubleSolenoid *m_doubleSolenoid; + DigitalInput *m_fakeSolenoid1, *m_fakeSolenoid2; - virtual void SetUp() override { - m_compressor = new Compressor(); + virtual void SetUp() override { + m_compressor = new Compressor(); - m_fakePressureSwitch = new DigitalOutput(TestBench::kFakePressureSwitchChannel); - m_fakeCompressor = new AnalogInput(TestBench::kFakeCompressorChannel); - m_fakeSolenoid1 = new DigitalInput(TestBench::kFakeSolenoid1Channel); - m_fakeSolenoid2 = new DigitalInput(TestBench::kFakeSolenoid2Channel); - } + m_fakePressureSwitch = + new DigitalOutput(TestBench::kFakePressureSwitchChannel); + m_fakeCompressor = new AnalogInput(TestBench::kFakeCompressorChannel); + m_fakeSolenoid1 = new DigitalInput(TestBench::kFakeSolenoid1Channel); + m_fakeSolenoid2 = new DigitalInput(TestBench::kFakeSolenoid2Channel); + } - virtual void TearDown() override { - delete m_compressor; - delete m_fakePressureSwitch; - delete m_fakeCompressor; - delete m_fakeSolenoid1; - delete m_fakeSolenoid2; - } + virtual void TearDown() override { + delete m_compressor; + delete m_fakePressureSwitch; + delete m_fakeCompressor; + delete m_fakeSolenoid1; + delete m_fakeSolenoid2; + } - void Reset() { - m_compressor->Stop(); - m_fakePressureSwitch->Set(false); - } + void Reset() { + m_compressor->Stop(); + m_fakePressureSwitch->Set(false); + } }; /** * Test if the compressor turns on and off when the pressure switch is toggled */ TEST_F(PCMTest, DISABLED_PressureSwitch) { - Reset(); + Reset(); - m_compressor->SetClosedLoopControl(true); + m_compressor->SetClosedLoopControl(true); - // Turn on the compressor - m_fakePressureSwitch->Set(true); - Wait(kCompressorDelayTime); - EXPECT_NEAR(kCompressorOnVoltage, m_fakeCompressor->GetVoltage(), 0.1) - << "Compressor did not turn on when the pressure switch turned on."; + // Turn on the compressor + m_fakePressureSwitch->Set(true); + Wait(kCompressorDelayTime); + EXPECT_NEAR(kCompressorOnVoltage, m_fakeCompressor->GetVoltage(), 0.1) + << "Compressor did not turn on when the pressure switch turned on."; - // Turn off the compressor - m_fakePressureSwitch->Set(false); - Wait(kCompressorDelayTime); - EXPECT_NEAR(kCompressorOffVoltage, m_fakeCompressor->GetVoltage(), 0.1) - << "Compressor did not turn off when the pressure switch turned off."; + // Turn off the compressor + m_fakePressureSwitch->Set(false); + Wait(kCompressorDelayTime); + EXPECT_NEAR(kCompressorOffVoltage, m_fakeCompressor->GetVoltage(), 0.1) + << "Compressor did not turn off when the pressure switch turned off."; } /** * Test if the correct solenoids turn on and off when they should */ TEST_F(PCMTest, DISABLED_Solenoid) { - Reset(); - Solenoid solenoid1(TestBench::kSolenoidChannel1); - Solenoid solenoid2(TestBench::kSolenoidChannel2); + Reset(); + Solenoid solenoid1(TestBench::kSolenoidChannel1); + Solenoid solenoid2(TestBench::kSolenoidChannel2); - // Turn both solenoids off - solenoid1.Set(false); - solenoid2.Set(false); - Wait(kSolenoidDelayTime); - EXPECT_TRUE(m_fakeSolenoid1->Get()) << "Solenoid #1 did not turn off"; - EXPECT_TRUE(m_fakeSolenoid2->Get()) << "Solenoid #2 did not turn off"; + // Turn both solenoids off + solenoid1.Set(false); + solenoid2.Set(false); + Wait(kSolenoidDelayTime); + EXPECT_TRUE(m_fakeSolenoid1->Get()) << "Solenoid #1 did not turn off"; + EXPECT_TRUE(m_fakeSolenoid2->Get()) << "Solenoid #2 did not turn off"; - // Turn one solenoid on and one off - solenoid1.Set(true); - solenoid2.Set(false); - Wait(kSolenoidDelayTime); - EXPECT_FALSE(m_fakeSolenoid1->Get()) << "Solenoid #1 did not turn on"; - EXPECT_TRUE(m_fakeSolenoid2->Get()) << "Solenoid #2 did not turn off"; + // Turn one solenoid on and one off + solenoid1.Set(true); + solenoid2.Set(false); + Wait(kSolenoidDelayTime); + EXPECT_FALSE(m_fakeSolenoid1->Get()) << "Solenoid #1 did not turn on"; + EXPECT_TRUE(m_fakeSolenoid2->Get()) << "Solenoid #2 did not turn off"; - // Turn one solenoid on and one off - solenoid1.Set(false); - solenoid2.Set(true); - Wait(kSolenoidDelayTime); - EXPECT_TRUE(m_fakeSolenoid1->Get()) << "Solenoid #1 did not turn off"; - EXPECT_FALSE(m_fakeSolenoid2->Get()) << "Solenoid #2 did not turn on"; + // Turn one solenoid on and one off + solenoid1.Set(false); + solenoid2.Set(true); + Wait(kSolenoidDelayTime); + EXPECT_TRUE(m_fakeSolenoid1->Get()) << "Solenoid #1 did not turn off"; + EXPECT_FALSE(m_fakeSolenoid2->Get()) << "Solenoid #2 did not turn on"; - // Turn both on - solenoid1.Set(true); - solenoid2.Set(true); - Wait(kSolenoidDelayTime); - EXPECT_FALSE(m_fakeSolenoid1->Get()) << "Solenoid #1 did not turn on"; - EXPECT_FALSE(m_fakeSolenoid2->Get()) << "Solenoid #2 did not turn on"; + // Turn both on + solenoid1.Set(true); + solenoid2.Set(true); + Wait(kSolenoidDelayTime); + EXPECT_FALSE(m_fakeSolenoid1->Get()) << "Solenoid #1 did not turn on"; + EXPECT_FALSE(m_fakeSolenoid2->Get()) << "Solenoid #2 did not turn on"; } /** @@ -116,20 +117,21 @@ TEST_F(PCMTest, DISABLED_Solenoid) { * with the DoubleSolenoid class. */ TEST_F(PCMTest, DISABLED_DoubleSolenoid) { - DoubleSolenoid solenoid(TestBench::kSolenoidChannel1, TestBench::kSolenoidChannel2); + DoubleSolenoid solenoid(TestBench::kSolenoidChannel1, + TestBench::kSolenoidChannel2); - solenoid.Set(DoubleSolenoid::kOff); - Wait(kSolenoidDelayTime); - EXPECT_TRUE(m_fakeSolenoid1->Get()) << "Solenoid #1 did not turn off"; - EXPECT_TRUE(m_fakeSolenoid2->Get()) << "Solenoid #2 did not turn off"; + solenoid.Set(DoubleSolenoid::kOff); + Wait(kSolenoidDelayTime); + EXPECT_TRUE(m_fakeSolenoid1->Get()) << "Solenoid #1 did not turn off"; + EXPECT_TRUE(m_fakeSolenoid2->Get()) << "Solenoid #2 did not turn off"; - solenoid.Set(DoubleSolenoid::kForward); - Wait(kSolenoidDelayTime); - EXPECT_FALSE(m_fakeSolenoid1->Get()) << "Solenoid #1 did not turn on"; - EXPECT_TRUE(m_fakeSolenoid2->Get()) << "Solenoid #2 did not turn off"; + solenoid.Set(DoubleSolenoid::kForward); + Wait(kSolenoidDelayTime); + EXPECT_FALSE(m_fakeSolenoid1->Get()) << "Solenoid #1 did not turn on"; + EXPECT_TRUE(m_fakeSolenoid2->Get()) << "Solenoid #2 did not turn off"; - solenoid.Set(DoubleSolenoid::kReverse); - Wait(kSolenoidDelayTime); - EXPECT_TRUE(m_fakeSolenoid1->Get()) << "Solenoid #1 did not turn off"; - EXPECT_FALSE(m_fakeSolenoid2->Get()) << "Solenoid #2 did not turn on"; + solenoid.Set(DoubleSolenoid::kReverse); + Wait(kSolenoidDelayTime); + EXPECT_TRUE(m_fakeSolenoid1->Get()) << "Solenoid #1 did not turn off"; + EXPECT_FALSE(m_fakeSolenoid2->Get()) << "Solenoid #2 did not turn on"; } diff --git a/wpilibc/wpilibC++IntegrationTests/src/PowerDistributionPanelTest.cpp b/wpilibc/wpilibC++IntegrationTests/src/PowerDistributionPanelTest.cpp index b71e1da615..c099323448 100644 --- a/wpilibc/wpilibC++IntegrationTests/src/PowerDistributionPanelTest.cpp +++ b/wpilibc/wpilibC++IntegrationTests/src/PowerDistributionPanelTest.cpp @@ -12,80 +12,80 @@ static const double kMotorTime = 0.25; class PowerDistributionPanelTest : public testing::Test { -protected: - PowerDistributionPanel *m_pdp; - Talon *m_talon; - Victor *m_victor; - Jaguar *m_jaguar; + protected: + PowerDistributionPanel *m_pdp; + Talon *m_talon; + Victor *m_victor; + Jaguar *m_jaguar; - virtual void SetUp() override { - m_pdp = new PowerDistributionPanel(); - m_talon = new Talon(TestBench::kTalonChannel); - m_victor = new Victor(TestBench::kVictorChannel); - m_jaguar = new Jaguar(TestBench::kJaguarChannel); - } + virtual void SetUp() override { + m_pdp = new PowerDistributionPanel(); + m_talon = new Talon(TestBench::kTalonChannel); + m_victor = new Victor(TestBench::kVictorChannel); + m_jaguar = new Jaguar(TestBench::kJaguarChannel); + } - virtual void TearDown() override { - delete m_pdp; - delete m_talon; - delete m_victor; - delete m_jaguar; - } + virtual void TearDown() override { + delete m_pdp; + delete m_talon; + delete m_victor; + delete m_jaguar; + } }; /** * Test if the current changes when the motor is driven using a talon */ -TEST_F(PowerDistributionPanelTest, CheckCurrentTalon) { - Wait(kMotorTime); +TEST_F(PowerDistributionPanelTest, CheckCurrentTalon) { + Wait(kMotorTime); - /* The Current should be 0 */ - EXPECT_FLOAT_EQ(0, m_pdp->GetCurrent(TestBench::kTalonPDPChannel)) - << "The Talon current was non-zero"; + /* The Current should be 0 */ + EXPECT_FLOAT_EQ(0, m_pdp->GetCurrent(TestBench::kTalonPDPChannel)) + << "The Talon current was non-zero"; - /* Set the motor to full forward */ - m_talon->Set(1.0); - Wait(kMotorTime); + /* Set the motor to full forward */ + m_talon->Set(1.0); + Wait(kMotorTime); - /* The current should now be positive */ - ASSERT_GT(m_pdp->GetCurrent(TestBench::kTalonPDPChannel), 0) - << "The Talon current was not positive"; + /* The current should now be positive */ + ASSERT_GT(m_pdp->GetCurrent(TestBench::kTalonPDPChannel), 0) + << "The Talon current was not positive"; } /** * Test if the current changes when the motor is driven using a victor */ TEST_F(PowerDistributionPanelTest, CheckCurrentVictor) { - Wait(kMotorTime); + Wait(kMotorTime); - /* The Current should be 0 */ - EXPECT_FLOAT_EQ(0, m_pdp->GetCurrent(TestBench::kVictorPDPChannel)) - << "The Victor current was non-zero"; + /* The Current should be 0 */ + EXPECT_FLOAT_EQ(0, m_pdp->GetCurrent(TestBench::kVictorPDPChannel)) + << "The Victor current was non-zero"; - /* Set the motor to full forward */ - m_victor->Set(1.0); - Wait(kMotorTime); + /* Set the motor to full forward */ + m_victor->Set(1.0); + Wait(kMotorTime); - /* The current should now be positive */ - ASSERT_GT(m_pdp->GetCurrent(TestBench::kVictorPDPChannel), 0) - << "The Victor current was not positive"; + /* The current should now be positive */ + ASSERT_GT(m_pdp->GetCurrent(TestBench::kVictorPDPChannel), 0) + << "The Victor current was not positive"; } /** * Test if the current changes when the motor is driven using a jaguar */ -TEST_F(PowerDistributionPanelTest, CheckCurrentJaguar) { - Wait(kMotorTime); +TEST_F(PowerDistributionPanelTest, CheckCurrentJaguar) { + Wait(kMotorTime); - /* The Current should be 0 */ - EXPECT_FLOAT_EQ(0, m_pdp->GetCurrent(TestBench::kJaguarPDPChannel)) - << "The Jaguar current was non-zero"; + /* The Current should be 0 */ + EXPECT_FLOAT_EQ(0, m_pdp->GetCurrent(TestBench::kJaguarPDPChannel)) + << "The Jaguar current was non-zero"; - /* Set the motor to full forward */ - m_jaguar->Set(1.0); - Wait(kMotorTime); + /* Set the motor to full forward */ + m_jaguar->Set(1.0); + Wait(kMotorTime); - /* The current should now be positive */ - ASSERT_GT(m_pdp->GetCurrent(TestBench::kJaguarPDPChannel), 0) - << "The Jaguar current was not positive"; + /* The current should now be positive */ + ASSERT_GT(m_pdp->GetCurrent(TestBench::kJaguarPDPChannel), 0) + << "The Jaguar current was not positive"; } diff --git a/wpilibc/wpilibC++IntegrationTests/src/PreferencesTest.cpp b/wpilibc/wpilibC++IntegrationTests/src/PreferencesTest.cpp index 1140e47e15..69b939cf6e 100644 --- a/wpilibc/wpilibC++IntegrationTests/src/PreferencesTest.cpp +++ b/wpilibc/wpilibC++IntegrationTests/src/PreferencesTest.cpp @@ -18,24 +18,26 @@ static const double kSaveTime = 0.2; * we get those same values back using the Preference class. */ TEST(PreferencesTest, ReadPreferencesFromFile) { - std::remove(kFileName); - std::ofstream preferencesFile(kFileName); - preferencesFile << "[Preferences]" << std::endl; - preferencesFile << "testFileGetString=\"Hello, preferences file\"" << std::endl; - preferencesFile << "testFileGetInt=\"1\"" << std::endl; - preferencesFile << "testFileGetDouble=\"0.5\"" << std::endl; - preferencesFile << "testFileGetFloat=\"0.25\"" << std::endl; - preferencesFile << "testFileGetBoolean=\"true\"" << std::endl; - preferencesFile << "testFileGetLong=\"1000000000000000000\"" << std::endl; - preferencesFile.close(); + std::remove(kFileName); + std::ofstream preferencesFile(kFileName); + preferencesFile << "[Preferences]" << std::endl; + preferencesFile << "testFileGetString=\"Hello, preferences file\"" + << std::endl; + preferencesFile << "testFileGetInt=\"1\"" << std::endl; + preferencesFile << "testFileGetDouble=\"0.5\"" << std::endl; + preferencesFile << "testFileGetFloat=\"0.25\"" << std::endl; + preferencesFile << "testFileGetBoolean=\"true\"" << std::endl; + preferencesFile << "testFileGetLong=\"1000000000000000000\"" << std::endl; + preferencesFile.close(); - Preferences *preferences = Preferences::GetInstance(); - EXPECT_EQ("Hello, preferences file", preferences->GetString("testFileGetString")); - EXPECT_EQ(1, preferences->GetInt("testFileGetInt")); - EXPECT_FLOAT_EQ(0.5, preferences->GetDouble("testFileGetDouble")); - EXPECT_FLOAT_EQ(0.25f, preferences->GetFloat("testFileGetFloat")); - EXPECT_TRUE(preferences->GetBoolean("testFileGetBoolean")); - EXPECT_EQ(1000000000000000000ll, preferences->GetLong("testFileGetLong")); + Preferences *preferences = Preferences::GetInstance(); + EXPECT_EQ("Hello, preferences file", + preferences->GetString("testFileGetString")); + EXPECT_EQ(1, preferences->GetInt("testFileGetInt")); + EXPECT_FLOAT_EQ(0.5, preferences->GetDouble("testFileGetDouble")); + EXPECT_FLOAT_EQ(0.25f, preferences->GetFloat("testFileGetFloat")); + EXPECT_TRUE(preferences->GetBoolean("testFileGetBoolean")); + EXPECT_EQ(1000000000000000000ll, preferences->GetLong("testFileGetLong")); } /** @@ -43,36 +45,32 @@ TEST(PreferencesTest, ReadPreferencesFromFile) { * in wpilib-preferences.ini */ TEST(PreferencesTest, WritePreferencesToFile) { - Preferences *preferences = Preferences::GetInstance(); - preferences->PutString("testFilePutString", "Hello, preferences file"); - preferences->PutInt("testFilePutInt", 1); - preferences->PutDouble("testFilePutDouble", 0.5); - preferences->PutFloat("testFilePutFloat", 0.25f); - preferences->PutBoolean("testFilePutBoolean", true); - preferences->PutLong("testFilePutLong", 1000000000000000000ll); - preferences->Save(); + Preferences *preferences = Preferences::GetInstance(); + preferences->PutString("testFilePutString", "Hello, preferences file"); + preferences->PutInt("testFilePutInt", 1); + preferences->PutDouble("testFilePutDouble", 0.5); + preferences->PutFloat("testFilePutFloat", 0.25f); + preferences->PutBoolean("testFilePutBoolean", true); + preferences->PutLong("testFilePutLong", 1000000000000000000ll); + preferences->Save(); - Wait(kSaveTime); + Wait(kSaveTime); - static char const *kExpectedFileContents[] = { - "[Preferences]", - "testFileGetString=\"Hello, preferences file\"", - "testFileGetInt=\"1\"", - "testFileGetDouble=\"0.5\"", - "testFileGetFloat=\"0.25\"", - "testFileGetBoolean=\"true\"", - "testFileGetLong=\"1000000000000000000\"" - }; + static char const *kExpectedFileContents[] = { + "[Preferences]", "testFileGetString=\"Hello, preferences file\"", + "testFileGetInt=\"1\"", "testFileGetDouble=\"0.5\"", + "testFileGetFloat=\"0.25\"", "testFileGetBoolean=\"true\"", + "testFileGetLong=\"1000000000000000000\""}; - std::ifstream preferencesFile(kFileName); - for(int i = 0; i < 7; i++) { - ASSERT_FALSE(preferencesFile.eof()) - << "Preferences file prematurely reached EOF"; + std::ifstream preferencesFile(kFileName); + for (int i = 0; i < 7; i++) { + ASSERT_FALSE(preferencesFile.eof()) + << "Preferences file prematurely reached EOF"; - std::string line; - std::getline(preferencesFile, line); + std::string line; + std::getline(preferencesFile, line); - ASSERT_EQ(kExpectedFileContents[i], line) - << "A line in wpilib-preferences.ini was not correct"; - } + ASSERT_EQ(kExpectedFileContents[i], line) + << "A line in wpilib-preferences.ini was not correct"; + } } diff --git a/wpilibc/wpilibC++IntegrationTests/src/RelayTest.cpp b/wpilibc/wpilibC++IntegrationTests/src/RelayTest.cpp index 7f6c0ba9aa..ee6133d5ea 100644 --- a/wpilibc/wpilibC++IntegrationTests/src/RelayTest.cpp +++ b/wpilibc/wpilibC++IntegrationTests/src/RelayTest.cpp @@ -13,65 +13,52 @@ static const double kDelayTime = 0.01; class RelayTest : public testing::Test { -protected: - Relay *m_relay; - DigitalInput *m_forward; - DigitalInput *m_reverse; + protected: + Relay *m_relay; + DigitalInput *m_forward; + DigitalInput *m_reverse; + virtual void SetUp() override { + m_relay = new Relay(TestBench::kRelayChannel); + m_forward = new DigitalInput(TestBench::kFakeRelayForward); + m_reverse = new DigitalInput(TestBench::kFakeRelayReverse); + } - virtual void SetUp() override { - m_relay = new Relay(TestBench::kRelayChannel); - m_forward = new DigitalInput(TestBench::kFakeRelayForward); - m_reverse = new DigitalInput(TestBench::kFakeRelayReverse); - } + virtual void TearDown() override { + delete m_relay; + delete m_forward; + delete m_reverse; + } - virtual void TearDown() override { - delete m_relay; - delete m_forward; - delete m_reverse; - } - - virtual void Reset() { - m_relay->Set(Relay::kOff); - } + virtual void Reset() { m_relay->Set(Relay::kOff); } }; - /** - * Test the relay by setting it forward, reverse, off, and on. - */ - TEST_F(RelayTest, Relay) { - Reset(); +/** + * Test the relay by setting it forward, reverse, off, and on. + */ +TEST_F(RelayTest, Relay) { + Reset(); - //set the relay to forward - m_relay->Set(Relay::kForward); - Wait(kDelayTime); - EXPECT_TRUE(m_forward->Get()) - <<"Relay did not set forward"; - EXPECT_FALSE(m_reverse->Get()) - <<"Relay did not set forward"; + // set the relay to forward + m_relay->Set(Relay::kForward); + Wait(kDelayTime); + EXPECT_TRUE(m_forward->Get()) << "Relay did not set forward"; + EXPECT_FALSE(m_reverse->Get()) << "Relay did not set forward"; + // set the relay to reverse + m_relay->Set(Relay::kReverse); + Wait(kDelayTime); + EXPECT_TRUE(m_reverse->Get()) << "Relay did not set reverse"; + EXPECT_FALSE(m_forward->Get()) << "Relay did not set reverse"; - //set the relay to reverse - m_relay->Set(Relay::kReverse); - Wait(kDelayTime); - EXPECT_TRUE(m_reverse->Get()) - <<"Relay did not set reverse"; - EXPECT_FALSE(m_forward->Get()) - <<"Relay did not set reverse"; + // set the relay to off + m_relay->Set(Relay::kOff); + Wait(kDelayTime); + EXPECT_FALSE(m_forward->Get()) << "Relay did not set off"; + EXPECT_FALSE(m_reverse->Get()) << "Relay did not set off"; - //set the relay to off - m_relay->Set(Relay::kOff); - Wait(kDelayTime); - EXPECT_FALSE(m_forward->Get()) - <<"Relay did not set off"; - EXPECT_FALSE(m_reverse->Get()) - <<"Relay did not set off"; - - - //set the relay to on - m_relay->Set(Relay::kOn); - Wait(kDelayTime); - EXPECT_TRUE(m_forward->Get()) - <<"Relay did not set on"; - EXPECT_TRUE(m_reverse->Get()) - <<"Relay did not set on"; - } + // set the relay to on + m_relay->Set(Relay::kOn); + Wait(kDelayTime); + EXPECT_TRUE(m_forward->Get()) << "Relay did not set on"; + EXPECT_TRUE(m_reverse->Get()) << "Relay did not set on"; +} diff --git a/wpilibc/wpilibC++IntegrationTests/src/TestEnvironment.cpp b/wpilibc/wpilibC++IntegrationTests/src/TestEnvironment.cpp index c9ae1518db..4dd71a93d8 100644 --- a/wpilibc/wpilibC++IntegrationTests/src/TestEnvironment.cpp +++ b/wpilibc/wpilibC++IntegrationTests/src/TestEnvironment.cpp @@ -9,38 +9,38 @@ #include "WPILib.h" class TestEnvironment : public testing::Environment { - bool m_alreadySetUp; + bool m_alreadySetUp; -public: - TestEnvironment(): m_alreadySetUp(false) {} + public: + TestEnvironment() : m_alreadySetUp(false) {} - virtual void SetUp() override { - /* Only set up once. This allows gtest_repeat to be used to - automatically repeat tests. */ - if(m_alreadySetUp) return; - m_alreadySetUp = true; + virtual void SetUp() override { + /* Only set up once. This allows gtest_repeat to be used to + automatically repeat tests. */ + if (m_alreadySetUp) return; + m_alreadySetUp = true; - if(!HALInitialize()) { - std::cerr << "FATAL ERROR: HAL could not be initialized" << std::endl; - exit(-1); - } + if (!HALInitialize()) { + std::cerr << "FATAL ERROR: HAL could not be initialized" << std::endl; + exit(-1); + } - /* This sets up the network communications library to enable the driver - station. After starting network coms, it will loop until the driver - station returns that the robot is enabled, to ensure that tests - will be able to run on the hardware. */ - HALNetworkCommunicationObserveUserProgramStarting(); - LiveWindow::GetInstance()->SetEnabled(false); + /* This sets up the network communications library to enable the driver + station. After starting network coms, it will loop until the driver + station returns that the robot is enabled, to ensure that tests + will be able to run on the hardware. */ + HALNetworkCommunicationObserveUserProgramStarting(); + LiveWindow::GetInstance()->SetEnabled(false); - std::cout << "Waiting for enable" << std::endl; + std::cout << "Waiting for enable" << std::endl; - while(!DriverStation::GetInstance()->IsEnabled()) { - Wait(0.1); - } - } + while (!DriverStation::GetInstance()->IsEnabled()) { + Wait(0.1); + } + } - virtual void TearDown() override { - } + virtual void TearDown() override {} }; -testing::Environment *const environment = testing::AddGlobalTestEnvironment(new TestEnvironment); +testing::Environment *const environment = + testing::AddGlobalTestEnvironment(new TestEnvironment); diff --git a/wpilibc/wpilibC++IntegrationTests/src/TiltPanCameraTest.cpp b/wpilibc/wpilibC++IntegrationTests/src/TiltPanCameraTest.cpp index c9021e9781..caa5c42b1d 100644 --- a/wpilibc/wpilibC++IntegrationTests/src/TiltPanCameraTest.cpp +++ b/wpilibc/wpilibC++IntegrationTests/src/TiltPanCameraTest.cpp @@ -24,40 +24,38 @@ static constexpr double kAccelerometerTolerance = 0.2; * @author Thomas Clark */ class TiltPanCameraTest : public testing::Test { -protected: - static Gyro *m_gyro; - Servo *m_tilt, *m_pan; - Accelerometer *m_spiAccel; + protected: + static Gyro *m_gyro; + Servo *m_tilt, *m_pan; + Accelerometer *m_spiAccel; - static void SetUpTestCase() { - // The gyro object blocks for 5 seconds in the constructor, so only - // construct it once for the whole test case - m_gyro = new Gyro(TestBench::kCameraGyroChannel); - m_gyro->SetSensitivity(0.013); - } + static void SetUpTestCase() { + // The gyro object blocks for 5 seconds in the constructor, so only + // construct it once for the whole test case + m_gyro = new Gyro(TestBench::kCameraGyroChannel); + m_gyro->SetSensitivity(0.013); + } - static void TearDownTestCase() { - delete m_gyro; - } + static void TearDownTestCase() { delete m_gyro; } - virtual void SetUp() override { - m_tilt = new Servo(TestBench::kCameraTiltChannel); - m_pan = new Servo(TestBench::kCameraPanChannel); - m_spiAccel = new ADXL345_SPI(SPI::kOnboardCS0); + virtual void SetUp() override { + m_tilt = new Servo(TestBench::kCameraTiltChannel); + m_pan = new Servo(TestBench::kCameraPanChannel); + m_spiAccel = new ADXL345_SPI(SPI::kOnboardCS0); - m_tilt->Set(kTiltSetpoint45); - m_pan->SetAngle(0.0f); + m_tilt->Set(kTiltSetpoint45); + m_pan->SetAngle(0.0f); - Wait(kServoResetTime); + Wait(kServoResetTime); - m_gyro->Reset(); - } + m_gyro->Reset(); + } - virtual void TearDown() override { - delete m_tilt; - delete m_pan; - delete m_spiAccel; - } + virtual void TearDown() override { + delete m_tilt; + delete m_pan; + delete m_spiAccel; + } }; Gyro *TiltPanCameraTest::m_gyro = 0; @@ -66,7 +64,7 @@ Gyro *TiltPanCameraTest::m_gyro = 0; * Test if the gyro angle defaults to 0 immediately after being reset. */ TEST_F(TiltPanCameraTest, DefaultGyroAngle) { - EXPECT_NEAR(0.0f, m_gyro->GetAngle(), 1.0f); + EXPECT_NEAR(0.0f, m_gyro->GetAngle(), 1.0f); } /** @@ -81,15 +79,16 @@ TEST_F(TiltPanCameraTest, GyroAngle) { Wait(0.25); m_gyro->Reset(); - for(int i = 0; i < 600; i++) { - m_pan->Set(i / 1000.0); - Wait(0.001); - } + for (int i = 0; i < 600; i++) { + m_pan->Set(i / 1000.0); + Wait(0.001); + } - double gyroAngle = m_gyro->GetAngle(); + double gyroAngle = m_gyro->GetAngle(); - EXPECT_NEAR(gyroAngle, kTestAngle, 10.0) << "Gyro measured " << gyroAngle - << " degrees, servo should have turned " << kTestAngle << " degrees"; + EXPECT_NEAR(gyroAngle, kTestAngle, 10.0) + << "Gyro measured " << gyroAngle << " degrees, servo should have turned " + << kTestAngle << " degrees"; } /** @@ -97,21 +96,21 @@ TEST_F(TiltPanCameraTest, GyroAngle) { * camera rotates */ TEST_F(TiltPanCameraTest, SPIAccelerometer) { - m_tilt->Set(kTiltSetpoint0); - Wait(kTiltTime); - EXPECT_NEAR(-1.0, m_spiAccel->GetX(), kAccelerometerTolerance); - EXPECT_NEAR(0.0, m_spiAccel->GetY(), kAccelerometerTolerance); - EXPECT_NEAR(0.0, m_spiAccel->GetZ(), kAccelerometerTolerance); + m_tilt->Set(kTiltSetpoint0); + Wait(kTiltTime); + EXPECT_NEAR(-1.0, m_spiAccel->GetX(), kAccelerometerTolerance); + EXPECT_NEAR(0.0, m_spiAccel->GetY(), kAccelerometerTolerance); + EXPECT_NEAR(0.0, m_spiAccel->GetZ(), kAccelerometerTolerance); - m_tilt->Set(kTiltSetpoint45); - Wait(kTiltTime); - EXPECT_NEAR(-std::sqrt(0.5), m_spiAccel->GetX(), kAccelerometerTolerance); - EXPECT_NEAR(0.0, m_spiAccel->GetY(), kAccelerometerTolerance); - EXPECT_NEAR(std::sqrt(0.5), m_spiAccel->GetZ(), kAccelerometerTolerance); + m_tilt->Set(kTiltSetpoint45); + Wait(kTiltTime); + EXPECT_NEAR(-std::sqrt(0.5), m_spiAccel->GetX(), kAccelerometerTolerance); + EXPECT_NEAR(0.0, m_spiAccel->GetY(), kAccelerometerTolerance); + EXPECT_NEAR(std::sqrt(0.5), m_spiAccel->GetZ(), kAccelerometerTolerance); - m_tilt->Set(kTiltSetpoint90); - Wait(kTiltTime); - EXPECT_NEAR(0.0, m_spiAccel->GetX(), kAccelerometerTolerance); - EXPECT_NEAR(0.0, m_spiAccel->GetY(), kAccelerometerTolerance); - EXPECT_NEAR(1.0, m_spiAccel->GetZ(), kAccelerometerTolerance); + m_tilt->Set(kTiltSetpoint90); + Wait(kTiltTime); + EXPECT_NEAR(0.0, m_spiAccel->GetX(), kAccelerometerTolerance); + EXPECT_NEAR(0.0, m_spiAccel->GetY(), kAccelerometerTolerance); + EXPECT_NEAR(1.0, m_spiAccel->GetZ(), kAccelerometerTolerance); } diff --git a/wpilibc/wpilibC++IntegrationTests/src/TimerTest.cpp b/wpilibc/wpilibC++IntegrationTests/src/TimerTest.cpp index 298dabe740..8a4c0a7d10 100644 --- a/wpilibc/wpilibC++IntegrationTests/src/TimerTest.cpp +++ b/wpilibc/wpilibC++IntegrationTests/src/TimerTest.cpp @@ -12,34 +12,27 @@ static const double kWaitTime = 0.5; class TimerTest : public testing::Test { -protected: - Timer *m_timer; - - virtual void SetUp() override { - m_timer = new Timer; - } - - virtual void TearDown() override { - delete m_timer; - } - - void Reset() { - m_timer->Reset(); - } + protected: + Timer *m_timer; + + virtual void SetUp() override { m_timer = new Timer; } + + virtual void TearDown() override { delete m_timer; } + + void Reset() { m_timer->Reset(); } }; /** * Test if the Wait function works */ TEST_F(TimerTest, Wait) { - Reset(); - - double initialTime = m_timer->GetFPGATimestamp(); - - Wait(kWaitTime); - - double finalTime = m_timer->GetFPGATimestamp(); - - EXPECT_NEAR(kWaitTime, finalTime - initialTime, 0.001); -} + Reset(); + double initialTime = m_timer->GetFPGATimestamp(); + + Wait(kWaitTime); + + double finalTime = m_timer->GetFPGATimestamp(); + + EXPECT_NEAR(kWaitTime, finalTime - initialTime, 0.001); +} diff --git a/wpilibc/wpilibC++IntegrationTests/src/command/CommandTest.cpp b/wpilibc/wpilibC++IntegrationTests/src/command/CommandTest.cpp index 2a0b59eaef..9c7ede98ce 100644 --- a/wpilibc/wpilibC++IntegrationTests/src/command/CommandTest.cpp +++ b/wpilibc/wpilibC++IntegrationTests/src/command/CommandTest.cpp @@ -12,450 +12,427 @@ #include "DriverStation.h" class CommandTest : public testing::Test { -protected: - virtual void SetUp() override { - RobotState::SetImplementation(DriverStation::GetInstance()); - Scheduler::GetInstance()->SetEnabled(true); - } + protected: + virtual void SetUp() override { + RobotState::SetImplementation(DriverStation::GetInstance()); + Scheduler::GetInstance()->SetEnabled(true); + } - /** - * Tears Down the Scheduler at the end of each test. - * Must be called at the end of each test inside each test in order to prevent them being deallocated - * when they leave the scope of the test (causing a segfault). - * This can not be done within the virtual void Teardown() method because it is called outside of the - * scope of the test. - */ - void TeardownScheduler(){ - Scheduler::GetInstance()->ResetAll(); - } - - void AssertCommandState(MockCommand &command, int initialize, int execute, int isFinished, int end, int interrupted){ - EXPECT_EQ(initialize, command.GetInitializeCount()); - EXPECT_EQ(execute, command.GetExecuteCount()); - EXPECT_EQ(isFinished, command.GetIsFinishedCount()); - EXPECT_EQ(end, command.GetEndCount()); - EXPECT_EQ(interrupted, command.GetInterruptedCount()); - } + /** + * Tears Down the Scheduler at the end of each test. + * Must be called at the end of each test inside each test in order to prevent + * them being deallocated + * when they leave the scope of the test (causing a segfault). + * This can not be done within the virtual void Teardown() method because it + * is called outside of the + * scope of the test. + */ + void TeardownScheduler() { Scheduler::GetInstance()->ResetAll(); } + void AssertCommandState(MockCommand &command, int initialize, int execute, + int isFinished, int end, int interrupted) { + EXPECT_EQ(initialize, command.GetInitializeCount()); + EXPECT_EQ(execute, command.GetExecuteCount()); + EXPECT_EQ(isFinished, command.GetIsFinishedCount()); + EXPECT_EQ(end, command.GetEndCount()); + EXPECT_EQ(interrupted, command.GetInterruptedCount()); + } }; -class ASubsystem : public Subsystem{ -private: - Command *m_command; -public: - ASubsystem(const char *name): - Subsystem(name) - { - m_command = NULL; - } +class ASubsystem : public Subsystem { + private: + Command *m_command; - virtual void InitDefaultCommand() override { - if(m_command != NULL){ - SetDefaultCommand(m_command); - } - } + public: + ASubsystem(const char *name) : Subsystem(name) { m_command = NULL; } - void Init(Command *command){ - m_command = command; - } + virtual void InitDefaultCommand() override { + if (m_command != NULL) { + SetDefaultCommand(m_command); + } + } + void Init(Command *command) { m_command = command; } }; -//CommandParallelGroupTest ported from CommandParallelGroupTest.java -TEST_F(CommandTest, ParallelCommands){ - MockCommand command1; - MockCommand command2; - CommandGroup commandGroup; +// CommandParallelGroupTest ported from CommandParallelGroupTest.java +TEST_F(CommandTest, ParallelCommands) { + MockCommand command1; + MockCommand command2; + CommandGroup commandGroup; - commandGroup.AddParallel(&command1); - commandGroup.AddParallel(&command2); + commandGroup.AddParallel(&command1); + commandGroup.AddParallel(&command2); - AssertCommandState(command1, 0, 0, 0, 0, 0); - AssertCommandState(command2, 0, 0, 0, 0, 0); - commandGroup.Start(); - AssertCommandState(command1, 0, 0, 0, 0, 0); - AssertCommandState(command2, 0, 0, 0, 0, 0); - Scheduler::GetInstance()->Run(); - AssertCommandState(command1, 0, 0, 0, 0, 0); - AssertCommandState(command2, 0, 0, 0, 0, 0); - Scheduler::GetInstance()->Run(); - AssertCommandState(command1, 1, 1, 1, 0, 0); - AssertCommandState(command2, 1, 1, 1, 0, 0); - Scheduler::GetInstance()->Run(); - AssertCommandState(command1, 1, 2, 2, 0, 0); - AssertCommandState(command2, 1, 2, 2, 0, 0); - command1.SetHasFinished(true); - Scheduler::GetInstance()->Run(); - AssertCommandState(command1, 1, 3, 3, 1, 0); - AssertCommandState(command2, 1, 3, 3, 0, 0); - Scheduler::GetInstance()->Run(); - AssertCommandState(command1, 1, 3, 3, 1, 0); - AssertCommandState(command2, 1, 4, 4, 0, 0); - command2.SetHasFinished(true); - Scheduler::GetInstance()->Run(); - AssertCommandState(command1, 1, 3, 3, 1, 0); - AssertCommandState(command2, 1, 5, 5, 1, 0); + AssertCommandState(command1, 0, 0, 0, 0, 0); + AssertCommandState(command2, 0, 0, 0, 0, 0); + commandGroup.Start(); + AssertCommandState(command1, 0, 0, 0, 0, 0); + AssertCommandState(command2, 0, 0, 0, 0, 0); + Scheduler::GetInstance()->Run(); + AssertCommandState(command1, 0, 0, 0, 0, 0); + AssertCommandState(command2, 0, 0, 0, 0, 0); + Scheduler::GetInstance()->Run(); + AssertCommandState(command1, 1, 1, 1, 0, 0); + AssertCommandState(command2, 1, 1, 1, 0, 0); + Scheduler::GetInstance()->Run(); + AssertCommandState(command1, 1, 2, 2, 0, 0); + AssertCommandState(command2, 1, 2, 2, 0, 0); + command1.SetHasFinished(true); + Scheduler::GetInstance()->Run(); + AssertCommandState(command1, 1, 3, 3, 1, 0); + AssertCommandState(command2, 1, 3, 3, 0, 0); + Scheduler::GetInstance()->Run(); + AssertCommandState(command1, 1, 3, 3, 1, 0); + AssertCommandState(command2, 1, 4, 4, 0, 0); + command2.SetHasFinished(true); + Scheduler::GetInstance()->Run(); + AssertCommandState(command1, 1, 3, 3, 1, 0); + AssertCommandState(command2, 1, 5, 5, 1, 0); - TeardownScheduler(); + TeardownScheduler(); } -//END CommandParallelGroupTest +// END CommandParallelGroupTest -//CommandScheduleTest ported from CommandScheduleTest.java -TEST_F(CommandTest, RunAndTerminate){ - MockCommand command; - command.Start(); - AssertCommandState(command, 0, 0, 0, 0, 0); - Scheduler::GetInstance()->Run(); - AssertCommandState(command, 0, 0, 0, 0, 0); - Scheduler::GetInstance()->Run(); - AssertCommandState(command, 1, 1, 1, 0, 0); - Scheduler::GetInstance()->Run(); - AssertCommandState(command, 1, 2, 2, 0, 0); - command.SetHasFinished(true); - AssertCommandState(command, 1, 2, 2, 0, 0); - Scheduler::GetInstance()->Run(); - AssertCommandState(command, 1, 3, 3, 1, 0); - Scheduler::GetInstance()->Run(); - AssertCommandState(command, 1, 3, 3, 1, 0); +// CommandScheduleTest ported from CommandScheduleTest.java +TEST_F(CommandTest, RunAndTerminate) { + MockCommand command; + command.Start(); + AssertCommandState(command, 0, 0, 0, 0, 0); + Scheduler::GetInstance()->Run(); + AssertCommandState(command, 0, 0, 0, 0, 0); + Scheduler::GetInstance()->Run(); + AssertCommandState(command, 1, 1, 1, 0, 0); + Scheduler::GetInstance()->Run(); + AssertCommandState(command, 1, 2, 2, 0, 0); + command.SetHasFinished(true); + AssertCommandState(command, 1, 2, 2, 0, 0); + Scheduler::GetInstance()->Run(); + AssertCommandState(command, 1, 3, 3, 1, 0); + Scheduler::GetInstance()->Run(); + AssertCommandState(command, 1, 3, 3, 1, 0); - TeardownScheduler(); + TeardownScheduler(); } -TEST_F(CommandTest, RunAndCancel){ - MockCommand command; - command.Start(); - AssertCommandState(command, 0, 0, 0, 0, 0); - Scheduler::GetInstance()->Run(); - AssertCommandState(command, 0, 0, 0, 0, 0); - Scheduler::GetInstance()->Run(); - AssertCommandState(command, 1, 1, 1, 0, 0); - Scheduler::GetInstance()->Run(); - AssertCommandState(command, 1, 2, 2, 0, 0); - Scheduler::GetInstance()->Run(); - AssertCommandState(command, 1, 3, 3, 0, 0); - command.Cancel(); - AssertCommandState(command, 1, 3, 3, 0, 0); - Scheduler::GetInstance()->Run(); - AssertCommandState(command, 1, 3, 3, 0, 1); - Scheduler::GetInstance()->Run(); - AssertCommandState(command, 1, 3, 3, 0, 1); +TEST_F(CommandTest, RunAndCancel) { + MockCommand command; + command.Start(); + AssertCommandState(command, 0, 0, 0, 0, 0); + Scheduler::GetInstance()->Run(); + AssertCommandState(command, 0, 0, 0, 0, 0); + Scheduler::GetInstance()->Run(); + AssertCommandState(command, 1, 1, 1, 0, 0); + Scheduler::GetInstance()->Run(); + AssertCommandState(command, 1, 2, 2, 0, 0); + Scheduler::GetInstance()->Run(); + AssertCommandState(command, 1, 3, 3, 0, 0); + command.Cancel(); + AssertCommandState(command, 1, 3, 3, 0, 0); + Scheduler::GetInstance()->Run(); + AssertCommandState(command, 1, 3, 3, 0, 1); + Scheduler::GetInstance()->Run(); + AssertCommandState(command, 1, 3, 3, 0, 1); - TeardownScheduler(); + TeardownScheduler(); } -//END CommandScheduleTest +// END CommandScheduleTest -//CommandSequentialGroupTest ported from CommandSequentialGroupTest.java -TEST_F(CommandTest, ThreeCommandOnSubSystem){ - ASubsystem subsystem("Three Command Test Subsystem"); - MockCommand command1; - command1.Requires(&subsystem); - MockCommand command2; - command2.Requires(&subsystem); - MockCommand command3; - command3.Requires(&subsystem); +// CommandSequentialGroupTest ported from CommandSequentialGroupTest.java +TEST_F(CommandTest, ThreeCommandOnSubSystem) { + ASubsystem subsystem("Three Command Test Subsystem"); + MockCommand command1; + command1.Requires(&subsystem); + MockCommand command2; + command2.Requires(&subsystem); + MockCommand command3; + command3.Requires(&subsystem); + CommandGroup commandGroup; + commandGroup.AddSequential(&command1, 1.0); + commandGroup.AddSequential(&command2, 2.0); + commandGroup.AddSequential(&command3); - CommandGroup commandGroup; - commandGroup.AddSequential(&command1, 1.0 ); - commandGroup.AddSequential(&command2, 2.0 ); - commandGroup.AddSequential(&command3); + AssertCommandState(command1, 0, 0, 0, 0, 0); + AssertCommandState(command2, 0, 0, 0, 0, 0); + AssertCommandState(command3, 0, 0, 0, 0, 0); - AssertCommandState(command1, 0, 0, 0, 0, 0); - AssertCommandState(command2, 0, 0, 0, 0, 0); - AssertCommandState(command3, 0, 0, 0, 0, 0); + commandGroup.Start(); + AssertCommandState(command1, 0, 0, 0, 0, 0); + AssertCommandState(command2, 0, 0, 0, 0, 0); + AssertCommandState(command3, 0, 0, 0, 0, 0); - commandGroup.Start(); - AssertCommandState(command1, 0, 0, 0, 0, 0); - AssertCommandState(command2, 0, 0, 0, 0, 0); - AssertCommandState(command3, 0, 0, 0, 0, 0); + Scheduler::GetInstance()->Run(); + AssertCommandState(command1, 0, 0, 0, 0, 0); + AssertCommandState(command2, 0, 0, 0, 0, 0); + AssertCommandState(command3, 0, 0, 0, 0, 0); - Scheduler::GetInstance()->Run(); - AssertCommandState(command1, 0, 0, 0, 0, 0); - AssertCommandState(command2, 0, 0, 0, 0, 0); - AssertCommandState(command3, 0, 0, 0, 0, 0); + Scheduler::GetInstance()->Run(); + AssertCommandState(command1, 1, 1, 1, 0, 0); + AssertCommandState(command2, 0, 0, 0, 0, 0); + AssertCommandState(command3, 0, 0, 0, 0, 0); + Wait(1); // command 1 timeout - Scheduler::GetInstance()->Run(); - AssertCommandState(command1, 1, 1, 1, 0, 0); - AssertCommandState(command2, 0, 0, 0, 0, 0); - AssertCommandState(command3, 0, 0, 0, 0, 0); - Wait(1);//command 1 timeout + Scheduler::GetInstance()->Run(); + AssertCommandState(command1, 1, 1, 1, 0, 1); + AssertCommandState(command2, 1, 1, 1, 0, 0); + AssertCommandState(command3, 0, 0, 0, 0, 0); - Scheduler::GetInstance()->Run(); - AssertCommandState(command1, 1, 1, 1, 0, 1); - AssertCommandState(command2, 1, 1, 1, 0, 0); - AssertCommandState(command3, 0, 0, 0, 0, 0); + Scheduler::GetInstance()->Run(); + AssertCommandState(command1, 1, 1, 1, 0, 1); + AssertCommandState(command2, 1, 2, 2, 0, 0); + AssertCommandState(command3, 0, 0, 0, 0, 0); + Wait(2); // command 2 timeout - Scheduler::GetInstance()->Run(); - AssertCommandState(command1, 1, 1, 1, 0, 1); - AssertCommandState(command2, 1, 2, 2, 0, 0); - AssertCommandState(command3, 0, 0, 0, 0, 0); - Wait(2);//command 2 timeout + Scheduler::GetInstance()->Run(); + AssertCommandState(command1, 1, 1, 1, 0, 1); + AssertCommandState(command2, 1, 2, 2, 0, 1); + AssertCommandState(command3, 1, 1, 1, 0, 0); - Scheduler::GetInstance()->Run(); - AssertCommandState(command1, 1, 1, 1, 0, 1); - AssertCommandState(command2, 1, 2, 2, 0, 1); - AssertCommandState(command3, 1, 1 ,1, 0, 0); + Scheduler::GetInstance()->Run(); + AssertCommandState(command1, 1, 1, 1, 0, 1); + AssertCommandState(command2, 1, 2, 2, 0, 1); + AssertCommandState(command3, 1, 2, 2, 0, 0); + command3.SetHasFinished(true); + AssertCommandState(command1, 1, 1, 1, 0, 1); + AssertCommandState(command2, 1, 2, 2, 0, 1); + AssertCommandState(command3, 1, 2, 2, 0, 0); + Scheduler::GetInstance()->Run(); + AssertCommandState(command1, 1, 1, 1, 0, 1); + AssertCommandState(command2, 1, 2, 2, 0, 1); + AssertCommandState(command3, 1, 3, 3, 1, 0); - Scheduler::GetInstance()->Run(); - AssertCommandState(command1, 1, 1, 1, 0, 1); - AssertCommandState(command2, 1, 2, 2, 0, 1); - AssertCommandState(command3, 1, 2, 2, 0, 0); - command3.SetHasFinished(true); - AssertCommandState(command1, 1, 1, 1, 0, 1); - AssertCommandState(command2, 1, 2, 2, 0, 1); - AssertCommandState(command3, 1, 2, 2, 0, 0); + Scheduler::GetInstance()->Run(); + AssertCommandState(command1, 1, 1, 1, 0, 1); + AssertCommandState(command2, 1, 2, 2, 0, 1); + AssertCommandState(command3, 1, 3, 3, 1, 0); - Scheduler::GetInstance()->Run(); - AssertCommandState(command1, 1, 1, 1, 0, 1); - AssertCommandState(command2, 1, 2, 2, 0, 1); - AssertCommandState(command3, 1, 3, 3, 1, 0); - - Scheduler::GetInstance()->Run(); - AssertCommandState(command1, 1, 1, 1, 0, 1); - AssertCommandState(command2, 1, 2, 2, 0, 1); - AssertCommandState(command3, 1, 3, 3, 1, 0); - - - TeardownScheduler(); + TeardownScheduler(); } -//END CommandSequentialGroupTest +// END CommandSequentialGroupTest +// CommandSequentialGroupTest ported from CommandSequentialGroupTest.java +TEST_F(CommandTest, OneCommandSupersedingAnotherBecauseOfDependencies) { + ASubsystem *subsystem = new ASubsystem("Command Superseding Test Subsystem"); + MockCommand command1; + command1.Requires(subsystem); + MockCommand command2; + command2.Requires(subsystem); -//CommandSequentialGroupTest ported from CommandSequentialGroupTest.java -TEST_F(CommandTest, OneCommandSupersedingAnotherBecauseOfDependencies){ - ASubsystem* subsystem = new ASubsystem("Command Superseding Test Subsystem"); - MockCommand command1; - command1.Requires(subsystem); - MockCommand command2; - command2.Requires(subsystem); + AssertCommandState(command1, 0, 0, 0, 0, 0); + AssertCommandState(command2, 0, 0, 0, 0, 0); + command1.Start(); + AssertCommandState(command1, 0, 0, 0, 0, 0); + AssertCommandState(command2, 0, 0, 0, 0, 0); - AssertCommandState(command1, 0, 0, 0, 0, 0); - AssertCommandState(command2, 0, 0, 0, 0, 0); + Scheduler::GetInstance()->Run(); + AssertCommandState(command1, 0, 0, 0, 0, 0); + AssertCommandState(command2, 0, 0, 0, 0, 0); - command1.Start(); - AssertCommandState(command1, 0, 0, 0, 0, 0); - AssertCommandState(command2, 0, 0, 0, 0, 0); + Scheduler::GetInstance()->Run(); + AssertCommandState(command1, 1, 1, 1, 0, 0); + AssertCommandState(command2, 0, 0, 0, 0, 0); - Scheduler::GetInstance()->Run(); - AssertCommandState(command1, 0, 0, 0, 0, 0); - AssertCommandState(command2, 0, 0, 0, 0, 0); + Scheduler::GetInstance()->Run(); + AssertCommandState(command1, 1, 2, 2, 0, 0); + AssertCommandState(command2, 0, 0, 0, 0, 0); - Scheduler::GetInstance()->Run(); - AssertCommandState(command1, 1, 1, 1, 0, 0); - AssertCommandState(command2, 0, 0, 0, 0, 0); + Scheduler::GetInstance()->Run(); + AssertCommandState(command1, 1, 3, 3, 0, 0); + AssertCommandState(command2, 0, 0, 0, 0, 0); - Scheduler::GetInstance()->Run(); - AssertCommandState(command1, 1, 2, 2, 0, 0); - AssertCommandState(command2, 0, 0, 0, 0, 0); + command2.Start(); + AssertCommandState(command1, 1, 3, 3, 0, 0); + AssertCommandState(command2, 0, 0, 0, 0, 0); - Scheduler::GetInstance()->Run(); - AssertCommandState(command1, 1, 3, 3, 0, 0); - AssertCommandState(command2, 0, 0, 0, 0, 0); + Scheduler::GetInstance()->Run(); + AssertCommandState(command1, 1, 4, 4, 0, 1); + AssertCommandState(command2, 0, 0, 0, 0, 0); - command2.Start(); - AssertCommandState(command1, 1, 3, 3, 0, 0); - AssertCommandState(command2, 0, 0, 0, 0, 0); + Scheduler::GetInstance()->Run(); + AssertCommandState(command1, 1, 4, 4, 0, 1); + AssertCommandState(command2, 1, 1, 1, 0, 0); - Scheduler::GetInstance()->Run(); - AssertCommandState(command1, 1, 4, 4, 0, 1); - AssertCommandState(command2, 0, 0, 0, 0, 0); + Scheduler::GetInstance()->Run(); + AssertCommandState(command1, 1, 4, 4, 0, 1); + AssertCommandState(command2, 1, 2, 2, 0, 0); - Scheduler::GetInstance()->Run(); - AssertCommandState(command1, 1, 4, 4, 0, 1); - AssertCommandState(command2, 1, 1, 1, 0, 0); + Scheduler::GetInstance()->Run(); + AssertCommandState(command1, 1, 4, 4, 0, 1); + AssertCommandState(command2, 1, 3, 3, 0, 0); - Scheduler::GetInstance()->Run(); - AssertCommandState(command1, 1, 4, 4, 0, 1); - AssertCommandState(command2, 1, 2, 2, 0, 0); - - Scheduler::GetInstance()->Run(); - AssertCommandState(command1, 1, 4, 4, 0, 1); - AssertCommandState(command2, 1, 3, 3, 0, 0); - - - TeardownScheduler(); + TeardownScheduler(); } +TEST_F(CommandTest, + OneCommandFailingSupersedingBecauseFirstCanNotBeInterrupted) { + ASubsystem subsystem("Command Superseding Test Subsystem"); + MockCommand command1; -TEST_F(CommandTest, OneCommandFailingSupersedingBecauseFirstCanNotBeInterrupted){ + command1.Requires(&subsystem); - ASubsystem subsystem("Command Superseding Test Subsystem"); - MockCommand command1; + command1.SetInterruptible(false); + MockCommand command2; + command2.Requires(&subsystem); - command1.Requires(&subsystem); + AssertCommandState(command1, 0, 0, 0, 0, 0); + AssertCommandState(command2, 0, 0, 0, 0, 0); - command1.SetInterruptible(false); - MockCommand command2; - command2.Requires(&subsystem); + command1.Start(); + AssertCommandState(command1, 0, 0, 0, 0, 0); + AssertCommandState(command2, 0, 0, 0, 0, 0); + Scheduler::GetInstance()->Run(); + AssertCommandState(command1, 0, 0, 0, 0, 0); + AssertCommandState(command2, 0, 0, 0, 0, 0); - AssertCommandState(command1, 0, 0, 0, 0, 0); - AssertCommandState(command2, 0, 0, 0, 0, 0); + Scheduler::GetInstance()->Run(); + AssertCommandState(command1, 1, 1, 1, 0, 0); + AssertCommandState(command2, 0, 0, 0, 0, 0); - command1.Start(); - AssertCommandState(command1, 0, 0, 0, 0, 0); - AssertCommandState(command2, 0, 0, 0, 0, 0); + Scheduler::GetInstance()->Run(); + AssertCommandState(command1, 1, 2, 2, 0, 0); + AssertCommandState(command2, 0, 0, 0, 0, 0); - Scheduler::GetInstance()->Run(); - AssertCommandState(command1, 0, 0, 0, 0, 0); - AssertCommandState(command2, 0, 0, 0, 0, 0); + Scheduler::GetInstance()->Run(); + AssertCommandState(command1, 1, 3, 3, 0, 0); + AssertCommandState(command2, 0, 0, 0, 0, 0); - Scheduler::GetInstance()->Run(); - AssertCommandState(command1, 1, 1, 1, 0, 0); - AssertCommandState(command2, 0, 0, 0, 0, 0); + command2.Start(); + AssertCommandState(command1, 1, 3, 3, 0, 0); + AssertCommandState(command2, 0, 0, 0, 0, 0); - Scheduler::GetInstance()->Run(); - AssertCommandState(command1, 1, 2, 2, 0, 0); - AssertCommandState(command2, 0, 0, 0, 0, 0); + Scheduler::GetInstance()->Run(); + AssertCommandState(command1, 1, 4, 4, 0, 0); + AssertCommandState(command2, 0, 0, 0, 0, 0); - Scheduler::GetInstance()->Run(); - AssertCommandState(command1, 1, 3, 3, 0, 0); - AssertCommandState(command2, 0, 0, 0, 0, 0); - - command2.Start(); - AssertCommandState(command1, 1, 3, 3, 0, 0); - AssertCommandState(command2, 0, 0, 0, 0, 0); - - Scheduler::GetInstance()->Run(); - AssertCommandState(command1, 1, 4, 4, 0, 0); - AssertCommandState(command2, 0, 0, 0, 0, 0); - - TeardownScheduler(); + TeardownScheduler(); } -//END CommandSequentialGroupTest +// END CommandSequentialGroupTest -class ModifiedMockCommand : public MockCommand{ -public: - ModifiedMockCommand(): - MockCommand() - { - SetTimeout(2.0); - } - bool IsFinished() override { - return MockCommand::IsFinished() || IsTimedOut(); - } +class ModifiedMockCommand : public MockCommand { + public: + ModifiedMockCommand() : MockCommand() { SetTimeout(2.0); } + bool IsFinished() override { + return MockCommand::IsFinished() || IsTimedOut(); + } }; +TEST_F(CommandTest, TwoSecondTimeout) { + ASubsystem subsystem("Two Second Timeout Test Subsystem"); + ModifiedMockCommand command; + command.Requires(&subsystem); -TEST_F(CommandTest, TwoSecondTimeout){ - ASubsystem subsystem("Two Second Timeout Test Subsystem"); - ModifiedMockCommand command; - command.Requires(&subsystem); + command.Start(); + AssertCommandState(command, 0, 0, 0, 0, 0); + Scheduler::GetInstance()->Run(); + AssertCommandState(command, 0, 0, 0, 0, 0); + Scheduler::GetInstance()->Run(); + AssertCommandState(command, 1, 1, 1, 0, 0); + Scheduler::GetInstance()->Run(); + AssertCommandState(command, 1, 2, 2, 0, 0); + Scheduler::GetInstance()->Run(); + AssertCommandState(command, 1, 3, 3, 0, 0); + Wait(2); + Scheduler::GetInstance()->Run(); + AssertCommandState(command, 1, 4, 4, 1, 0); + Scheduler::GetInstance()->Run(); + AssertCommandState(command, 1, 4, 4, 1, 0); - command.Start(); - AssertCommandState(command, 0, 0, 0, 0, 0); - Scheduler::GetInstance()->Run(); - AssertCommandState(command, 0, 0, 0, 0, 0); - Scheduler::GetInstance()->Run(); - AssertCommandState(command, 1, 1, 1, 0, 0); - Scheduler::GetInstance()->Run(); - AssertCommandState(command, 1, 2, 2, 0, 0); - Scheduler::GetInstance()->Run(); - AssertCommandState(command, 1, 3, 3, 0, 0); - Wait(2); - Scheduler::GetInstance()->Run(); - AssertCommandState(command, 1, 4, 4, 1, 0); - Scheduler::GetInstance()->Run(); - AssertCommandState(command, 1, 4, 4, 1, 0); - - TeardownScheduler(); + TeardownScheduler(); } +TEST_F(CommandTest, DefaultCommandWhereTheInteruptingCommandEndsItself) { + ASubsystem subsystem("Default Command Test Subsystem"); + MockCommand defaultCommand; + defaultCommand.Requires(&subsystem); + MockCommand anotherCommand; + anotherCommand.Requires(&subsystem); + AssertCommandState(defaultCommand, 0, 0, 0, 0, 0); + subsystem.Init(&defaultCommand); -TEST_F(CommandTest, DefaultCommandWhereTheInteruptingCommandEndsItself){ - ASubsystem subsystem("Default Command Test Subsystem"); - MockCommand defaultCommand; - defaultCommand.Requires(&subsystem); - MockCommand anotherCommand; - anotherCommand.Requires(&subsystem); + AssertCommandState(defaultCommand, 0, 0, 0, 0, 0); + Scheduler::GetInstance()->Run(); + AssertCommandState(defaultCommand, 0, 0, 0, 0, 0); + Scheduler::GetInstance()->Run(); + AssertCommandState(defaultCommand, 1, 1, 1, 0, 0); + Scheduler::GetInstance()->Run(); + AssertCommandState(defaultCommand, 1, 2, 2, 0, 0); - AssertCommandState(defaultCommand, 0, 0, 0, 0, 0); - subsystem.Init(&defaultCommand); + anotherCommand.Start(); + AssertCommandState(defaultCommand, 1, 2, 2, 0, 0); + AssertCommandState(anotherCommand, 0, 0, 0, 0, 0); + Scheduler::GetInstance()->Run(); + AssertCommandState(defaultCommand, 1, 3, 3, 0, 1); + AssertCommandState(anotherCommand, 0, 0, 0, 0, 0); + Scheduler::GetInstance()->Run(); + AssertCommandState(defaultCommand, 1, 3, 3, 0, 1); + AssertCommandState(anotherCommand, 1, 1, 1, 0, 0); + Scheduler::GetInstance()->Run(); + AssertCommandState(defaultCommand, 1, 3, 3, 0, 1); + AssertCommandState(anotherCommand, 1, 2, 2, 0, 0); + anotherCommand.SetHasFinished(true); + AssertCommandState(defaultCommand, 1, 3, 3, 0, 1); + AssertCommandState(anotherCommand, 1, 2, 2, 0, 0); + Scheduler::GetInstance()->Run(); + AssertCommandState(defaultCommand, 1, 3, 3, 0, 1); + AssertCommandState(anotherCommand, 1, 3, 3, 1, 0); + Scheduler::GetInstance()->Run(); + AssertCommandState(defaultCommand, 2, 4, 4, 0, 1); + AssertCommandState(anotherCommand, 1, 3, 3, 1, 0); + Scheduler::GetInstance()->Run(); + AssertCommandState(defaultCommand, 2, 5, 5, 0, 1); + AssertCommandState(anotherCommand, 1, 3, 3, 1, 0); - AssertCommandState(defaultCommand, 0, 0, 0, 0, 0); - Scheduler::GetInstance()->Run(); - AssertCommandState(defaultCommand, 0, 0, 0, 0, 0); - Scheduler::GetInstance()->Run(); - AssertCommandState(defaultCommand, 1, 1, 1, 0, 0); - Scheduler::GetInstance()->Run(); - AssertCommandState(defaultCommand, 1, 2, 2, 0, 0); - - anotherCommand.Start(); - AssertCommandState(defaultCommand, 1, 2, 2, 0, 0); - AssertCommandState(anotherCommand, 0, 0, 0, 0, 0); - Scheduler::GetInstance()->Run(); - AssertCommandState(defaultCommand, 1, 3, 3, 0, 1); - AssertCommandState(anotherCommand, 0, 0, 0, 0, 0); - Scheduler::GetInstance()->Run(); - AssertCommandState(defaultCommand, 1, 3, 3, 0, 1); - AssertCommandState(anotherCommand, 1, 1, 1, 0, 0); - Scheduler::GetInstance()->Run(); - AssertCommandState(defaultCommand, 1, 3, 3, 0, 1); - AssertCommandState(anotherCommand, 1, 2, 2, 0, 0); - anotherCommand.SetHasFinished(true); - AssertCommandState(defaultCommand, 1, 3, 3, 0, 1); - AssertCommandState(anotherCommand, 1, 2, 2, 0, 0); - Scheduler::GetInstance()->Run(); - AssertCommandState(defaultCommand, 1, 3, 3, 0, 1); - AssertCommandState(anotherCommand, 1, 3, 3, 1, 0); - Scheduler::GetInstance()->Run(); - AssertCommandState(defaultCommand, 2, 4, 4, 0, 1); - AssertCommandState(anotherCommand, 1, 3, 3, 1, 0); - Scheduler::GetInstance()->Run(); - AssertCommandState(defaultCommand, 2, 5, 5, 0, 1); - AssertCommandState(anotherCommand, 1, 3, 3, 1, 0); - - TeardownScheduler(); + TeardownScheduler(); } +TEST_F(CommandTest, DefaultCommandsInterruptingCommandCanceled) { + ASubsystem subsystem("Default Command Test Subsystem"); + MockCommand defaultCommand; + defaultCommand.Requires(&subsystem); + MockCommand anotherCommand; + anotherCommand.Requires(&subsystem); + AssertCommandState(defaultCommand, 0, 0, 0, 0, 0); + subsystem.Init(&defaultCommand); + subsystem.InitDefaultCommand(); + AssertCommandState(defaultCommand, 0, 0, 0, 0, 0); + Scheduler::GetInstance()->Run(); + AssertCommandState(defaultCommand, 0, 0, 0, 0, 0); + Scheduler::GetInstance()->Run(); + AssertCommandState(defaultCommand, 1, 1, 1, 0, 0); + Scheduler::GetInstance()->Run(); + AssertCommandState(defaultCommand, 1, 2, 2, 0, 0); -TEST_F(CommandTest, DefaultCommandsInterruptingCommandCanceled){ - ASubsystem subsystem("Default Command Test Subsystem"); - MockCommand defaultCommand; - defaultCommand.Requires(&subsystem); - MockCommand anotherCommand; - anotherCommand.Requires(&subsystem); + anotherCommand.Start(); + AssertCommandState(defaultCommand, 1, 2, 2, 0, 0); + AssertCommandState(anotherCommand, 0, 0, 0, 0, 0); + Scheduler::GetInstance()->Run(); + AssertCommandState(defaultCommand, 1, 3, 3, 0, 1); + AssertCommandState(anotherCommand, 0, 0, 0, 0, 0); + Scheduler::GetInstance()->Run(); + AssertCommandState(defaultCommand, 1, 3, 3, 0, 1); + AssertCommandState(anotherCommand, 1, 1, 1, 0, 0); + Scheduler::GetInstance()->Run(); + AssertCommandState(defaultCommand, 1, 3, 3, 0, 1); + AssertCommandState(anotherCommand, 1, 2, 2, 0, 0); + anotherCommand.Cancel(); + AssertCommandState(defaultCommand, 1, 3, 3, 0, 1); + AssertCommandState(anotherCommand, 1, 2, 2, 0, 0); + Scheduler::GetInstance()->Run(); + AssertCommandState(defaultCommand, 1, 3, 3, 0, 1); + AssertCommandState(anotherCommand, 1, 2, 2, 0, 1); + Scheduler::GetInstance()->Run(); + AssertCommandState(defaultCommand, 2, 4, 4, 0, 1); + AssertCommandState(anotherCommand, 1, 2, 2, 0, 1); + Scheduler::GetInstance()->Run(); + AssertCommandState(defaultCommand, 2, 5, 5, 0, 1); + AssertCommandState(anotherCommand, 1, 2, 2, 0, 1); - AssertCommandState(defaultCommand, 0, 0, 0, 0, 0); - subsystem.Init(&defaultCommand); - subsystem.InitDefaultCommand(); - AssertCommandState(defaultCommand, 0, 0, 0, 0, 0); - Scheduler::GetInstance()->Run(); - AssertCommandState(defaultCommand, 0, 0, 0, 0, 0); - Scheduler::GetInstance()->Run(); - AssertCommandState(defaultCommand, 1, 1, 1, 0, 0); - Scheduler::GetInstance()->Run(); - AssertCommandState(defaultCommand, 1, 2, 2, 0, 0); - - anotherCommand.Start(); - AssertCommandState(defaultCommand, 1, 2, 2, 0, 0); - AssertCommandState(anotherCommand, 0, 0, 0, 0, 0); - Scheduler::GetInstance()->Run(); - AssertCommandState(defaultCommand, 1, 3, 3, 0, 1); - AssertCommandState(anotherCommand, 0, 0, 0, 0, 0); - Scheduler::GetInstance()->Run(); - AssertCommandState(defaultCommand, 1, 3, 3, 0, 1); - AssertCommandState(anotherCommand, 1, 1, 1, 0, 0); - Scheduler::GetInstance()->Run(); - AssertCommandState(defaultCommand, 1, 3, 3, 0, 1); - AssertCommandState(anotherCommand, 1, 2, 2, 0, 0); - anotherCommand.Cancel(); - AssertCommandState(defaultCommand, 1, 3, 3, 0, 1); - AssertCommandState(anotherCommand, 1, 2, 2, 0, 0); - Scheduler::GetInstance()->Run(); - AssertCommandState(defaultCommand, 1, 3, 3, 0, 1); - AssertCommandState(anotherCommand, 1, 2, 2, 0, 1); - Scheduler::GetInstance()->Run(); - AssertCommandState(defaultCommand, 2, 4, 4, 0, 1); - AssertCommandState(anotherCommand, 1, 2, 2, 0, 1); - Scheduler::GetInstance()->Run(); - AssertCommandState(defaultCommand, 2, 5, 5, 0, 1); - AssertCommandState(anotherCommand, 1, 2, 2, 0, 1); - - TeardownScheduler(); + TeardownScheduler(); } diff --git a/wpilibc/wpilibC++IntegrationTests/src/command/MockCommand.cpp b/wpilibc/wpilibC++IntegrationTests/src/command/MockCommand.cpp index d8dbc8e0b4..a4d22f872d 100644 --- a/wpilibc/wpilibC++IntegrationTests/src/command/MockCommand.cpp +++ b/wpilibc/wpilibC++IntegrationTests/src/command/MockCommand.cpp @@ -7,45 +7,30 @@ #include "command/MockCommand.h" -MockCommand::MockCommand(){ - m_initializeCount = 0; - m_executeCount = 0; - m_isFinishedCount = 0; - m_hasFinished = false; - m_endCount = 0; - m_interruptedCount = 0; +MockCommand::MockCommand() { + m_initializeCount = 0; + m_executeCount = 0; + m_isFinishedCount = 0; + m_hasFinished = false; + m_endCount = 0; + m_interruptedCount = 0; } -void MockCommand::Initialize(){ - ++m_initializeCount; +void MockCommand::Initialize() { ++m_initializeCount; } + +void MockCommand::Execute() { ++m_executeCount; } + +bool MockCommand::IsFinished() { + ++m_isFinishedCount; + return IsHasFinished(); } -void MockCommand::Execute(){ - ++m_executeCount; -} +void MockCommand::End() { ++m_endCount; } -bool MockCommand::IsFinished(){ - ++m_isFinishedCount; - return IsHasFinished(); -} +void MockCommand::Interrupted() { ++m_interruptedCount; } -void MockCommand::End(){ - ++m_endCount; -} +bool MockCommand::HasInitialized() { return GetInitializeCount() > 0; } -void MockCommand::Interrupted(){ - ++m_interruptedCount; -} +bool MockCommand::HasEnd() { return GetEndCount() > 0; } - -bool MockCommand::HasInitialized(){ - return GetInitializeCount()>0; -} - -bool MockCommand::HasEnd(){ - return GetEndCount()>0; -} - -bool MockCommand::HasInterrupted(){ - return GetInterruptedCount()>0; -} +bool MockCommand::HasInterrupted() { return GetInterruptedCount() > 0; } diff --git a/wpilibj/wpilibJava/src/main/java/edu/wpi/first/wpilibj/Controller.java b/wpilibj/wpilibJava/src/main/java/edu/wpi/first/wpilibj/Controller.java index d03c926aad..6e39298bf3 100644 --- a/wpilibj/wpilibJava/src/main/java/edu/wpi/first/wpilibj/Controller.java +++ b/wpilibj/wpilibJava/src/main/java/edu/wpi/first/wpilibj/Controller.java @@ -1,6 +1,6 @@ /* - * To change this template, choose Tools | Templates - * and open the template in the editor. + * To change this template, choose Tools | Templates and open the template in + * the editor. */ package edu.wpi.first.wpilibj; @@ -12,14 +12,14 @@ package edu.wpi.first.wpilibj; * @author alex */ interface Controller { - /** - * Allows the control loop to run. - */ - public void enable(); + /** + * Allows the control loop to run. + */ + public void enable(); - /** - * Stops the control loop from running until explicitly re-enabled by calling - * {@link enable()}. - */ - public void disable(); + /** + * Stops the control loop from running until explicitly re-enabled by calling + * {@link enable()}. + */ + public void disable(); } diff --git a/wpilibj/wpilibJava/src/main/java/edu/wpi/first/wpilibj/GenericHID.java b/wpilibj/wpilibJava/src/main/java/edu/wpi/first/wpilibj/GenericHID.java index 5d929dc377..e5bd9b5e1f 100644 --- a/wpilibj/wpilibJava/src/main/java/edu/wpi/first/wpilibj/GenericHID.java +++ b/wpilibj/wpilibJava/src/main/java/edu/wpi/first/wpilibj/GenericHID.java @@ -1,8 +1,8 @@ /*----------------------------------------------------------------------------*/ -/* Copyright (c) FIRST 2008-2012. All Rights Reserved. */ -/* Open Source Software - may be modified and shared by FRC teams. The code */ +/* Copyright (c) FIRST 2008-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 the root directory of */ -/* the project. */ +/* the project. */ /*----------------------------------------------------------------------------*/ package edu.wpi.first.wpilibj; @@ -12,150 +12,166 @@ package edu.wpi.first.wpilibj; */ public abstract class GenericHID { + /** + * Which hand the Human Interface Device is associated with. + */ + public static class Hand { + /** - * Which hand the Human Interface Device is associated with. + * The integer value representing this enumeration */ - public static class Hand { + public final int value; + static final int kLeft_val = 0; + static final int kRight_val = 1; + /** + * hand: left + */ + public static final Hand kLeft = new Hand(kLeft_val); + /** + * hand: right + */ + public static final Hand kRight = new Hand(kRight_val); - /** - * The integer value representing this enumeration - */ - public final int value; - static final int kLeft_val = 0; - static final int kRight_val = 1; - /** - * hand: left - */ - public static final Hand kLeft = new Hand(kLeft_val); - /** - * hand: right - */ - public static final Hand kRight = new Hand(kRight_val); - - private Hand(int value) { - this.value = value; - } + private Hand(int value) { + this.value = value; } + } - /** - * Get the x position of the HID - * @return the x position of the HID - */ - public final double getX() { - return getX(Hand.kRight); - } + /** + * Get the x position of the HID + *$ + * @return the x position of the HID + */ + public final double getX() { + return getX(Hand.kRight); + } - /** - * Get the x position of HID - * @param hand which hand, left or right - * @return the x position - */ - public abstract double getX(Hand hand); + /** + * Get the x position of HID + *$ + * @param hand which hand, left or right + * @return the x position + */ + public abstract double getX(Hand hand); - /** - * Get the y position of the HID - * @return the y position - */ - public final double getY() { - return getY(Hand.kRight); - } + /** + * Get the y position of the HID + *$ + * @return the y position + */ + public final double getY() { + return getY(Hand.kRight); + } - /** - * Get the y position of the HID - * @param hand which hand, left or right - * @return the y position - */ - public abstract double getY(Hand hand); + /** + * Get the y position of the HID + *$ + * @param hand which hand, left or right + * @return the y position + */ + public abstract double getY(Hand hand); - /** - * Get the z position of the HID - * @return the z position - */ - public final double getZ() { - return getZ(Hand.kRight); - } + /** + * Get the z position of the HID + *$ + * @return the z position + */ + public final double getZ() { + return getZ(Hand.kRight); + } - /** - * Get the z position of the HID - * @param hand which hand, left or right - * @return the z position - */ - public abstract double getZ(Hand hand); + /** + * Get the z position of the HID + *$ + * @param hand which hand, left or right + * @return the z position + */ + public abstract double getZ(Hand hand); - /** - * Get the twist value - * @return the twist value - */ - public abstract double getTwist(); + /** + * Get the twist value + *$ + * @return the twist value + */ + public abstract double getTwist(); - /** - * Get the throttle - * @return the throttle value - */ - public abstract double getThrottle(); + /** + * Get the throttle + *$ + * @return the throttle value + */ + public abstract double getThrottle(); - /** - * Get the raw axis - * @param which index of the axis - * @return the raw value of the selected axis - */ - public abstract double getRawAxis(int which); + /** + * Get the raw axis + *$ + * @param which index of the axis + * @return the raw value of the selected axis + */ + public abstract double getRawAxis(int which); - /** - * Is the trigger pressed - * @return true if pressed - */ - public final boolean getTrigger() { - return getTrigger(Hand.kRight); - } + /** + * Is the trigger pressed + *$ + * @return true if pressed + */ + public final boolean getTrigger() { + return getTrigger(Hand.kRight); + } - /** - * Is the trigger pressed - * @param hand which hand - * @return true if the trigger for the given hand is pressed - */ - public abstract boolean getTrigger(Hand hand); + /** + * Is the trigger pressed + *$ + * @param hand which hand + * @return true if the trigger for the given hand is pressed + */ + public abstract boolean getTrigger(Hand hand); - /** - * Is the top button pressed - * @return true if the top button is pressed - */ - public final boolean getTop() { - return getTop(Hand.kRight); - } + /** + * Is the top button pressed + *$ + * @return true if the top button is pressed + */ + public final boolean getTop() { + return getTop(Hand.kRight); + } - /** - * Is the top button pressed - * @param hand which hand - * @return true if hte top button for the given hand is pressed - */ - public abstract boolean getTop(Hand hand); + /** + * Is the top button pressed + *$ + * @param hand which hand + * @return true if hte top button for the given hand is pressed + */ + public abstract boolean getTop(Hand hand); - /** - * Is the bumper pressed - * @return true if the bumper is pressed - */ - public final boolean getBumper() { - return getBumper(Hand.kRight); - } + /** + * Is the bumper pressed + *$ + * @return true if the bumper is pressed + */ + public final boolean getBumper() { + return getBumper(Hand.kRight); + } - /** - * Is the bumper pressed - * @param hand which hand - * @return true if hte bumper is pressed - */ - public abstract boolean getBumper(Hand hand); + /** + * Is the bumper pressed + *$ + * @param hand which hand + * @return true if hte bumper is pressed + */ + public abstract boolean getBumper(Hand hand); - /** - * Is the given button pressed - * @param button which button number - * @return true if the button is pressed - */ - public abstract boolean getRawButton(int button); + /** + * Is the given button pressed + *$ + * @param button which button number + * @return true if the button is pressed + */ + public abstract boolean getRawButton(int button); - public abstract int getPOV(int pov); + public abstract int getPOV(int pov); - public int getPOV() { - return getPOV(0); - } + public int getPOV() { + return getPOV(0); + } } diff --git a/wpilibj/wpilibJava/src/main/java/edu/wpi/first/wpilibj/HLUsageReporting.java b/wpilibj/wpilibJava/src/main/java/edu/wpi/first/wpilibj/HLUsageReporting.java index 83a8d4a435..5dfc243c8a 100644 --- a/wpilibj/wpilibJava/src/main/java/edu/wpi/first/wpilibj/HLUsageReporting.java +++ b/wpilibj/wpilibJava/src/main/java/edu/wpi/first/wpilibj/HLUsageReporting.java @@ -8,45 +8,49 @@ import edu.wpi.first.wpilibj.util.BaseSystemNotInitializedException; * @author alex */ public class HLUsageReporting { - private static Interface impl; + private static Interface impl; - public static void SetImplementation(Interface i) { - impl = i; - } + public static void SetImplementation(Interface i) { + impl = i; + } - public static void reportScheduler() { - if (impl != null) { - impl.reportScheduler(); - } else { - throw new BaseSystemNotInitializedException(Interface.class, HLUsageReporting.class); - } - } + public static void reportScheduler() { + if (impl != null) { + impl.reportScheduler(); + } else { + throw new BaseSystemNotInitializedException(Interface.class, HLUsageReporting.class); + } + } - public static void reportPIDController(int num) { - if (impl != null) { - impl.reportPIDController(num); - } else { - throw new BaseSystemNotInitializedException(Interface.class, HLUsageReporting.class); - } - } + public static void reportPIDController(int num) { + if (impl != null) { + impl.reportPIDController(num); + } else { + throw new BaseSystemNotInitializedException(Interface.class, HLUsageReporting.class); + } + } - public static void reportSmartDashboard() { - if(impl != null) { - impl.reportSmartDashboard(); - } else { - throw new BaseSystemNotInitializedException(Interface.class, HLUsageReporting.class); - } - } + public static void reportSmartDashboard() { + if (impl != null) { + impl.reportSmartDashboard(); + } else { + throw new BaseSystemNotInitializedException(Interface.class, HLUsageReporting.class); + } + } - public interface Interface { - void reportScheduler(); - void reportPIDController(int num); - void reportSmartDashboard(); - } + public interface Interface { + void reportScheduler(); - public static class Null implements Interface { - public void reportScheduler() {} - public void reportPIDController(int num) {} - public void reportSmartDashboard() {} - } + void reportPIDController(int num); + + void reportSmartDashboard(); + } + + public static class Null implements Interface { + public void reportScheduler() {} + + public void reportPIDController(int num) {} + + public void reportSmartDashboard() {} + } } diff --git a/wpilibj/wpilibJava/src/main/java/edu/wpi/first/wpilibj/MotorSafety.java b/wpilibj/wpilibJava/src/main/java/edu/wpi/first/wpilibj/MotorSafety.java index f566f14867..50af727c17 100644 --- a/wpilibj/wpilibJava/src/main/java/edu/wpi/first/wpilibj/MotorSafety.java +++ b/wpilibj/wpilibJava/src/main/java/edu/wpi/first/wpilibj/MotorSafety.java @@ -1,8 +1,8 @@ /*----------------------------------------------------------------------------*/ -/* Copyright (c) FIRST 2008-2012. All Rights Reserved. */ -/* Open Source Software - may be modified and shared by FRC teams. The code */ +/* Copyright (c) FIRST 2008-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 the root directory of */ -/* the project. */ +/* the project. */ /*----------------------------------------------------------------------------*/ package edu.wpi.first.wpilibj; @@ -12,12 +12,19 @@ package edu.wpi.first.wpilibj; * @author brad */ public interface MotorSafety { - public static final double DEFAULT_SAFETY_EXPIRATION = 0.1; - void setExpiration(double timeout); - double getExpiration(); - boolean isAlive(); - void stopMotor(); - void setSafetyEnabled(boolean enabled); - boolean isSafetyEnabled(); - String getDescription(); + public static final double DEFAULT_SAFETY_EXPIRATION = 0.1; + + void setExpiration(double timeout); + + double getExpiration(); + + boolean isAlive(); + + void stopMotor(); + + void setSafetyEnabled(boolean enabled); + + boolean isSafetyEnabled(); + + String getDescription(); } diff --git a/wpilibj/wpilibJava/src/main/java/edu/wpi/first/wpilibj/MotorSafetyHelper.java b/wpilibj/wpilibJava/src/main/java/edu/wpi/first/wpilibj/MotorSafetyHelper.java index 5fb7c95f1b..b4d7c55e36 100644 --- a/wpilibj/wpilibJava/src/main/java/edu/wpi/first/wpilibj/MotorSafetyHelper.java +++ b/wpilibj/wpilibJava/src/main/java/edu/wpi/first/wpilibj/MotorSafetyHelper.java @@ -1,8 +1,8 @@ /*----------------------------------------------------------------------------*/ -/* Copyright (c) FIRST 2008-2012. All Rights Reserved. */ -/* Open Source Software - may be modified and shared by FRC teams. The code */ +/* Copyright (c) FIRST 2008-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 the root directory of */ -/* the project. */ +/* the project. */ /*----------------------------------------------------------------------------*/ package edu.wpi.first.wpilibj; @@ -10,116 +10,123 @@ package edu.wpi.first.wpilibj; import edu.wpi.first.wpilibj.Timer; /** - * The MotorSafetyHelper object is constructed for every object that wants to implement the Motor - * Safety protocol. The helper object has the code to actually do the timing and call the - * motors Stop() method when the timeout expires. The motor object is expected to call the - * Feed() method whenever the motors value is updated. + * The MotorSafetyHelper object is constructed for every object that wants to + * implement the Motor Safety protocol. The helper object has the code to + * actually do the timing and call the motors Stop() method when the timeout + * expires. The motor object is expected to call the Feed() method whenever the + * motors value is updated. * * @author brad */ public class MotorSafetyHelper { - double m_expiration; - boolean m_enabled; - double m_stopTime; - MotorSafety m_safeObject; - MotorSafetyHelper m_nextHelper; - static MotorSafetyHelper m_headHelper = null; + double m_expiration; + boolean m_enabled; + double m_stopTime; + MotorSafety m_safeObject; + MotorSafetyHelper m_nextHelper; + static MotorSafetyHelper m_headHelper = null; - /** - * The constructor for a MotorSafetyHelper object. - * The helper object is constructed for every object that wants to implement the Motor - * Safety protocol. The helper object has the code to actually do the timing and call the - * motors Stop() method when the timeout expires. The motor object is expected to call the - * Feed() method whenever the motors value is updated. - * - * @param safeObject a pointer to the motor object implementing MotorSafety. This is used - * to call the Stop() method on the motor. - */ - public MotorSafetyHelper(MotorSafety safeObject) { - m_safeObject = safeObject; - m_enabled = false; - m_expiration = MotorSafety.DEFAULT_SAFETY_EXPIRATION; - m_stopTime = Timer.getFPGATimestamp(); - m_nextHelper = m_headHelper; - m_headHelper = this; + /** + * The constructor for a MotorSafetyHelper object. The helper object is + * constructed for every object that wants to implement the Motor Safety + * protocol. The helper object has the code to actually do the timing and call + * the motors Stop() method when the timeout expires. The motor object is + * expected to call the Feed() method whenever the motors value is updated. + * + * @param safeObject a pointer to the motor object implementing MotorSafety. + * This is used to call the Stop() method on the motor. + */ + public MotorSafetyHelper(MotorSafety safeObject) { + m_safeObject = safeObject; + m_enabled = false; + m_expiration = MotorSafety.DEFAULT_SAFETY_EXPIRATION; + m_stopTime = Timer.getFPGATimestamp(); + m_nextHelper = m_headHelper; + m_headHelper = this; + } + + /** + * Feed the motor safety object. Resets the timer on this object that is used + * to do the timeouts. + */ + public void feed() { + m_stopTime = Timer.getFPGATimestamp() + m_expiration; + } + + /** + * Set the expiration time for the corresponding motor safety object. + *$ + * @param expirationTime The timeout value in seconds. + */ + public void setExpiration(double expirationTime) { + m_expiration = expirationTime; + } + + /** + * Retrieve the timeout value for the corresponding motor safety object. + *$ + * @return the timeout value in seconds. + */ + public double getExpiration() { + return m_expiration; + } + + /** + * Determine of the motor is still operating or has timed out. + *$ + * @return a true value if the motor is still operating normally and hasn't + * timed out. + */ + public boolean isAlive() { + return !m_enabled || m_stopTime > Timer.getFPGATimestamp(); + } + + /** + * Check if this motor has exceeded its timeout. This method is called + * periodically to determine if this motor has exceeded its timeout value. If + * it has, the stop method is called, and the motor is shut down until its + * value is updated again. + */ + public void check() { + if (!m_enabled || RobotState.isDisabled() || RobotState.isTest()) + return; + if (m_stopTime < Timer.getFPGATimestamp()) { + System.err.println(m_safeObject.getDescription() + "... Output not updated often enough."); + + m_safeObject.stopMotor(); } + } - /** - * Feed the motor safety object. - * Resets the timer on this object that is used to do the timeouts. - */ - public void feed() { - m_stopTime = Timer.getFPGATimestamp() + m_expiration; - } - - /** - * Set the expiration time for the corresponding motor safety object. - * @param expirationTime The timeout value in seconds. - */ - public void setExpiration(double expirationTime) { - m_expiration = expirationTime; - } - - /** - * Retrieve the timeout value for the corresponding motor safety object. - * @return the timeout value in seconds. - */ - public double getExpiration() { - return m_expiration; - } - - /** - * Determine of the motor is still operating or has timed out. - * @return a true value if the motor is still operating normally and hasn't timed out. - */ - public boolean isAlive() { - return !m_enabled || m_stopTime > Timer.getFPGATimestamp(); - } - - /** - * Check if this motor has exceeded its timeout. - * This method is called periodically to determine if this motor has exceeded its timeout - * value. If it has, the stop method is called, and the motor is shut down until its value is - * updated again. - */ - public void check() { - if (!m_enabled || RobotState.isDisabled() || RobotState.isTest()) - return; - if (m_stopTime < Timer.getFPGATimestamp()) { - System.err.println(m_safeObject.getDescription() + "... Output not updated often enough."); - - m_safeObject.stopMotor(); - } - } - - /** - * Enable/disable motor safety for this device - * Turn on and off the motor safety option for this PWM object. - * @param enabled True if motor safety is enforced for this object - */ - public void setSafetyEnabled(boolean enabled) { - m_enabled = enabled; - } - - /** - * Return the state of the motor safety enabled flag - * Return if the motor safety is currently enabled for this devicce. - * @return True if motor safety is enforced for this device - */ - public boolean isSafetyEnabled() { - return m_enabled; - } - - /** - * Check the motors to see if any have timed out. - * This static method is called periodically to poll all the motors and stop any that have - * timed out. - */ - //TODO: these should be synchronized with the setting methods in case it's called from a different thread - public static void checkMotors() { - for (MotorSafetyHelper msh = m_headHelper; msh != null; msh = msh.m_nextHelper) { - msh.check(); - } + /** + * Enable/disable motor safety for this device Turn on and off the motor + * safety option for this PWM object. + *$ + * @param enabled True if motor safety is enforced for this object + */ + public void setSafetyEnabled(boolean enabled) { + m_enabled = enabled; + } + + /** + * Return the state of the motor safety enabled flag Return if the motor + * safety is currently enabled for this devicce. + *$ + * @return True if motor safety is enforced for this device + */ + public boolean isSafetyEnabled() { + return m_enabled; + } + + /** + * Check the motors to see if any have timed out. This static method is called + * periodically to poll all the motors and stop any that have timed out. + */ + // TODO: these should be synchronized with the setting methods in case it's + // called from a different thread + public static void checkMotors() { + for (MotorSafetyHelper msh = m_headHelper; msh != null; msh = msh.m_nextHelper) { + msh.check(); } + } } diff --git a/wpilibj/wpilibJava/src/main/java/edu/wpi/first/wpilibj/NamedSendable.java b/wpilibj/wpilibJava/src/main/java/edu/wpi/first/wpilibj/NamedSendable.java index e0b8ae9636..a192bd4e8d 100644 --- a/wpilibj/wpilibJava/src/main/java/edu/wpi/first/wpilibj/NamedSendable.java +++ b/wpilibj/wpilibJava/src/main/java/edu/wpi/first/wpilibj/NamedSendable.java @@ -2,13 +2,15 @@ package edu.wpi.first.wpilibj; /** - * 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 * */ public interface NamedSendable extends Sendable { - /** - * @return the name of the subtable of SmartDashboard that the Sendable object will use - */ - public String getName(); + /** + * @return the name of the subtable of SmartDashboard that the Sendable object + * will use + */ + public String getName(); } diff --git a/wpilibj/wpilibJava/src/main/java/edu/wpi/first/wpilibj/PIDController.java b/wpilibj/wpilibJava/src/main/java/edu/wpi/first/wpilibj/PIDController.java index f84211ed6d..aa669fa4a4 100644 --- a/wpilibj/wpilibJava/src/main/java/edu/wpi/first/wpilibj/PIDController.java +++ b/wpilibj/wpilibJava/src/main/java/edu/wpi/first/wpilibj/PIDController.java @@ -1,7 +1,7 @@ -/* Copyright (c) FIRST 2008-2012. All Rights Reserved. */ -/* Open Source Software - may be modified and shared by FRC teams. The code */ +/* Copyright (c) FIRST 2008-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 the root directory of */ -/* the project. */ +/* the project. */ /*----------------------------------------------------------------------------*/ package edu.wpi.first.wpilibj; @@ -15,612 +15,638 @@ import edu.wpi.first.wpilibj.util.BoundaryException; /** * Class implements a PID Control Loop. * - * Creates a separate thread which reads the given PIDSource and takes - * care of the integral calculations, as well as writing the given - * PIDOutput + * Creates a separate thread which reads the given PIDSource and takes care of + * the integral calculations, as well as writing the given PIDOutput */ public class PIDController implements PIDInterface, LiveWindowSendable, Controller { - public static final double kDefaultPeriod = .05; - private static int instances = 0; - private double m_P; // factor for "proportional" control - private double m_I; // factor for "integral" control - private double m_D; // factor for "derivative" control - private double m_F; // factor for feedforward term - private double m_maximumOutput = 1.0; // |maximum output| - private double m_minimumOutput = -1.0; // |minimum output| - private double m_maximumInput = 0.0; // maximum input - limit setpoint to this - private double m_minimumInput = 0.0; // minimum input - limit setpoint to this - private boolean m_continuous = false; // do the endpoints wrap around? eg. Absolute encoder - private boolean m_enabled = false; //is the pid controller enabled - private double m_prevError = 0.0; // the prior sensor input (used to compute velocity) - private double m_totalError = 0.0; //the sum of the errors for use in the integral calc - private Tolerance m_tolerance; //the tolerance object used to check if on target - private double m_setpoint = 0.0; - private double m_error = 0.0; - private double m_result = 0.0; - private double m_period = kDefaultPeriod; - PIDSource m_pidInput; - PIDOutput m_pidOutput; - java.util.Timer m_controlLoop; - private boolean m_freed = false; - private boolean m_usingPercentTolerance; + public static final double kDefaultPeriod = .05; + private static int instances = 0; + private double m_P; // factor for "proportional" control + private double m_I; // factor for "integral" control + private double m_D; // factor for "derivative" control + private double m_F; // factor for feedforward term + private double m_maximumOutput = 1.0; // |maximum output| + private double m_minimumOutput = -1.0; // |minimum output| + private double m_maximumInput = 0.0; // maximum input - limit setpoint to this + private double m_minimumInput = 0.0; // minimum input - limit setpoint to this + private boolean m_continuous = false; // do the endpoints wrap around? eg. + // Absolute encoder + private boolean m_enabled = false; // is the pid controller enabled + private double m_prevError = 0.0; // the prior sensor input (used to compute + // velocity) + private double m_totalError = 0.0; // the sum of the errors for use in the + // integral calc + private Tolerance m_tolerance; // the tolerance object used to check if on + // target + private double m_setpoint = 0.0; + private double m_error = 0.0; + private double m_result = 0.0; + private double m_period = kDefaultPeriod; + PIDSource m_pidInput; + PIDOutput m_pidOutput; + java.util.Timer m_controlLoop; + private boolean m_freed = false; + private boolean m_usingPercentTolerance; - /** - * Tolerance is the type of tolerance used to specify if the PID controller - * is on target. - * - * The various implementations of this class such as PercentageTolerance and - * AbsoluteTolerance specify types of tolerance specifications to use. - */ - public interface Tolerance { - public boolean onTarget(); + /** + * Tolerance is the type of tolerance used to specify if the PID controller is + * on target. + * + * The various implementations of this class such as PercentageTolerance and + * AbsoluteTolerance specify types of tolerance specifications to use. + */ + public interface Tolerance { + public boolean onTarget(); + } + + /** + * Used internally for when Tolerance hasn't been set. + */ + public class NullTolerance implements Tolerance { + @Override + public boolean onTarget() { + throw new RuntimeException("No tolerance value set when calling onTarget()."); + } + } + + public class PercentageTolerance implements Tolerance { + double percentage; + + PercentageTolerance(double value) { + percentage = value; } - /** - * Used internally for when Tolerance hasn't been set. - */ - public class NullTolerance implements Tolerance { - @Override - public boolean onTarget() { - throw new RuntimeException("No tolerance value set when calling onTarget()."); - } + @Override + public boolean onTarget() { + return (Math.abs(getError()) < percentage / 100 * (m_maximumInput - m_minimumInput)); + } + } + + public class AbsoluteTolerance implements Tolerance { + double value; + + AbsoluteTolerance(double value) { + this.value = value; } - public class PercentageTolerance implements Tolerance { - double percentage; - - PercentageTolerance(double value) { - percentage = value; - } - - @Override - public boolean onTarget() { - return (Math.abs(getError()) < percentage / 100 - * (m_maximumInput - m_minimumInput)); - } + @Override + public boolean onTarget() { + return Math.abs(getError()) < value; } + } - public class AbsoluteTolerance implements Tolerance { - double value; + private class PIDTask extends TimerTask { - AbsoluteTolerance(double value) { - this.value = value; - } + private PIDController m_controller; - @Override - public boolean onTarget() { - return Math.abs(getError()) < value; - } - } - - private class PIDTask extends TimerTask { - - private PIDController m_controller; - - public PIDTask(PIDController controller) { - if (controller == null) { - throw new NullPointerException("Given PIDController was null"); - } - m_controller = controller; - } - - @Override - public void run() { - m_controller.calculate(); - } - } - - /** - * Allocate a PID object with the given constants for P, I, D, and F - * @param Kp the proportional coefficient - * @param Ki the integral coefficient - * @param Kd the derivative coefficient - * @param Kf the feed forward term - * @param source The PIDSource object that is used to get values - * @param output The PIDOutput object that is set to the output percentage - * @param period the loop time for doing calculations. This particularly effects calculations of the - * integral and differential terms. The default is 50ms. - */ - public PIDController(double Kp, double Ki, double Kd, double Kf, - PIDSource source, PIDOutput output, - double period) { - - if (source == null) { - throw new NullPointerException("Null PIDSource was given"); - } - if (output == null) { - throw new NullPointerException("Null PIDOutput was given"); - } - - m_controlLoop = new java.util.Timer(); - - - m_P = Kp; - m_I = Ki; - m_D = Kd; - m_F = Kf; - - m_pidInput = source; - m_pidOutput = output; - m_period = period; - - m_controlLoop.schedule(new PIDTask(this), 0L, (long) (m_period * 1000)); - - instances++; - HLUsageReporting.reportPIDController(instances); - m_tolerance = new NullTolerance(); - } - - /** - * Allocate a PID object with the given constants for P, I, D and period - * @param Kp the proportional coefficient - * @param Ki the integral coefficient - * @param Kd the derivative coefficient - * @param source the PIDSource object that is used to get values - * @param output the PIDOutput object that is set to the output percentage - * @param period the loop time for doing calculations. This particularly effects calculations of the - * integral and differential terms. The default is 50ms. - */ - public PIDController(double Kp, double Ki, double Kd, - PIDSource source, PIDOutput output, - double period) { - this(Kp, Ki, Kd, 0.0, source, output, period); - } - - /** - * Allocate a PID object with the given constants for P, I, D, using a 50ms period. - * @param Kp the proportional coefficient - * @param Ki the integral coefficient - * @param Kd the derivative coefficient - * @param source The PIDSource object that is used to get values - * @param output The PIDOutput object that is set to the output percentage - */ - public PIDController(double Kp, double Ki, double Kd, - PIDSource source, PIDOutput output) { - this(Kp, Ki, Kd, source, output, kDefaultPeriod); - } - - /** - * Allocate a PID object with the given constants for P, I, D, using a 50ms period. - * @param Kp the proportional coefficient - * @param Ki the integral coefficient - * @param Kd the derivative coefficient - * @param Kf the feed forward term - * @param source The PIDSource object that is used to get values - * @param output The PIDOutput object that is set to the output percentage - */ - public PIDController(double Kp, double Ki, double Kd, double Kf, - PIDSource source, PIDOutput output) { - this(Kp, Ki, Kd, Kf, source, output, kDefaultPeriod); - } - - /** - * Free the PID object - */ - public void free() { - m_controlLoop.cancel(); - synchronized (this) { - m_freed = true; - m_pidOutput = null; - m_pidInput = null; - m_controlLoop = null; + public PIDTask(PIDController controller) { + if (controller == null) { + throw new NullPointerException("Given PIDController was null"); } - if(this.table!=null) table.removeTableListener(listener); + m_controller = controller; } - /** - * Read the input, calculate the output accordingly, and write to the output. - * This should only be called by the PIDTask - * and is created during initialization. - */ - protected void calculate() { - boolean enabled; - PIDSource pidInput; + @Override + public void run() { + m_controller.calculate(); + } + } - synchronized (this) { - if (m_pidInput == null) { - return; - } - if (m_pidOutput == null) { - return; - } - enabled = m_enabled; // take snapshot of these values... - pidInput = m_pidInput; - } + /** + * Allocate a PID object with the given constants for P, I, D, and F + *$ + * @param Kp the proportional coefficient + * @param Ki the integral coefficient + * @param Kd the derivative coefficient + * @param Kf the feed forward term + * @param source The PIDSource object that is used to get values + * @param output The PIDOutput object that is set to the output percentage + * @param period the loop time for doing calculations. This particularly + * effects calculations of the integral and differential terms. The + * default is 50ms. + */ + public PIDController(double Kp, double Ki, double Kd, double Kf, PIDSource source, + PIDOutput output, double period) { - if (enabled) { - double input; - double result; - PIDOutput pidOutput = null; - synchronized (this){ - input = pidInput.pidGet(); - } - synchronized (this) { - m_error = m_setpoint - input; - if (m_continuous) { - if (Math.abs(m_error) - > (m_maximumInput - m_minimumInput) / 2) { - if (m_error > 0) { - m_error = m_error - m_maximumInput + m_minimumInput; - } else { - m_error = m_error - + m_maximumInput - m_minimumInput; - } - } - } - - if (m_I != 0) { - double potentialIGain = (m_totalError + m_error) * m_I; - if (potentialIGain < m_maximumOutput) { - if (potentialIGain > m_minimumOutput) { - m_totalError += m_error; - } else { - m_totalError = m_minimumOutput / m_I; - } - } else { - m_totalError = m_maximumOutput / m_I; - } - } - - m_result = m_P * m_error + m_I * m_totalError + m_D * (m_error - m_prevError) + m_setpoint * m_F; - m_prevError = m_error; - - if (m_result > m_maximumOutput) { - m_result = m_maximumOutput; - } else if (m_result < m_minimumOutput) { - m_result = m_minimumOutput; - } - pidOutput = m_pidOutput; - result = m_result; - } - - pidOutput.pidWrite(result); - } + if (source == null) { + throw new NullPointerException("Null PIDSource was given"); + } + if (output == null) { + throw new NullPointerException("Null PIDOutput was given"); } - /** - * Set the PID Controller gain parameters. - * Set the proportional, integral, and differential coefficients. - * @param p Proportional coefficient - * @param i Integral coefficient - * @param d Differential coefficient - */ - public synchronized void setPID(double p, double i, double d) { - m_P = p; - m_I = i; - m_D = d; + m_controlLoop = new java.util.Timer(); - if (table != null) { - table.putNumber("p", p); - table.putNumber("i", i); - table.putNumber("d", d); - } + + m_P = Kp; + m_I = Ki; + m_D = Kd; + m_F = Kf; + + m_pidInput = source; + m_pidOutput = output; + m_period = period; + + m_controlLoop.schedule(new PIDTask(this), 0L, (long) (m_period * 1000)); + + instances++; + HLUsageReporting.reportPIDController(instances); + m_tolerance = new NullTolerance(); + } + + /** + * Allocate a PID object with the given constants for P, I, D and period + *$ + * @param Kp the proportional coefficient + * @param Ki the integral coefficient + * @param Kd the derivative coefficient + * @param source the PIDSource object that is used to get values + * @param output the PIDOutput object that is set to the output percentage + * @param period the loop time for doing calculations. This particularly + * effects calculations of the integral and differential terms. The + * default is 50ms. + */ + public PIDController(double Kp, double Ki, double Kd, PIDSource source, PIDOutput output, + double period) { + this(Kp, Ki, Kd, 0.0, source, output, period); + } + + /** + * Allocate a PID object with the given constants for P, I, D, using a 50ms + * period. + *$ + * @param Kp the proportional coefficient + * @param Ki the integral coefficient + * @param Kd the derivative coefficient + * @param source The PIDSource object that is used to get values + * @param output The PIDOutput object that is set to the output percentage + */ + public PIDController(double Kp, double Ki, double Kd, PIDSource source, PIDOutput output) { + this(Kp, Ki, Kd, source, output, kDefaultPeriod); + } + + /** + * Allocate a PID object with the given constants for P, I, D, using a 50ms + * period. + *$ + * @param Kp the proportional coefficient + * @param Ki the integral coefficient + * @param Kd the derivative coefficient + * @param Kf the feed forward term + * @param source The PIDSource object that is used to get values + * @param output The PIDOutput object that is set to the output percentage + */ + public PIDController(double Kp, double Ki, double Kd, double Kf, PIDSource source, + PIDOutput output) { + this(Kp, Ki, Kd, Kf, source, output, kDefaultPeriod); + } + + /** + * Free the PID object + */ + public void free() { + m_controlLoop.cancel(); + synchronized (this) { + m_freed = true; + m_pidOutput = null; + m_pidInput = null; + m_controlLoop = null; + } + if (this.table != null) + table.removeTableListener(listener); + } + + /** + * Read the input, calculate the output accordingly, and write to the output. + * This should only be called by the PIDTask and is created during + * initialization. + */ + protected void calculate() { + boolean enabled; + PIDSource pidInput; + + synchronized (this) { + if (m_pidInput == null) { + return; + } + if (m_pidOutput == null) { + return; + } + enabled = m_enabled; // take snapshot of these values... + pidInput = m_pidInput; } - /** - * Set the PID Controller gain parameters. - * Set the proportional, integral, and differential coefficients. - * @param p Proportional coefficient - * @param i Integral coefficient - * @param d Differential coefficient - * @param f Feed forward coefficient - */ - public synchronized void setPID(double p, double i, double d, double f) { - m_P = p; - m_I = i; - m_D = d; - m_F = f; - - if (table != null) { - table.putNumber("p", p); - table.putNumber("i", i); - table.putNumber("d", d); - table.putNumber("f", f); - } - } - - /** - * Get the Proportional coefficient - * @return proportional coefficient - */ - public synchronized double getP() { - return m_P; - } - - /** - * Get the Integral coefficient - * @return integral coefficient - */ - public synchronized double getI() { - return m_I; - } - - /** - * Get the Differential coefficient - * @return differential coefficient - */ - public synchronized double getD() { - return m_D; - } - - /** - * Get the Feed forward coefficient - * @return feed forward coefficient - */ - public synchronized double getF() { - return m_F; - } - - /** - * Return the current PID result - * This is always centered on zero and constrained the the max and min outs - * @return the latest calculated output - */ - public synchronized double get() { - return m_result; - } - - /** - * Set the PID controller to consider the input to be continuous, - * Rather then using the max and min in as constraints, it considers them to - * be the same point and automatically calculates the shortest route to - * the setpoint. - * @param continuous Set to true turns on continuous, false turns off continuous - */ - public synchronized void setContinuous(boolean continuous) { - m_continuous = continuous; - } - - /** - * Set the PID controller to consider the input to be continuous, - * Rather then using the max and min in as constraints, it considers them to - * be the same point and automatically calculates the shortest route to - * the setpoint. - */ - public synchronized void setContinuous() { - this.setContinuous(true); - } - - /** - * Sets the maximum and minimum values expected from the input and setpoint. - * - * @param minimumInput the minimum value expected from the input - * @param maximumInput the maximum value expected from the input - */ - public synchronized void setInputRange(double minimumInput, double maximumInput) { - if (minimumInput > maximumInput) { - throw new BoundaryException("Lower bound is greater than upper bound"); - } - m_minimumInput = minimumInput; - m_maximumInput = maximumInput; - setSetpoint(m_setpoint); - } - - /** - * Sets the minimum and maximum values to write. - * - * @param minimumOutput the minimum percentage to write to the output - * @param maximumOutput the maximum percentage to write to the output - */ - public synchronized void setOutputRange(double minimumOutput, double maximumOutput) { - if (minimumOutput > maximumOutput) { - throw new BoundaryException("Lower bound is greater than upper bound"); - } - m_minimumOutput = minimumOutput; - m_maximumOutput = maximumOutput; - } - - /** - * Set the setpoint for the PIDController - * @param setpoint the desired setpoint - */ - public synchronized void setSetpoint(double setpoint) { - if (m_maximumInput > m_minimumInput) { - if (setpoint > m_maximumInput) { - m_setpoint = m_maximumInput; - } else if (setpoint < m_minimumInput) { - m_setpoint = m_minimumInput; + if (enabled) { + double input; + double result; + PIDOutput pidOutput = null; + synchronized (this) { + input = pidInput.pidGet(); + } + synchronized (this) { + m_error = m_setpoint - input; + if (m_continuous) { + if (Math.abs(m_error) > (m_maximumInput - m_minimumInput) / 2) { + if (m_error > 0) { + m_error = m_error - m_maximumInput + m_minimumInput; } else { - m_setpoint = setpoint; + m_error = m_error + m_maximumInput - m_minimumInput; } - } else { - m_setpoint = setpoint; + } } - if (table != null) - table.putNumber("setpoint", m_setpoint); + if (m_I != 0) { + double potentialIGain = (m_totalError + m_error) * m_I; + if (potentialIGain < m_maximumOutput) { + if (potentialIGain > m_minimumOutput) { + m_totalError += m_error; + } else { + m_totalError = m_minimumOutput / m_I; + } + } else { + m_totalError = m_maximumOutput / m_I; + } + } + + m_result = + m_P * m_error + m_I * m_totalError + m_D * (m_error - m_prevError) + m_setpoint * m_F; + m_prevError = m_error; + + if (m_result > m_maximumOutput) { + m_result = m_maximumOutput; + } else if (m_result < m_minimumOutput) { + m_result = m_minimumOutput; + } + pidOutput = m_pidOutput; + result = m_result; + } + + pidOutput.pidWrite(result); + } + } + + /** + * Set the PID Controller gain parameters. Set the proportional, integral, and + * differential coefficients. + *$ + * @param p Proportional coefficient + * @param i Integral coefficient + * @param d Differential coefficient + */ + public synchronized void setPID(double p, double i, double d) { + m_P = p; + m_I = i; + m_D = d; + + if (table != null) { + table.putNumber("p", p); + table.putNumber("i", i); + table.putNumber("d", d); + } + } + + /** + * Set the PID Controller gain parameters. Set the proportional, integral, and + * differential coefficients. + *$ + * @param p Proportional coefficient + * @param i Integral coefficient + * @param d Differential coefficient + * @param f Feed forward coefficient + */ + public synchronized void setPID(double p, double i, double d, double f) { + m_P = p; + m_I = i; + m_D = d; + m_F = f; + + if (table != null) { + table.putNumber("p", p); + table.putNumber("i", i); + table.putNumber("d", d); + table.putNumber("f", f); + } + } + + /** + * Get the Proportional coefficient + *$ + * @return proportional coefficient + */ + public synchronized double getP() { + return m_P; + } + + /** + * Get the Integral coefficient + *$ + * @return integral coefficient + */ + public synchronized double getI() { + return m_I; + } + + /** + * Get the Differential coefficient + *$ + * @return differential coefficient + */ + public synchronized double getD() { + return m_D; + } + + /** + * Get the Feed forward coefficient + *$ + * @return feed forward coefficient + */ + public synchronized double getF() { + return m_F; + } + + /** + * Return the current PID result This is always centered on zero and + * constrained the the max and min outs + *$ + * @return the latest calculated output + */ + public synchronized double get() { + return m_result; + } + + /** + * Set the PID controller to consider the input to be continuous, Rather then + * using the max and min in as constraints, it considers them to be the same + * point and automatically calculates the shortest route to the setpoint. + *$ + * @param continuous Set to true turns on continuous, false turns off + * continuous + */ + public synchronized void setContinuous(boolean continuous) { + m_continuous = continuous; + } + + /** + * Set the PID controller to consider the input to be continuous, Rather then + * using the max and min in as constraints, it considers them to be the same + * point and automatically calculates the shortest route to the setpoint. + */ + public synchronized void setContinuous() { + this.setContinuous(true); + } + + /** + * Sets the maximum and minimum values expected from the input and setpoint. + * + * @param minimumInput the minimum value expected from the input + * @param maximumInput the maximum value expected from the input + */ + public synchronized void setInputRange(double minimumInput, double maximumInput) { + if (minimumInput > maximumInput) { + throw new BoundaryException("Lower bound is greater than upper bound"); + } + m_minimumInput = minimumInput; + m_maximumInput = maximumInput; + setSetpoint(m_setpoint); + } + + /** + * Sets the minimum and maximum values to write. + * + * @param minimumOutput the minimum percentage to write to the output + * @param maximumOutput the maximum percentage to write to the output + */ + public synchronized void setOutputRange(double minimumOutput, double maximumOutput) { + if (minimumOutput > maximumOutput) { + throw new BoundaryException("Lower bound is greater than upper bound"); + } + m_minimumOutput = minimumOutput; + m_maximumOutput = maximumOutput; + } + + /** + * Set the setpoint for the PIDController + *$ + * @param setpoint the desired setpoint + */ + public synchronized void setSetpoint(double setpoint) { + if (m_maximumInput > m_minimumInput) { + if (setpoint > m_maximumInput) { + m_setpoint = m_maximumInput; + } else if (setpoint < m_minimumInput) { + m_setpoint = m_minimumInput; + } else { + m_setpoint = setpoint; + } + } else { + m_setpoint = setpoint; } - /** - * Returns the current setpoint of the PIDController - * @return the current setpoint - */ - public synchronized double getSetpoint() { - return m_setpoint; - } + if (table != null) + table.putNumber("setpoint", m_setpoint); + } - /** - * Returns the current difference of the input from the setpoint - * @return the current error - */ - public synchronized double getError() { - //return m_error; - return getSetpoint() - m_pidInput.pidGet(); - } + /** + * Returns the current setpoint of the PIDController + *$ + * @return the current setpoint + */ + public synchronized double getSetpoint() { + return m_setpoint; + } - /** - * Set the percentage error which is considered tolerable for use with - * OnTarget. (Input of 15.0 = 15 percent) - * @param percent error which is tolerable - * @deprecated Use {@link #setPercentTolerance(double)} or {@link #setAbsoluteTolerance(double)} instead. - */ - @Deprecated + /** + * Returns the current difference of the input from the setpoint + *$ + * @return the current error + */ + public synchronized double getError() { + // return m_error; + return getSetpoint() - m_pidInput.pidGet(); + } + + /** + * Set the percentage error which is considered tolerable for use with + * OnTarget. (Input of 15.0 = 15 percent) + *$ + * @param percent error which is tolerable + * @deprecated Use {@link #setPercentTolerance(double)} or + * {@link #setAbsoluteTolerance(double)} instead. + */ + @Deprecated public synchronized void setTolerance(double percent) { - m_tolerance = new PercentageTolerance(percent); - } + m_tolerance = new PercentageTolerance(percent); + } - /** Set the PID tolerance using a Tolerance object. - * Tolerance can be specified as a percentage of the range or as an absolute - * value. The Tolerance object encapsulates those options in an object. Use it by - * creating the type of tolerance that you want to use: setTolerance(new PIDController.AbsoluteTolerance(0.1)) - * @param tolerance a tolerance object of the right type, e.g. PercentTolerance - * or AbsoluteTolerance - */ - public void setTolerance(Tolerance tolerance) { - m_tolerance = tolerance; - } + /** + * Set the PID tolerance using a Tolerance object. Tolerance can be specified + * as a percentage of the range or as an absolute value. The Tolerance object + * encapsulates those options in an object. Use it by creating the type of + * tolerance that you want to use: setTolerance(new + * PIDController.AbsoluteTolerance(0.1)) + *$ + * @param tolerance a tolerance object of the right type, e.g. + * PercentTolerance or AbsoluteTolerance + */ + public void setTolerance(Tolerance tolerance) { + m_tolerance = tolerance; + } - /** - * Set the absolute error which is considered tolerable for use with - * OnTarget. - * @param absvalue absolute error which is tolerable in the units of the input object - */ - public synchronized void setAbsoluteTolerance(double absvalue) { - m_tolerance = new AbsoluteTolerance(absvalue); - } + /** + * Set the absolute error which is considered tolerable for use with OnTarget. + *$ + * @param absvalue absolute error which is tolerable in the units of the input + * object + */ + public synchronized void setAbsoluteTolerance(double absvalue) { + m_tolerance = new AbsoluteTolerance(absvalue); + } - /** - * Set the percentage error which is considered tolerable for use with - * OnTarget. (Input of 15.0 = 15 percent) - * @param percentage percent error which is tolerable - */ - public synchronized void setPercentTolerance(double percentage) { - m_tolerance = new PercentageTolerance(percentage); - } + /** + * Set the percentage error which is considered tolerable for use with + * OnTarget. (Input of 15.0 = 15 percent) + *$ + * @param percentage percent error which is tolerable + */ + public synchronized void setPercentTolerance(double percentage) { + m_tolerance = new PercentageTolerance(percentage); + } - /** - * Return true if the error is within the percentage of the total input range, - * determined by setTolerance. This assumes that the maximum and minimum input - * were set using setInput. - * @return true if the error is less than the tolerance - */ - public synchronized boolean onTarget() { - return m_tolerance.onTarget(); - } + /** + * Return true if the error is within the percentage of the total input range, + * determined by setTolerance. This assumes that the maximum and minimum input + * were set using setInput. + *$ + * @return true if the error is less than the tolerance + */ + public synchronized boolean onTarget() { + return m_tolerance.onTarget(); + } - /** - * Begin running the PIDController - */ - @Override + /** + * Begin running the PIDController + */ + @Override public synchronized void enable() { - m_enabled = true; + m_enabled = true; - if (table != null) { - table.putBoolean("enabled", true); - } + if (table != null) { + table.putBoolean("enabled", true); } + } - /** - * Stop running the PIDController, this sets the output to zero before stopping. - */ - @Override - public synchronized void disable() { - m_pidOutput.pidWrite(0); - m_enabled = false; + /** + * Stop running the PIDController, this sets the output to zero before + * stopping. + */ + @Override + public synchronized void disable() { + m_pidOutput.pidWrite(0); + m_enabled = false; - if (table != null) { - table.putBoolean("enabled", false); - } + if (table != null) { + table.putBoolean("enabled", false); } + } - /** - * Return true if PIDController is enabled. - * - * @deprecated Call {@link #isEnabled()} instead. - */ - @Deprecated - public synchronized boolean isEnable() { - return isEnabled(); - } + /** + * Return true if PIDController is enabled. + * + * @deprecated Call {@link #isEnabled()} instead. + */ + @Deprecated + public synchronized boolean isEnable() { + return isEnabled(); + } - /** - * Return true if PIDController is enabled. - */ - public boolean isEnabled() { - return m_enabled; - } + /** + * Return true if PIDController is enabled. + */ + public boolean isEnabled() { + return m_enabled; + } - /** - * Reset the previous error,, the integral term, and disable the controller. - */ - public synchronized void reset() { - disable(); - m_prevError = 0; - m_totalError = 0; - m_result = 0; - } + /** + * Reset the previous error,, the integral term, and disable the controller. + */ + public synchronized void reset() { + disable(); + m_prevError = 0; + m_totalError = 0; + m_result = 0; + } - @Override + @Override public String getSmartDashboardType() { - return "PIDController"; - } + return "PIDController"; + } - private final ITableListener listener = new ITableListener() { - @Override + private final ITableListener listener = new ITableListener() { + @Override public void valueChanged(ITable table, String key, Object value, boolean isNew) { - if (key.equals("p") || key.equals("i") || key.equals("d") || key.equals("f")) { - if (getP() != table.getNumber("p", 0.0) || getI() != table.getNumber("i", 0.0) || - getD() != table.getNumber("d", 0.0) || getF() != table.getNumber("f", 0.0)) - setPID(table.getNumber("p", 0.0), table.getNumber("i", 0.0), table.getNumber("d", 0.0), table.getNumber("f", 0.0)); - } else if (key.equals("setpoint")) { - if (getSetpoint() != ((Double) value).doubleValue()) - setSetpoint(((Double) value).doubleValue()); - } else if (key.equals("enabled")) { - if (isEnable() != ((Boolean) value).booleanValue()) { - if (((Boolean) value).booleanValue()) { - enable(); - } else { - disable(); - } - } - } + if (key.equals("p") || key.equals("i") || key.equals("d") || key.equals("f")) { + if (getP() != table.getNumber("p", 0.0) || getI() != table.getNumber("i", 0.0) + || getD() != table.getNumber("d", 0.0) || getF() != table.getNumber("f", 0.0)) + setPID(table.getNumber("p", 0.0), table.getNumber("i", 0.0), table.getNumber("d", 0.0), + table.getNumber("f", 0.0)); + } else if (key.equals("setpoint")) { + if (getSetpoint() != ((Double) value).doubleValue()) + setSetpoint(((Double) value).doubleValue()); + } else if (key.equals("enabled")) { + if (isEnable() != ((Boolean) value).booleanValue()) { + if (((Boolean) value).booleanValue()) { + enable(); + } else { + disable(); + } } - }; - private ITable table; - @Override + } + } + }; + private ITable table; + + @Override public void initTable(ITable table) { - if(this.table!=null) - this.table.removeTableListener(listener); - this.table = table; - if(table!=null) { - table.putNumber("p", getP()); - table.putNumber("i", getI()); - table.putNumber("d", getD()); - table.putNumber("f", getF()); - table.putNumber("setpoint", getSetpoint()); - table.putBoolean("enabled", isEnable()); - table.addTableListener(listener, false); - } + if (this.table != null) + this.table.removeTableListener(listener); + this.table = table; + if (table != null) { + table.putNumber("p", getP()); + table.putNumber("i", getI()); + table.putNumber("d", getD()); + table.putNumber("f", getF()); + table.putNumber("setpoint", getSetpoint()); + table.putBoolean("enabled", isEnable()); + table.addTableListener(listener, false); } + } - /** - * {@inheritDoc} - */ - @Override + /** + * {@inheritDoc} + */ + @Override public ITable getTable() { - return table; - } + return table; + } - /** - * {@inheritDoc} - */ - @Override - public void updateTable() { - } + /** + * {@inheritDoc} + */ + @Override + public void updateTable() {} - /** - * {@inheritDoc} - */ - @Override + /** + * {@inheritDoc} + */ + @Override public void startLiveWindowMode() { - disable(); - } + disable(); + } - /** - * {@inheritDoc} - */ - @Override - public void stopLiveWindowMode() { - } + /** + * {@inheritDoc} + */ + @Override + public void stopLiveWindowMode() {} } diff --git a/wpilibj/wpilibJava/src/main/java/edu/wpi/first/wpilibj/PIDInterface.java b/wpilibj/wpilibJava/src/main/java/edu/wpi/first/wpilibj/PIDInterface.java index ab8b334ce0..a001c8dc1d 100644 --- a/wpilibj/wpilibJava/src/main/java/edu/wpi/first/wpilibj/PIDInterface.java +++ b/wpilibj/wpilibJava/src/main/java/edu/wpi/first/wpilibj/PIDInterface.java @@ -2,15 +2,25 @@ package edu.wpi.first.wpilibj; public interface PIDInterface extends Controller { - public void setPID(double p, double i, double d); - public double getP(); - public double getI(); - public double getD(); - public void setSetpoint(double setpoint); - public double getSetpoint(); - public double getError(); - public void enable(); - public void disable(); - public boolean isEnabled(); - public void reset(); + public void setPID(double p, double i, double d); + + public double getP(); + + public double getI(); + + public double getD(); + + public void setSetpoint(double setpoint); + + public double getSetpoint(); + + public double getError(); + + public void enable(); + + public void disable(); + + public boolean isEnabled(); + + public void reset(); } diff --git a/wpilibj/wpilibJava/src/main/java/edu/wpi/first/wpilibj/PIDOutput.java b/wpilibj/wpilibJava/src/main/java/edu/wpi/first/wpilibj/PIDOutput.java index 668eca2a1e..4e865311d2 100644 --- a/wpilibj/wpilibJava/src/main/java/edu/wpi/first/wpilibj/PIDOutput.java +++ b/wpilibj/wpilibJava/src/main/java/edu/wpi/first/wpilibj/PIDOutput.java @@ -1,21 +1,23 @@ /*----------------------------------------------------------------------------*/ -/* Copyright (c) FIRST 2008-2012. All Rights Reserved. */ -/* Open Source Software - may be modified and shared by FRC teams. The code */ +/* Copyright (c) FIRST 2008-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 the root directory of */ -/* the project. */ +/* the project. */ /*----------------------------------------------------------------------------*/ package edu.wpi.first.wpilibj; /** * This interface allows PIDController to write it's results to its output. + *$ * @author dtjones */ public interface PIDOutput { - /** - * Set the output to the value calculated by PIDController - * @param output the value calculated by PIDController - */ - public void pidWrite(double output); + /** + * Set the output to the value calculated by PIDController + *$ + * @param output the value calculated by PIDController + */ + public void pidWrite(double output); } diff --git a/wpilibj/wpilibJava/src/main/java/edu/wpi/first/wpilibj/PIDSource.java b/wpilibj/wpilibJava/src/main/java/edu/wpi/first/wpilibj/PIDSource.java index 73e83d73fe..60b7457e0d 100644 --- a/wpilibj/wpilibJava/src/main/java/edu/wpi/first/wpilibj/PIDSource.java +++ b/wpilibj/wpilibJava/src/main/java/edu/wpi/first/wpilibj/PIDSource.java @@ -1,8 +1,8 @@ /*----------------------------------------------------------------------------*/ -/* Copyright (c) FIRST 2008-2012. All Rights Reserved. */ -/* Open Source Software - may be modified and shared by FRC teams. The code */ +/* Copyright (c) FIRST 2008-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 the root directory of */ -/* the project. */ +/* the project. */ /*----------------------------------------------------------------------------*/ package edu.wpi.first.wpilibj; @@ -10,30 +10,32 @@ package edu.wpi.first.wpilibj; /** * This interface allows for PIDController to automatically read from this * object + *$ * @author dtjones */ public interface PIDSource { - /** - * A description for the type of output value to provide to a PIDController - */ - public static class PIDSourceParameter { - public final int value; - static final int kDistance_val = 0; - static final int kRate_val = 1; - static final int kAngle_val = 2; - public static final PIDSourceParameter kDistance = new PIDSourceParameter(kDistance_val); - public static final PIDSourceParameter kRate = new PIDSourceParameter(kRate_val); - public static final PIDSourceParameter kAngle = new PIDSourceParameter(kAngle_val); + /** + * A description for the type of output value to provide to a PIDController + */ + public static class PIDSourceParameter { + public final int value; + static final int kDistance_val = 0; + static final int kRate_val = 1; + static final int kAngle_val = 2; + public static final PIDSourceParameter kDistance = new PIDSourceParameter(kDistance_val); + public static final PIDSourceParameter kRate = new PIDSourceParameter(kRate_val); + public static final PIDSourceParameter kAngle = new PIDSourceParameter(kAngle_val); - private PIDSourceParameter(int value) { - this.value = value; - } + private PIDSourceParameter(int value) { + this.value = value; } + } - /** - * Get the result to use in PIDController - * @return the result to use in PIDController - */ - public double pidGet(); + /** + * Get the result to use in PIDController + *$ + * @return the result to use in PIDController + */ + public double pidGet(); } diff --git a/wpilibj/wpilibJava/src/main/java/edu/wpi/first/wpilibj/RobotState.java b/wpilibj/wpilibJava/src/main/java/edu/wpi/first/wpilibj/RobotState.java index 7b502b75b4..7dd0e3fdaf 100644 --- a/wpilibj/wpilibJava/src/main/java/edu/wpi/first/wpilibj/RobotState.java +++ b/wpilibj/wpilibJava/src/main/java/edu/wpi/first/wpilibj/RobotState.java @@ -3,57 +3,61 @@ package edu.wpi.first.wpilibj; import edu.wpi.first.wpilibj.util.BaseSystemNotInitializedException; public class RobotState { - private static Interface impl; + private static Interface impl; - public static void SetImplementation(Interface i) { - impl = i; - } + public static void SetImplementation(Interface i) { + impl = i; + } - public static boolean isDisabled() { - if (impl != null) { - return impl.isDisabled(); - } else { - throw new BaseSystemNotInitializedException(Interface.class, RobotState.class); - } - } + public static boolean isDisabled() { + if (impl != null) { + return impl.isDisabled(); + } else { + throw new BaseSystemNotInitializedException(Interface.class, RobotState.class); + } + } - public static boolean isEnabled() { - if (impl != null) { - return impl.isEnabled(); - } else { - throw new BaseSystemNotInitializedException(Interface.class, RobotState.class); - } - } + public static boolean isEnabled() { + if (impl != null) { + return impl.isEnabled(); + } else { + throw new BaseSystemNotInitializedException(Interface.class, RobotState.class); + } + } - public static boolean isOperatorControl() { - if (impl != null) { - return impl.isOperatorControl(); - } else { - throw new BaseSystemNotInitializedException(Interface.class, RobotState.class); - } - } + public static boolean isOperatorControl() { + if (impl != null) { + return impl.isOperatorControl(); + } else { + throw new BaseSystemNotInitializedException(Interface.class, RobotState.class); + } + } - public static boolean isAutonomous() { - if (impl != null) { - return impl.isAutonomous(); - } else { - throw new BaseSystemNotInitializedException(Interface.class, RobotState.class); - } - } + public static boolean isAutonomous() { + if (impl != null) { + return impl.isAutonomous(); + } else { + throw new BaseSystemNotInitializedException(Interface.class, RobotState.class); + } + } - public static boolean isTest() { - if (impl != null) { - return impl.isTest(); - } else { - throw new BaseSystemNotInitializedException(Interface.class, RobotState.class); - } - } + public static boolean isTest() { + if (impl != null) { + return impl.isTest(); + } else { + throw new BaseSystemNotInitializedException(Interface.class, RobotState.class); + } + } - interface Interface { - boolean isDisabled(); - boolean isEnabled(); - boolean isOperatorControl(); - boolean isAutonomous(); - boolean isTest(); - } + interface Interface { + boolean isDisabled(); + + boolean isEnabled(); + + boolean isOperatorControl(); + + boolean isAutonomous(); + + boolean isTest(); + } } diff --git a/wpilibj/wpilibJava/src/main/java/edu/wpi/first/wpilibj/Sendable.java b/wpilibj/wpilibJava/src/main/java/edu/wpi/first/wpilibj/Sendable.java index 978b4a7851..ec79ff868b 100644 --- a/wpilibj/wpilibJava/src/main/java/edu/wpi/first/wpilibj/Sendable.java +++ b/wpilibj/wpilibJava/src/main/java/edu/wpi/first/wpilibj/Sendable.java @@ -4,23 +4,25 @@ import edu.wpi.first.wpilibj.tables.ITable; /** - * The base interface for objects that can be sent over the network - * through network tables. + * The base interface for objects that can be sent over the network through + * network tables. */ public interface Sendable { - /** - * Initializes a table for this sendable object. - * @param subtable The table to put the values in. - */ - public void initTable(ITable subtable); + /** + * Initializes a table for this sendable object. + *$ + * @param subtable The table to put the values in. + */ + public void initTable(ITable subtable); - /** - * @return the table that is currently associated with the sendable - */ - public ITable getTable(); + /** + * @return the table that is currently associated with the sendable + */ + public ITable getTable(); - /** - * @return the string representation of the named data type that will be used by the smart dashboard for this sendable - */ - public String getSmartDashboardType(); + /** + * @return the string representation of the named data type that will be used + * by the smart dashboard for this sendable + */ + public String getSmartDashboardType(); } diff --git a/wpilibj/wpilibJava/src/main/java/edu/wpi/first/wpilibj/Timer.java b/wpilibj/wpilibJava/src/main/java/edu/wpi/first/wpilibj/Timer.java index 8a1391b859..f208b7034b 100644 --- a/wpilibj/wpilibJava/src/main/java/edu/wpi/first/wpilibj/Timer.java +++ b/wpilibj/wpilibJava/src/main/java/edu/wpi/first/wpilibj/Timer.java @@ -3,169 +3,170 @@ package edu.wpi.first.wpilibj; import edu.wpi.first.wpilibj.util.BaseSystemNotInitializedException; public class Timer { - private static StaticInterface impl; + private static StaticInterface impl; - public static void SetImplementation(StaticInterface ti) { - impl = ti; - } + public static void SetImplementation(StaticInterface ti) { + impl = ti; + } - /** - * Return the system clock time in seconds. Return the time from the - * FPGA hardware clock in seconds since the FPGA started. - * - * @return Robot running time in seconds. - */ - public static double getFPGATimestamp() { - if (impl != null) { - return impl.getFPGATimestamp(); - } else { - throw new BaseSystemNotInitializedException(StaticInterface.class, Timer.class); - } - } + /** + * Return the system clock time in seconds. Return the time from the FPGA + * hardware clock in seconds since the FPGA started. + * + * @return Robot running time in seconds. + */ + public static double getFPGATimestamp() { + if (impl != null) { + return impl.getFPGATimestamp(); + } else { + throw new BaseSystemNotInitializedException(StaticInterface.class, Timer.class); + } + } - /** - * Return the approximate match time - * The FMS does not currently send the official match time to the robots - * This returns the time since the enable signal sent from the Driver Station - * At the beginning of autonomous, the time is reset to 0.0 seconds - * At the beginning of teleop, the time is reset to +15.0 seconds - * If the robot is disabled, this returns 0.0 seconds - * Warning: This is not an official time (so it cannot be used to argue with referees) - * @return Match time in seconds since the beginning of autonomous - */ - public static double getMatchTime() { - if (impl != null) { - return impl.getMatchTime(); - } else { - throw new BaseSystemNotInitializedException(StaticInterface.class, Timer.class); - } - } + /** + * Return the approximate match time The FMS does not currently send the + * official match time to the robots This returns the time since the enable + * signal sent from the Driver Station At the beginning of autonomous, the + * time is reset to 0.0 seconds At the beginning of teleop, the time is reset + * to +15.0 seconds If the robot is disabled, this returns 0.0 seconds + * Warning: This is not an official time (so it cannot be used to argue with + * referees) + *$ + * @return Match time in seconds since the beginning of autonomous + */ + public static double getMatchTime() { + if (impl != null) { + return impl.getMatchTime(); + } else { + throw new BaseSystemNotInitializedException(StaticInterface.class, Timer.class); + } + } - /** - * Pause the thread for a specified time. Pause the execution of the - * thread for a specified period of time given in seconds. Motors will - * continue to run at their last assigned values, and sensors will continue - * to update. Only the task containing the wait will pause until the wait - * time is expired. - * - * @param seconds Length of time to pause - */ - public static void delay(final double seconds) { - if (impl != null) { - impl.delay(seconds); - } else { - throw new BaseSystemNotInitializedException(StaticInterface.class, Timer.class); - } - } + /** + * Pause the thread for a specified time. Pause the execution of the thread + * for a specified period of time given in seconds. Motors will continue to + * run at their last assigned values, and sensors will continue to update. + * Only the task containing the wait will pause until the wait time is + * expired. + * + * @param seconds Length of time to pause + */ + public static void delay(final double seconds) { + if (impl != null) { + impl.delay(seconds); + } else { + throw new BaseSystemNotInitializedException(StaticInterface.class, Timer.class); + } + } - public interface StaticInterface { - double getFPGATimestamp(); - double getMatchTime(); - void delay(final double seconds); - Interface newTimer(); - } + public interface StaticInterface { + double getFPGATimestamp(); - private final Interface timer; - - public Timer() { - if(impl != null){ - timer = impl.newTimer(); - } else { - throw new BaseSystemNotInitializedException(StaticInterface.class, Timer.class); - } - } + double getMatchTime(); - /** - * Get the current time from the timer. If the clock is running it is derived from - * the current system clock the start time stored in the timer class. If the clock - * is not running, then return the time when it was last stopped. - * - * @return Current time value for this timer in seconds - */ - public double get() { - return timer.get(); - } + void delay(final double seconds); - /** - * Reset the timer by setting the time to 0. - * Make the timer startTime the current time so new requests will be relative now - */ - public void reset() { - timer.reset(); - } + Interface newTimer(); + } - /** - * Start the timer running. - * Just set the running flag to true indicating that all time requests should be - * relative to the system clock. - */ - public void start() { - timer.start(); - } + private final Interface timer; - /** - * Stop the timer. - * This computes the time as of now and clears the running flag, causing all - * subsequent time requests to be read from the accumulated time rather than - * looking at the system clock. - */ - public void stop() { - timer.stop(); - } + public Timer() { + if (impl != null) { + timer = impl.newTimer(); + } else { + throw new BaseSystemNotInitializedException(StaticInterface.class, Timer.class); + } + } - /** - * Check if the period specified has passed and if it has, advance the start - * time by that period. This is useful to decide if it's time to do periodic - * work without drifting later by the time it took to get around to checking. - * - * @param period The period to check for (in seconds). - * @return If the period has passed. - */ - public boolean hasPeriodPassed(double period) - { - return timer.hasPeriodPassed(period); - } + /** + * Get the current time from the timer. If the clock is running it is derived + * from the current system clock the start time stored in the timer class. If + * the clock is not running, then return the time when it was last stopped. + * + * @return Current time value for this timer in seconds + */ + public double get() { + return timer.get(); + } - public interface Interface { - /** - * Get the current time from the timer. If the clock is running it is derived from - * the current system clock the start time stored in the timer class. If the clock - * is not running, then return the time when it was last stopped. - * - * @return Current time value for this timer in seconds - */ - public double get(); + /** + * Reset the timer by setting the time to 0. Make the timer startTime the + * current time so new requests will be relative now + */ + public void reset() { + timer.reset(); + } - /** - * Reset the timer by setting the time to 0. - * Make the timer startTime the current time so new requests will be relative now - */ - public void reset(); + /** + * Start the timer running. Just set the running flag to true indicating that + * all time requests should be relative to the system clock. + */ + public void start() { + timer.start(); + } - /** - * Start the timer running. - * Just set the running flag to true indicating that all time requests should be - * relative to the system clock. - */ - public void start(); + /** + * Stop the timer. This computes the time as of now and clears the running + * flag, causing all subsequent time requests to be read from the accumulated + * time rather than looking at the system clock. + */ + public void stop() { + timer.stop(); + } - /** - * Stop the timer. - * This computes the time as of now and clears the running flag, causing all - * subsequent time requests to be read from the accumulated time rather than - * looking at the system clock. - */ - public void stop(); + /** + * Check if the period specified has passed and if it has, advance the start + * time by that period. This is useful to decide if it's time to do periodic + * work without drifting later by the time it took to get around to checking. + * + * @param period The period to check for (in seconds). + * @return If the period has passed. + */ + public boolean hasPeriodPassed(double period) { + return timer.hasPeriodPassed(period); + } + + public interface Interface { + /** + * Get the current time from the timer. If the clock is running it is + * derived from the current system clock the start time stored in the timer + * class. If the clock is not running, then return the time when it was last + * stopped. + * + * @return Current time value for this timer in seconds + */ + public double get(); + + /** + * Reset the timer by setting the time to 0. Make the timer startTime the + * current time so new requests will be relative now + */ + public void reset(); + + /** + * Start the timer running. Just set the running flag to true indicating + * that all time requests should be relative to the system clock. + */ + public void start(); + + /** + * Stop the timer. This computes the time as of now and clears the running + * flag, causing all subsequent time requests to be read from the + * accumulated time rather than looking at the system clock. + */ + public void stop(); - /** - * Check if the period specified has passed and if it has, advance the start - * time by that period. This is useful to decide if it's time to do periodic - * work without drifting later by the time it took to get around to checking. - * - * @param period The period to check for (in seconds). - * @return If the period has passed. - */ - public boolean hasPeriodPassed(double period); - } + /** + * Check if the period specified has passed and if it has, advance the start + * time by that period. This is useful to decide if it's time to do periodic + * work without drifting later by the time it took to get around to + * checking. + * + * @param period The period to check for (in seconds). + * @return If the period has passed. + */ + public boolean hasPeriodPassed(double period); + } } diff --git a/wpilibj/wpilibJava/src/main/java/edu/wpi/first/wpilibj/buttons/Button.java b/wpilibj/wpilibJava/src/main/java/edu/wpi/first/wpilibj/buttons/Button.java index 02981c2212..a6ff80f489 100644 --- a/wpilibj/wpilibJava/src/main/java/edu/wpi/first/wpilibj/buttons/Button.java +++ b/wpilibj/wpilibJava/src/main/java/edu/wpi/first/wpilibj/buttons/Button.java @@ -1,8 +1,8 @@ /*----------------------------------------------------------------------------*/ -/* Copyright (c) FIRST 2008-2012. All Rights Reserved. */ -/* Open Source Software - may be modified and shared by FRC teams. The code */ +/* Copyright (c) FIRST 2008-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 the root directory of */ -/* the project. */ +/* the project. */ /*----------------------------------------------------------------------------*/ package edu.wpi.first.wpilibj.buttons; @@ -12,59 +12,63 @@ import edu.wpi.first.wpilibj.command.Command; /** * This class provides an easy way to link commands to OI inputs. * - * It is very easy to link a button to a command. For instance, you could - * link the trigger button of a joystick to a "score" command. + * It is very easy to link a button to a command. For instance, you could link + * the trigger button of a joystick to a "score" command. * * This class represents a subclass of Trigger that is specifically aimed at * buttons on an operator interface as a common use case of the more generalized - * Trigger objects. This is a simple wrapper around Trigger with the method names - * renamed to fit the Button object use. + * Trigger objects. This is a simple wrapper around Trigger with the method + * names renamed to fit the Button object use. * * @author brad */ public abstract class Button extends Trigger { - /** - * Starts the given command whenever the button is newly pressed. - * @param command the command to start - */ - public void whenPressed(final Command command) { - whenActive(command); - } + /** + * Starts the given command whenever the button is newly pressed. + *$ + * @param command the command to start + */ + public void whenPressed(final Command command) { + whenActive(command); + } - /** - * Constantly starts the given command while the button is held. - * - * {@link Command#start()} will be called repeatedly while the button is held, - * and will be canceled when the button is released. - * - * @param command the command to start - */ - public void whileHeld(final Command command) { - whileActive(command); - } + /** + * Constantly starts the given command while the button is held. + * + * {@link Command#start()} will be called repeatedly while the button is held, + * and will be canceled when the button is released. + * + * @param command the command to start + */ + public void whileHeld(final Command command) { + whileActive(command); + } - /** - * Starts the command when the button is released - * @param command the command to start - */ - public void whenReleased(final Command command) { - whenInactive(command); - } + /** + * Starts the command when the button is released + *$ + * @param command the command to start + */ + public void whenReleased(final Command command) { + whenInactive(command); + } - /** - * Toggles the command whenever the button is pressed (on then off then on) - * @param command the command to start - */ - public void toggleWhenPressed(final Command command) { - toggleWhenActive(command); - } + /** + * Toggles the command whenever the button is pressed (on then off then on) + *$ + * @param command the command to start + */ + public void toggleWhenPressed(final Command command) { + toggleWhenActive(command); + } - /** - * Cancel the command when the button is pressed - * @param command the command to start - */ - public void cancelWhenPressed(final Command command) { - cancelWhenActive(command); - } + /** + * Cancel the command when the button is pressed + *$ + * @param command the command to start + */ + public void cancelWhenPressed(final Command command) { + cancelWhenActive(command); + } } diff --git a/wpilibj/wpilibJava/src/main/java/edu/wpi/first/wpilibj/buttons/InternalButton.java b/wpilibj/wpilibJava/src/main/java/edu/wpi/first/wpilibj/buttons/InternalButton.java index 8757c271c7..92e84578e8 100644 --- a/wpilibj/wpilibJava/src/main/java/edu/wpi/first/wpilibj/buttons/InternalButton.java +++ b/wpilibj/wpilibJava/src/main/java/edu/wpi/first/wpilibj/buttons/InternalButton.java @@ -1,48 +1,50 @@ /*----------------------------------------------------------------------------*/ -/* Copyright (c) FIRST 2008-2012. All Rights Reserved. */ -/* Open Source Software - may be modified and shared by FRC teams. The code */ +/* Copyright (c) FIRST 2008-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 the root directory of */ -/* the project. */ +/* the project. */ /*----------------------------------------------------------------------------*/ package edu.wpi.first.wpilibj.buttons; /** - * This class is intended to be used within a program. The programmer can manually set its value. - * Also includes a setting for whether or not it should invert its value. + * This class is intended to be used within a program. The programmer can + * manually set its value. Also includes a setting for whether or not it should + * invert its value. * * @author Joe */ public class InternalButton extends Button { - boolean pressed; - boolean inverted; + boolean pressed; + boolean inverted; - /** - * Creates an InternalButton that is not inverted. - */ - public InternalButton() { - this(false); - } + /** + * Creates an InternalButton that is not inverted. + */ + public InternalButton() { + this(false); + } - /** - * Creates an InternalButton which is inverted depending on the input. - * - * @param inverted if false, then this button is pressed when set to true, otherwise it is pressed when set to false. - */ - public InternalButton(boolean inverted) { - this.pressed = this.inverted = inverted; - } + /** + * Creates an InternalButton which is inverted depending on the input. + * + * @param inverted if false, then this button is pressed when set to true, + * otherwise it is pressed when set to false. + */ + public InternalButton(boolean inverted) { + this.pressed = this.inverted = inverted; + } - public void setInverted(boolean inverted) { - this.inverted = inverted; - } + public void setInverted(boolean inverted) { + this.inverted = inverted; + } - public void setPressed(boolean pressed) { - this.pressed = pressed; - } + public void setPressed(boolean pressed) { + this.pressed = pressed; + } - public boolean get() { - return pressed ^ inverted; - } + public boolean get() { + return pressed ^ inverted; + } } diff --git a/wpilibj/wpilibJava/src/main/java/edu/wpi/first/wpilibj/buttons/JoystickButton.java b/wpilibj/wpilibJava/src/main/java/edu/wpi/first/wpilibj/buttons/JoystickButton.java index 5beff0d7ec..fb03606dca 100644 --- a/wpilibj/wpilibJava/src/main/java/edu/wpi/first/wpilibj/buttons/JoystickButton.java +++ b/wpilibj/wpilibJava/src/main/java/edu/wpi/first/wpilibj/buttons/JoystickButton.java @@ -1,8 +1,8 @@ /*----------------------------------------------------------------------------*/ -/* Copyright (c) FIRST 2008-2012. All Rights Reserved. */ -/* Open Source Software - may be modified and shared by FRC teams. The code */ +/* Copyright (c) FIRST 2008-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 the root directory of */ -/* the project. */ +/* the project. */ /*----------------------------------------------------------------------------*/ package edu.wpi.first.wpilibj.buttons; @@ -15,24 +15,28 @@ import edu.wpi.first.wpilibj.GenericHID; */ public class JoystickButton extends Button { - GenericHID m_joystick; - int m_buttonNumber; + GenericHID m_joystick; + int m_buttonNumber; - /** - * Create a joystick button for triggering commands - * @param joystick The GenericHID object that has the button (e.g. Joystick, KinectStick, etc) - * @param buttonNumber The button number (see {@link GenericHID#getRawButton(int) } - */ - public JoystickButton(GenericHID joystick, int buttonNumber) { - m_joystick = joystick; - m_buttonNumber = buttonNumber; - } + /** + * Create a joystick button for triggering commands + *$ + * @param joystick The GenericHID object that has the button (e.g. Joystick, + * KinectStick, etc) + * @param buttonNumber The button number (see + * {@link GenericHID#getRawButton(int) } + */ + public JoystickButton(GenericHID joystick, int buttonNumber) { + m_joystick = joystick; + m_buttonNumber = buttonNumber; + } - /** - * Gets the value of the joystick button - * @return The value of the joystick button - */ - public boolean get() { - return m_joystick.getRawButton(m_buttonNumber); - } + /** + * Gets the value of the joystick button + *$ + * @return The value of the joystick button + */ + public boolean get() { + return m_joystick.getRawButton(m_buttonNumber); + } } diff --git a/wpilibj/wpilibJava/src/main/java/edu/wpi/first/wpilibj/buttons/NetworkButton.java b/wpilibj/wpilibJava/src/main/java/edu/wpi/first/wpilibj/buttons/NetworkButton.java index fd0a23149c..3941fd1a0a 100644 --- a/wpilibj/wpilibJava/src/main/java/edu/wpi/first/wpilibj/buttons/NetworkButton.java +++ b/wpilibj/wpilibJava/src/main/java/edu/wpi/first/wpilibj/buttons/NetworkButton.java @@ -1,8 +1,8 @@ /*----------------------------------------------------------------------------*/ -/* Copyright (c) FIRST 2008-2012. All Rights Reserved. */ -/* Open Source Software - may be modified and shared by FRC teams. The code */ +/* Copyright (c) FIRST 2008-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 the root directory of */ -/* the project. */ +/* the project. */ /*----------------------------------------------------------------------------*/ package edu.wpi.first.wpilibj.buttons; @@ -15,19 +15,19 @@ import edu.wpi.first.wpilibj.networktables.NetworkTable; */ public class NetworkButton extends Button { - NetworkTable table; - String field; + NetworkTable table; + String field; - public NetworkButton(String table, String field) { - this(NetworkTable.getTable(table), field); - } + public NetworkButton(String table, String field) { + this(NetworkTable.getTable(table), field); + } - public NetworkButton(NetworkTable table, String field) { - this.table = table; - this.field = field; - } + public NetworkButton(NetworkTable table, String field) { + this.table = table; + this.field = field; + } - public boolean get() { - return table.isConnected() && table.getBoolean(field, false); - } + public boolean get() { + return table.isConnected() && table.getBoolean(field, false); + } } diff --git a/wpilibj/wpilibJava/src/main/java/edu/wpi/first/wpilibj/buttons/Trigger.java b/wpilibj/wpilibJava/src/main/java/edu/wpi/first/wpilibj/buttons/Trigger.java index 4e6ca903ec..02c489ea8a 100644 --- a/wpilibj/wpilibJava/src/main/java/edu/wpi/first/wpilibj/buttons/Trigger.java +++ b/wpilibj/wpilibJava/src/main/java/edu/wpi/first/wpilibj/buttons/Trigger.java @@ -1,8 +1,8 @@ /*----------------------------------------------------------------------------*/ -/* Copyright (c) FIRST 2008-2012. All Rights Reserved. */ -/* Open Source Software - may be modified and shared by FRC teams. The code */ +/* Copyright (c) FIRST 2008-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 the root directory of */ -/* the project. */ +/* the project. */ /*----------------------------------------------------------------------------*/ package edu.wpi.first.wpilibj.buttons; @@ -15,186 +15,200 @@ import edu.wpi.first.wpilibj.tables.ITable; /** * This class provides an easy way to link commands to inputs. * - * It is very easy to link a button to a command. For instance, you could - * link the trigger button of a joystick to a "score" command. + * It is very easy to link a button to a command. For instance, you could link + * the trigger button of a joystick to a "score" command. * * It is encouraged that teams write a subclass of Trigger if they want to have - * something unusual (for instance, if they want to react to the user holding - * a button while the robot is reading a certain sensor input). For this, they - * only have to write the {@link Trigger#get()} method to get the full functionality - * of the Trigger class. + * something unusual (for instance, if they want to react to the user holding a + * button while the robot is reading a certain sensor input). For this, they + * only have to write the {@link Trigger#get()} method to get the full + * functionality of the Trigger class. * * @author Joe Grinstead */ public abstract class Trigger implements Sendable { - /** - * Returns whether or not the trigger is active - * - * This method will be called repeatedly a command is linked to the Trigger. - * - * @return whether or not the trigger condition is active. - */ - public abstract boolean get(); + /** + * Returns whether or not the trigger is active + * + * This method will be called repeatedly a command is linked to the Trigger. + * + * @return whether or not the trigger condition is active. + */ + public abstract boolean get(); - /** - * Returns whether get() return true or the internal table for SmartDashboard use is pressed. - * @return whether get() return true or the internal table for SmartDashboard use is pressed - */ - private boolean grab() { - return get() || (table != null /*&& table.isConnected()*/ && table.getBoolean("pressed", false));//FIXME make is connected work? - } + /** + * Returns whether get() return true or the internal table for SmartDashboard + * use is pressed. + *$ + * @return whether get() return true or the internal table for SmartDashboard + * use is pressed + */ + private boolean grab() { + return get() + || (table != null /* && table.isConnected() */&& table.getBoolean("pressed", false));// FIXME + // make + // is + // connected + // work? + } - /** - * Starts the given command whenever the trigger just becomes active. - * @param command the command to start - */ - public void whenActive(final Command command) { - new ButtonScheduler() { + /** + * Starts the given command whenever the trigger just becomes active. + *$ + * @param command the command to start + */ + public void whenActive(final Command command) { + new ButtonScheduler() { - boolean pressedLast = grab(); + boolean pressedLast = grab(); - public void execute() { - if (grab()) { - if (!pressedLast) { - pressedLast = true; - command.start(); - } - } else { - pressedLast = false; - } - } - } .start(); - } - - /** - * Constantly starts the given command while the button is held. - * - * {@link Command#start()} will be called repeatedly while the trigger is active, - * and will be canceled when the trigger becomes inactive. - * - * @param command the command to start - */ - public void whileActive(final Command command) { - new ButtonScheduler() { - - boolean pressedLast = grab(); - - public void execute() { - if (grab()) { - pressedLast = true; - command.start(); - } else { - if (pressedLast) { - pressedLast = false; - command.cancel(); - } - } - } - } .start(); - } - - /** - * Starts the command when the trigger becomes inactive - * @param command the command to start - */ - public void whenInactive(final Command command) { - new ButtonScheduler() { - - boolean pressedLast = grab(); - - public void execute() { - if (grab()) { - pressedLast = true; - } else { - if (pressedLast) { - pressedLast = false; - command.start(); - } - } - } - } .start(); - } - - /** - * Toggles a command when the trigger becomes active - * @param command the command to toggle - */ - public void toggleWhenActive(final Command command) { - new ButtonScheduler() { - - boolean pressedLast = grab(); - - public void execute() { - if (grab()) { - if (!pressedLast) { - pressedLast = true; - if (command.isRunning()) { - command.cancel(); - } else { - command.start(); - } - } - } else { - pressedLast = false; - } - } - } .start(); - } - - /** - * Cancels a command when the trigger becomes active - * @param command the command to cancel - */ - public void cancelWhenActive(final Command command) { - new ButtonScheduler() { - - boolean pressedLast = grab(); - - public void execute() { - if (grab()) { - if (!pressedLast) { - pressedLast = true; - command.cancel(); - } - } else { - pressedLast = false; - } - } - } .start(); - } - - /** - * An internal class of {@link Trigger}. The user should ignore this, it is - * only public to interface between packages. - */ - public abstract class ButtonScheduler { - public abstract void execute(); - - protected void start() { - Scheduler.getInstance().addButton(this); + public void execute() { + if (grab()) { + if (!pressedLast) { + pressedLast = true; + command.start(); + } + } else { + pressedLast = false; } - } + } + }.start(); + } - /** - * These methods continue to return the "Button" SmartDashboard type until we decided - * to create a Trigger widget type for the dashboard. - */ - public String getSmartDashboardType() { - return "Button"; - } - private ITable table; - public void initTable(ITable table) { - this.table = table; - if(table!=null) { - table.putBoolean("pressed", get()); + /** + * Constantly starts the given command while the button is held. + * + * {@link Command#start()} will be called repeatedly while the trigger is + * active, and will be canceled when the trigger becomes inactive. + * + * @param command the command to start + */ + public void whileActive(final Command command) { + new ButtonScheduler() { + + boolean pressedLast = grab(); + + public void execute() { + if (grab()) { + pressedLast = true; + command.start(); + } else { + if (pressedLast) { + pressedLast = false; + command.cancel(); + } } - } + } + }.start(); + } - /** - * {@inheritDoc} - */ - public ITable getTable() { - return table; + /** + * Starts the command when the trigger becomes inactive + *$ + * @param command the command to start + */ + public void whenInactive(final Command command) { + new ButtonScheduler() { + + boolean pressedLast = grab(); + + public void execute() { + if (grab()) { + pressedLast = true; + } else { + if (pressedLast) { + pressedLast = false; + command.start(); + } + } + } + }.start(); + } + + /** + * Toggles a command when the trigger becomes active + *$ + * @param command the command to toggle + */ + public void toggleWhenActive(final Command command) { + new ButtonScheduler() { + + boolean pressedLast = grab(); + + public void execute() { + if (grab()) { + if (!pressedLast) { + pressedLast = true; + if (command.isRunning()) { + command.cancel(); + } else { + command.start(); + } + } + } else { + pressedLast = false; + } + } + }.start(); + } + + /** + * Cancels a command when the trigger becomes active + *$ + * @param command the command to cancel + */ + public void cancelWhenActive(final Command command) { + new ButtonScheduler() { + + boolean pressedLast = grab(); + + public void execute() { + if (grab()) { + if (!pressedLast) { + pressedLast = true; + command.cancel(); + } + } else { + pressedLast = false; + } + } + }.start(); + } + + /** + * An internal class of {@link Trigger}. The user should ignore this, it is + * only public to interface between packages. + */ + public abstract class ButtonScheduler { + public abstract void execute(); + + protected void start() { + Scheduler.getInstance().addButton(this); } + } + + /** + * These methods continue to return the "Button" SmartDashboard type until we + * decided to create a Trigger widget type for the dashboard. + */ + public String getSmartDashboardType() { + return "Button"; + } + + private ITable table; + + public void initTable(ITable table) { + this.table = table; + if (table != null) { + table.putBoolean("pressed", get()); + } + } + + /** + * {@inheritDoc} + */ + public ITable getTable() { + return table; + } } diff --git a/wpilibj/wpilibJava/src/main/java/edu/wpi/first/wpilibj/command/Command.java b/wpilibj/wpilibJava/src/main/java/edu/wpi/first/wpilibj/command/Command.java index b25757ac82..526f3b0712 100644 --- a/wpilibj/wpilibJava/src/main/java/edu/wpi/first/wpilibj/command/Command.java +++ b/wpilibj/wpilibJava/src/main/java/edu/wpi/first/wpilibj/command/Command.java @@ -1,8 +1,8 @@ /*----------------------------------------------------------------------------*/ -/* Copyright (c) FIRST 2008-2012. All Rights Reserved. */ -/* Open Source Software - may be modified and shared by FRC teams. The code */ +/* Copyright (c) FIRST 2008-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 the root directory of */ -/* the project. */ +/* the project. */ /*----------------------------------------------------------------------------*/ package edu.wpi.first.wpilibj.command; @@ -16,26 +16,35 @@ import java.util.Enumeration; import java.util.NoSuchElementException; /** - * The Command class is at the very core of the entire command framework. - * Every command can be started with a call to {@link Command#start() start()}. - * Once a command is started it will call {@link Command#initialize() initialize()}, and then - * will repeatedly call {@link Command#execute() execute()} until the {@link Command#isFinished() isFinished()} - * returns true. Once it does, {@link Command#end() end()} will be called. + * The Command class is at the very core of the entire command framework. Every + * command can be started with a call to {@link Command#start() start()}. Once a + * command is started it will call {@link Command#initialize() initialize()}, + * and then will repeatedly call {@link Command#execute() execute()} until the + * {@link Command#isFinished() isFinished()} returns true. Once it does, + * {@link Command#end() end()} will be called. * - *

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.

+ *

+ * 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. + *

* - *

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.

+ *

+ * 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. + *

* - *

If a command is running and a new command with shared requirements is started, - * then one of two things will happen. If the active command is interruptible, - * then {@link Command#cancel() cancel()} will be called and the command will be removed - * to make way for the new one. If the active command is not interruptible, the - * other one will not even be started, and the active one will continue functioning.

+ *

+ * If a command is running and a new command with shared requirements is + * started, then one of two things will happen. If the active command is + * interruptible, then {@link Command#cancel() cancel()} will be called and the + * command will be removed to make way for the new one. If the active command is + * not interruptible, the other one will not even be started, and the active one + * will continue functioning. + *

* * @author Brad Miller * @author Joe Grinstead @@ -45,479 +54,538 @@ import java.util.NoSuchElementException; */ public abstract class Command implements NamedSendable { - /** The name of this command */ - private String m_name; - /** The time since this command was initialized */ - private double m_startTime = -1; - /** The time (in seconds) before this command "times out" (or -1 if no timeout) */ - private double m_timeout = -1; - /** Whether or not this command has been initialized */ - private boolean m_initialized = false; - /** The requirements (or null if no requirements) */ - private Set m_requirements; - /** Whether or not it is running */ - private boolean m_running = false; - /** Whether or not it is interruptible*/ - private boolean m_interruptible = true; - /** Whether or not it has been canceled */ - private boolean m_canceled = false; - /** Whether or not it has been locked */ - private boolean m_locked = false; - /** Whether this command should run when the robot is disabled */ - private boolean m_runWhenDisabled = false; - /** The {@link CommandGroup} this is in */ - private CommandGroup m_parent; + /** The name of this command */ + private String m_name; + /** The time since this command was initialized */ + private double m_startTime = -1; + /** + * The time (in seconds) before this command "times out" (or -1 if no timeout) + */ + private double m_timeout = -1; + /** Whether or not this command has been initialized */ + private boolean m_initialized = false; + /** The requirements (or null if no requirements) */ + private Set m_requirements; + /** Whether or not it is running */ + private boolean m_running = false; + /** Whether or not it is interruptible */ + private boolean m_interruptible = true; + /** Whether or not it has been canceled */ + private boolean m_canceled = false; + /** Whether or not it has been locked */ + private boolean m_locked = false; + /** Whether this command should run when the robot is disabled */ + private boolean m_runWhenDisabled = false; + /** The {@link CommandGroup} this is in */ + private CommandGroup m_parent; - /** - * Creates a new command. - * The name of this command will be set to its class name. - */ - public Command() { - m_name = getClass().getName(); - m_name = m_name.substring(m_name.lastIndexOf('.') + 1); + /** + * Creates a new command. The name of this command will be set to its class + * name. + */ + public Command() { + m_name = getClass().getName(); + m_name = m_name.substring(m_name.lastIndexOf('.') + 1); + } + + /** + * Creates a new command with the given name. + *$ + * @param name the name for this command + * @throws IllegalArgumentException if name is null + */ + public Command(String name) { + if (name == null) { + throw new IllegalArgumentException("Name must not be null."); + } + m_name = name; + } + + /** + * Creates a new command with the given timeout and a default name. The + * default name is the name of the class. + *$ + * @param timeout the time (in seconds) before this command "times out" + * @throws IllegalArgumentException if given a negative timeout + * @see Command#isTimedOut() isTimedOut() + */ + public Command(double timeout) { + this(); + if (timeout < 0) { + throw new IllegalArgumentException("Timeout must not be negative. Given:" + timeout); + } + m_timeout = timeout; + } + + /** + * Creates a new command with the given name and timeout. + *$ + * @param name the name of the command + * @param timeout the time (in seconds) before this command "times out" + * @throws IllegalArgumentException if given a negative timeout or name was + * null. + * @see Command#isTimedOut() isTimedOut() + */ + public Command(String name, double timeout) { + this(name); + if (timeout < 0) { + throw new IllegalArgumentException("Timeout must not be negative. Given:" + timeout); + } + m_timeout = timeout; + } + + /** + * Returns the name of this command. If no name was specified in the + * constructor, then the default is the name of the class. + *$ + * @return the name of this command + */ + public String getName() { + return m_name; + } + + /** + * Sets the timeout of this command. + *$ + * @param seconds the timeout (in seconds) + * @throws IllegalArgumentException if seconds is negative + * @see Command#isTimedOut() isTimedOut() + */ + protected synchronized final void setTimeout(double seconds) { + if (seconds < 0) { + throw new IllegalArgumentException("Seconds must be positive. Given:" + seconds); + } + m_timeout = seconds; + } + + /** + * Returns the time since this command was initialized (in seconds). This + * function will work even if there is no specified timeout. + *$ + * @return the time since this command was initialized (in seconds). + */ + public synchronized final double timeSinceInitialized() { + return m_startTime < 0 ? 0 : Timer.getFPGATimestamp() - m_startTime; + } + + /** + * 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. + * + *

+ * Note that the recommended way to call this method is in the constructor. + *

+ * + * @param subsystem the {@link Subsystem} required + * @throws IllegalArgumentException if subsystem is null + * @throws IllegalUseOfCommandException if this command has started before or + * if it has been given to a {@link CommandGroup} + * @see Subsystem + */ + protected synchronized void requires(Subsystem subsystem) { + validate("Can not add new requirement to command"); + if (subsystem != null) { + if (m_requirements == null) { + m_requirements = new Set(); + } + m_requirements.add(subsystem); + } else { + throw new IllegalArgumentException("Subsystem must not be null."); + } + } + + /** + * Called when the command has been removed. This will call + * {@link Command#interrupted() interrupted()} or {@link Command#end() end()}. + */ + synchronized void removed() { + if (m_initialized) { + if (isCanceled()) { + interrupted(); + _interrupted(); + } else { + end(); + _end(); + } + } + m_initialized = false; + m_canceled = false; + m_running = false; + if (table != null) { + table.putBoolean("running", false); + } + } + + /** + * The run method is used internally to actually run the commands. + *$ + * @return whether or not the command should stay within the {@link Scheduler} + * . + */ + synchronized boolean run() { + if (!m_runWhenDisabled && m_parent == null && RobotState.isDisabled()) { + cancel(); + } + if (isCanceled()) { + return false; + } + if (!m_initialized) { + m_initialized = true; + startTiming(); + _initialize(); + initialize(); + } + _execute(); + execute(); + return !isFinished(); + } + + /** + * The initialize method is called the first time this Command is run after + * being started. + */ + protected abstract void initialize(); + + /** A shadow method called before {@link Command#initialize() initialize()} */ + void _initialize() {} + + /** + * The execute method is called repeatedly until this Command either finishes + * or is canceled. + */ + protected abstract void execute(); + + /** A shadow method called before {@link Command#execute() execute()} */ + void _execute() {} + + /** + * Returns whether this command is finished. If it is, then the command will + * be removed and {@link Command#end() end()} will be called. + * + *

+ * It may be useful for a team to reference the {@link Command#isTimedOut() + * isTimedOut()} method for time-sensitive commands. + *

+ *$ + * @return whether this command is finished. + * @see Command#isTimedOut() isTimedOut() + */ + protected abstract boolean isFinished(); + + /** + * 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. + */ + protected abstract void end(); + + /** A shadow method called after {@link Command#end() end()}. */ + void _end() {} + + /** + * 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. + * + *

+ * This is where you may want to wrap up loose ends, like shutting off a motor + * that was being used in the command. + *

+ * + *

+ * Generally, it is useful to simply call the {@link Command#end() end()} + * method within this method + *

+ */ + protected abstract void interrupted(); + + /** A shadow method called after {@link Command#interrupted() interrupted()}. */ + void _interrupted() {} + + /** + * Called to indicate that the timer should start. This is called right before + * {@link Command#initialize() initialize()} is, inside the + * {@link Command#run() run()} method. + */ + private void 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. If there is no timeout, this will + * always return false. + *$ + * @return whether the time has expired + */ + protected synchronized boolean isTimedOut() { + return m_timeout != -1 && timeSinceInitialized() >= m_timeout; + } + + /** + * Returns the requirements (as an {@link Enumeration Enumeration} of + * {@link Subsystem Subsystems}) of this command + *$ + * @return the requirements (as an {@link Enumeration Enumeration} of + * {@link Subsystem Subsystems}) of this command + */ + synchronized Enumeration getRequirements() { + return m_requirements == null ? emptyEnumeration : m_requirements.getElements(); + } + + /** + * Prevents further changes from being made + */ + synchronized void lockChanges() { + m_locked = true; + } + + /** + * If changes are locked, then this will throw an + * {@link IllegalUseOfCommandException}. + *$ + * @param message the message to say (it is appended by a default message) + */ + synchronized void validate(String message) { + if (m_locked) { + throw new IllegalUseOfCommandException(message + + " after being started or being added to a command group"); + } + } + + /** + * Sets the parent of this command. No actual change is made to the group. + *$ + * @param parent the parent + * @throws IllegalUseOfCommandException if this {@link Command} already is + * already in a group + */ + synchronized void setParent(CommandGroup parent) { + if (this.m_parent != null) { + throw new IllegalUseOfCommandException( + "Can not give command to a command group after already being put in a command group"); + } + lockChanges(); + this.m_parent = parent; + if (table != null) { + table.putBoolean("isParented", true); + } + } + + /** + * Starts up the command. Gets the command ready to start. + *

+ * 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. + *

+ *$ + * @throws IllegalUseOfCommandException if the command is a part of a + * CommandGroup + */ + public synchronized void start() { + lockChanges(); + if (m_parent != null) { + throw new IllegalUseOfCommandException( + "Can not start a command that is a part of a command group"); + } + Scheduler.getInstance().add(this); + } + + /** + * This is used internally to mark that the command has been started. The + * lifecycle of a command is: + * + * startRunning() is called. run() is called (multiple times potentially) + * removed() is called + * + * It is very important that startRunning and removed be called in order or + * some assumptions of the code will be broken. + */ + synchronized void startRunning() { + m_running = true; + m_startTime = -1; + if (table != null) { + table.putBoolean("running", true); + } + } + + /** + * Returns whether or not the command is running. This may return true even if + * the command has just been canceled, as it may not have yet called + * {@link Command#interrupted()}. + *$ + * @return whether or not the command is running + */ + public synchronized boolean isRunning() { + return m_running; + } + + /** + * This will cancel the current command. + *

+ * 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. + *

+ *

+ * A command can not be canceled if it is a part of a command group, you must + * cancel the command group instead. + *

+ *$ + * @throws IllegalUseOfCommandException if this command is a part of a command + * group + */ + public synchronized void cancel() { + if (m_parent != null) { + throw new IllegalUseOfCommandException("Can not manually cancel a command in a command group"); + } + _cancel(); + } + + /** + * 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. + */ + synchronized void _cancel() { + if (isRunning()) { + m_canceled = true; + } + } + + /** + * Returns whether or not this has been canceled. + *$ + * @return whether or not this has been canceled + */ + public synchronized boolean isCanceled() { + return m_canceled; + } + + /** + * Returns whether or not this command can be interrupted. + *$ + * @return whether or not this command can be interrupted + */ + public synchronized boolean isInterruptible() { + return m_interruptible; + } + + /** + * Sets whether or not this command can be interrupted. + *$ + * @param interruptible whether or not this command can be interrupted + */ + protected synchronized void setInterruptible(boolean interruptible) { + this.m_interruptible = interruptible; + } + + /** + * Checks if the command requires the given {@link Subsystem}. + *$ + * @param system the system + * @return whether or not the subsystem is required, or false if given null + */ + public synchronized boolean doesRequire(Subsystem system) { + return m_requirements != null && m_requirements.contains(system); + } + + /** + * 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) + */ + public synchronized CommandGroup getGroup() { + return m_parent; + } + + /** + * Sets whether or not this {@link Command} should run when the robot is + * disabled. + * + *

+ * By default a command will not run when the robot is disabled, and will in + * fact be canceled. + *

+ *$ + * @param run whether or not this command should run when the robot is + * disabled + */ + public void setRunWhenDisabled(boolean 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 + */ + public boolean willRunWhenDisabled() { + return m_runWhenDisabled; + } + + /** An empty enumeration given whenever there are no requirements */ + private static Enumeration emptyEnumeration = new Enumeration() { + + public boolean hasMoreElements() { + return false; } - /** - * Creates a new command with the given name. - * @param name the name for this command - * @throws IllegalArgumentException if name is null - */ - public Command(String name) { - if (name == null) { - throw new IllegalArgumentException("Name must not be null."); - } - m_name = name; + public Object nextElement() { + throw new NoSuchElementException(); } + }; - /** - * Creates a new command with the given timeout and a default name. - * The default name is the name of the class. - * @param timeout the time (in seconds) before this command "times out" - * @throws IllegalArgumentException if given a negative timeout - * @see Command#isTimedOut() isTimedOut() - */ - public Command(double timeout) { - this(); - if (timeout < 0) { - throw new IllegalArgumentException("Timeout must not be negative. Given:" + timeout); - } - m_timeout = timeout; + /** + * The string representation for a {@link Command} is by default its name. + *$ + * @return the string representation of this object + */ + public String toString() { + return getName(); + } + + + public String getSmartDashboardType() { + return "Command"; + } + + private ITableListener listener = new ITableListener() { + public void valueChanged(ITable table, String key, Object value, boolean isNew) { + if (((Boolean) value).booleanValue()) { + start(); + } else { + cancel(); + } } + }; + private ITable table; - /** - * Creates a new command with the given name and timeout. - * @param name the name of the command - * @param timeout the time (in seconds) before this command "times out" - * @throws IllegalArgumentException if given a negative timeout or name was null. - * @see Command#isTimedOut() isTimedOut() - */ - public Command(String name, double timeout) { - this(name); - if (timeout < 0) { - throw new IllegalArgumentException("Timeout must not be negative. Given:" + timeout); - } - m_timeout = timeout; + public void initTable(ITable table) { + if (this.table != null) + this.table.removeTableListener(listener); + this.table = table; + if (table != null) { + table.putString("name", getName()); + table.putBoolean("running", isRunning()); + table.putBoolean("isParented", m_parent != null); + table.addTableListener("running", listener, false); } + } - /** - * Returns the name of this command. - * If no name was specified in the constructor, - * then the default is the name of the class. - * @return the name of this command - */ - public String getName() { - return m_name; - } - - /** - * Sets the timeout of this command. - * @param seconds the timeout (in seconds) - * @throws IllegalArgumentException if seconds is negative - * @see Command#isTimedOut() isTimedOut() - */ - protected synchronized final void setTimeout(double seconds) { - if (seconds < 0) { - throw new IllegalArgumentException("Seconds must be positive. Given:" + seconds); - } - m_timeout = seconds; - } - - /** - * Returns the time since this command was initialized (in seconds). - * This function will work even if there is no specified timeout. - * @return the time since this command was initialized (in seconds). - */ - public synchronized final double timeSinceInitialized() { - return m_startTime < 0 ? 0 : Timer.getFPGATimestamp() - m_startTime; - } - - /** - * 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. - * - *

Note that the recommended way to call this method is in the constructor.

- * - * @param subsystem the {@link Subsystem} required - * @throws IllegalArgumentException if subsystem is null - * @throws IllegalUseOfCommandException if this command has started before or if it has been given to a {@link CommandGroup} - * @see Subsystem - */ - protected synchronized void requires(Subsystem subsystem) { - validate("Can not add new requirement to command"); - if (subsystem != null) { - if (m_requirements == null) { - m_requirements = new Set(); - } - m_requirements.add(subsystem); - } else { - throw new IllegalArgumentException("Subsystem must not be null."); - } - } - - /** - * Called when the command has been removed. - * This will call {@link Command#interrupted() interrupted()} or {@link Command#end() end()}. - */ - synchronized void removed() { - if (m_initialized) { - if (isCanceled()) { - interrupted(); - _interrupted(); - } else { - end(); - _end(); - } - } - m_initialized = false; - m_canceled = false; - m_running = false; - if (table != null) { - table.putBoolean("running", false); - } - } - - /** - * The run method is used internally to actually run the commands. - * @return whether or not the command should stay within the {@link Scheduler}. - */ - synchronized boolean run() { - if (!m_runWhenDisabled && m_parent == null && RobotState.isDisabled()) { - cancel(); - } - if (isCanceled()) { - return false; - } - if (!m_initialized) { - m_initialized = true; - startTiming(); - _initialize(); - initialize(); - } - _execute(); - execute(); - return !isFinished(); - } - - /** - * The initialize method is called the first time this Command is run after - * being started. - */ - protected abstract void initialize(); - - /** A shadow method called before {@link Command#initialize() initialize()} */ - void _initialize() { - } - - /** - * The execute method is called repeatedly until this Command either finishes - * or is canceled. - */ - protected abstract void execute(); - - /** A shadow method called before {@link Command#execute() execute()} */ - void _execute() { - } - - /** - * Returns whether this command is finished. - * If it is, then the command will be removed - * and {@link Command#end() end()} will be called. - * - *

It may be useful for a team to reference the {@link Command#isTimedOut() isTimedOut()} method - * for time-sensitive commands.

- * @return whether this command is finished. - * @see Command#isTimedOut() isTimedOut() - */ - protected abstract boolean isFinished(); - - /** - * 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. - */ - protected abstract void end(); - - /** A shadow method called after {@link Command#end() end()}. */ - void _end() { - } - - /** - * 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. - * - *

This is where you may want - * to wrap up loose ends, like shutting off a motor that was being used - * in the command.

- * - *

Generally, it is useful to simply call the {@link Command#end() end()} method - * within this method

- */ - protected abstract void interrupted(); - - /** A shadow method called after {@link Command#interrupted() interrupted()}. */ - void _interrupted() { - } - - /** - * Called to indicate that the timer should start. - * This is called right before {@link Command#initialize() initialize()} is, inside the - * {@link Command#run() run()} method. - */ - private void 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. - * If there is no timeout, this will always return false. - * @return whether the time has expired - */ - protected synchronized boolean isTimedOut() { - return m_timeout != -1 && timeSinceInitialized() >= m_timeout; - } - - /** - * Returns the requirements (as an {@link Enumeration Enumeration} of {@link Subsystem Subsystems}) of this command - * @return the requirements (as an {@link Enumeration Enumeration} of {@link Subsystem Subsystems}) of this command - */ - synchronized Enumeration getRequirements() { - return m_requirements == null ? emptyEnumeration : m_requirements.getElements(); - } - - /** - * Prevents further changes from being made - */ - synchronized void lockChanges() { - m_locked = true; - } - - /** - * If changes are locked, then this will throw an {@link IllegalUseOfCommandException}. - * @param message the message to say (it is appended by a default message) - */ - synchronized void validate(String message) { - if (m_locked) { - throw new IllegalUseOfCommandException(message + " after being started or being added to a command group"); - } - } - - /** - * Sets the parent of this command. No actual change is made to the group. - * @param parent the parent - * @throws IllegalUseOfCommandException if this {@link Command} already is already in a group - */ - synchronized void setParent(CommandGroup parent) { - if (this.m_parent != null) { - throw new IllegalUseOfCommandException("Can not give command to a command group after already being put in a command group"); - } - lockChanges(); - this.m_parent = parent; - if (table != null) { - table.putBoolean("isParented", true); - } - } - - /** - * Starts up the command. Gets the command ready to start. - *

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.

- * @throws IllegalUseOfCommandException if the command is a part of a CommandGroup - */ - public synchronized void start() { - lockChanges(); - if (m_parent != null) { - throw new IllegalUseOfCommandException("Can not start a command that is a part of a command group"); - } - Scheduler.getInstance().add(this); - } - - /** - * This is used internally to mark that the command has been started. - * The lifecycle of a command is: - * - * startRunning() is called. - * run() is called (multiple times potentially) - * removed() is called - * - * It is very important that startRunning and removed be called in order or some assumptions - * of the code will be broken. - */ - synchronized void startRunning() { - m_running = true; - m_startTime = -1; - if (table != null) { - table.putBoolean("running", true); - } - } - - /** - * Returns whether or not the command is running. - * This may return true even if the command has just been canceled, as it may - * not have yet called {@link Command#interrupted()}. - * @return whether or not the command is running - */ - public synchronized boolean isRunning() { - return m_running; - } - - /** - * This will cancel the current command. - *

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.

- *

A command can not be canceled - * if it is a part of a command group, you must cancel the command group instead.

- * @throws IllegalUseOfCommandException if this command is a part of a command group - */ - public synchronized void cancel() { - if (m_parent != null) { - throw new IllegalUseOfCommandException("Can not manually cancel a command in a command group"); - } - _cancel(); - } - - /** - * 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. - */ - synchronized void _cancel() { - if (isRunning()) { - m_canceled = true; - } - } - - /** - * Returns whether or not this has been canceled. - * @return whether or not this has been canceled - */ - public synchronized boolean isCanceled() { - return m_canceled; - } - - /** - * Returns whether or not this command can be interrupted. - * @return whether or not this command can be interrupted - */ - public synchronized boolean isInterruptible() { - return m_interruptible; - } - - /** - * Sets whether or not this command can be interrupted. - * @param interruptible whether or not this command can be interrupted - */ - protected synchronized void setInterruptible(boolean interruptible) { - this.m_interruptible = interruptible; - } - - /** - * Checks if the command requires the given {@link Subsystem}. - * @param system the system - * @return whether or not the subsystem is required, or false if given null - */ - public synchronized boolean doesRequire(Subsystem system) { - return m_requirements != null && m_requirements.contains(system); - } - - /** - * 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) - */ - public synchronized CommandGroup getGroup() { - return m_parent; - } - - /** - * Sets whether or not this {@link Command} should run when the robot is disabled. - * - *

By default a command will not run when the robot is disabled, and will in fact be canceled.

- * @param run whether or not this command should run when the robot is disabled - */ - public void setRunWhenDisabled(boolean 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 - */ - public boolean willRunWhenDisabled() { - return m_runWhenDisabled; - } - /** An empty enumeration given whenever there are no requirements */ - private static Enumeration emptyEnumeration = new Enumeration() { - - public boolean hasMoreElements() { - return false; - } - - public Object nextElement() { - throw new NoSuchElementException(); - } - }; - - /** - * The string representation for a {@link Command} is by default its name. - * @return the string representation of this object - */ - public String toString() { - return getName(); - } - - - public String getSmartDashboardType() { - return "Command"; - } - private ITableListener listener = new ITableListener() { - public void valueChanged(ITable table, String key, Object value, boolean isNew) { - if (((Boolean) value).booleanValue()) { - start(); - } else { - cancel(); - } - } - }; - private ITable table; - public void initTable(ITable table) { - if(this.table!=null) - this.table.removeTableListener(listener); - this.table = table; - if(table!=null) { - table.putString("name", getName()); - table.putBoolean("running", isRunning()); - table.putBoolean("isParented", m_parent != null); - table.addTableListener("running", listener, false); - } - } - - /** - * {@inheritDoc} - */ - public ITable getTable() { - return table; - } + /** + * {@inheritDoc} + */ + public ITable getTable() { + return table; + } } diff --git a/wpilibj/wpilibJava/src/main/java/edu/wpi/first/wpilibj/command/CommandGroup.java b/wpilibj/wpilibJava/src/main/java/edu/wpi/first/wpilibj/command/CommandGroup.java index cf9c133ab7..6f1409c640 100644 --- a/wpilibj/wpilibJava/src/main/java/edu/wpi/first/wpilibj/command/CommandGroup.java +++ b/wpilibj/wpilibJava/src/main/java/edu/wpi/first/wpilibj/command/CommandGroup.java @@ -1,8 +1,8 @@ /*----------------------------------------------------------------------------*/ -/* Copyright (c) FIRST 2008-2012. All Rights Reserved. */ -/* Open Source Software - may be modified and shared by FRC teams. The code */ +/* Copyright (c) FIRST 2008-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 the root directory of */ -/* the project. */ +/* the project. */ /*----------------------------------------------------------------------------*/ package edu.wpi.first.wpilibj.command; @@ -13,17 +13,25 @@ import java.util.Vector; /** * A {@link CommandGroup} is a list of commands which are executed in sequence. * - *

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}.

+ *

+ * 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}. + *

* - *

{@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.

+ *

+ * {@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. + *

* - *

CommandGroups can also execute commands in parallel, simply by adding them - * using {@link CommandGroup#addParallel(Command) addParallel(...)}.

+ *

+ * CommandGroups can also execute commands in parallel, simply by adding them + * using {@link CommandGroup#addParallel(Command) addParallel(...)}. + *

* * @author Brad Miller * @author Joe Grinstead @@ -33,366 +41,396 @@ import java.util.Vector; */ public class CommandGroup extends Command { - /** The commands in this group (stored in entries) */ - Vector m_commands = new Vector(); - /** The active children in this group (stored in entries) */ - Vector m_children = new Vector(); - /** The current command, -1 signifies that none have been run */ - int m_currentCommandIndex = -1; + /** The commands in this group (stored in entries) */ + Vector m_commands = new Vector(); + /** The active children in this group (stored in entries) */ + Vector m_children = new Vector(); + /** The current command, -1 signifies that none have been run */ + int m_currentCommandIndex = -1; - /** - * Creates a new {@link CommandGroup CommandGroup}. - * The name of this command will be set to its class name. - */ - public CommandGroup() { + /** + * Creates a new {@link CommandGroup CommandGroup}. The name of this command + * will be set to its class name. + */ + public CommandGroup() {} + + /** + * Creates a new {@link CommandGroup CommandGroup} with the given name. + *$ + * @param name the name for this command group + * @throws IllegalArgumentException if name is null + */ + public CommandGroup(String name) { + super(name); + } + + /** + * Adds a new {@link Command Command} to the group. The {@link Command + * Command} will be started after all the previously added {@link Command + * Commands}. + * + *

+ * 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. + *

+ * + *

+ * It is recommended that this method be called in the constructor. + *

+ * + * @param command The {@link Command Command} to be added + * @throws IllegalUseOfCommandException if the group has been started before + * or been given to another group + * @throws IllegalArgumentException if command is null + */ + public synchronized final void addSequential(Command command) { + validate("Can not add new command to command group"); + if (command == null) { + throw new IllegalArgumentException("Given null command"); } - /** - * Creates a new {@link CommandGroup CommandGroup} with the given name. - * @param name the name for this command group - * @throws IllegalArgumentException if name is null - */ - public CommandGroup(String name) { - super(name); + command.setParent(this); + + m_commands.addElement(new Entry(command, Entry.IN_SEQUENCE)); + for (Enumeration e = command.getRequirements(); e.hasMoreElements();) { + requires((Subsystem) e.nextElement()); + } + } + + /** + * 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. + * + *

+ * 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. + *

+ * + *

+ * 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. + *

+ * + *

+ * It is recommended that this method be called in the constructor. + *

+ * + * @param command The {@link Command Command} to be added + * @param timeout The timeout (in seconds) + * @throws IllegalUseOfCommandException if the group has been started before + * or been given to another group or if the {@link Command Command} + * has been started before or been given to another group + * @throws IllegalArgumentException if command is null or timeout is negative + */ + public synchronized final void addSequential(Command command, double timeout) { + validate("Can not add new command to command group"); + if (command == null) { + throw new IllegalArgumentException("Given null command"); + } + if (timeout < 0) { + throw new IllegalArgumentException("Can not be given a negative timeout"); } - /** - * Adds a new {@link Command Command} to the group. The {@link Command Command} will be started after - * all the previously added {@link Command Commands}. - * - *

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.

- * - *

It is recommended that this method be called in the constructor.

- * - * @param command The {@link Command Command} to be added - * @throws IllegalUseOfCommandException if the group has been started before or been given to another group - * @throws IllegalArgumentException if command is null - */ - public synchronized final void addSequential(Command command) { - validate("Can not add new command to command group"); - if (command == null) { - throw new IllegalArgumentException("Given null command"); - } + command.setParent(this); - command.setParent(this); + m_commands.addElement(new Entry(command, Entry.IN_SEQUENCE, timeout)); + for (Enumeration e = command.getRequirements(); e.hasMoreElements();) { + requires((Subsystem) e.nextElement()); + } + } - m_commands.addElement(new Entry(command, Entry.IN_SEQUENCE)); - for (Enumeration e = command.getRequirements(); e.hasMoreElements();) { - requires((Subsystem) e.nextElement()); - } + /** + * Adds a new child {@link Command} to the group. The {@link Command} will be + * started after all the previously added {@link Command Commands}. + * + *

+ * 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 two cases, the child will be + * canceled even if it says it can't be interrupted. + *

+ * + *

+ * 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. + *

+ * + *

+ * It is recommended that this method be called in the constructor. + *

+ * + * @param command The command to be added + * @throws IllegalUseOfCommandException if the group has been started before + * or been given to another command group + * @throws IllegalArgumentException if command is null + */ + public synchronized final void addParallel(Command command) { + validate("Can not add new command to command group"); + if (command == null) { + throw new NullPointerException("Given null command"); } - /** - * 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. - * - *

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.

- * - *

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.

- * - *

It is recommended that this method be called in the constructor.

- * - * @param command The {@link Command Command} to be added - * @param timeout The timeout (in seconds) - * @throws IllegalUseOfCommandException if the group has been started before or been given to another group or - * if the {@link Command Command} has been started before or been given to another group - * @throws IllegalArgumentException if command is null or timeout is negative - */ - public synchronized final void addSequential(Command command, double timeout) { - validate("Can not add new command to command group"); - if (command == null) { - throw new IllegalArgumentException("Given null command"); - } - if (timeout < 0) { - throw new IllegalArgumentException("Can not be given a negative timeout"); - } + command.setParent(this); - command.setParent(this); + m_commands.addElement(new Entry(command, Entry.BRANCH_CHILD)); + for (Enumeration e = command.getRequirements(); e.hasMoreElements();) { + requires((Subsystem) e.nextElement()); + } + } - m_commands.addElement(new Entry(command, Entry.IN_SEQUENCE, timeout)); - for (Enumeration e = command.getRequirements(); e.hasMoreElements();) { - requires((Subsystem) e.nextElement()); - } + /** + * 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}. + * + *

+ * 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. + *

+ * + *

+ * 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. + *

+ * + *

+ * 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. + *

+ * + *

+ * It is recommended that this method be called in the constructor. + *

+ * + * @param command The command to be added + * @param timeout The timeout (in seconds) + * @throws IllegalUseOfCommandException if the group has been started before + * or been given to another command group + * @throws IllegalArgumentException if command is null + */ + public synchronized final void addParallel(Command command, double timeout) { + validate("Can not add new command to command group"); + if (command == null) { + throw new NullPointerException("Given null command"); + } + if (timeout < 0) { + throw new IllegalArgumentException("Can not be given a negative timeout"); } - /** - * Adds a new child {@link Command} to the group. The {@link Command} will be started after - * all the previously added {@link Command Commands}. - * - *

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 - * two cases, the child will be canceled even if it says it can't be - * interrupted.

- * - *

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.

- * - *

It is recommended that this method be called in the constructor.

- * - * @param command The command to be added - * @throws IllegalUseOfCommandException if the group has been started before or been given to another command group - * @throws IllegalArgumentException if command is null - */ - public synchronized final void addParallel(Command command) { - validate("Can not add new command to command group"); - if (command == null) { - throw new NullPointerException("Given null command"); - } + command.setParent(this); - command.setParent(this); + m_commands.addElement(new Entry(command, Entry.BRANCH_CHILD, timeout)); + for (Enumeration e = command.getRequirements(); e.hasMoreElements();) { + requires((Subsystem) e.nextElement()); + } + } - m_commands.addElement(new Entry(command, Entry.BRANCH_CHILD)); - for (Enumeration e = command.getRequirements(); e.hasMoreElements();) { - requires((Subsystem) e.nextElement()); - } + void _initialize() { + m_currentCommandIndex = -1; + } + + void _execute() { + Entry entry = null; + Command cmd = null; + boolean firstRun = false; + if (m_currentCommandIndex == -1) { + firstRun = true; + m_currentCommandIndex = 0; } - /** - * 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}. - * - *

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.

- * - *

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.

- * - *

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.

- * - *

It is recommended that this method be called in the constructor.

- * - * @param command The command to be added - * @param timeout The timeout (in seconds) - * @throws IllegalUseOfCommandException if the group has been started before or been given to another command group - * @throws IllegalArgumentException if command is null - */ - public synchronized final void addParallel(Command command, double timeout) { - validate("Can not add new command to command group"); - if (command == null) { - throw new NullPointerException("Given null command"); - } - if (timeout < 0) { - throw new IllegalArgumentException("Can not be given a negative timeout"); - } + while (m_currentCommandIndex < m_commands.size()) { - command.setParent(this); - - m_commands.addElement(new Entry(command, Entry.BRANCH_CHILD, timeout)); - for (Enumeration e = command.getRequirements(); e.hasMoreElements();) { - requires((Subsystem) e.nextElement()); + if (cmd != null) { + if (entry.isTimedOut()) { + cmd._cancel(); } + if (cmd.run()) { + break; + } else { + cmd.removed(); + m_currentCommandIndex++; + firstRun = true; + cmd = null; + continue; + } + } + + entry = (Entry) m_commands.elementAt(m_currentCommandIndex); + cmd = null; + + switch (entry.state) { + case Entry.IN_SEQUENCE: + cmd = entry.command; + if (firstRun) { + cmd.startRunning(); + cancelConflicts(cmd); + } + firstRun = false; + break; + case Entry.BRANCH_PEER: + m_currentCommandIndex++; + entry.command.start(); + break; + case Entry.BRANCH_CHILD: + m_currentCommandIndex++; + cancelConflicts(entry.command); + entry.command.startRunning(); + m_children.addElement(entry); + break; + } } - void _initialize() { - m_currentCommandIndex = -1; + // Run Children + for (int i = 0; i < m_children.size(); i++) { + entry = (Entry) m_children.elementAt(i); + Command child = entry.command; + if (entry.isTimedOut()) { + child._cancel(); + } + if (!child.run()) { + child.removed(); + m_children.removeElementAt(i--); + } + } + } + + void _end() { + // Theoretically, we don't have to check this, but we do if teams override + // the isFinished method + if (m_currentCommandIndex != -1 && m_currentCommandIndex < m_commands.size()) { + Command cmd = ((Entry) m_commands.elementAt(m_currentCommandIndex)).command; + cmd._cancel(); + cmd.removed(); } - void _execute() { - Entry entry = null; - Command cmd = null; - boolean firstRun = false; - if (m_currentCommandIndex == -1) { - firstRun = true; - m_currentCommandIndex = 0; - } + Enumeration children = m_children.elements(); + while (children.hasMoreElements()) { + Command cmd = ((Entry) children.nextElement()).command; + cmd._cancel(); + cmd.removed(); + } + m_children.removeAllElements(); + } - while (m_currentCommandIndex < m_commands.size()) { + void _interrupted() { + _end(); + } - if (cmd != null) { - if (entry.isTimedOut()) { - cmd._cancel(); - } - if (cmd.run()) { - break; - } else { - cmd.removed(); - m_currentCommandIndex++; - firstRun = true; - cmd = null; - continue; - } - } + /** + * Returns true if all the {@link Command Commands} in this group have been + * started and have finished. + * + *

+ * Teams may override this method, although they should probably reference + * super.isFinished() if they do. + *

+ * + * @return whether this {@link CommandGroup} is finished + */ + protected boolean isFinished() { + return m_currentCommandIndex >= m_commands.size() && m_children.isEmpty(); + } - entry = (Entry) m_commands.elementAt(m_currentCommandIndex); - cmd = null; + // Can be overwritten by teams + protected void initialize() {} - switch (entry.state) { - case Entry.IN_SEQUENCE: - cmd = entry.command; - if (firstRun) { - cmd.startRunning(); - cancelConflicts(cmd); - } - firstRun = false; - break; - case Entry.BRANCH_PEER: - m_currentCommandIndex++; - entry.command.start(); - break; - case Entry.BRANCH_CHILD: - m_currentCommandIndex++; - cancelConflicts(entry.command); - entry.command.startRunning(); - m_children.addElement(entry); - break; - } - } + // Can be overwritten by teams + protected void execute() {} - // Run Children - for (int i = 0; i < m_children.size(); i++) { - entry = (Entry) m_children.elementAt(i); - Command child = entry.command; - if (entry.isTimedOut()) { - child._cancel(); - } - if (!child.run()) { - child.removed(); - m_children.removeElementAt(i--); - } - } + // Can be overwritten by teams + protected void end() {} + + // Can be overwritten by teams + protected void interrupted() {} + + /** + * Returns whether or not this group is interruptible. A command group will be + * uninterruptible if {@link CommandGroup#setInterruptible(boolean) + * setInterruptable(false)} was called or if it is currently running an + * uninterruptible command or child. + * + * @return whether or not this {@link CommandGroup} is interruptible. + */ + public synchronized boolean isInterruptible() { + if (!super.isInterruptible()) { + return false; } - void _end() { - // Theoretically, we don't have to check this, but we do if teams override the isFinished method - if (m_currentCommandIndex != -1 && m_currentCommandIndex < m_commands.size()) { - Command cmd = ((Entry) m_commands.elementAt(m_currentCommandIndex)).command; - cmd._cancel(); - cmd.removed(); + if (m_currentCommandIndex != -1 && m_currentCommandIndex < m_commands.size()) { + Command cmd = ((Entry) m_commands.elementAt(m_currentCommandIndex)).command; + if (!cmd.isInterruptible()) { + return false; + } + } + + for (int i = 0; i < m_children.size(); i++) { + if (!((Entry) m_children.elementAt(i)).command.isInterruptible()) { + return false; + } + } + + return true; + } + + private void cancelConflicts(Command command) { + for (int i = 0; i < m_children.size(); i++) { + Command child = ((Entry) m_children.elementAt(i)).command; + + Enumeration requirements = command.getRequirements(); + + while (requirements.hasMoreElements()) { + Object requirement = requirements.nextElement(); + if (child.doesRequire((Subsystem) requirement)) { + child._cancel(); + child.removed(); + m_children.removeElementAt(i--); + break; } + } + } + } - Enumeration children = m_children.elements(); - while (children.hasMoreElements()) { - Command cmd = ((Entry) children.nextElement()).command; - cmd._cancel(); - cmd.removed(); - } - m_children.removeAllElements(); + private static class Entry { + + private static final int IN_SEQUENCE = 0; + private static final int BRANCH_PEER = 1; + private static final int BRANCH_CHILD = 2; + Command command; + int state; + double timeout; + + Entry(Command command, int state) { + this.command = command; + this.state = state; + this.timeout = -1; } - void _interrupted() { - _end(); + Entry(Command command, int state, double timeout) { + this.command = command; + this.state = state; + this.timeout = timeout; } - /** - * Returns true if all the {@link Command Commands} in this group - * have been started and have finished. - * - *

Teams may override this method, although they should probably - * reference super.isFinished() if they do.

- * - * @return whether this {@link CommandGroup} is finished - */ - protected boolean isFinished() { - return m_currentCommandIndex >= m_commands.size() && m_children.isEmpty(); - } - - // Can be overwritten by teams - protected void initialize() { - } - - // Can be overwritten by teams - protected void execute() { - } - - // Can be overwritten by teams - protected void end() { - } - - // Can be overwritten by teams - protected void interrupted() { - } - - /** - * Returns whether or not this group is interruptible. - * A command group will be uninterruptible if {@link CommandGroup#setInterruptible(boolean) setInterruptable(false)} - * was called or if it is currently running an uninterruptible command - * or child. - * - * @return whether or not this {@link CommandGroup} is interruptible. - */ - public synchronized boolean isInterruptible() { - if (!super.isInterruptible()) { - return false; - } - - if (m_currentCommandIndex != -1 && m_currentCommandIndex < m_commands.size()) { - Command cmd = ((Entry) m_commands.elementAt(m_currentCommandIndex)).command; - if (!cmd.isInterruptible()) { - return false; - } - } - - for (int i = 0; i < m_children.size(); i++) { - if (!((Entry) m_children.elementAt(i)).command.isInterruptible()) { - return false; - } - } - - return true; - } - - private void cancelConflicts(Command command) { - for (int i = 0; i < m_children.size(); i++) { - Command child = ((Entry) m_children.elementAt(i)).command; - - Enumeration requirements = command.getRequirements(); - - while (requirements.hasMoreElements()) { - Object requirement = requirements.nextElement(); - if (child.doesRequire((Subsystem) requirement)) { - child._cancel(); - child.removed(); - m_children.removeElementAt(i--); - break; - } - } - } - } - - private static class Entry { - - private static final int IN_SEQUENCE = 0; - private static final int BRANCH_PEER = 1; - private static final int BRANCH_CHILD = 2; - Command command; - int state; - double timeout; - - Entry(Command command, int state) { - this.command = command; - this.state = state; - this.timeout = -1; - } - - Entry(Command command, int state, double timeout) { - this.command = command; - this.state = state; - this.timeout = timeout; - } - - boolean isTimedOut() { - if (timeout == -1) { - return false; - } else { - double time = command.timeSinceInitialized(); - return time == 0 ? false : time >= timeout; - } - } + boolean isTimedOut() { + if (timeout == -1) { + return false; + } else { + double time = command.timeSinceInitialized(); + return time == 0 ? false : time >= timeout; + } } + } } diff --git a/wpilibj/wpilibJava/src/main/java/edu/wpi/first/wpilibj/command/IllegalUseOfCommandException.java b/wpilibj/wpilibJava/src/main/java/edu/wpi/first/wpilibj/command/IllegalUseOfCommandException.java index ae13045782..94305313ab 100644 --- a/wpilibj/wpilibJava/src/main/java/edu/wpi/first/wpilibj/command/IllegalUseOfCommandException.java +++ b/wpilibj/wpilibJava/src/main/java/edu/wpi/first/wpilibj/command/IllegalUseOfCommandException.java @@ -1,38 +1,43 @@ /*----------------------------------------------------------------------------*/ -/* Copyright (c) FIRST 2008-2012. All Rights Reserved. */ -/* Open Source Software - may be modified and shared by FRC teams. The code */ +/* Copyright (c) FIRST 2008-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 the root directory of */ -/* the project. */ +/* the project. */ /*----------------------------------------------------------------------------*/ package edu.wpi.first.wpilibj.command; /** - * This exception will be thrown if a command is used illegally. There are + * This exception will be thrown if a command is used illegally. There are * several ways for this to happen. * - *

Basically, a command becomes "locked" after it is first started or added - * to a command group.

+ *

+ * Basically, a command becomes "locked" after it is first started or added to a + * command group. + *

* - *

This exception should be thrown if (after a command has been locked) its requirements - * change, it is put into multiple command groups, - * it is started from outside its command group, or it adds a new child.

+ *

+ * This exception should be thrown if (after a command has been locked) its + * requirements change, it is put into multiple command groups, it is started + * from outside its command group, or it adds a new child. + *

* * @author Joe Grinstead */ public class IllegalUseOfCommandException extends RuntimeException { - /** - * Instantiates an {@link IllegalUseOfCommandException}. - */ - public IllegalUseOfCommandException() { - } + /** + * Instantiates an {@link IllegalUseOfCommandException}. + */ + public IllegalUseOfCommandException() {} - /** - * Instantiates an {@link IllegalUseOfCommandException} with the given message. - * @param message the message - */ - public IllegalUseOfCommandException(String message) { - super(message); - } + /** + * Instantiates an {@link IllegalUseOfCommandException} with the given + * message. + *$ + * @param message the message + */ + public IllegalUseOfCommandException(String message) { + super(message); + } } diff --git a/wpilibj/wpilibJava/src/main/java/edu/wpi/first/wpilibj/command/LinkedListElement.java b/wpilibj/wpilibJava/src/main/java/edu/wpi/first/wpilibj/command/LinkedListElement.java index 1d2dcc6f81..8ddaea7437 100644 --- a/wpilibj/wpilibJava/src/main/java/edu/wpi/first/wpilibj/command/LinkedListElement.java +++ b/wpilibj/wpilibJava/src/main/java/edu/wpi/first/wpilibj/command/LinkedListElement.java @@ -1,8 +1,8 @@ /*----------------------------------------------------------------------------*/ -/* Copyright (c) FIRST 2008-2012. All Rights Reserved. */ -/* Open Source Software - may be modified and shared by FRC teams. The code */ +/* Copyright (c) FIRST 2008-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 the root directory of */ -/* the project. */ +/* the project. */ /*----------------------------------------------------------------------------*/ package edu.wpi.first.wpilibj.command; @@ -12,55 +12,54 @@ package edu.wpi.first.wpilibj.command; * @author Greg */ class LinkedListElement { - private LinkedListElement next; - private LinkedListElement previous; - private Command data; + private LinkedListElement next; + private LinkedListElement previous; + private Command data; - public LinkedListElement() { + public LinkedListElement() {} + + public void setData(Command newData) { + data = newData; + } + + public Command getData() { + return data; + } + + public LinkedListElement getNext() { + return next; + } + + public LinkedListElement getPrevious() { + return previous; + } + + public void add(LinkedListElement l) { + if (next == null) { + next = l; + next.previous = this; + } else { + next.previous = l; + l.next = next; + l.previous = this; + next = l; } + } - public void setData(Command newData) { - data = newData; - } - - public Command getData() { - return data; - } - - public LinkedListElement getNext() { - return next; - } - - public LinkedListElement getPrevious() { - return previous; - } - - public void add(LinkedListElement l) { - if(next == null) { - next = l; - next.previous = this; - } else { - next.previous = l; - l.next = next; - l.previous = this; - next = l; - } - } - - public LinkedListElement remove() { - if(previous == null && next == null) { - - } else if(next == null) { - previous.next = null; - } else if(previous == null) { - next.previous = null; - } else { - next.previous = previous; - previous.next = next; - } - LinkedListElement n = next; - next = null; - previous = null; - return n; + public LinkedListElement remove() { + if (previous == null && next == null) { + + } else if (next == null) { + previous.next = null; + } else if (previous == null) { + next.previous = null; + } else { + next.previous = previous; + previous.next = next; } + LinkedListElement n = next; + next = null; + previous = null; + return n; + } } diff --git a/wpilibj/wpilibJava/src/main/java/edu/wpi/first/wpilibj/command/PIDCommand.java b/wpilibj/wpilibJava/src/main/java/edu/wpi/first/wpilibj/command/PIDCommand.java index 4801157e67..c05ec02b5f 100644 --- a/wpilibj/wpilibJava/src/main/java/edu/wpi/first/wpilibj/command/PIDCommand.java +++ b/wpilibj/wpilibJava/src/main/java/edu/wpi/first/wpilibj/command/PIDCommand.java @@ -1,8 +1,8 @@ /*----------------------------------------------------------------------------*/ -/* Copyright (c) FIRST 2008-2012. All Rights Reserved. */ -/* Open Source Software - may be modified and shared by FRC teams. The code */ +/* Copyright (c) FIRST 2008-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 the root directory of */ -/* the project. */ +/* the project. */ /*----------------------------------------------------------------------------*/ package edu.wpi.first.wpilibj.command; @@ -16,182 +16,207 @@ import edu.wpi.first.wpilibj.tables.ITable; /** * This class defines a {@link Command} which interacts heavily with a PID loop. * - *

It provides some convenience methods to run an internal {@link PIDController}. - * It will also start and stop said {@link PIDController} when the {@link PIDCommand} is - * first initialized and ended/interrupted.

+ *

+ * It provides some convenience methods to run an internal {@link PIDController} + * . It will also start and stop said {@link PIDController} when the + * {@link PIDCommand} is first initialized and ended/interrupted. + *

* * @author Joe Grinstead */ public abstract class PIDCommand extends Command implements Sendable { - /** The internal {@link PIDController} */ - private PIDController controller; - /** An output which calls {@link PIDCommand#usePIDOutput(double)} */ - private PIDOutput output = new PIDOutput() { + /** The internal {@link PIDController} */ + private PIDController controller; + /** An output which calls {@link PIDCommand#usePIDOutput(double)} */ + private PIDOutput output = new PIDOutput() { - public void pidWrite(double output) { - usePIDOutput(output); - } - }; - /** A source which calls {@link PIDCommand#returnPIDInput()} */ - private PIDSource source = new PIDSource() { - - public double pidGet() { - return returnPIDInput(); - } - }; - - /** - * Instantiates a {@link PIDCommand} that will use the given p, i and d values. - * @param name the name of the command - * @param p the proportional value - * @param i the integral value - * @param d the derivative value - */ - public PIDCommand(String name, double p, double i, double d) { - super(name); - controller = new PIDController(p, i, d, source, output); + public void pidWrite(double output) { + usePIDOutput(output); } + }; + /** A source which calls {@link PIDCommand#returnPIDInput()} */ + private PIDSource source = new PIDSource() { - /** - * Instantiates a {@link PIDCommand} 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 - * @param i the integral value - * @param d the derivative value - * @param period the time (in seconds) between calculations - */ - public PIDCommand(String name, double p, double i, double d, double period) { - super(name); - controller = new PIDController(p, i, d, source, output, period); + public double pidGet() { + return returnPIDInput(); } + }; - /** - * Instantiates a {@link PIDCommand} 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 - */ - public PIDCommand(double p, double i, double d) { - controller = new PIDController(p, i, d, source, output); - } + /** + * Instantiates a {@link PIDCommand} that will use the given p, i and d + * values. + *$ + * @param name the name of the command + * @param p the proportional value + * @param i the integral value + * @param d the derivative value + */ + public PIDCommand(String name, double p, double i, double d) { + super(name); + controller = new PIDController(p, i, d, source, output); + } - /** - * Instantiates a {@link PIDCommand} 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. - * @param p the proportional value - * @param i the integral value - * @param d the derivative value - * @param period the time (in seconds) between calculations - */ - public PIDCommand(double p, double i, double d, double period) { - controller = new PIDController(p, i, d, source, output, period); - } + /** + * Instantiates a {@link PIDCommand} 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 + * @param i the integral value + * @param d the derivative value + * @param period the time (in seconds) between calculations + */ + public PIDCommand(String name, double p, double i, double d, double period) { + super(name); + controller = new PIDController(p, i, d, source, output, period); + } - /** - * Returns the {@link PIDController} used by this {@link PIDCommand}. - * Use this if you would like to fine tune the pid loop. - * - * @return the {@link PIDController} used by this {@link PIDCommand} - */ - protected PIDController getPIDController() { - return controller; - } + /** + * Instantiates a {@link PIDCommand} 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 + */ + public PIDCommand(double p, double i, double d) { + controller = new PIDController(p, i, d, source, output); + } - void _initialize() { - controller.enable(); - } + /** + * Instantiates a {@link PIDCommand} 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. + *$ + * @param p the proportional value + * @param i the integral value + * @param d the derivative value + * @param period the time (in seconds) between calculations + */ + public PIDCommand(double p, double i, double d, double period) { + controller = new PIDController(p, i, d, source, output, period); + } - void _end() { - controller.disable(); - } + /** + * Returns the {@link PIDController} used by this {@link PIDCommand}. Use this + * if you would like to fine tune the pid loop. + * + * @return the {@link PIDController} used by this {@link PIDCommand} + */ + protected PIDController getPIDController() { + return controller; + } - void _interrupted() { - _end(); - } + void _initialize() { + controller.enable(); + } - /** - * Adds the given value to the setpoint. - * If {@link PIDCommand#setInputRange(double, double) setInputRange(...)} was used, - * then the bounds will still be honored by this method. - * @param deltaSetpoint the change in the setpoint - */ - public void setSetpointRelative(double deltaSetpoint) { - setSetpoint(getSetpoint() + deltaSetpoint); - } + void _end() { + controller.disable(); + } - /** - * Sets the setpoint to the given value. If {@link PIDCommand#setInputRange(double, double) setInputRange(...)} - * was called, - * then the given setpoint - * will be trimmed to fit within the range. - * @param setpoint the new setpoint - */ - protected void setSetpoint(double setpoint) { - controller.setSetpoint(setpoint); - } + void _interrupted() { + _end(); + } - /** - * Returns the setpoint. - * @return the setpoint - */ - protected double getSetpoint() { - return controller.getSetpoint(); - } + /** + * Adds the given value to the setpoint. If + * {@link PIDCommand#setInputRange(double, double) setInputRange(...)} was + * used, then the bounds will still be honored by this method. + *$ + * @param deltaSetpoint the change in the setpoint + */ + public void setSetpointRelative(double deltaSetpoint) { + setSetpoint(getSetpoint() + deltaSetpoint); + } - /** - * Returns the current position - * @return the current position - */ - protected double getPosition() { - return returnPIDInput(); - } - - /** - * Sets the maximum and minimum values expected from the input and setpoint. - * - * @param minimumInput the minimum value expected from the input and setpoint - * @param maximumInput the maximum value expected from the input and setpoint - */ - protected void setInputRange(double minimumInput, double maximumInput) { - controller.setInputRange(minimumInput, maximumInput); - } + /** + * Sets the setpoint to the given value. If + * {@link PIDCommand#setInputRange(double, double) setInputRange(...)} was + * called, then the given setpoint will be trimmed to fit within the range. + *$ + * @param setpoint the new setpoint + */ + protected void setSetpoint(double setpoint) { + controller.setSetpoint(setpoint); + } - /** - * Returns the input for the pid loop. - * - *

It returns the input for the pid loop, so if this command was based - * off of a gyro, then it should return the angle of the gyro

- * - *

All subclasses of {@link PIDCommand} must override this method.

- * - *

This method will be called in a different thread then the {@link Scheduler} thread.

- * - * @return the value the pid loop should use as input - */ - protected abstract double returnPIDInput(); + /** + * Returns the setpoint. + *$ + * @return the setpoint + */ + protected double getSetpoint() { + return controller.getSetpoint(); + } - /** - * Uses the value that the pid loop calculated. The calculated value is the "output" parameter. - * This method is a good time to set motor values, maybe something along the lines of driveline.tankDrive(output, -output) - * - *

All subclasses of {@link PIDCommand} must override this method.

- * - *

This method will be called in a different thread then the {@link Scheduler} thread.

- * - * @param output the value the pid loop calculated - */ - protected abstract void usePIDOutput(double output); + /** + * Returns the current position + *$ + * @return the current position + */ + protected double getPosition() { + return returnPIDInput(); + } - public String getSmartDashboardType() { - return "PIDCommand"; - } - public void initTable(ITable table) { - controller.initTable(table); - super.initTable(table); - } + /** + * Sets the maximum and minimum values expected from the input and setpoint. + * + * @param minimumInput the minimum value expected from the input and setpoint + * @param maximumInput the maximum value expected from the input and setpoint + */ + protected void setInputRange(double minimumInput, double maximumInput) { + controller.setInputRange(minimumInput, maximumInput); + } + + /** + * Returns the input for the pid loop. + * + *

+ * It returns the input for the pid loop, so if this command was based off of + * a gyro, then it should return the angle of the gyro + *

+ * + *

+ * All subclasses of {@link PIDCommand} must override this method. + *

+ * + *

+ * This method will be called in a different thread then the {@link Scheduler} + * thread. + *

+ * + * @return the value the pid loop should use as input + */ + protected abstract double returnPIDInput(); + + /** + * Uses the value that the pid loop calculated. The calculated value is the + * "output" parameter. This method is a good time to set motor values, maybe + * something along the lines of + * driveline.tankDrive(output, -output) + * + *

+ * All subclasses of {@link PIDCommand} must override this method. + *

+ * + *

+ * This method will be called in a different thread then the {@link Scheduler} + * thread. + *

+ * + * @param output the value the pid loop calculated + */ + protected abstract void usePIDOutput(double output); + + public String getSmartDashboardType() { + return "PIDCommand"; + } + + public void initTable(ITable table) { + controller.initTable(table); + super.initTable(table); + } } diff --git a/wpilibj/wpilibJava/src/main/java/edu/wpi/first/wpilibj/command/PIDSubsystem.java b/wpilibj/wpilibJava/src/main/java/edu/wpi/first/wpilibj/command/PIDSubsystem.java index a55bd76193..2f9f097d0a 100644 --- a/wpilibj/wpilibJava/src/main/java/edu/wpi/first/wpilibj/command/PIDSubsystem.java +++ b/wpilibj/wpilibJava/src/main/java/edu/wpi/first/wpilibj/command/PIDSubsystem.java @@ -1,8 +1,8 @@ /*----------------------------------------------------------------------------*/ -/* Copyright (c) FIRST 2008-2012. All Rights Reserved. */ -/* Open Source Software - may be modified and shared by FRC teams. The code */ +/* Copyright (c) FIRST 2008-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 the root directory of */ -/* the project. */ +/* the project. */ /*----------------------------------------------------------------------------*/ package edu.wpi.first.wpilibj.command; @@ -15,250 +15,274 @@ import edu.wpi.first.wpilibj.tables.ITable; /** * This class is designed to handle the case where there is a {@link Subsystem} - * which uses a single {@link PIDController} almost constantly (for instance, - * an elevator which attempts to stay at a constant height). + * which uses a single {@link PIDController} almost constantly (for instance, an + * elevator which attempts to stay at a constant height). * - *

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.

+ *

+ * 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. + *

* * @author Joe Grinstead */ public abstract class PIDSubsystem extends Subsystem implements Sendable { - /** The internal {@link PIDController} */ - private PIDController controller; - /** An output which calls {@link PIDCommand#usePIDOutput(double)} */ - private PIDOutput output = new PIDOutput() { + /** The internal {@link PIDController} */ + private PIDController controller; + /** An output which calls {@link PIDCommand#usePIDOutput(double)} */ + private PIDOutput output = new PIDOutput() { - public void pidWrite(double output) { - usePIDOutput(output); - } - }; - /** A source which calls {@link PIDCommand#returnPIDInput()} */ - private PIDSource source = new PIDSource() { - - public double pidGet() { - return returnPIDInput(); - } - }; - - /** - * 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 - */ - public PIDSubsystem(String name, double p, double i, double d) { - super(name); - controller = new PIDController(p, i, d, source, output); + public void pidWrite(double output) { + usePIDOutput(output); } + }; + /** A source which calls {@link PIDCommand#returnPIDInput()} */ + private PIDSource source = new PIDSource() { - /** - * 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 feed forward value - */ - public PIDSubsystem(String name, double p, double i, double d, double f) { - super(name); - controller = new PIDController(p, i, d, f, source, output); + public double pidGet() { + return returnPIDInput(); } + }; - /** - * 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 - * @param i the integral value - * @param d the derivative value - * @param period the time (in seconds) between calculations - */ - public PIDSubsystem(String name, double p, double i, double d, double f, double period) { - super(name); - controller = new PIDController(p, i, d, f, source, output, period); - } + /** + * 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 + */ + public PIDSubsystem(String name, double p, double i, double d) { + super(name); + controller = new PIDController(p, i, d, source, output); + } - /** - * 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 - */ - public PIDSubsystem(double p, double i, double d) { - controller = new PIDController(p, i, d, source, output); - } + /** + * 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 feed forward value + */ + public PIDSubsystem(String name, double p, double i, double d, double f) { + super(name); + controller = new PIDController(p, i, d, f, source, output); + } - /** - * 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. - * @param p the proportional value - * @param i the integral value - * @param d the derivative value - * @param f the feed forward coefficient - * @param period the time (in seconds) between calculations - */ - public PIDSubsystem(double p, double i, double d, double period, double f) { - controller = new PIDController(p, i, d, f, source, output, period); - } + /** + * 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 + * @param i the integral value + * @param d the derivative value + * @param period the time (in seconds) between calculations + */ + public PIDSubsystem(String name, double p, double i, double d, double f, double period) { + super(name); + controller = new PIDController(p, i, d, f, source, output, period); + } - /** - * 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. - * @param p the proportional value - * @param i the integral value - * @param d the derivative value - * @param period the time (in seconds) between calculations - */ - public PIDSubsystem(double p, double i, double d, double period) { - controller = new PIDController(p, i, d, source, output, period); - } + /** + * 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 + */ + public PIDSubsystem(double p, double i, double d) { + controller = new PIDController(p, i, d, source, output); + } - /** - * Returns the {@link PIDController} used by this {@link PIDSubsystem}. - * Use this if you would like to fine tune the pid loop. - * - * @return the {@link PIDController} used by this {@link PIDSubsystem} - */ - public PIDController getPIDController() { - return controller; - } + /** + * 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. + *$ + * @param p the proportional value + * @param i the integral value + * @param d the derivative value + * @param f the feed forward coefficient + * @param period the time (in seconds) between calculations + */ + public PIDSubsystem(double p, double i, double d, double period, double f) { + controller = new PIDController(p, i, d, f, source, output, period); + } + + /** + * 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. + *$ + * @param p the proportional value + * @param i the integral value + * @param d the derivative value + * @param period the time (in seconds) between calculations + */ + public PIDSubsystem(double p, double i, double d, double period) { + controller = new PIDController(p, i, d, source, output, period); + } + + /** + * Returns the {@link PIDController} used by this {@link PIDSubsystem}. Use + * this if you would like to fine tune the pid loop. + * + * @return the {@link PIDController} used by this {@link PIDSubsystem} + */ + public PIDController getPIDController() { + return controller; + } - /** - * Adds the given value to the setpoint. - * If {@link PIDSubsystem#setInputRange(double, double) setInputRange(...)} was used, - * then the bounds will still be honored by this method. - * @param deltaSetpoint the change in the setpoint - */ - public void setSetpointRelative(double deltaSetpoint) { - setSetpoint(getPosition() + deltaSetpoint); - } + /** + * Adds the given value to the setpoint. If + * {@link PIDSubsystem#setInputRange(double, double) setInputRange(...)} was + * used, then the bounds will still be honored by this method. + *$ + * @param deltaSetpoint the change in the setpoint + */ + public void setSetpointRelative(double deltaSetpoint) { + setSetpoint(getPosition() + deltaSetpoint); + } - /** - * Sets the setpoint to the given value. If {@link PIDSubsystem#setInputRange(double, double) setInputRange(...)} - * was called, - * then the given setpoint - * will be trimmed to fit within the range. - * @param setpoint the new setpoint - */ - public void setSetpoint(double setpoint) { - controller.setSetpoint(setpoint); - } + /** + * Sets the setpoint to the given value. If + * {@link PIDSubsystem#setInputRange(double, double) setInputRange(...)} was + * called, then the given setpoint will be trimmed to fit within the range. + *$ + * @param setpoint the new setpoint + */ + public void setSetpoint(double setpoint) { + controller.setSetpoint(setpoint); + } - /** - * Returns the setpoint. - * @return the setpoint - */ - public double getSetpoint() { - return controller.getSetpoint(); - } + /** + * Returns the setpoint. + *$ + * @return the setpoint + */ + public double getSetpoint() { + return controller.getSetpoint(); + } - /** - * Returns the current position - * @return the current position - */ - public double getPosition() { - return returnPIDInput(); - } + /** + * Returns the current position + *$ + * @return the current position + */ + public double getPosition() { + return returnPIDInput(); + } - /** - * Sets the maximum and minimum values expected from the input. - * - * @param minimumInput the minimum value expected from the input - * @param maximumInput the maximum value expected from the output - */ - public void setInputRange(double minimumInput, double maximumInput) { - controller.setInputRange(minimumInput, maximumInput); - } + /** + * Sets the maximum and minimum values expected from the input. + * + * @param minimumInput the minimum value expected from the input + * @param maximumInput the maximum value expected from the output + */ + public void setInputRange(double minimumInput, double maximumInput) { + controller.setInputRange(minimumInput, maximumInput); + } - /** - * Sets the maximum and minimum values to write. - * - * @param minimumOutput the minimum value to write to the output - * @param maximumOutput the maximum value to write to the output - */ - public void setOutputRange(double minimumOutput, double maximumOutput) { - controller.setOutputRange(minimumOutput, maximumOutput); - } + /** + * Sets the maximum and minimum values to write. + * + * @param minimumOutput the minimum value to write to the output + * @param maximumOutput the maximum value to write to the output + */ + public void setOutputRange(double minimumOutput, double maximumOutput) { + controller.setOutputRange(minimumOutput, maximumOutput); + } - /** - * Set the absolute error which is considered tolerable for use with - * OnTarget. The value is in the same range as the PIDInput values. - * @param t the absolute tolerance - */ - public void setAbsoluteTolerance(double t) { - controller.setAbsoluteTolerance(t); - } + /** + * Set the absolute error which is considered tolerable for use with OnTarget. + * The value is in the same range as the PIDInput values. + *$ + * @param t the absolute tolerance + */ + public void setAbsoluteTolerance(double t) { + controller.setAbsoluteTolerance(t); + } - /** - * Set the percentage error which is considered tolerable for use with - * OnTarget. (Value of 15.0 == 15 percent) - * @param p the percent tolerance - */ - public void setPercentTolerance(double p) { - controller.setPercentTolerance(p); - } + /** + * Set the percentage error which is considered tolerable for use with + * OnTarget. (Value of 15.0 == 15 percent) + *$ + * @param p the percent tolerance + */ + public void setPercentTolerance(double p) { + controller.setPercentTolerance(p); + } - /** - * Return true if the error is within the percentage of the total input range, - * determined by setTolerance. This assumes that the maximum and minimum input - * were set using setInput. - * @return true if the error is less than the tolerance - */ - public boolean onTarget() { - return controller.onTarget(); - } + /** + * Return true if the error is within the percentage of the total input range, + * determined by setTolerance. This assumes that the maximum and minimum input + * were set using setInput. + *$ + * @return true if the error is less than the tolerance + */ + public boolean onTarget() { + return controller.onTarget(); + } - /** - * Returns the input for the pid loop. - * - *

It returns the input for the pid loop, so if this Subsystem was based - * off of a gyro, then it should return the angle of the gyro

- * - *

All subclasses of {@link PIDSubsystem} must override this method.

- * - * @return the value the pid loop should use as input - */ - protected abstract double returnPIDInput(); + /** + * Returns the input for the pid loop. + * + *

+ * It returns the input for the pid loop, so if this Subsystem was based off + * of a gyro, then it should return the angle of the gyro + *

+ * + *

+ * All subclasses of {@link PIDSubsystem} must override this method. + *

+ * + * @return the value the pid loop should use as input + */ + protected abstract double returnPIDInput(); - /** - * Uses the value that the pid loop calculated. The calculated value is the "output" parameter. - * This method is a good time to set motor values, maybe something along the lines of driveline.tankDrive(output, -output) - * - *

All subclasses of {@link PIDSubsystem} must override this method.

- * - * @param output the value the pid loop calculated - */ - protected abstract void usePIDOutput(double output); + /** + * Uses the value that the pid loop calculated. The calculated value is the + * "output" parameter. This method is a good time to set motor values, maybe + * something along the lines of + * driveline.tankDrive(output, -output) + * + *

+ * All subclasses of {@link PIDSubsystem} must override this method. + *

+ * + * @param output the value the pid loop calculated + */ + protected abstract void usePIDOutput(double output); - /** - * Enables the internal {@link PIDController} - */ - public void enable() { - controller.enable(); - } + /** + * Enables the internal {@link PIDController} + */ + public void enable() { + controller.enable(); + } - /** - * Disables the internal {@link PIDController} - */ - public void disable() { - controller.disable(); - } + /** + * Disables the internal {@link PIDController} + */ + public void disable() { + controller.disable(); + } - public String getSmartDashboardType() { - return "PIDSubsystem"; - } - public void initTable(ITable table) { - controller.initTable(table); - super.initTable(table); - } + public String getSmartDashboardType() { + return "PIDSubsystem"; + } + + public void initTable(ITable table) { + controller.initTable(table); + super.initTable(table); + } } diff --git a/wpilibj/wpilibJava/src/main/java/edu/wpi/first/wpilibj/command/PrintCommand.java b/wpilibj/wpilibJava/src/main/java/edu/wpi/first/wpilibj/command/PrintCommand.java index 2ca0a514a8..781070cce3 100644 --- a/wpilibj/wpilibJava/src/main/java/edu/wpi/first/wpilibj/command/PrintCommand.java +++ b/wpilibj/wpilibJava/src/main/java/edu/wpi/first/wpilibj/command/PrintCommand.java @@ -1,46 +1,46 @@ /*----------------------------------------------------------------------------*/ -/* Copyright (c) FIRST 2008-2012. All Rights Reserved. */ -/* Open Source Software - may be modified and shared by FRC teams. The code */ +/* Copyright (c) FIRST 2008-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 the root directory of */ -/* the project. */ +/* the project. */ /*----------------------------------------------------------------------------*/ package edu.wpi.first.wpilibj.command; /** - * A {@link PrintCommand} is a command which prints out a string when it is initialized, and then immediately finishes. - * It is useful if you want a {@link CommandGroup} to print out a string when it reaches a certain point. + * A {@link PrintCommand} is a command which prints out a string when it is + * initialized, and then immediately finishes. It is useful if you want a + * {@link CommandGroup} to print out a string when it reaches a certain point. * * @author Joe Grinstead */ public class PrintCommand extends Command { - /** The message to print out */ - private String message; + /** The message to print out */ + private String message; - /** - * Instantiates a {@link PrintCommand} which will print the given message when it is run. - * @param message the message to print - */ - public PrintCommand(String message) { - super("Print(\"" + message + "\""); - this.message = message; - } + /** + * Instantiates a {@link PrintCommand} which will print the given message when + * it is run. + *$ + * @param message the message to print + */ + public PrintCommand(String message) { + super("Print(\"" + message + "\""); + this.message = message; + } - protected void initialize() { - System.out.println(message); - } + protected void initialize() { + System.out.println(message); + } - protected void execute() { - } + protected void execute() {} - protected boolean isFinished() { - return true; - } + protected boolean isFinished() { + return true; + } - protected void end() { - } + protected void end() {} - protected void interrupted() { - } + protected void interrupted() {} } diff --git a/wpilibj/wpilibJava/src/main/java/edu/wpi/first/wpilibj/command/Scheduler.java b/wpilibj/wpilibJava/src/main/java/edu/wpi/first/wpilibj/command/Scheduler.java index dd998cf8f2..e7ad4acb02 100644 --- a/wpilibj/wpilibJava/src/main/java/edu/wpi/first/wpilibj/command/Scheduler.java +++ b/wpilibj/wpilibJava/src/main/java/edu/wpi/first/wpilibj/command/Scheduler.java @@ -1,8 +1,8 @@ /*----------------------------------------------------------------------------*/ -/* Copyright (c) FIRST 2008-2012. All Rights Reserved. */ -/* Open Source Software - may be modified and shared by FRC teams. The code */ +/* Copyright (c) FIRST 2008-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 the root directory of */ -/* the project. */ +/* the project. */ /*----------------------------------------------------------------------------*/ package edu.wpi.first.wpilibj.command; @@ -19,351 +19,360 @@ import edu.wpi.first.wpilibj.tables.ITable; /** * The {@link Scheduler} is a singleton which holds the top-level running - * commands. It is in charge of both calling the command's - * {@link Command#run() run()} method and to make sure that there are no two - * commands with conflicting requirements running. + * commands. It is in charge of both calling the command's {@link Command#run() + * run()} method and to make sure that there are no two commands with + * conflicting requirements running. * - *

It is fine if teams wish to take control of the {@link Scheduler} - * themselves, all that needs to be done is to call - * {@link Scheduler#getInstance() Scheduler.getInstance()}.{@link Scheduler#run() run()} - * often to have {@link Command Commands} function correctly. However, this is - * already done for you if you use the CommandBased Robot template.

+ *

+ * It is fine if teams wish to take control of the {@link Scheduler} themselves, + * all that needs to be done is to call {@link Scheduler#getInstance() + * Scheduler.getInstance()}.{@link Scheduler#run() run()} often to have + * {@link Command Commands} function correctly. However, this is already done + * for you if you use the CommandBased Robot template. + *

* * @author Joe Grinstead * @see Command */ public class Scheduler implements NamedSendable { - /** - * The Singleton Instance - */ - private static Scheduler instance; + /** + * The Singleton Instance + */ + private static Scheduler instance; - /** - * Returns the {@link Scheduler}, creating it if one does not exist. - * - * @return the {@link Scheduler} - */ - public synchronized static Scheduler getInstance() { - return instance == null ? instance = new Scheduler() : instance; + /** + * Returns the {@link Scheduler}, creating it if one does not exist. + * + * @return the {@link Scheduler} + */ + public synchronized static Scheduler getInstance() { + return instance == null ? instance = new Scheduler() : instance; + } + + /** + * A hashtable of active {@link Command Commands} to their + * {@link LinkedListElement} + */ + private Hashtable commandTable = new Hashtable(); + /** + * The {@link Set} of all {@link Subsystem Subsystems} + */ + private Set subsystems = new Set(); + /** + * The first {@link Command} in the list + */ + private LinkedListElement firstCommand; + /** + * The last {@link Command} in the list + */ + private LinkedListElement lastCommand; + /** + * Whether or not we are currently adding a command + */ + private boolean adding = false; + /** + * Whether or not we are currently disabled + */ + private boolean disabled = false; + /** + * A list of all {@link Command Commands} which need to be added + */ + private Vector additions = new Vector(); + private ITable m_table; + /** + * A list of all {@link edu.wpi.first.wpilibj.buttons.Trigger.ButtonScheduler + * Buttons}. It is created lazily. + */ + private Vector buttons; + private boolean m_runningCommandsChanged; + + /** + * Instantiates a {@link Scheduler}. + */ + private Scheduler() { + HLUsageReporting.reportScheduler(); + } + + /** + * Adds the command to the {@link Scheduler}. This will not add the + * {@link Command} immediately, but will instead wait for the proper time in + * the {@link Scheduler#run()} loop before doing so. The command returns + * immediately and does nothing if given null. + * + *

+ * Adding a {@link Command} to the {@link Scheduler} involves the + * {@link Scheduler} removing any {@link Command} which has shared + * requirements. + *

+ * + * @param command the command to add + */ + public void add(Command command) { + if (command != null) { + additions.addElement(command); } - /** - * A hashtable of active {@link Command Commands} to their - * {@link LinkedListElement} - */ - private Hashtable commandTable = new Hashtable(); - /** - * The {@link Set} of all {@link Subsystem Subsystems} - */ - private Set subsystems = new Set(); - /** - * The first {@link Command} in the list - */ - private LinkedListElement firstCommand; - /** - * The last {@link Command} in the list - */ - private LinkedListElement lastCommand; - /** - * Whether or not we are currently adding a command - */ - private boolean adding = false; - /** - * Whether or not we are currently disabled - */ - private boolean disabled = false; - /** - * A list of all {@link Command Commands} which need to be added - */ - private Vector additions = new Vector(); - private ITable m_table; - /** - * A list of all - * {@link edu.wpi.first.wpilibj.buttons.Trigger.ButtonScheduler Buttons}. It - * is created lazily. - */ - private Vector buttons; - private boolean m_runningCommandsChanged; + } - /** - * Instantiates a {@link Scheduler}. - */ - private Scheduler() { - HLUsageReporting.reportScheduler(); + /** + * Adds a button to the {@link Scheduler}. The {@link Scheduler} will poll the + * button during its {@link Scheduler#run()}. + * + * @param button the button to add + */ + public void addButton(ButtonScheduler button) { + if (buttons == null) { + buttons = new Vector(); + } + buttons.addElement(button); + } + + /** + * Adds a command immediately to the {@link Scheduler}. This should only be + * called in the {@link Scheduler#run()} loop. Any command with conflicting + * requirements will be removed, unless it is uninterruptable. Giving + * null does nothing. + * + * @param command the {@link Command} to add + */ + private void _add(Command command) { + if (command == null) { + return; } - /** - * Adds the command to the {@link Scheduler}. This will not add the - * {@link Command} immediately, but will instead wait for the proper time in - * the {@link Scheduler#run()} loop before doing so. The command returns - * immediately and does nothing if given null. - * - *

Adding a {@link Command} to the {@link Scheduler} involves the - * {@link Scheduler} removing any {@link Command} which has shared - * requirements.

- * - * @param command the command to add - */ - public void add(Command command) { - if (command != null) { - additions.addElement(command); - } + // Check to make sure no adding during adding + if (adding) { + System.err.println("WARNING: Can not start command from cancel method. Ignoring:" + command); + return; } - /** - * Adds a button to the {@link Scheduler}. The {@link Scheduler} will poll - * the button during its {@link Scheduler#run()}. - * - * @param button the button to add - */ - public void addButton(ButtonScheduler button) { - if (buttons == null) { - buttons = new Vector(); + // Only add if not already in + if (!commandTable.containsKey(command)) { + + // Check that the requirements can be had + Enumeration requirements = command.getRequirements(); + while (requirements.hasMoreElements()) { + Subsystem lock = (Subsystem) requirements.nextElement(); + if (lock.getCurrentCommand() != null && !lock.getCurrentCommand().isInterruptible()) { + return; } - buttons.addElement(button); + } + + // Give it the requirements + adding = true; + requirements = command.getRequirements(); + while (requirements.hasMoreElements()) { + Subsystem lock = (Subsystem) requirements.nextElement(); + if (lock.getCurrentCommand() != null) { + lock.getCurrentCommand().cancel(); + remove(lock.getCurrentCommand()); + } + lock.setCurrentCommand(command); + } + adding = false; + + // Add it to the list + LinkedListElement element = new LinkedListElement(); + element.setData(command); + if (firstCommand == null) { + firstCommand = lastCommand = element; + } else { + lastCommand.add(element); + lastCommand = element; + } + commandTable.put(command, element); + + m_runningCommandsChanged = true; + + command.startRunning(); + } + } + + /** + * 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: + * + *
    + *
  1. Poll the Buttons
  2. + *
  3. Execute/Remove the Commands
  4. + *
  5. Send values to SmartDashboard
  6. + *
  7. Add Commands
  8. + *
  9. Add Defaults
  10. + *
+ */ + public void run() { + + m_runningCommandsChanged = false; + + if (disabled) { + return; + } // Don't run when disabled + + // Get button input (going backwards preserves button priority) + if (buttons != null) { + for (int i = buttons.size() - 1; i >= 0; i--) { + ((ButtonScheduler) buttons.elementAt(i)).execute(); + } + } + // Loop through the commands + LinkedListElement e = firstCommand; + while (e != null) { + Command c = e.getData(); + e = e.getNext(); + if (!c.run()) { + remove(c); + m_runningCommandsChanged = true; + } } - /** - * Adds a command immediately to the {@link Scheduler}. This should only be - * called in the {@link Scheduler#run()} loop. Any command with conflicting - * requirements will be removed, unless it is uninterruptable. Giving - * null does nothing. - * - * @param command the {@link Command} to add - */ - private void _add(Command command) { - if (command == null) { - return; - } + // Add the new things + for (int i = 0; i < additions.size(); i++) { + _add((Command) additions.elementAt(i)); + } + additions.removeAllElements(); - // Check to make sure no adding during adding - if (adding) { - System.err.println("WARNING: Can not start command from cancel method. Ignoring:" + command); - return; - } + // Add in the defaults + Enumeration locks = subsystems.getElements(); + while (locks.hasMoreElements()) { + Subsystem lock = (Subsystem) locks.nextElement(); + if (lock.getCurrentCommand() == null) { + _add(lock.getDefaultCommand()); + } + lock.confirmCommand(); + } - // Only add if not already in - if (!commandTable.containsKey(command)) { + updateTable(); + } - // Check that the requirements can be had - Enumeration requirements = command.getRequirements(); - while (requirements.hasMoreElements()) { - Subsystem lock = (Subsystem) requirements.nextElement(); - if (lock.getCurrentCommand() != null && !lock.getCurrentCommand().isInterruptible()) { - return; - } + /** + * 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 registerSubsystem(Subsystem system) { + if (system != null) { + subsystems.add(system); + } + } + + /** + * Removes the {@link Command} from the {@link Scheduler}. + * + * @param command the command to remove + */ + void remove(Command command) { + if (command == null || !commandTable.containsKey(command)) { + return; + } + LinkedListElement e = (LinkedListElement) commandTable.get(command); + commandTable.remove(command); + + if (e.equals(lastCommand)) { + lastCommand = e.getPrevious(); + } + if (e.equals(firstCommand)) { + firstCommand = e.getNext(); + } + e.remove(); + + Enumeration requirements = command.getRequirements(); + while (requirements.hasMoreElements()) { + ((Subsystem) requirements.nextElement()).setCurrentCommand(null); + } + + command.removed(); + } + + /** + * Removes all commands + */ + public void removeAll() { + // TODO: Confirm that this works with "uninteruptible" commands + while (firstCommand != null) { + remove(firstCommand.getData()); + } + } + + /** + * Disable the command scheduler. + */ + public void disable() { + disabled = true; + } + + /** + * Enable the command scheduler. + */ + public void enable() { + disabled = false; + } + + public String getName() { + return "Scheduler"; + } + + public String getType() { + return "Scheduler"; + } + + private StringArray commands; + private NumberArray ids, toCancel; + + /** + * {@inheritDoc} + */ + public void initTable(ITable subtable) { + 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); + } + + private void updateTable() { + if (m_table != null) { + // Get the commands to cancel + m_table.retrieveValue("Cancel", toCancel); + if (toCancel.size() > 0) { + for (LinkedListElement e = firstCommand; e != null; e = e.getNext()) { + for (int i = 0; i < toCancel.size(); i++) { + if (e.getData().hashCode() == toCancel.get(i)) { + e.getData().cancel(); } - - // Give it the requirements - adding = true; - requirements = command.getRequirements(); - while (requirements.hasMoreElements()) { - Subsystem lock = (Subsystem) requirements.nextElement(); - if (lock.getCurrentCommand() != null) { - lock.getCurrentCommand().cancel(); - remove(lock.getCurrentCommand()); - } - lock.setCurrentCommand(command); - } - adding = false; - - // Add it to the list - LinkedListElement element = new LinkedListElement(); - element.setData(command); - if (firstCommand == null) { - firstCommand = lastCommand = element; - } else { - lastCommand.add(element); - lastCommand = element; - } - commandTable.put(command, element); - - m_runningCommandsChanged = true; - - command.startRunning(); + } } - } + toCancel.setSize(0); + m_table.putValue("Cancel", toCancel); + } - /** - * 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: - * - *
  1. Poll the Buttons
  2. Execute/Remove the Commands
  3. - *
  4. Send values to SmartDashboard
  5. Add Commands
  6. Add - * Defaults
- */ - public void run() { - - m_runningCommandsChanged = false; - - if (disabled) { - return; - } // Don't run when disabled - - // Get button input (going backwards preserves button priority) - if (buttons != null) { - for (int i = buttons.size() - 1; i >= 0; i--) { - ((ButtonScheduler) buttons.elementAt(i)).execute(); - } + if (m_runningCommandsChanged) { + commands.setSize(0); + ids.setSize(0); + // Set the the running commands + for (LinkedListElement e = firstCommand; e != null; e = e.getNext()) { + commands.add(e.getData().getName()); + ids.add(e.getData().hashCode()); } - // Loop through the commands - LinkedListElement e = firstCommand; - while (e != null) { - Command c = e.getData(); - e = e.getNext(); - if (!c.run()) { - remove(c); - m_runningCommandsChanged = true; - } - } - - // Add the new things - for (int i = 0; i < additions.size(); i++) { - _add((Command) additions.elementAt(i)); - } - additions.removeAllElements(); - - // Add in the defaults - Enumeration locks = subsystems.getElements(); - while (locks.hasMoreElements()) { - Subsystem lock = (Subsystem) locks.nextElement(); - if (lock.getCurrentCommand() == null) { - _add(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. - * - * @param system the system - */ - void registerSubsystem(Subsystem system) { - if (system != null) { - subsystems.add(system); - } - } - - /** - * Removes the {@link Command} from the {@link Scheduler}. - * - * @param command the command to remove - */ - void remove(Command command) { - if (command == null || !commandTable.containsKey(command)) { - return; - } - LinkedListElement e = (LinkedListElement) commandTable.get(command); - commandTable.remove(command); - - if (e.equals(lastCommand)) { - lastCommand = e.getPrevious(); - } - if (e.equals(firstCommand)) { - firstCommand = e.getNext(); - } - e.remove(); - - Enumeration requirements = command.getRequirements(); - while (requirements.hasMoreElements()) { - ((Subsystem) requirements.nextElement()).setCurrentCommand(null); - } - - command.removed(); - } - - /** - * Removes all commands - */ - public void removeAll() { - // TODO: Confirm that this works with "uninteruptible" commands - while (firstCommand != null) { - remove(firstCommand.getData()); - } - } - - /** - * Disable the command scheduler. - */ - public void disable() { - disabled = true; - } - - /** - * Enable the command scheduler. - */ - public void enable() { - disabled = false; - } - - public String getName() { - return "Scheduler"; - } - - public String getType() { - return "Scheduler"; - } - private StringArray commands; - private NumberArray ids, toCancel; - - /** - * {@inheritDoc} - */ - public void initTable(ITable subtable) { - 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); + } } + } - private void updateTable() { - if (m_table != null) { - // Get the commands to cancel - m_table.retrieveValue("Cancel", toCancel); - if (toCancel.size() > 0) { - for (LinkedListElement e = firstCommand; e != null; e = e.getNext()) { - for (int i = 0; i < toCancel.size(); i++) { - if (e.getData().hashCode() == toCancel.get(i)) { - e.getData().cancel(); - } - } - } - toCancel.setSize(0); - m_table.putValue("Cancel", toCancel); - } + /** + * {@inheritDoc} + */ + public ITable getTable() { + return m_table; + } - if (m_runningCommandsChanged) { - commands.setSize(0); - ids.setSize(0); - // Set the the running commands - for (LinkedListElement e = firstCommand; e != null; e = e.getNext()) { - commands.add(e.getData().getName()); - ids.add(e.getData().hashCode()); - } - m_table.putValue("Names", commands); - m_table.putValue("Ids", ids); - } - } - } - - /** - * {@inheritDoc} - */ - public ITable getTable() { - return m_table; - } - - public String getSmartDashboardType() { - return "Scheduler"; - } + public String getSmartDashboardType() { + return "Scheduler"; + } } diff --git a/wpilibj/wpilibJava/src/main/java/edu/wpi/first/wpilibj/command/Set.java b/wpilibj/wpilibJava/src/main/java/edu/wpi/first/wpilibj/command/Set.java index 6da9ec7ba2..8dd2c469cc 100644 --- a/wpilibj/wpilibJava/src/main/java/edu/wpi/first/wpilibj/command/Set.java +++ b/wpilibj/wpilibJava/src/main/java/edu/wpi/first/wpilibj/command/Set.java @@ -1,8 +1,8 @@ /*----------------------------------------------------------------------------*/ -/* Copyright (c) FIRST 2008-2012. All Rights Reserved. */ -/* Open Source Software - may be modified and shared by FRC teams. The code */ +/* Copyright (c) FIRST 2008-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 the root directory of */ -/* the project. */ +/* the project. */ /*----------------------------------------------------------------------------*/ package edu.wpi.first.wpilibj.command; @@ -15,28 +15,28 @@ import java.util.Vector; * @author Greg */ class Set { - Vector set = new Vector(); + Vector set = new Vector(); - public Set() { - } + public Set() {} - public void add(Object o) { - if(set.contains(o)) return; - set.addElement(o); - } + public void add(Object o) { + if (set.contains(o)) + return; + set.addElement(o); + } - public void add(Set s) { - Enumeration stuff = s.getElements(); - for(Enumeration e = stuff; e.hasMoreElements();) { - add(e.nextElement()); - } + public void add(Set s) { + Enumeration stuff = s.getElements(); + for (Enumeration e = stuff; e.hasMoreElements();) { + add(e.nextElement()); } + } - public boolean contains(Object o) { - return set.contains(o); - } + public boolean contains(Object o) { + return set.contains(o); + } - public Enumeration getElements() { - return set.elements(); - } + public Enumeration getElements() { + return set.elements(); + } } diff --git a/wpilibj/wpilibJava/src/main/java/edu/wpi/first/wpilibj/command/StartCommand.java b/wpilibj/wpilibJava/src/main/java/edu/wpi/first/wpilibj/command/StartCommand.java index f00448aba9..ba8a1c5a14 100644 --- a/wpilibj/wpilibJava/src/main/java/edu/wpi/first/wpilibj/command/StartCommand.java +++ b/wpilibj/wpilibJava/src/main/java/edu/wpi/first/wpilibj/command/StartCommand.java @@ -1,47 +1,45 @@ /*----------------------------------------------------------------------------*/ -/* Copyright (c) FIRST 2008-2012. All Rights Reserved. */ -/* Open Source Software - may be modified and shared by FRC teams. The code */ +/* Copyright (c) FIRST 2008-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 the root directory of */ -/* the project. */ +/* the project. */ /*----------------------------------------------------------------------------*/ package edu.wpi.first.wpilibj.command; /** - * A {@link StartCommand} will call the {@link Command#start() start()} method of another command when it is initialized - * and will finish immediately. + * A {@link StartCommand} will call the {@link Command#start() start()} method + * of another command when it is initialized and will finish immediately. * * @author Joe Grinstead */ public class StartCommand extends Command { - /** The command to fork */ - private Command m_commandToFork; + /** The command to fork */ + private Command m_commandToFork; - /** - * Instantiates a {@link StartCommand} which will start the - * given command whenever its {@link Command#initialize() initialize()} is called. - * @param commandToStart the {@link Command} to start - */ - public StartCommand(Command commandToStart) { - super("Start(" + commandToStart + ")"); - m_commandToFork = commandToStart; - } + /** + * Instantiates a {@link StartCommand} which will start the given command + * whenever its {@link Command#initialize() initialize()} is called. + *$ + * @param commandToStart the {@link Command} to start + */ + public StartCommand(Command commandToStart) { + super("Start(" + commandToStart + ")"); + m_commandToFork = commandToStart; + } - protected void initialize() { - m_commandToFork.start(); - } + protected void initialize() { + m_commandToFork.start(); + } - protected void execute() { - } + protected void execute() {} - protected boolean isFinished() { - return true; - } + protected boolean isFinished() { + return true; + } - protected void end() { - } + protected void end() {} - protected void interrupted() { - } + protected void interrupted() {} } diff --git a/wpilibj/wpilibJava/src/main/java/edu/wpi/first/wpilibj/command/Subsystem.java b/wpilibj/wpilibJava/src/main/java/edu/wpi/first/wpilibj/command/Subsystem.java index c8ba2904b1..02373ad49c 100644 --- a/wpilibj/wpilibJava/src/main/java/edu/wpi/first/wpilibj/command/Subsystem.java +++ b/wpilibj/wpilibJava/src/main/java/edu/wpi/first/wpilibj/command/Subsystem.java @@ -1,8 +1,8 @@ /*----------------------------------------------------------------------------*/ -/* Copyright (c) FIRST 2008-2012. All Rights Reserved. */ -/* Open Source Software - may be modified and shared by FRC teams. The code */ +/* Copyright (c) FIRST 2008-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 the root directory of */ -/* the project. */ +/* the project. */ /*----------------------------------------------------------------------------*/ package edu.wpi.first.wpilibj.command; @@ -15,183 +15,203 @@ import java.util.Vector; /** * This class defines a major component of the robot. * - *

A good example of a subsystem is the driveline, or a claw if the robot has one.

+ *

+ * A good example of a subsystem is the driveline, or a claw if the robot has + * one. + *

* - *

All motors should be a part of a subsystem. For instance, all the wheel motors should be - * a part of some kind of "Driveline" subsystem.

+ *

+ * All motors should be a part of a subsystem. For instance, all the wheel + * motors should be a part of some kind of "Driveline" subsystem. + *

* - *

Subsystems are used within the command system as requirements for {@link Command}. - * Only one command which requires a subsystem can run at a time. Also, subsystems - * can have default commands which are started if there is no command running which - * requires this subsystem.

+ *

+ * Subsystems are used within the command system as requirements for + * {@link Command}. Only one command which requires a subsystem can run at a + * time. Also, subsystems can have default commands which are started if there + * is no command running which requires this subsystem. + *

* * @author Joe Grinstead * @see Command */ public abstract class Subsystem implements NamedSendable { - /** Whether or not getDefaultCommand() was called */ - private boolean initializedDefaultCommand = false; - /** The current command */ - private Command currentCommand; - private boolean currentCommandChanged; + /** Whether or not getDefaultCommand() was called */ + private boolean initializedDefaultCommand = false; + /** The current command */ + private Command currentCommand; + private boolean currentCommandChanged; - /** The default command */ - private Command defaultCommand; - /** The name */ - private String name; - /** List of all subsystems created */ - private static Vector allSubsystems = new Vector(); + /** The default command */ + private Command defaultCommand; + /** The name */ + private String name; + /** List of all subsystems created */ + private static Vector allSubsystems = new Vector(); - /** - * Creates a subsystem with the given name - * @param name the name of the subsystem - */ - public Subsystem(String name) { - this.name = name; - Scheduler.getInstance().registerSubsystem(this); + /** + * Creates a subsystem with the given name + *$ + * @param name the name of the subsystem + */ + public Subsystem(String name) { + this.name = name; + Scheduler.getInstance().registerSubsystem(this); + } + + /** + * Creates a subsystem. This will set the name to the name of the class. + */ + public Subsystem() { + this.name = getClass().getName().substring(getClass().getName().lastIndexOf('.') + 1); + Scheduler.getInstance().registerSubsystem(this); + currentCommandChanged = true; + } + + /** + * Initialize the default command for a subsystem By default subsystems have + * no default command, but if they do, the default command is set with this + * method. It is called on all Subsystems by CommandBase in the users program + * after all the Subsystems are created. + */ + protected abstract void 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. + * + *

+ * WARNING: This should NOT be called in a constructor if the + * subsystem is a singleton. + *

+ * + * @param command the default command (or null if there should be none) + * @throws IllegalUseOfCommandException if the command does not require the + * subsystem + */ + protected void setDefaultCommand(Command command) { + if (command == null) { + defaultCommand = null; + } else { + boolean found = false; + Enumeration requirements = command.getRequirements(); + while (requirements.hasMoreElements()) { + if (requirements.nextElement().equals(this)) { + found = true; + // } else { + // throw new + // IllegalUseOfCommandException("A default command cannot require multiple subsystems"); + } + } + if (!found) { + throw new IllegalUseOfCommandException("A default command must require the subsystem"); + } + defaultCommand = command; } - - /** - * Creates a subsystem. This will set the name to the name of the class. - */ - public Subsystem() { - this.name = getClass().getName().substring(getClass().getName().lastIndexOf('.') + 1); - Scheduler.getInstance().registerSubsystem(this); - currentCommandChanged = true; + if (table != null) { + if (defaultCommand != null) { + table.putBoolean("hasDefault", true); + table.putString("default", defaultCommand.getName()); + } else { + table.putBoolean("hasDefault", false); + } } + } - /** - * Initialize the default command for a subsystem - * By default subsystems have no default command, but if they do, the default command is set - * with this method. It is called on all Subsystems by CommandBase in the users program after - * all the Subsystems are created. - */ - protected abstract void initDefaultCommand(); + /** + * Returns the default command (or null if there is none). + *$ + * @return the default command + */ + protected Command getDefaultCommand() { + if (!initializedDefaultCommand) { + initializedDefaultCommand = true; + initDefaultCommand(); + } + return defaultCommand; + } - /** - * Sets the default command. If this is not called or is called with null, - * then there will be no default command for the subsystem. - * - *

WARNING: This should NOT be called in a constructor if the subsystem is a - * singleton.

- * - * @param command the default command (or null if there should be none) - * @throws IllegalUseOfCommandException if the command does not require the subsystem - */ - protected void setDefaultCommand(Command command) { - if (command == null) { - defaultCommand = null; + /** + * Sets the current command + *$ + * @param command the new current command + */ + void setCurrentCommand(Command command) { + currentCommand = command; + currentCommandChanged = true; + } + + /** + * 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 confirmCommand() { + if (currentCommandChanged) { + if (table != null) { + if (currentCommand != null) { + table.putBoolean("hasCommand", true); + table.putString("command", currentCommand.getName()); } else { - boolean found = false; - Enumeration requirements = command.getRequirements(); - while (requirements.hasMoreElements()) { - if (requirements.nextElement().equals(this)) { - found = true; -// } else { -// throw new IllegalUseOfCommandException("A default command cannot require multiple subsystems"); - } - } - if (!found) { - throw new IllegalUseOfCommandException("A default command must require the subsystem"); - } - defaultCommand = command; - } - if (table != null) { - if (defaultCommand != null) { - table.putBoolean("hasDefault", true); - table.putString("default", defaultCommand.getName()); - } else { - table.putBoolean("hasDefault", false); - } + table.putBoolean("hasCommand", false); } + } + currentCommandChanged = false; } + } - /** - * Returns the default command (or null if there is none). - * @return the default command - */ - protected Command getDefaultCommand() { - if (!initializedDefaultCommand) { - initializedDefaultCommand = true; - initDefaultCommand(); - } - return defaultCommand; - } + /** + * Returns the command which currently claims this subsystem. + *$ + * @return the command which currently claims this subsystem + */ + public Command getCurrentCommand() { + return currentCommand; + } - /** - * Sets the current command - * @param command the new current command - */ - void setCurrentCommand(Command command) { - currentCommand = command; - currentCommandChanged = true; - } + public String toString() { + return getName(); + } - /** - * 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 confirmCommand() { - if (currentCommandChanged) { - if (table != null) { - if (currentCommand != null) { - table.putBoolean("hasCommand", true); - table.putString("command", currentCommand.getName()); - } else { - table.putBoolean("hasCommand", false); - } - } - currentCommandChanged = false; - } - } + /** + * Returns the name of this subsystem, which is by default the class name. + *$ + * @return the name of this subsystem + */ + public String getName() { + return name; + } - /** - * Returns the command which currently claims this subsystem. - * @return the command which currently claims this subsystem - */ - public Command getCurrentCommand() { - return currentCommand; - } + public String getSmartDashboardType() { + return "Subsystem"; + } - public String toString() { - return getName(); - } + private ITable table; - /** - * Returns the name of this subsystem, which is by default the class name. - * @return the name of this subsystem - */ - public String getName() { - return name; + public void initTable(ITable table) { + this.table = table; + if (table != null) { + if (defaultCommand != null) { + table.putBoolean("hasDefault", true); + table.putString("default", defaultCommand.getName()); + } else { + table.putBoolean("hasDefault", false); + } + if (currentCommand != null) { + table.putBoolean("hasCommand", true); + table.putString("command", currentCommand.getName()); + } else { + table.putBoolean("hasCommand", false); + } } + } - public String getSmartDashboardType() { - return "Subsystem"; - } - private ITable table; - public void initTable(ITable table) { - this.table = table; - if(table!=null) { - if (defaultCommand != null) { - table.putBoolean("hasDefault", true); - table.putString("default", defaultCommand.getName()); - } else { - table.putBoolean("hasDefault", false); - } - if (currentCommand != null) { - table.putBoolean("hasCommand", true); - table.putString("command", currentCommand.getName()); - } else { - table.putBoolean("hasCommand", false); - } - } - } - /** - * {@inheritDoc} - */ - public ITable getTable() { - return table; - } + /** + * {@inheritDoc} + */ + public ITable getTable() { + return table; + } } diff --git a/wpilibj/wpilibJava/src/main/java/edu/wpi/first/wpilibj/command/WaitCommand.java b/wpilibj/wpilibJava/src/main/java/edu/wpi/first/wpilibj/command/WaitCommand.java index eaf6f19e79..6417f7dde5 100644 --- a/wpilibj/wpilibJava/src/main/java/edu/wpi/first/wpilibj/command/WaitCommand.java +++ b/wpilibj/wpilibJava/src/main/java/edu/wpi/first/wpilibj/command/WaitCommand.java @@ -1,50 +1,50 @@ /*----------------------------------------------------------------------------*/ -/* Copyright (c) FIRST 2008-2012. All Rights Reserved. */ -/* Open Source Software - may be modified and shared by FRC teams. The code */ +/* Copyright (c) FIRST 2008-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 the root directory of */ -/* the project. */ +/* the project. */ /*----------------------------------------------------------------------------*/ package edu.wpi.first.wpilibj.command; /** - * A {@link WaitCommand} will wait for a certain amount of time before finishing. - * It is useful if you want a {@link CommandGroup} to pause for a moment. + * A {@link WaitCommand} will wait for a certain amount of time before + * finishing. It is useful if you want a {@link CommandGroup} to pause for a + * moment. + *$ * @author Joe Grinstead * @see CommandGroup */ public class WaitCommand extends Command { - /** - * Instantiates a {@link WaitCommand} with the given timeout. - * @param timeout the time the command takes to run - */ - public WaitCommand(double timeout) { - this("Wait(" + timeout + ")", timeout); - } + /** + * Instantiates a {@link WaitCommand} with the given timeout. + *$ + * @param timeout the time the command takes to run + */ + public WaitCommand(double timeout) { + this("Wait(" + timeout + ")", timeout); + } - /** - * Instantiates a {@link WaitCommand} with the given timeout. - * @param name the name of the command - * @param timeout the time the command takes to run - */ - public WaitCommand(String name, double timeout) { - super(name, timeout); - } + /** + * Instantiates a {@link WaitCommand} with the given timeout. + *$ + * @param name the name of the command + * @param timeout the time the command takes to run + */ + public WaitCommand(String name, double timeout) { + super(name, timeout); + } - protected void initialize() { - } + protected void initialize() {} - protected void execute() { - } + protected void execute() {} - protected boolean isFinished() { - return isTimedOut(); - } + protected boolean isFinished() { + return isTimedOut(); + } - protected void end() { - } + protected void end() {} - protected void interrupted() { - } + protected void interrupted() {} } diff --git a/wpilibj/wpilibJava/src/main/java/edu/wpi/first/wpilibj/command/WaitForChildren.java b/wpilibj/wpilibJava/src/main/java/edu/wpi/first/wpilibj/command/WaitForChildren.java index 6972a989ca..3df99e35a0 100644 --- a/wpilibj/wpilibJava/src/main/java/edu/wpi/first/wpilibj/command/WaitForChildren.java +++ b/wpilibj/wpilibJava/src/main/java/edu/wpi/first/wpilibj/command/WaitForChildren.java @@ -1,36 +1,37 @@ /*----------------------------------------------------------------------------*/ -/* Copyright (c) FIRST 2008-2012. All Rights Reserved. */ -/* Open Source Software - may be modified and shared by FRC teams. The code */ +/* Copyright (c) FIRST 2008-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 the root directory of */ -/* the project. */ +/* the project. */ /*----------------------------------------------------------------------------*/ package edu.wpi.first.wpilibj.command; /** - * This command will only finish if whatever {@link CommandGroup} it is in has no active children. - * If it is not a part of a {@link CommandGroup}, then it will finish immediately. If it is itself an - * active child, then the {@link CommandGroup} will never end. + * This command will only finish if whatever {@link CommandGroup} it is in has + * no active children. If it is not a part of a {@link CommandGroup}, then it + * will finish immediately. If it is itself an active child, then the + * {@link CommandGroup} will never end. * - *

This class is useful for the situation where you want to allow anything running in parallel to finish, before continuing - * in the main {@link CommandGroup} sequence.

+ *

+ * This class is useful for the situation where you want to allow anything + * running in parallel to finish, before continuing in the main + * {@link CommandGroup} sequence. + *

+ *$ * @author Joe Grinstead */ public class WaitForChildren extends Command { - protected void initialize() { - } + protected void initialize() {} - protected void execute() { - } + protected void execute() {} - protected void end() { - } + protected void end() {} - protected void interrupted() { - } + protected void interrupted() {} - protected boolean isFinished() { - return getGroup() == null || getGroup().m_children.isEmpty(); - } + protected boolean isFinished() { + return getGroup() == null || getGroup().m_children.isEmpty(); + } } diff --git a/wpilibj/wpilibJava/src/main/java/edu/wpi/first/wpilibj/command/WaitUntilCommand.java b/wpilibj/wpilibJava/src/main/java/edu/wpi/first/wpilibj/command/WaitUntilCommand.java index ff15d4a66d..738c69af33 100644 --- a/wpilibj/wpilibJava/src/main/java/edu/wpi/first/wpilibj/command/WaitUntilCommand.java +++ b/wpilibj/wpilibJava/src/main/java/edu/wpi/first/wpilibj/command/WaitUntilCommand.java @@ -1,8 +1,8 @@ /*----------------------------------------------------------------------------*/ -/* Copyright (c) FIRST 2008-2012. All Rights Reserved. */ -/* Open Source Software - may be modified and shared by FRC teams. The code */ +/* Copyright (c) FIRST 2008-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 the root directory of */ -/* the project. */ +/* the project. */ /*----------------------------------------------------------------------------*/ package edu.wpi.first.wpilibj.command; @@ -10,36 +10,33 @@ package edu.wpi.first.wpilibj.command; import edu.wpi.first.wpilibj.Timer; /** - * WaitUntilCommand - waits until an absolute game time. - * This will wait until the game clock reaches some value, then continue to the next command. + * WaitUntilCommand - waits until an absolute game time. This will wait until + * the game clock reaches some value, then continue to the next command. + *$ * @author brad * */ public class WaitUntilCommand extends Command { - private double m_time; + private double m_time; - public WaitUntilCommand(double time) { - super("WaitUntil(" + time + ")"); - m_time = time; - } + public WaitUntilCommand(double time) { + super("WaitUntil(" + time + ")"); + m_time = time; + } - public void initialize() { - } + public void initialize() {} - public void execute() { - } + public void execute() {} - /** - * Check if we've reached the actual finish time. - */ - public boolean isFinished() { - return Timer.getMatchTime() >= m_time; - } + /** + * Check if we've reached the actual finish time. + */ + public boolean isFinished() { + return Timer.getMatchTime() >= m_time; + } - public void end() { - } + public void end() {} - public void interrupted() { - } + public void interrupted() {} } diff --git a/wpilibj/wpilibJava/src/main/java/edu/wpi/first/wpilibj/interfaces/Accelerometer.java b/wpilibj/wpilibJava/src/main/java/edu/wpi/first/wpilibj/interfaces/Accelerometer.java index 0eb4c182ef..728b8b9bbf 100644 --- a/wpilibj/wpilibJava/src/main/java/edu/wpi/first/wpilibj/interfaces/Accelerometer.java +++ b/wpilibj/wpilibJava/src/main/java/edu/wpi/first/wpilibj/interfaces/Accelerometer.java @@ -1,7 +1,7 @@ /*----------------------------------------------------------------------------*/ -/* Copyright (c) FIRST 2014. 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. */ +/* Copyright (c) FIRST 2014. 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. */ /*----------------------------------------------------------------------------*/ package edu.wpi.first.wpilibj.interfaces; @@ -9,40 +9,37 @@ package edu.wpi.first.wpilibj.interfaces; * Interface for 3-axis accelerometers */ public interface Accelerometer { - public enum Range - { - k2G, - k4G, - k8G, - k16G - } + public enum Range { + k2G, k4G, k8G, k16G + } - /** - * 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. - */ - public void setRange(Range range); + /** + * 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. + */ + public void setRange(Range range); - /** - * Common interface for getting the x axis acceleration - * - * @return The acceleration along the x axis in g-forces - */ - public double getX(); + /** + * Common interface for getting the x axis acceleration + * + * @return The acceleration along the x axis in g-forces + */ + public double getX(); - /** - * Common interface for getting the y axis acceleration - * - * @return The acceleration along the y axis in g-forces - */ - public double getY(); + /** + * Common interface for getting the y axis acceleration + * + * @return The acceleration along the y axis in g-forces + */ + public double getY(); - /** - * Common interface for getting the z axis acceleration - * - * @return The acceleration along the z axis in g-forces - */ - public double getZ(); + /** + * Common interface for getting the z axis acceleration + * + * @return The acceleration along the z axis in g-forces + */ + public double getZ(); } diff --git a/wpilibj/wpilibJava/src/main/java/edu/wpi/first/wpilibj/interfaces/Potentiometer.java b/wpilibj/wpilibJava/src/main/java/edu/wpi/first/wpilibj/interfaces/Potentiometer.java index b0109a317d..8fe6e93ce3 100644 --- a/wpilibj/wpilibJava/src/main/java/edu/wpi/first/wpilibj/interfaces/Potentiometer.java +++ b/wpilibj/wpilibJava/src/main/java/edu/wpi/first/wpilibj/interfaces/Potentiometer.java @@ -1,8 +1,8 @@ /*----------------------------------------------------------------------------*/ -/* Copyright (c) FIRST 2008-2014. All Rights Reserved. */ -/* Open Source Software - may be modified and shared by FRC teams. The code */ +/* Copyright (c) FIRST 2008-2014. All Rights Reserved. */ +/* Open Source Software - may be modified and shared by FRC teams. The code */ /* must be accompanied by the FIRST BSD license file in the root directory of */ -/* the project. */ +/* the project. */ /*----------------------------------------------------------------------------*/ package edu.wpi.first.wpilibj.interfaces; @@ -13,5 +13,5 @@ import edu.wpi.first.wpilibj.PIDSource; * @author alex */ public interface Potentiometer extends PIDSource { - double get(); + double get(); } diff --git a/wpilibj/wpilibJava/src/main/java/edu/wpi/first/wpilibj/livewindow/LiveWindow.java b/wpilibj/wpilibJava/src/main/java/edu/wpi/first/wpilibj/livewindow/LiveWindow.java index 49e1e97e44..e5a86f6f30 100644 --- a/wpilibj/wpilibJava/src/main/java/edu/wpi/first/wpilibj/livewindow/LiveWindow.java +++ b/wpilibj/wpilibJava/src/main/java/edu/wpi/first/wpilibj/livewindow/LiveWindow.java @@ -1,6 +1,6 @@ /* - * To change this template, choose Tools | Templates - * and open the template in the editor. + * To change this template, choose Tools | Templates and open the template in + * the editor. */ package edu.wpi.first.wpilibj.livewindow; @@ -12,36 +12,39 @@ import java.util.Hashtable; import java.util.Vector; /** - * A LiveWindow component is a device (sensor or actuator) that should be added to the - * SmartDashboard in test mode. The components are cached until the first time the robot - * enters Test mode. This allows the components to be inserted, then renamed. + * A LiveWindow component is a device (sensor or actuator) that should be added + * to the SmartDashboard in test mode. The components are cached until the first + * time the robot enters Test mode. This allows the components to be inserted, + * then renamed. + *$ * @author brad */ class LiveWindowComponent { - String m_subsystem; - String m_name; - boolean m_isSensor; + String m_subsystem; + String m_name; + boolean m_isSensor; - public LiveWindowComponent(String subsystem, String name, boolean isSensor) { - m_subsystem = subsystem; - m_name = name; - m_isSensor = isSensor; - } + public LiveWindowComponent(String subsystem, String name, boolean isSensor) { + m_subsystem = subsystem; + m_name = name; + m_isSensor = isSensor; + } - public String getName() { - return m_name; - } + public String getName() { + return m_name; + } - public String getSubsystem() { - return m_subsystem; - } + public String getSubsystem() { + return m_subsystem; + } - public boolean isSensor() { - return m_isSensor; - } + public boolean isSensor() { + return m_isSensor; + } } + /** * The LiveWindow class is the public interface for putting sensors and * actuators on the LiveWindow. @@ -50,172 +53,170 @@ class LiveWindowComponent { */ public class LiveWindow { - private static Vector sensors = new Vector(); -// private static Vector actuators = new Vector(); - private static Hashtable components = new Hashtable(); - private static ITable livewindowTable; - private static ITable statusTable; - private static boolean liveWindowEnabled = false; - private static boolean firstTime = true; + private static Vector sensors = new Vector(); + // private static Vector actuators = new Vector(); + private static Hashtable components = new Hashtable(); + private static ITable livewindowTable; + private static ITable statusTable; + private static boolean liveWindowEnabled = false; + private static boolean firstTime = true; - /** - * 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. - */ - private static void initializeLiveWindowComponents() { - System.out.println("Initializing the components first time"); - livewindowTable = NetworkTable.getTable("LiveWindow"); - statusTable = livewindowTable.getSubTable("~STATUS~"); - for (Enumeration e = components.keys(); e.hasMoreElements();) { - LiveWindowSendable component = (LiveWindowSendable) e.nextElement(); - LiveWindowComponent c = (LiveWindowComponent) components.get(component); - String subsystem = c.getSubsystem(); - String name = c.getName(); - System.out.println("Initializing table for '" + subsystem + "' '" + name + "'"); - livewindowTable.getSubTable(subsystem).putString("~TYPE~", "LW Subsystem"); - ITable table = livewindowTable.getSubTable(subsystem).getSubTable(name); - table.putString("~TYPE~", component.getSmartDashboardType()); - table.putString("Name", name); - table.putString("Subsystem", subsystem); - component.initTable(table); - if (c.isSensor()) { - sensors.addElement(component); - } - } - } - - /** - * Set the enabled state of LiveWindow. If it's being enabled, turn off the - * scheduler and remove all the commands from the queue and enable all the - * components registered for LiveWindow. If it's being disabled, stop all - * the registered components and reenable the scheduler. TODO: add code to - * disable PID loops when enabling LiveWindow. The commands should reenable - * the PID loops themselves when they get rescheduled. This prevents arms - * from starting to move around, etc. after a period of adjusting them in - * LiveWindow mode. - */ - public static void setEnabled(boolean enabled) { - if (liveWindowEnabled != enabled) { - if (enabled) { - System.out.println("Starting live window mode."); - if (firstTime) { - initializeLiveWindowComponents(); - firstTime = false; - } - Scheduler.getInstance().disable(); - Scheduler.getInstance().removeAll(); - for (Enumeration e = components.keys(); e.hasMoreElements();) { - LiveWindowSendable component = (LiveWindowSendable) e.nextElement(); - component.startLiveWindowMode(); - } - } else { - System.out.println("stopping live window mode."); - for (Enumeration e = components.keys(); e.hasMoreElements();) { - LiveWindowSendable component = (LiveWindowSendable) e.nextElement(); - component.stopLiveWindowMode(); - } - Scheduler.getInstance().enable(); - } - liveWindowEnabled = enabled; - statusTable.putBoolean("LW Enabled", enabled); - } - } - - /** - * The run method is called repeatedly to keep the values refreshed on the screen in - * test mode. - */ - public static void run() { - updateValues(); - } - - /** - * 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. - */ - public static void addSensor(String subsystem, String name, LiveWindowSendable component) { - components.put(component, new LiveWindowComponent(subsystem, name, true)); - } - - /** - * 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. - */ - public static void addActuator(String subsystem, String name, LiveWindowSendable component) { - components.put(component, new LiveWindowComponent(subsystem, name, false)); - } - - /** - * Puts all sensor values on the live window. - */ - private static void updateValues() { - //TODO: gross - needs to be sped up - for (int i = 0; i < sensors.size(); i++) { - LiveWindowSendable lws = (LiveWindowSendable) sensors.elementAt(i); - lws.updateTable(); - } - // TODO: Add actuators? - // TODO: Add better rate limiting. - } - - /** - * Add Sensor to LiveWindow. The components are shown with the type and - * channel like this: Gyro[1] for a gyro object connected to the first - * analog channel. - * - * @param moduleType A string indicating the type of the module used in the - * naming (above) - * @param channel The channel number the device is connected to - * @param component A reference to the object being added - */ - public static void addSensor(String moduleType, int channel, LiveWindowSendable component) { - addSensor("Ungrouped", moduleType + "[" + channel + "]", component); - if (sensors.contains(component)) { - sensors.removeElement(component); - } + /** + * 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. + */ + private static void initializeLiveWindowComponents() { + System.out.println("Initializing the components first time"); + livewindowTable = NetworkTable.getTable("LiveWindow"); + statusTable = livewindowTable.getSubTable("~STATUS~"); + for (Enumeration e = components.keys(); e.hasMoreElements();) { + LiveWindowSendable component = (LiveWindowSendable) e.nextElement(); + LiveWindowComponent c = (LiveWindowComponent) components.get(component); + String subsystem = c.getSubsystem(); + String name = c.getName(); + System.out.println("Initializing table for '" + subsystem + "' '" + name + "'"); + livewindowTable.getSubTable(subsystem).putString("~TYPE~", "LW Subsystem"); + ITable table = livewindowTable.getSubTable(subsystem).getSubTable(name); + table.putString("~TYPE~", component.getSmartDashboardType()); + table.putString("Name", name); + table.putString("Subsystem", subsystem); + component.initTable(table); + if (c.isSensor()) { sensors.addElement(component); + } } + } - /** - * Add Actuator to LiveWindow. The components are shown with the module - * type, slot and channel like this: Servo[1,2] for a servo object connected - * to the first digital module and PWM port 2. - * - * @param moduleType A string that defines the module name in the label for - * the value - * @param channel The channel number the device is plugged into (usually - * PWM) - * @param component The reference to the object being added - */ - public static void addActuator(String moduleType, int channel, LiveWindowSendable component) { - addActuator("Ungrouped", moduleType + "[" + channel + "]", component); + /** + * Set the enabled state of LiveWindow. If it's being enabled, turn off the + * scheduler and remove all the commands from the queue and enable all the + * components registered for LiveWindow. If it's being disabled, stop all the + * registered components and reenable the scheduler. TODO: add code to disable + * PID loops when enabling LiveWindow. The commands should reenable the PID + * loops themselves when they get rescheduled. This prevents arms from + * starting to move around, etc. after a period of adjusting them in + * LiveWindow mode. + */ + public static void setEnabled(boolean enabled) { + if (liveWindowEnabled != enabled) { + if (enabled) { + System.out.println("Starting live window mode."); + if (firstTime) { + initializeLiveWindowComponents(); + firstTime = false; + } + Scheduler.getInstance().disable(); + Scheduler.getInstance().removeAll(); + for (Enumeration e = components.keys(); e.hasMoreElements();) { + LiveWindowSendable component = (LiveWindowSendable) e.nextElement(); + component.startLiveWindowMode(); + } + } else { + System.out.println("stopping live window mode."); + for (Enumeration e = components.keys(); e.hasMoreElements();) { + LiveWindowSendable component = (LiveWindowSendable) e.nextElement(); + component.stopLiveWindowMode(); + } + Scheduler.getInstance().enable(); + } + liveWindowEnabled = enabled; + statusTable.putBoolean("LW Enabled", enabled); } + } - /** - * Add Actuator to LiveWindow. The components are shown with the module - * type, slot and channel like this: Servo[1,2] for a servo object connected - * to the first digital module and PWM port 2. - * - * @param moduleType A string that defines the module name in the label for - * the value - * @param moduleNumber The number of the particular module type - * @param channel The channel number the device is plugged into (usually - * PWM) - * @param component The reference to the object being added - */ - public static void addActuator(String moduleType, int moduleNumber, int channel, LiveWindowSendable component) { - addActuator("Ungrouped", moduleType + "[" + moduleNumber + "," + channel + "]", component); + /** + * The run method is called repeatedly to keep the values refreshed on the + * screen in test mode. + */ + public static void run() { + updateValues(); + } + + /** + * 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. + */ + public static void addSensor(String subsystem, String name, LiveWindowSendable component) { + components.put(component, new LiveWindowComponent(subsystem, name, true)); + } + + /** + * 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. + */ + public static void addActuator(String subsystem, String name, LiveWindowSendable component) { + components.put(component, new LiveWindowComponent(subsystem, name, false)); + } + + /** + * Puts all sensor values on the live window. + */ + private static void updateValues() { + // TODO: gross - needs to be sped up + for (int i = 0; i < sensors.size(); i++) { + LiveWindowSendable lws = (LiveWindowSendable) sensors.elementAt(i); + lws.updateTable(); } + // TODO: Add actuators? + // TODO: Add better rate limiting. + } + + /** + * Add Sensor to LiveWindow. The components are shown with the type and + * channel like this: Gyro[1] for a gyro object connected to the first analog + * channel. + * + * @param moduleType A string indicating the type of the module used in the + * naming (above) + * @param channel The channel number the device is connected to + * @param component A reference to the object being added + */ + public static void addSensor(String moduleType, int channel, LiveWindowSendable component) { + addSensor("Ungrouped", moduleType + "[" + channel + "]", component); + if (sensors.contains(component)) { + sensors.removeElement(component); + } + sensors.addElement(component); + } + + /** + * Add Actuator to LiveWindow. The components are shown with the module type, + * slot and channel like this: Servo[1,2] for a servo object connected to the + * first digital module and PWM port 2. + * + * @param moduleType A string that defines the module name in the label for + * the value + * @param channel The channel number the device is plugged into (usually PWM) + * @param component The reference to the object being added + */ + public static void addActuator(String moduleType, int channel, LiveWindowSendable component) { + addActuator("Ungrouped", moduleType + "[" + channel + "]", component); + } + + /** + * Add Actuator to LiveWindow. The components are shown with the module type, + * slot and channel like this: Servo[1,2] for a servo object connected to the + * first digital module and PWM port 2. + * + * @param moduleType A string that defines the module name in the label for + * the value + * @param moduleNumber The number of the particular module type + * @param channel The channel number the device is plugged into (usually PWM) + * @param component The reference to the object being added + */ + public static void addActuator(String moduleType, int moduleNumber, int channel, + LiveWindowSendable component) { + addActuator("Ungrouped", moduleType + "[" + moduleNumber + "," + channel + "]", component); + } } diff --git a/wpilibj/wpilibJava/src/main/java/edu/wpi/first/wpilibj/livewindow/LiveWindowSendable.java b/wpilibj/wpilibJava/src/main/java/edu/wpi/first/wpilibj/livewindow/LiveWindowSendable.java index 34aa7737ea..4a46fe8c66 100644 --- a/wpilibj/wpilibJava/src/main/java/edu/wpi/first/wpilibj/livewindow/LiveWindowSendable.java +++ b/wpilibj/wpilibJava/src/main/java/edu/wpi/first/wpilibj/livewindow/LiveWindowSendable.java @@ -1,6 +1,6 @@ /* - * To change this template, choose Tools | Templates - * and open the template in the editor. + * To change this template, choose Tools | Templates and open the template in + * the editor. */ package edu.wpi.first.wpilibj.livewindow; @@ -12,21 +12,19 @@ import edu.wpi.first.wpilibj.Sendable; * @author Alex Henning */ public interface LiveWindowSendable extends Sendable { - /** - * Update the table for this sendable object with the latest - * values. - */ - public void updateTable(); + /** + * Update the table for this sendable object with the latest values. + */ + public void updateTable(); - /** - * Start having this sendable object automatically respond to - * value changes reflect the value on the table. - */ - public void startLiveWindowMode(); + /** + * Start having this sendable object automatically respond to value changes + * reflect the value on the table. + */ + public void startLiveWindowMode(); - /** - * Stop having this sendable object automatically respond to value - * changes. - */ - public void stopLiveWindowMode(); + /** + * Stop having this sendable object automatically respond to value changes. + */ + public void stopLiveWindowMode(); } diff --git a/wpilibj/wpilibJava/src/main/java/edu/wpi/first/wpilibj/smartdashboard/SendableChooser.java b/wpilibj/wpilibJava/src/main/java/edu/wpi/first/wpilibj/smartdashboard/SendableChooser.java index f2d97ee97a..8111bd1fc8 100644 --- a/wpilibj/wpilibJava/src/main/java/edu/wpi/first/wpilibj/smartdashboard/SendableChooser.java +++ b/wpilibj/wpilibJava/src/main/java/edu/wpi/first/wpilibj/smartdashboard/SendableChooser.java @@ -1,8 +1,8 @@ /*----------------------------------------------------------------------------*/ -/* Copyright (c) FIRST 2008-2012. All Rights Reserved. */ -/* Open Source Software - may be modified and shared by FRC teams. The code */ +/* Copyright (c) FIRST 2008-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 the root directory of */ -/* the project. */ +/* the project. */ /*----------------------------------------------------------------------------*/ package edu.wpi.first.wpilibj.smartdashboard; @@ -16,131 +16,132 @@ import edu.wpi.first.wpilibj.tables.ITable; * The {@link SendableChooser} class is a useful tool for presenting a selection * of options to the {@link SmartDashboard}. * - *

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.

+ *

+ * 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. + *

* * @author Joe Grinstead */ public class SendableChooser implements Sendable { - /** - * The key for the default value - */ - private static final String DEFAULT = "default"; - /** - * The key for the selected option - */ - private static final String SELECTED = "selected"; - /** - * The key for the option array - */ - private static final String OPTIONS = "options"; - /** - * A table linking strings to the objects the represent - */ - private StringArray choices = new StringArray(); - private List values = new List(); - private String defaultChoice = null; - private Object defaultValue = null; + /** + * The key for the default value + */ + private static final String DEFAULT = "default"; + /** + * The key for the selected option + */ + private static final String SELECTED = "selected"; + /** + * The key for the option array + */ + private static final String OPTIONS = "options"; + /** + * A table linking strings to the objects the represent + */ + private StringArray choices = new StringArray(); + private List values = new List(); + private String defaultChoice = null; + private Object defaultValue = null; - /** - * Instantiates a {@link SendableChooser}. - */ - public SendableChooser() { + /** + * Instantiates a {@link SendableChooser}. + */ + public SendableChooser() {} + + /** + * 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 + */ + public void addObject(String name, Object object) { + // if we don't have a default, set the default automatically + if (defaultChoice == null) { + addDefault(name, object); + return; } - - /** - * 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 - */ - public void addObject(String name, Object object) { - //if we don't have a default, set the default automatically - if (defaultChoice == null) { - addDefault(name, object); - return; - } - for (int i = 0; i < choices.size(); ++i) { - if (choices.get(i).equals(name)) { - choices.set(i, name); - values.set(i, object); - return; - } - } - //not found - choices.add(name); - values.add(object); - if (table != null) { - table.putValue(OPTIONS, choices); - } + for (int i = 0; i < choices.size(); ++i) { + if (choices.get(i).equals(name)) { + choices.set(i, name); + values.set(i, object); + return; + } } - - /** - * Add the given object to the list of options and marks it as the default. - * Functionally, this is very close to - * {@link SendableChooser#addObject(java.lang.String, java.lang.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 - */ - public void addDefault(String name, Object object) { - if (name == null) { - throw new NullPointerException("Name cannot be null"); - } - defaultChoice = name; - defaultValue = object; - if (table != null) { - table.putString(DEFAULT, defaultChoice); - } - addObject(name, object); + // not found + choices.add(name); + values.add(object); + if (table != null) { + table.putValue(OPTIONS, choices); } + } - /** - * 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 - */ - public Object getSelected() { - String selected = table.getString(SELECTED, null); - for (int i = 0; i < values.size(); ++i) { - if (choices.get(i).equals(selected)) { - return values.get(i); - } - } - return defaultValue; - + /** + * Add the given object to the list of options and marks it as the default. + * Functionally, this is very close to + * {@link SendableChooser#addObject(java.lang.String, java.lang.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 + */ + public void addDefault(String name, Object object) { + if (name == null) { + throw new NullPointerException("Name cannot be null"); } - - public String getSmartDashboardType() { - return "String Chooser"; + defaultChoice = name; + defaultValue = object; + if (table != null) { + table.putString(DEFAULT, defaultChoice); } - private ITable table; + addObject(name, object); + } - public void initTable(ITable table) { - this.table = table; - if (table != null) { - table.putValue(OPTIONS, choices); - if (defaultChoice != null) { - table.putString(DEFAULT, defaultChoice); - } - } + /** + * 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 + */ + public Object getSelected() { + String selected = table.getString(SELECTED, null); + for (int i = 0; i < values.size(); ++i) { + if (choices.get(i).equals(selected)) { + return values.get(i); + } } + return defaultValue; - /** - * {@inheritDoc} - */ - public ITable getTable() { - return table; + } + + public String getSmartDashboardType() { + return "String Chooser"; + } + + private ITable table; + + public void initTable(ITable table) { + this.table = table; + if (table != null) { + table.putValue(OPTIONS, choices); + if (defaultChoice != null) { + table.putString(DEFAULT, defaultChoice); + } } + } + + /** + * {@inheritDoc} + */ + public ITable getTable() { + return table; + } } diff --git a/wpilibj/wpilibJava/src/main/java/edu/wpi/first/wpilibj/smartdashboard/SmartDashboard.java b/wpilibj/wpilibJava/src/main/java/edu/wpi/first/wpilibj/smartdashboard/SmartDashboard.java index b7c92ead6b..c3bad7e604 100644 --- a/wpilibj/wpilibJava/src/main/java/edu/wpi/first/wpilibj/smartdashboard/SmartDashboard.java +++ b/wpilibj/wpilibJava/src/main/java/edu/wpi/first/wpilibj/smartdashboard/SmartDashboard.java @@ -1,8 +1,8 @@ /*----------------------------------------------------------------------------*/ -/* Copyright (c) FIRST 2008-2012. All Rights Reserved. */ -/* Open Source Software - may be modified and shared by FRC teams. The code */ +/* Copyright (c) FIRST 2008-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 the root directory of */ -/* the project. */ +/* the project. */ /*----------------------------------------------------------------------------*/ package edu.wpi.first.wpilibj.smartdashboard; @@ -18,283 +18,312 @@ import java.util.Hashtable; import java.util.NoSuchElementException; /** - * The {@link SmartDashboard} class is the bridge between robot programs and the SmartDashboard on the - * laptop. + * The {@link SmartDashboard} class is the bridge between robot programs and the + * SmartDashboard on the laptop. * - *

When a value is put into the SmartDashboard here, it pops up on the SmartDashboard on the laptop. - * Users can put values into and get values from the SmartDashboard

+ *

+ * When a value is put into the SmartDashboard here, it pops up on the + * SmartDashboard on the laptop. Users can put values into and get values from + * the SmartDashboard + *

* * @author Joe Grinstead */ public class SmartDashboard { - /** The {@link NetworkTable} used by {@link SmartDashboard} */ - private static final NetworkTable table = NetworkTable.getTable("SmartDashboard"); - /** - * A table linking tables in the SmartDashboard to the {@link SmartDashboardData} objects - * they came from. - */ - private static final Hashtable tablesToData = new Hashtable(); + /** The {@link NetworkTable} used by {@link SmartDashboard} */ + private static final NetworkTable table = NetworkTable.getTable("SmartDashboard"); + /** + * A table linking tables in the SmartDashboard to the + * {@link SmartDashboardData} objects they came from. + */ + private static final Hashtable tablesToData = new Hashtable(); - static { - HLUsageReporting.reportSmartDashboard(); + static { + 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. + *$ + * @param key the key + * @param data the value + * @throws IllegalArgumentException if key is null + */ + public static void putData(String key, Sendable data) { + ITable dataTable = table.getSubTable(key); + dataTable.putString("~TYPE~", data.getSmartDashboardType()); + data.initTable(dataTable); + tablesToData.put(data, key); + } + + + // TODO should we reimplement NamedSendable? + /** + * Maps the specified key (where the key is the name of the + * {@link NamedSendable} 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. + *$ + * @param value the value + * @throws IllegalArgumentException if key is null + */ + public static void putData(NamedSendable value) { + putData(value.getName(), value); + } + + /** + * Returns the value at the specified key. + *$ + * @param key the key + * @return the value + * @throws NetworkTableKeyNotDefined if there is no value mapped to by the key + * @throws IllegalArgumentException if the key is null + */ + public static Sendable getData(String key) { + ITable subtable = table.getSubTable(key); + Object data = tablesToData.get(subtable); + if (data == null) { + throw new IllegalArgumentException("SmartDashboard data does not exist: " + key); + } else { + return (Sendable) data; } + } - /** - * 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. - * @param key the key - * @param data the value - * @throws IllegalArgumentException if key is null - */ - public static void putData(String key, Sendable data) { - ITable dataTable = table.getSubTable(key); - dataTable.putString("~TYPE~", data.getSmartDashboardType()); - data.initTable(dataTable); - tablesToData.put(data, key); + /** + * 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. + *$ + * @param key the key + * @param value the value + * @throws IllegalArgumentException if key is null + */ + public static void putBoolean(String key, boolean value) { + table.putBoolean(key, value); + } + + /** + * Returns the value at the specified key. + *$ + * @param key the key + * @return the value + * @throws NetworkTableKeyNotDefined if there is no value mapped to by the key + * @throws IllegalArgumentException if the value mapped to by the key is not a + * boolean + * @throws IllegalArgumentException if the key is null + */ + public static boolean getBoolean(String key) throws TableKeyNotDefinedException { + return table.getBoolean(key); + } + + /** + * Returns the value at the specified key. + *$ + * @param key the key + * @param defaultValue returned if the key doesn't exist + * @return the value + * @throws IllegalArgumentException if the value mapped to by the key is not a + * boolean + * @throws IllegalArgumentException if the key is null + */ + public static boolean getBoolean(String key, boolean defaultValue) { + return table.getBoolean(key, 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. + *$ + * @param key the key + * @param value the value + * @throws IllegalArgumentException if key is null + */ + public static void putNumber(String key, double value) { + table.putNumber(key, value); + } + + /** + * Returns the value at the specified key. + *$ + * @param key the key + * @return the value + * @throws TableKeyNotDefinedException if there is no value mapped to by the + * key + * @throws IllegalArgumentException if the value mapped to by the key is not a + * double + * @throws IllegalArgumentException if the key is null + */ + public static double getNumber(String key) throws TableKeyNotDefinedException { + return table.getNumber(key); + } + + /** + * Returns the value at the specified key. + *$ + * @param key the key + * @param defaultValue the value returned if the key is undefined + * @return the value + * @throws NetworkTableKeyNotDefined if there is no value mapped to by the key + * @throws IllegalArgumentException if the value mapped to by the key is not a + * double + * @throws IllegalArgumentException if the key is null + */ + public static double getNumber(String key, double defaultValue) { + return table.getNumber(key, 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. + *$ + * @param key the key + * @param value the value + * @throws IllegalArgumentException if key or value is null + */ + public static void putString(String key, String value) { + table.putString(key, value); + } + + /** + * Returns the value at the specified key. + *$ + * @param key the key + * @return the value + * @throws NetworkTableKeyNotDefined if there is no value mapped to by the key + * @throws IllegalArgumentException if the value mapped to by the key is not a + * string + * @throws IllegalArgumentException if the key is null + */ + public static String getString(String key) throws TableKeyNotDefinedException { + return table.getString(key); + } + + /** + * Returns the value at the specified key. + *$ + * @param key the key + * @param defaultValue The value returned if the key is undefined + * @return the value + * @throws NetworkTableKeyNotDefined if there is no value mapped to by the key + * @throws IllegalArgumentException if the value mapped to by the key is not a + * string + * @throws IllegalArgumentException if the key is null + */ + public static String getString(String key, String defaultValue) { + return table.getString(key, defaultValue); + } + + + + /* + * Deprecated Methods + */ + /** + * 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. + * + * @deprecated Use {@link #putNumber(java.lang.String, double) putNumber + * method} instead + * @param key the key + * @param value the value + * @throws IllegalArgumentException if key is null + */ + public static void putInt(String key, int value) { + table.putNumber(key, value); + } + + /** + * Returns the value at the specified key. + * + * @deprecated Use {@link #getNumber(java.lang.String) getNumber} instead + * @param key the key + * @return the value + * @throws TableKeyNotDefinedException if there is no value mapped to by the + * key + * @throws IllegalArgumentException if the value mapped to by the key is not + * an int + * @throws IllegalArgumentException if the key is null + */ + public static int getInt(String key) throws TableKeyNotDefinedException { + return (int) table.getNumber(key); + } + + /** + * Returns the value at the specified key. + * + * @deprecated Use {@link #getNumber(java.lang.String, double) getNumber} + * instead + * @param key the key + * @param defaultValue the value returned if the key is undefined + * @return the value + * @throws TableKeyNotDefinedException if there is no value mapped to by the + * key + * @throws IllegalArgumentException if the value mapped to by the key is not + * an int + * @throws IllegalArgumentException if the key is null + */ + public static int getInt(String key, int defaultValue) throws TableKeyNotDefinedException { + try { + return (int) table.getNumber(key); + } catch (NoSuchElementException ex) { + return 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. + * + * @deprecated Use{@link #putNumber(java.lang.String, double) putNumber} + * instead + * @param key the key + * @param value the value + * @throws IllegalArgumentException if key is null + */ + public static void putDouble(String key, double value) { + table.putNumber(key, value); + } - //TODO should we reimplement NamedSendable? - /** - * Maps the specified key (where the key is the name of the {@link NamedSendable} 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. - * @param value the value - * @throws IllegalArgumentException if key is null - */ - public static void putData(NamedSendable value) { - putData(value.getName(), value); - } + /** + * Returns the value at the specified key. + * + * @deprecated Use {@link #getNumber(java.lang.String) getNumber} instead + * @param key the key + * @return the value + * @throws TableKeyNotDefinedException if there is no value mapped to by the + * key + * @throws IllegalArgumentException if the value mapped to by the key is not a + * double + * @throws IllegalArgumentException if the key is null + */ + public static double getDouble(String key) throws TableKeyNotDefinedException { + return table.getNumber(key); + } - /** - * Returns the value at the specified key. - * @param key the key - * @return the value - * @throws NetworkTableKeyNotDefined if there is no value mapped to by the key - * @throws IllegalArgumentException if the key is null - */ - public static Sendable getData(String key) { - ITable subtable = table.getSubTable(key); - Object data = tablesToData.get(subtable); - if (data == null) { - throw new IllegalArgumentException("SmartDashboard data does not exist: " + key); - } else { - return (Sendable) data; - } - } - - /** - * 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. - * @param key the key - * @param value the value - * @throws IllegalArgumentException if key is null - */ - public static void putBoolean(String key, boolean value) { - table.putBoolean(key, value); - } - - /** - * Returns the value at the specified key. - * @param key the key - * @return the value - * @throws NetworkTableKeyNotDefined if there is no value mapped to by the key - * @throws IllegalArgumentException if the value mapped to by the key is not a boolean - * @throws IllegalArgumentException if the key is null - */ - public static boolean getBoolean(String key) throws TableKeyNotDefinedException { - return table.getBoolean(key); - } - - /** - * Returns the value at the specified key. - * @param key the key - * @param defaultValue returned if the key doesn't exist - * @return the value - * @throws IllegalArgumentException if the value mapped to by the key is not a boolean - * @throws IllegalArgumentException if the key is null - */ - public static boolean getBoolean(String key, boolean defaultValue) { - return table.getBoolean(key, 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. - * @param key the key - * @param value the value - * @throws IllegalArgumentException if key is null - */ - public static void putNumber(String key, double value) { - table.putNumber(key, value); - } - - /** - * Returns the value at the specified key. - * @param key the key - * @return the value - * @throws TableKeyNotDefinedException if there is no value mapped to by the key - * @throws IllegalArgumentException if the value mapped to by the key is not a double - * @throws IllegalArgumentException if the key is null - */ - public static double getNumber(String key) throws TableKeyNotDefinedException { - return table.getNumber(key); - } - - /** - * Returns the value at the specified key. - * @param key the key - * @param defaultValue the value returned if the key is undefined - * @return the value - * @throws NetworkTableKeyNotDefined if there is no value mapped to by the key - * @throws IllegalArgumentException if the value mapped to by the key is not a double - * @throws IllegalArgumentException if the key is null - */ - public static double getNumber(String key, double defaultValue) { - return table.getNumber(key, 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. - * @param key the key - * @param value the value - * @throws IllegalArgumentException if key or value is null - */ - public static void putString(String key, String value) { - table.putString(key, value); - } - - /** - * Returns the value at the specified key. - * @param key the key - * @return the value - * @throws NetworkTableKeyNotDefined if there is no value mapped to by the key - * @throws IllegalArgumentException if the value mapped to by the key is not a string - * @throws IllegalArgumentException if the key is null - */ - public static String getString(String key) throws TableKeyNotDefinedException { - return table.getString(key); - } - - /** - * Returns the value at the specified key. - * @param key the key - * @param defaultValue The value returned if the key is undefined - * @return the value - * @throws NetworkTableKeyNotDefined if there is no value mapped to by the key - * @throws IllegalArgumentException if the value mapped to by the key is not a string - * @throws IllegalArgumentException if the key is null - */ - public static String getString(String key, String defaultValue) { - return table.getString(key, defaultValue); - } - - - - - - - - - - /* - * Deprecated Methods - */ - /** - * 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. - * - * @deprecated Use {@link #putNumber(java.lang.String, double) putNumber method} instead - * @param key the key - * @param value the value - * @throws IllegalArgumentException if key is null - */ - public static void putInt(String key, int value) { - table.putNumber(key, value); - } - - /** - * Returns the value at the specified key. - * - * @deprecated Use {@link #getNumber(java.lang.String) getNumber} instead - * @param key the key - * @return the value - * @throws TableKeyNotDefinedException if there is no value mapped to by the key - * @throws IllegalArgumentException if the value mapped to by the key is not an int - * @throws IllegalArgumentException if the key is null - */ - public static int getInt(String key) throws TableKeyNotDefinedException { - return (int) table.getNumber(key); - } - - /** - * Returns the value at the specified key. - * - * @deprecated Use {@link #getNumber(java.lang.String, double) getNumber} instead - * @param key the key - * @param defaultValue the value returned if the key is undefined - * @return the value - * @throws TableKeyNotDefinedException if there is no value mapped to by the key - * @throws IllegalArgumentException if the value mapped to by the key is not an int - * @throws IllegalArgumentException if the key is null - */ - public static int getInt(String key, int defaultValue) throws TableKeyNotDefinedException { - try { - return (int) table.getNumber(key); - } catch (NoSuchElementException ex) { - return 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. - * - * @deprecated Use{@link #putNumber(java.lang.String, double) putNumber} instead - * @param key the key - * @param value the value - * @throws IllegalArgumentException if key is null - */ - public static void putDouble(String key, double value) { - table.putNumber(key, value); - } - - /** - * Returns the value at the specified key. - * - * @deprecated Use {@link #getNumber(java.lang.String) getNumber} instead - * @param key the key - * @return the value - * @throws TableKeyNotDefinedException if there is no value mapped to by the key - * @throws IllegalArgumentException if the value mapped to by the key is not a double - * @throws IllegalArgumentException if the key is null - */ - public static double getDouble(String key) throws TableKeyNotDefinedException { - return table.getNumber(key); - } - - /** - * Returns the value at the specified key. - * - * @deprecated Use {@link #getNumber(java.lang.String, double) getNumber} instead. - * @param key the key - * @param defaultValue the value returned if the key is undefined - * @return the value - * @throws TableKeyNotDefinedException if there is no value mapped to by the key - * @throws IllegalArgumentException if the value mapped to by the key is not a double - * @throws IllegalArgumentException if the key is null - */ - public static double getDouble(String key, double defaultValue) { - return table.getNumber(key, defaultValue); - } + /** + * Returns the value at the specified key. + * + * @deprecated Use {@link #getNumber(java.lang.String, double) getNumber} + * instead. + * @param key the key + * @param defaultValue the value returned if the key is undefined + * @return the value + * @throws TableKeyNotDefinedException if there is no value mapped to by the + * key + * @throws IllegalArgumentException if the value mapped to by the key is not a + * double + * @throws IllegalArgumentException if the key is null + */ + public static double getDouble(String key, double defaultValue) { + return table.getNumber(key, defaultValue); + } } diff --git a/wpilibj/wpilibJava/src/main/java/edu/wpi/first/wpilibj/util/AllocationException.java b/wpilibj/wpilibJava/src/main/java/edu/wpi/first/wpilibj/util/AllocationException.java index 15d04f464c..2557245ad4 100644 --- a/wpilibj/wpilibJava/src/main/java/edu/wpi/first/wpilibj/util/AllocationException.java +++ b/wpilibj/wpilibJava/src/main/java/edu/wpi/first/wpilibj/util/AllocationException.java @@ -1,23 +1,25 @@ /*----------------------------------------------------------------------------*/ -/* Copyright (c) FIRST 2008-2012. All Rights Reserved. */ -/* Open Source Software - may be modified and shared by FRC teams. The code */ +/* Copyright (c) FIRST 2008-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 the root directory of */ -/* the project. */ +/* the project. */ /*----------------------------------------------------------------------------*/ package edu.wpi.first.wpilibj.util; /** * Exception indicating that the resource is already allocated + *$ * @author dtjones */ public class AllocationException extends RuntimeException { - /** - * Create a new AllocationException - * @param msg the message to attach to the exception - */ - public AllocationException(String msg) { - super(msg); - } + /** + * Create a new AllocationException + *$ + * @param msg the message to attach to the exception + */ + public AllocationException(String msg) { + super(msg); + } } diff --git a/wpilibj/wpilibJava/src/main/java/edu/wpi/first/wpilibj/util/BaseSystemNotInitializedException.java b/wpilibj/wpilibJava/src/main/java/edu/wpi/first/wpilibj/util/BaseSystemNotInitializedException.java index f5877cff8d..35a667ec0f 100644 --- a/wpilibj/wpilibJava/src/main/java/edu/wpi/first/wpilibj/util/BaseSystemNotInitializedException.java +++ b/wpilibj/wpilibJava/src/main/java/edu/wpi/first/wpilibj/util/BaseSystemNotInitializedException.java @@ -1,35 +1,39 @@ /*----------------------------------------------------------------------------*/ -/* Copyright (c) FIRST 2008-2014. All Rights Reserved. */ -/* Open Source Software - may be modified and shared by FRC teams. The code */ +/* Copyright (c) FIRST 2008-2014. All Rights Reserved. */ +/* Open Source Software - may be modified and shared by FRC teams. The code */ /* must be accompanied by the FIRST BSD license file in the root directory of */ -/* the project. */ +/* the project. */ /*----------------------------------------------------------------------------*/ package edu.wpi.first.wpilibj.util; /** - * Thrown if there is an error caused by a basic system or setting - * not being properly initialized before being used. - * + * Thrown if there is an error caused by a basic system or setting not being + * properly initialized before being used. + *$ * @author Jonathan Leitschuh */ public class BaseSystemNotInitializedException extends RuntimeException { - /** - * Create a new BaseSystemNotInitializedException - * @param message the message to attach to the exception - */ - public BaseSystemNotInitializedException(String message) { - super(message); - } - - /** - * Create a new BaseSystemNotInitializedException using the offending class that was not set and the - * class that was affected. - * @param offender The class or interface that was not properly initialized. - * @param affected The class that was was affected by this missing initialization. - */ - public BaseSystemNotInitializedException(Class offender, Class affected){ - super("The " + offender.getSimpleName() + " for the " + affected.getSimpleName() + " was never set."); - } - + /** + * Create a new BaseSystemNotInitializedException + *$ + * @param message the message to attach to the exception + */ + public BaseSystemNotInitializedException(String message) { + super(message); + } + + /** + * Create a new BaseSystemNotInitializedException using the offending class + * that was not set and the class that was affected. + *$ + * @param offender The class or interface that was not properly initialized. + * @param affected The class that was was affected by this missing + * initialization. + */ + public BaseSystemNotInitializedException(Class offender, Class affected) { + super("The " + offender.getSimpleName() + " for the " + affected.getSimpleName() + + " was never set."); + } + } diff --git a/wpilibj/wpilibJava/src/main/java/edu/wpi/first/wpilibj/util/BoundaryException.java b/wpilibj/wpilibJava/src/main/java/edu/wpi/first/wpilibj/util/BoundaryException.java index d3b70d4902..74979432d1 100644 --- a/wpilibj/wpilibJava/src/main/java/edu/wpi/first/wpilibj/util/BoundaryException.java +++ b/wpilibj/wpilibJava/src/main/java/edu/wpi/first/wpilibj/util/BoundaryException.java @@ -1,8 +1,8 @@ /*----------------------------------------------------------------------------*/ -/* Copyright (c) FIRST 2008-2012. All Rights Reserved. */ -/* Open Source Software - may be modified and shared by FRC teams. The code */ +/* Copyright (c) FIRST 2008-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 the root directory of */ -/* the project. */ +/* the project. */ /*----------------------------------------------------------------------------*/ package edu.wpi.first.wpilibj.util; @@ -10,53 +10,44 @@ package edu.wpi.first.wpilibj.util; /** * This exception represents an error in which a lower limit was set as higher * than an upper limit. - * + *$ * @author dtjones */ public class BoundaryException extends RuntimeException { - /** - * Create a new exception with the given message - * - * @param message - * the message to attach to the exception - */ - public BoundaryException(String message) { - super(message); - } + /** + * Create a new exception with the given message + *$ + * @param message the message to attach to the exception + */ + public BoundaryException(String message) { + super(message); + } - /** - * Make sure that the given value is between the upper and lower bounds, and - * throw an exception if they are not. - * - * @param value - * The value to check. - * @param lower - * The minimum acceptable value. - * @param upper - * The maximum acceptable value. - */ - public static void assertWithinBounds(double value, double lower, - double upper) { - if (value < lower || value > upper) - throw new BoundaryException("Value must be between " + lower - + " and " + upper + ", " + value + " given"); - } + /** + * Make sure that the given value is between the upper and lower bounds, and + * throw an exception if they are not. + *$ + * @param value The value to check. + * @param lower The minimum acceptable value. + * @param upper The maximum acceptable value. + */ + public static void assertWithinBounds(double value, double lower, double upper) { + if (value < lower || value > upper) + throw new BoundaryException("Value must be between " + lower + " and " + upper + ", " + value + + " given"); + } - /** - * Returns the message for a boundary exception. Used to keep the message - * consistent across all boundary exceptions. - * - * @param value - * The given value - * @param lower - * The lower limit - * @param upper - * The upper limit - * @return the message for a boundary exception - */ - public static String getMessage(double value, double lower, double upper) { - return "Value must be between " + lower + " and " + upper + ", " - + value + " given"; - } + /** + * Returns the message for a boundary exception. Used to keep the message + * consistent across all boundary exceptions. + *$ + * @param value The given value + * @param lower The lower limit + * @param upper The upper limit + * @return the message for a boundary exception + */ + public static String getMessage(double value, double lower, double upper) { + return "Value must be between " + lower + " and " + upper + ", " + value + " given"; + } } diff --git a/wpilibj/wpilibJava/src/main/java/edu/wpi/first/wpilibj/util/CheckedAllocationException.java b/wpilibj/wpilibJava/src/main/java/edu/wpi/first/wpilibj/util/CheckedAllocationException.java index 763752666a..1e89c5efa4 100644 --- a/wpilibj/wpilibJava/src/main/java/edu/wpi/first/wpilibj/util/CheckedAllocationException.java +++ b/wpilibj/wpilibJava/src/main/java/edu/wpi/first/wpilibj/util/CheckedAllocationException.java @@ -1,24 +1,26 @@ /*----------------------------------------------------------------------------*/ -/* Copyright (c) FIRST 2008-2012. All Rights Reserved. */ -/* Open Source Software - may be modified and shared by FRC teams. The code */ +/* Copyright (c) FIRST 2008-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 the root directory of */ -/* the project. */ +/* the project. */ /*----------------------------------------------------------------------------*/ package edu.wpi.first.wpilibj.util; /** - * Exception indicating that the resource is already allocated - * This is meant to be thrown by the resource class + * Exception indicating that the resource is already allocated This is meant to + * be thrown by the resource class + *$ * @author dtjones */ public class CheckedAllocationException extends Exception { - /** - * Create a new CheckedAllocationException - * @param msg the message to attach to the exception - */ - public CheckedAllocationException(String msg) { - super(msg); - } + /** + * Create a new CheckedAllocationException + *$ + * @param msg the message to attach to the exception + */ + public CheckedAllocationException(String msg) { + super(msg); + } } diff --git a/wpilibj/wpilibJava/src/main/java/edu/wpi/first/wpilibj/util/SortedVector.java b/wpilibj/wpilibJava/src/main/java/edu/wpi/first/wpilibj/util/SortedVector.java index a3ae959d9d..47eef7b088 100644 --- a/wpilibj/wpilibJava/src/main/java/edu/wpi/first/wpilibj/util/SortedVector.java +++ b/wpilibj/wpilibJava/src/main/java/edu/wpi/first/wpilibj/util/SortedVector.java @@ -1,8 +1,8 @@ /*----------------------------------------------------------------------------*/ -/* Copyright (c) FIRST 2008-2012. All Rights Reserved. */ -/* Open Source Software - may be modified and shared by FRC teams. The code */ +/* Copyright (c) FIRST 2008-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 the root directory of */ -/* the project. */ +/* the project. */ /*----------------------------------------------------------------------------*/ package edu.wpi.first.wpilibj.util; @@ -14,62 +14,66 @@ import java.util.Vector; */ public class SortedVector extends Vector { - /** - * Interface used to determine the order to place sorted objects. - */ - public static interface Comparator { - - /** - * Compare the given two objects. - * @param object1 First object to compare - * @param object2 Second object to compare - * @return -1, 0, or 1 if the first object is less than, equal to, or - * greater than the second, respectively - */ - public int compare(Object object1, Object object2); - } - Comparator comparator; + /** + * Interface used to determine the order to place sorted objects. + */ + public static interface Comparator { /** - * Create a new sorted vector and use the given comparator to determine order. - * @param comparator The comparator to use to determine what order to place - * the elements in this vector. + * Compare the given two objects. + *$ + * @param object1 First object to compare + * @param object2 Second object to compare + * @return -1, 0, or 1 if the first object is less than, equal to, or + * greater than the second, respectively */ - public SortedVector(Comparator comparator) { - this.comparator = comparator; - } + public int compare(Object object1, Object object2); + } - /** - * Adds an element in the Vector, sorted from greatest to least. - * @param element The element to add to the Vector - */ - public void addElement(Object element) { - int highBound = size(); - int lowBound = 0; - while (highBound - lowBound > 0) { - int index = (highBound + lowBound) / 2; - int result = comparator.compare(element, elementAt(index)); - if (result < 0) { - lowBound = index + 1; - } else if (result > 0) { - highBound = index; - } else { - lowBound = index; - highBound = index; - } - } - insertElementAt(element, lowBound); - } + Comparator comparator; - /** - * Sort the vector. - */ - public void sort() { - Object[] array = new Object[size()]; - copyInto(array); - removeAllElements(); - for (int i = 0; i < array.length; i++) { - addElement(array[i]); - } + /** + * Create a new sorted vector and use the given comparator to determine order. + *$ + * @param comparator The comparator to use to determine what order to place + * the elements in this vector. + */ + public SortedVector(Comparator comparator) { + this.comparator = comparator; + } + + /** + * Adds an element in the Vector, sorted from greatest to least. + *$ + * @param element The element to add to the Vector + */ + public void addElement(Object element) { + int highBound = size(); + int lowBound = 0; + while (highBound - lowBound > 0) { + int index = (highBound + lowBound) / 2; + int result = comparator.compare(element, elementAt(index)); + if (result < 0) { + lowBound = index + 1; + } else if (result > 0) { + highBound = index; + } else { + lowBound = index; + highBound = index; + } } + insertElementAt(element, lowBound); + } + + /** + * Sort the vector. + */ + public void sort() { + Object[] array = new Object[size()]; + copyInto(array); + removeAllElements(); + for (int i = 0; i < array.length; i++) { + addElement(array[i]); + } + } } diff --git a/wpilibj/wpilibJava/src/main/java/edu/wpi/first/wpilibj/util/UncleanStatusException.java b/wpilibj/wpilibJava/src/main/java/edu/wpi/first/wpilibj/util/UncleanStatusException.java index 41313f5547..2442ef7a1c 100644 --- a/wpilibj/wpilibJava/src/main/java/edu/wpi/first/wpilibj/util/UncleanStatusException.java +++ b/wpilibj/wpilibJava/src/main/java/edu/wpi/first/wpilibj/util/UncleanStatusException.java @@ -1,58 +1,63 @@ /*----------------------------------------------------------------------------*/ -/* Copyright (c) FIRST 2008-2012. All Rights Reserved. */ -/* Open Source Software - may be modified and shared by FRC teams. The code */ +/* Copyright (c) FIRST 2008-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 the root directory of */ -/* the project. */ +/* the project. */ /*----------------------------------------------------------------------------*/ package edu.wpi.first.wpilibj.util; /** * Exception for bad status codes from the chip object + *$ * @author Brian */ public final class UncleanStatusException extends IllegalStateException { - private final int statusCode; + private final int statusCode; - /** - * Create a new UncleanStatusException - * @param status the status code that caused the exception - * @param message A message describing the exception - */ - public UncleanStatusException(int status, String message) { - super(message); - statusCode = status; - } + /** + * Create a new UncleanStatusException + *$ + * @param status the status code that caused the exception + * @param message A message describing the exception + */ + public UncleanStatusException(int status, String message) { + super(message); + statusCode = status; + } - /** - * Create a new UncleanStatusException - * @param status the status code that caused the exception - */ - public UncleanStatusException(int status) { - this(status, "Status code was non-zero"); - } + /** + * Create a new UncleanStatusException + *$ + * @param status the status code that caused the exception + */ + public UncleanStatusException(int status) { + this(status, "Status code was non-zero"); + } - /** - * Create a new UncleanStatusException - * @param message a message describing the exception - */ - public UncleanStatusException(String message) { - this(-1, message); - } + /** + * Create a new UncleanStatusException + *$ + * @param message a message describing the exception + */ + public UncleanStatusException(String message) { + this(-1, message); + } - /** - * Create a new UncleanStatusException - */ - public UncleanStatusException() { - this(-1, "Status code was non-zero"); - } + /** + * Create a new UncleanStatusException + */ + public UncleanStatusException() { + this(-1, "Status code was non-zero"); + } - /** - * Create a new UncleanStatusException - * @return the status code that caused the exception - */ - public int getStatus() { - return statusCode; - } + /** + * Create a new UncleanStatusException + *$ + * @return the status code that caused the exception + */ + public int getStatus() { + return statusCode; + } } diff --git a/wpilibj/wpilibJavaDevices/src/main/java/com/ni/vision/NIVision.java b/wpilibj/wpilibJavaDevices/src/main/java/com/ni/vision/NIVision.java index dfc46d5fd4..d2f0b623b1 100644 --- a/wpilibj/wpilibJavaDevices/src/main/java/com/ni/vision/NIVision.java +++ b/wpilibj/wpilibJavaDevices/src/main/java/com/ni/vision/NIVision.java @@ -12,25154 +12,31104 @@ import java.nio.ByteBuffer; import java.nio.ByteOrder; public class NIVision { - private NIVision() {} + private NIVision() {} - private static native void imaqDispose(long addr); + private static native void imaqDispose(long addr); - private static Constructor constructDirectByteBuffer; - private static Field bufferAddressField; + private static Constructor constructDirectByteBuffer; + private static Field bufferAddressField; - static { + static { + try { + Class[] cArg = new Class[2]; + cArg[0] = long.class; + cArg[1] = int.class; + constructDirectByteBuffer = + Class.forName("java.nio.DirectByteBuffer").getDeclaredConstructor(cArg); + constructDirectByteBuffer.setAccessible(true); + + bufferAddressField = Buffer.class.getDeclaredField("address"); + bufferAddressField.setAccessible(true); + } catch (ReflectiveOperationException e) { + throw new ExceptionInInitializerError(e); + } + } + + private static ByteBuffer newDirectByteBuffer(long addr, int cap) { + try { + return ((ByteBuffer) (constructDirectByteBuffer.newInstance(addr, cap))).order(ByteOrder + .nativeOrder()); + } catch (ReflectiveOperationException e) { + throw new ExceptionInInitializerError(e); + } + } + + private static long getByteBufferAddress(ByteBuffer bb) { + try { + return bufferAddressField.getLong(bb); + } catch (IllegalAccessException e) { + return 0; + } + } + + public static ByteBuffer sliceByteBuffer(ByteBuffer bb, int offset, int size) { + int pos = bb.position(); + int lim = bb.limit(); + bb.position(offset); + bb.limit(offset + size); + ByteBuffer new_bb = bb.slice().order(ByteOrder.nativeOrder()); + bb.position(pos); + bb.limit(lim); + return new_bb; + } + + public static ByteBuffer getBytes(ByteBuffer bb, byte[] dst, int offset, int size) { + int pos = bb.position(); + bb.position(offset); + bb.get(dst, 0, size); + bb.position(pos); + return bb; + } + + public static ByteBuffer putBytes(ByteBuffer bb, byte[] src, int offset, int size) { + int pos = bb.position(); + bb.position(offset); + bb.put(src, 0, size); + bb.position(pos); + return bb; + } + + private static abstract class DisposedStruct { + protected ByteBuffer backing; + private boolean owned; + + protected DisposedStruct(int size) { + backing = ByteBuffer.allocateDirect(size); + backing.order(ByteOrder.nativeOrder()); + owned = false; + } + + protected DisposedStruct(ByteBuffer backing, int offset, int size) { + this.backing = sliceByteBuffer(backing, offset, size); + owned = false; + } + + private DisposedStruct(long nativeObj, boolean owned, int size) { + backing = newDirectByteBuffer(nativeObj, size); + this.owned = owned; + } + + public void free() { + if (owned) { + imaqDispose(getByteBufferAddress(backing)); + owned = false; + backing = null; + } + } + + @Override + protected void finalize() throws Throwable { + if (owned) + imaqDispose(getByteBufferAddress(backing)); + super.finalize(); + } + + public long getAddress() { + if (backing == null) + return 0; + write(); + return getByteBufferAddress(backing); + } + + protected void setBuffer(ByteBuffer backing, int offset, int size) { + this.backing = sliceByteBuffer(backing, offset, size); + } + + abstract public void read(); + + abstract public void write(); + + abstract public int size(); + } + + private static abstract class OpaqueStruct { + private long nativeObj; + private boolean owned; + + protected OpaqueStruct() { + nativeObj = 0; + owned = false; + } + + protected OpaqueStruct(long nativeObj, boolean owned) { + this.nativeObj = nativeObj; + this.owned = owned; + } + + public void free() { + if (owned && nativeObj != 0) { + imaqDispose(nativeObj); + owned = false; + nativeObj = 0; + } + } + + @Override + protected void finalize() throws Throwable { + if (owned && nativeObj != 0) + imaqDispose(nativeObj); + super.finalize(); + } + + public long getAddress() { + return nativeObj; + } + } + + public static class RawData { + private ByteBuffer buf; + private boolean owned; + + public RawData() { + owned = false; + } + + public RawData(ByteBuffer buf) { + this.buf = buf; + owned = false; + } + + private RawData(long nativeObj, boolean owned, int size) { + buf = newDirectByteBuffer(nativeObj, size); + this.owned = owned; + } + + public void free() { + if (owned) { + imaqDispose(getByteBufferAddress(buf)); + owned = false; + buf = null; + } + } + + @Override + protected void finalize() throws Throwable { + if (owned) + imaqDispose(getByteBufferAddress(buf)); + super.finalize(); + } + + public long getAddress() { + if (buf == null) + return 0; + return getByteBufferAddress(buf); + } + + public ByteBuffer getBuffer() { + return buf; + } + + public void setBuffer(ByteBuffer buf) { + if (owned) + free(); + this.buf = buf; + } + } + + private static long getPointer(ByteBuffer bb, int offset) { + return (long) bb.getInt(offset); + } + + private static void putPointer(ByteBuffer bb, int offset, long address) { + bb.putInt(offset, (int) address); + } + + private static void putPointer(ByteBuffer bb, int offset, ByteBuffer buf) { + if (buf == null) + bb.putInt(offset, 0); + else + bb.putInt(offset, (int) getByteBufferAddress(buf)); + } + + private static void putPointer(ByteBuffer bb, int offset, DisposedStruct struct) { + if (struct == null) + bb.putInt(offset, 0); + else + bb.putInt(offset, (int) struct.getAddress()); + } + + private static void putPointer(ByteBuffer bb, int offset, OpaqueStruct struct) { + if (struct == null) + bb.putInt(offset, 0); + else + bb.putInt(offset, (int) struct.getAddress()); + } + + /** + * Opaque Structures + */ + + public static class CharSet extends OpaqueStruct { + private CharSet() {} + + private CharSet(long nativeObj, boolean owned) { + super(nativeObj, owned); + } + } + + public static class ClassifierSession extends OpaqueStruct { + private ClassifierSession() {} + + private ClassifierSession(long nativeObj, boolean owned) { + super(nativeObj, owned); + } + } + + public static class Image extends OpaqueStruct { + private Image() {} + + private Image(long nativeObj, boolean owned) { + super(nativeObj, owned); + } + } + + public static class MultipleGeometricPattern extends OpaqueStruct { + private MultipleGeometricPattern() {} + + private MultipleGeometricPattern(long nativeObj, boolean owned) { + super(nativeObj, owned); + } + } + + public static class Overlay extends OpaqueStruct { + private Overlay() {} + + private Overlay(long nativeObj, boolean owned) { + super(nativeObj, owned); + } + } + + public static class ROI extends OpaqueStruct { + private ROI() {} + + private ROI(long nativeObj, boolean owned) { + super(nativeObj, owned); + } + } + + /** + * Manifest Constants + */ + public static final boolean DEFAULT_SHOW_COORDINATES = true; + public static final int DEFAULT_MAX_ICONS_PER_LINE = 4; + public static final boolean DEFAULT_BMP_COMPRESS = false; + public static final int DEFAULT_PNG_QUALITY = 750; + public static final int DEFAULT_JPEG_QUALITY = 750; + public static final int ALL_CONTOURS = -1; + public static final int ALL_WINDOWS = -1; + public static final int SHIFT = 1; + public static final int ALT = 2; + public static final int CTRL = 4; + public static final int CAPS_LOCK = 8; + public static final int MODAL_DIALOG = -1; + public static final int USE_DEFAULT_QUALITY = -1; + public static final int ALL_SAMPLES = -1; + public static final int ALL_OBJECTS = -1; + public static final int ALL_CHARACTERS = -1; + + /** + * Predefined Valid Characters + */ + public static final byte[] ANY_CHARACTER = {0}; + public static final byte[] ALPHABETIC = {0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, + 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f, 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, + 0x59, 0x5a, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6a, 0x6b, 0x6c, 0x6d, + 0x6e, 0x6f, 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7a, 0}; + public static final byte[] ALPHANUMERIC = {0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, + 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f, 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, + 0x59, 0x5a, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6a, 0x6b, 0x6c, 0x6d, + 0x6e, 0x6f, 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7a, 0x30, 0x31, + 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0}; + public static final byte[] UPPERCASE_LETTERS = {0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, + 0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f, 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, + 0x58, 0x59, 0x5a, 0}; + public static final byte[] LOWERCASE_LETTERS = {0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, + 0x69, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f, 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, + 0x78, 0x79, 0x7a, 0}; + public static final byte[] DECIMAL_DIGITS = {0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, + 0x38, 0x39, 0}; + public static final byte[] HEXADECIMAL_DIGITS = {0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, + 0x38, 0x39, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0}; + public static final byte[] PATTERN = {0x5c, 0x78, 0x46, 0x46, 0}; + public static final byte[] FORCE_SPACE = {0x20, 0}; + + /** + * Enumerated Types + */ + + public static enum PointSymbol { + POINT_AS_PIXEL(0), // A single pixel represents a point in the overlay. + POINT_AS_CROSS(1), // A cross represents a point in the overlay. + POINT_USER_DEFINED(2), // The pattern supplied by the user represents a + // point in the overlay. + ; + private final int value; + + private PointSymbol(int value) { + this.value = value; + } + + public static PointSymbol fromValue(int val) { + try { + return values()[val]; + } catch (ArrayIndexOutOfBoundsException e) { + return null; + } + } + + public int getValue() { + return value; + } + } + + public static enum MeasurementValue { + AREA(0), // Surface area of the particle in pixels. + AREA_CALIBRATED(1), // Surface area of the particle in calibrated units. + NUM_HOLES(2), // Number of holes in the particle. + AREA_OF_HOLES(3), // Surface area of the holes in calibrated units. + TOTAL_AREA(4), // Total surface area (holes and particle) in calibrated + // units. + IMAGE_AREA(5), // Surface area of the entire image in calibrated units. + PARTICLE_TO_IMAGE(6), // Ratio, expressed as a percentage, of the surface + // area of a particle in relation to the total area of + // the particle. + PARTICLE_TO_TOTAL(7), // Ratio, expressed as a percentage, of the surface + // area of a particle in relation to the total area of + // the particle. + CENTER_MASS_X(8), // X-coordinate of the center of mass. + CENTER_MASS_Y(9), // Y-coordinate of the center of mass. + LEFT_COLUMN(10), // Left edge of the bounding rectangle. + TOP_ROW(11), // Top edge of the bounding rectangle. + RIGHT_COLUMN(12), // Right edge of the bounding rectangle. + BOTTOM_ROW(13), // Bottom edge of bounding rectangle. + WIDTH(14), // Width of bounding rectangle in calibrated units. + HEIGHT(15), // Height of bounding rectangle in calibrated units. + MAX_SEGMENT_LENGTH(16), // Length of longest horizontal line segment. + MAX_SEGMENT_LEFT_COLUMN(17), // Leftmost x-coordinate of longest horizontal + // line segment. + MAX_SEGMENT_TOP_ROW(18), // Y-coordinate of longest horizontal line segment. + PERIMETER(19), // Outer perimeter of the particle. + PERIMETER_OF_HOLES(20), // Perimeter of all holes within the particle. + SIGMA_X(21), // Sum of the particle pixels on the x-axis. + SIGMA_Y(22), // Sum of the particle pixels on the y-axis. + SIGMA_XX(23), // Sum of the particle pixels on the x-axis squared. + SIGMA_YY(24), // Sum of the particle pixels on the y-axis squared. + SIGMA_XY(25), // Sum of the particle pixels on the x-axis and y-axis. + PROJ_X(26), // Projection corrected in X. + PROJ_Y(27), // Projection corrected in Y. + INERTIA_XX(28), // Inertia matrix coefficient in XX. + INERTIA_YY(29), // Inertia matrix coefficient in YY. + INERTIA_XY(30), // Inertia matrix coefficient in XY. + MEAN_H(31), // Mean length of horizontal segments. + MEAN_V(32), // Mean length of vertical segments. + MAX_INTERCEPT(33), // Length of longest segment of the convex hull. + MEAN_INTERCEPT(34), // Mean length of the chords in an object perpendicular + // to its max intercept. + ORIENTATION(35), // The orientation based on the inertia of the pixels in + // the particle. + EQUIV_ELLIPSE_MINOR(36), // Total length of the axis of the ellipse having + // the same area as the particle and a major axis + // equal to half the max intercept. + ELLIPSE_MAJOR(37), // Total length of major axis having the same area and + // perimeter as the particle in calibrated units. + ELLIPSE_MINOR(38), // Total length of minor axis having the same area and + // perimeter as the particle in calibrated units. + ELLIPSE_RATIO(39), // Fraction of major axis to minor axis. + RECT_LONG_SIDE(40), // Length of the long side of a rectangle having the + // same area and perimeter as the particle in calibrated + // units. + RECT_SHORT_SIDE(41), // Length of the short side of a rectangle having the + // same area and perimeter as the particle in + // calibrated units. + RECT_RATIO(42), // Ratio of rectangle long side to rectangle short side. + ELONGATION(43), // Max intercept/mean perpendicular intercept. + COMPACTNESS(44), // Particle area/(height x width). + HEYWOOD(45), // Particle perimeter/perimeter of the circle having the same + // area as the particle. + TYPE_FACTOR(46), // A complex factor relating the surface area to the moment + // of inertia. + HYDRAULIC(47), // Particle area/particle perimeter. + WADDLE_DISK(48), // Diameter of the disk having the same area as the + // particle in user units. + DIAGONAL(49), // Diagonal of an equivalent rectangle in user units. + ; + private final int value; + + private MeasurementValue(int value) { + this.value = value; + } + + public static MeasurementValue fromValue(int val) { + try { + return values()[val]; + } catch (ArrayIndexOutOfBoundsException e) { + return null; + } + } + + public int getValue() { + return value; + } + } + + public static enum ScalingMode { + SCALE_LARGER(0), // The function duplicates pixels to make the image larger. + SCALE_SMALLER(1), // The function subsamples pixels to make the image + // smaller. + ; + private final int value; + + private ScalingMode(int value) { + this.value = value; + } + + public static ScalingMode fromValue(int val) { + try { + return values()[val]; + } catch (ArrayIndexOutOfBoundsException e) { + return null; + } + } + + public int getValue() { + return value; + } + } + + public static enum ScalingMethod { + SCALE_TO_PRESERVE_AREA(0), // Correction functions scale the image such that + // the features in the corrected image have the + // same area as the features in the input image. + SCALE_TO_FIT(1), // Correction functions scale the image such that the + // corrected image is the same size as the input image. + ; + private final int value; + + private ScalingMethod(int value) { + this.value = value; + } + + public static ScalingMethod fromValue(int val) { + try { + return values()[val]; + } catch (ArrayIndexOutOfBoundsException e) { + return null; + } + } + + public int getValue() { + return value; + } + } + + public static enum ReferenceMode { + COORD_X_Y(0), // This method requires three elements in the points array. + COORD_ORIGIN_X(1), // This method requires two elements in the points array. + ; + private final int value; + + private ReferenceMode(int value) { + this.value = value; + } + + public static ReferenceMode fromValue(int val) { + try { + return values()[val]; + } catch (ArrayIndexOutOfBoundsException e) { + return null; + } + } + + public int getValue() { + return value; + } + } + + public static enum RectOrientation { + BASE_INSIDE(0), // Specifies that the base of the rectangular image lies + // along the inside edge of the annulus. + BASE_OUTSIDE(1), // Specifies that the base of the rectangular image lies + // along the outside edge of the annulus. + ; + private final int value; + + private RectOrientation(int value) { + this.value = value; + } + + public static RectOrientation fromValue(int val) { + try { + return values()[val]; + } catch (ArrayIndexOutOfBoundsException e) { + return null; + } + } + + public int getValue() { + return value; + } + } + + public static enum ShapeMode { + SHAPE_RECT(1), // The function draws a rectangle. + SHAPE_OVAL(2), // The function draws an oval. + ; + private final int value; + + private ShapeMode(int value) { + this.value = value; + } + + public static ShapeMode fromValue(int val) { + for (ShapeMode v : values()) { + if (v.value == val) + return v; + } + return null; + } + + public int getValue() { + return value; + } + } + + public static enum PolarityType { + EDGE_RISING(1), // The edge is a rising edge. + EDGE_FALLING(-1), // The edge is a falling edge. + ; + private final int value; + + private PolarityType(int value) { + this.value = value; + } + + public static PolarityType fromValue(int val) { + for (PolarityType v : values()) { + if (v.value == val) + return v; + } + return null; + } + + public int getValue() { + return value; + } + } + + public static enum SizeType { + KEEP_LARGE(0), // The function keeps large particles remaining after the + // erosion. + KEEP_SMALL(1), // The function keeps small particles eliminated by the + // erosion. + ; + private final int value; + + private SizeType(int value) { + this.value = value; + } + + public static SizeType fromValue(int val) { + try { + return values()[val]; + } catch (ArrayIndexOutOfBoundsException e) { + return null; + } + } + + public int getValue() { + return value; + } + } + + public static enum Plane3D { + C3D_REAL(0), // The function shows the real part of complex images. + C3D_IMAGINARY(1), // The function shows the imaginary part of complex + // images. + C3D_MAGNITUDE(2), // The function shows the magnitude part of complex + // images. + C3D_PHASE(3), // The function shows the phase part of complex images. + ; + private final int value; + + private Plane3D(int value) { + this.value = value; + } + + public static Plane3D fromValue(int val) { + try { + return values()[val]; + } catch (ArrayIndexOutOfBoundsException e) { + return null; + } + } + + public int getValue() { + return value; + } + } + + public static enum PhotometricMode { + WHITE_IS_ZERO(0), // The function interprets zero-value pixels as white. + BLACK_IS_ZERO(1), // The function interprets zero-value pixels as black. + ; + private final int value; + + private PhotometricMode(int value) { + this.value = value; + } + + public static PhotometricMode fromValue(int val) { + try { + return values()[val]; + } catch (ArrayIndexOutOfBoundsException e) { + return null; + } + } + + public int getValue() { + return value; + } + } + + public static enum ParticleInfoMode { + BASIC_INFO(0), // The function returns only the following elements of each + // report: area, calibratedArea, boundingRect. + ALL_INFO(1), // The function returns all the information about each + // particle. + ; + private final int value; + + private ParticleInfoMode(int value) { + this.value = value; + } + + public static ParticleInfoMode fromValue(int val) { + try { + return values()[val]; + } catch (ArrayIndexOutOfBoundsException e) { + return null; + } + } + + public int getValue() { + return value; + } + } + + public static enum OutlineMethod { + EDGE_DIFFERENCE(0), // The function uses a method that produces continuous + // contours by highlighting each pixel where an + // intensity variation occurs between itself and its + // three upper-left neighbors. + EDGE_GRADIENT(1), // The function uses a method that outlines contours where + // an intensity variation occurs along the vertical axis. + EDGE_PREWITT(2), // The function uses a method that extracts the outer + // contours of objects. + EDGE_ROBERTS(3), // The function uses a method that outlines the contours + // that highlight pixels where an intensity variation + // occurs along the diagonal axes. + EDGE_SIGMA(4), // The function uses a method that outlines contours and + // details by setting pixels to the mean value found in their + // neighborhood, if their deviation from this value is not + // significant. + EDGE_SOBEL(5), // The function uses a method that extracts the outer + // contours of objects. + ; + private final int value; + + private OutlineMethod(int value) { + this.value = value; + } + + public static OutlineMethod fromValue(int val) { + try { + return values()[val]; + } catch (ArrayIndexOutOfBoundsException e) { + return null; + } + } + + public int getValue() { + return value; + } + } + + public static enum MorphologyMethod { + AUTOM(0), // The function uses a transformation that generates simpler + // particles that contain fewer details. + CLOSE(1), // The function uses a transformation that fills tiny holes and + // smooths boundaries. + DILATE(2), // The function uses a transformation that eliminates tiny holes + // isolated in particles and expands the contour of the particles + // according to the template defined by the structuring element. + ERODE(3), // The function uses a transformation that eliminates pixels + // isolated in the background and erodes the contour of particles + // according to the template defined by the structuring element. + GRADIENT(4), // The function uses a transformation that leaves only the + // pixels that would be added by the dilation process or + // eliminated by the erosion process. + GRADIENTOUT(5), // The function uses a transformation that leaves only the + // pixels that would be added by the dilation process. + GRADIENTIN(6), // The function uses a transformation that leaves only the + // pixels that would be eliminated by the erosion process. + HITMISS(7), // The function uses a transformation that extracts each pixel + // located in a neighborhood exactly matching the template + // defined by the structuring element. + OPEN(8), // The function uses a transformation that removes small particles + // and smooths boundaries. + PCLOSE(9), // The function uses a transformation that fills tiny holes and + // smooths the inner contour of particles according to the + // template defined by the structuring element. + POPEN(10), // The function uses a transformation that removes small + // particles and smooths the contour of particles according to + // the template defined by the structuring element. + THICK(11), // The function uses a transformation that adds to an image those + // pixels located in a neighborhood that matches a template + // specified by the structuring element. + THIN(12), // The function uses a transformation that eliminates pixels that + // are located in a neighborhood matching a template specified by + // the structuring element. + ; + private final int value; + + private MorphologyMethod(int value) { + this.value = value; + } + + public static MorphologyMethod fromValue(int val) { + try { + return values()[val]; + } catch (ArrayIndexOutOfBoundsException e) { + return null; + } + } + + public int getValue() { + return value; + } + } + + public static enum MeterArcMode { + METER_ARC_ROI(0), // The function uses the roi parameter and ignores the + // base, start, and end parameters. + METER_ARC_POINTS(1), // The function uses the base,start, and end parameters + // and ignores the roi parameter. + ; + private final int value; + + private MeterArcMode(int value) { + this.value = value; + } + + public static MeterArcMode fromValue(int val) { + try { + return values()[val]; + } catch (ArrayIndexOutOfBoundsException e) { + return null; + } + } + + public int getValue() { + return value; + } + } + + public static enum RakeDirection { + LEFT_TO_RIGHT(0), // The function searches from the left side of the search + // area to the right side of the search area. + RIGHT_TO_LEFT(1), // The function searches from the right side of the search + // area to the left side of the search area. + TOP_TO_BOTTOM(2), // The function searches from the top side of the search + // area to the bottom side of the search area. + BOTTOM_TO_TOP(3), // The function searches from the bottom side of the + // search area to the top side of the search area. + ; + private final int value; + + private RakeDirection(int value) { + this.value = value; + } + + public static RakeDirection fromValue(int val) { + try { + return values()[val]; + } catch (ArrayIndexOutOfBoundsException e) { + return null; + } + } + + public int getValue() { + return value; + } + } + + public static enum TruncateMode { + TRUNCATE_LOW(0), // The function truncates low frequencies. + TRUNCATE_HIGH(1), // The function truncates high frequencies. + ; + private final int value; + + private TruncateMode(int value) { + this.value = value; + } + + public static TruncateMode fromValue(int val) { + try { + return values()[val]; + } catch (ArrayIndexOutOfBoundsException e) { + return null; + } + } + + public int getValue() { + return value; + } + } + + public static enum AttenuateMode { + ATTENUATE_LOW(0), // The function attenuates low frequencies. + ATTENUATE_HIGH(1), // The function attenuates high frequencies. + ; + private final int value; + + private AttenuateMode(int value) { + this.value = value; + } + + public static AttenuateMode fromValue(int val) { + try { + return values()[val]; + } catch (ArrayIndexOutOfBoundsException e) { + return null; + } + } + + public int getValue() { + return value; + } + } + + public static enum WindowThreadPolicy { + CALLING_THREAD(0), // Using this policy, NI Vision creates windows in the + // thread that makes the first display function call for + // a given window number. + SEPARATE_THREAD(1), // Using this policy, NI Vision creates windows in a + // separate thread and processes messages for the + // windows automatically. + ; + private final int value; + + private WindowThreadPolicy(int value) { + this.value = value; + } + + public static WindowThreadPolicy fromValue(int val) { + try { + return values()[val]; + } catch (ArrayIndexOutOfBoundsException e) { + return null; + } + } + + public int getValue() { + return value; + } + } + + public static enum WindowOptions { + WIND_RESIZABLE(1), // When present, the user may resize the window + // interactively. + WIND_TITLEBAR(2), // When present, the title bar on the window is visible. + WIND_CLOSEABLE(4), // When present, the close box is available. + WIND_TOPMOST(8), // When present, the window is always on top. + ; + private final int value; + + private WindowOptions(int value) { + this.value = value; + } + + public static WindowOptions fromValue(int val) { + for (WindowOptions v : values()) { + if (v.value == val) + return v; + } + return null; + } + + public int getValue() { + return value; + } + } + + public static enum WindowEventType { + NO_EVENT(0), // No event occurred since the last call to imaqGetLastEvent(). + CLICK_EVENT(1), // The user clicked on a window. + DRAW_EVENT(2), // The user drew an ROI in a window. + MOVE_EVENT(3), // The user moved a window. + SIZE_EVENT(4), // The user sized a window. + SCROLL_EVENT(5), // The user scrolled a window. + ACTIVATE_EVENT(6), // The user activated a window. + CLOSE_EVENT(7), // The user closed a window. + DOUBLE_CLICK_EVENT(8), // The user double-clicked in a window. + ; + private final int value; + + private WindowEventType(int value) { + this.value = value; + } + + public static WindowEventType fromValue(int val) { + try { + return values()[val]; + } catch (ArrayIndexOutOfBoundsException e) { + return null; + } + } + + public int getValue() { + return value; + } + } + + public static enum VisionInfoType { + ANY_VISION_INFO(0), // The function checks if any extra vision information + // is associated with the image. + PATTERN_MATCHING_INFO(1), // The function checks if any pattern matching + // template information is associated with the + // image. + CALIBRATION_INFO(2), // The function checks if any calibration information + // is associated with the image. + OVERLAY_INFO(3), // The function checks if any overlay information is + // associated with the image. + ; + private final int value; + + private VisionInfoType(int value) { + this.value = value; + } + + public static VisionInfoType fromValue(int val) { + try { + return values()[val]; + } catch (ArrayIndexOutOfBoundsException e) { + return null; + } + } + + public int getValue() { + return value; + } + } + + public static enum SearchStrategy { + CONSERVATIVE(1), // Instructs the pattern matching algorithm to use the + // largest possible amount of information from the image at + // the expense of slowing down the speed of the algorithm. + BALANCED(2), // Instructs the pattern matching algorithm to balance the + // amount of information from the image it uses with the speed + // of the algorithm. + AGGRESSIVE(3), // Instructs the pattern matching algorithm to use a lower + // amount of information from the image, which allows the + // algorithm to run quickly but at the expense of accuracy. + VERY_AGGRESSIVE(4), // Instructs the pattern matching algorithm to use the + // smallest possible amount of information from the + // image, which allows the algorithm to run at the + // highest speed possible but at the expense of + // accuracy. + ; + private final int value; + + private SearchStrategy(int value) { + this.value = value; + } + + public static SearchStrategy fromValue(int val) { + for (SearchStrategy v : values()) { + if (v.value == val) + return v; + } + return null; + } + + public int getValue() { + return value; + } + } + + public static enum TwoEdgePolarityType { + NONE(0), // The function ignores the polarity of the edges. + RISING_FALLING(1), // The polarity of the first edge is rising (dark to + // light) and the polarity of the second edge is falling + // (light to dark). + FALLING_RISING(2), // The polarity of the first edge is falling (light to + // dark) and the polarity of the second edge is rising + // (dark to light). + RISING_RISING(3), // The polarity of the first edge is rising (dark to + // light) and the polarity of the second edge is rising + // (dark to light). + FALLING_FALLING(4), // The polarity of the first edge is falling (light to + // dark) and the polarity of the second edge is falling + // (light to dark). + ; + private final int value; + + private TwoEdgePolarityType(int value) { + this.value = value; + } + + public static TwoEdgePolarityType fromValue(int val) { + try { + return values()[val]; + } catch (ArrayIndexOutOfBoundsException e) { + return null; + } + } + + public int getValue() { + return value; + } + } + + public static enum ObjectType { + BRIGHT_OBJECTS(0), // The function detects bright objects. + DARK_OBJECTS(1), // The function detects dark objects. + ; + private final int value; + + private ObjectType(int value) { + this.value = value; + } + + public static ObjectType fromValue(int val) { + try { + return values()[val]; + } catch (ArrayIndexOutOfBoundsException e) { + return null; + } + } + + public int getValue() { + return value; + } + } + + public static enum Tool { + NO_TOOL(-1), // No tool is in the selected state. + SELECTION_TOOL(0), // The selection tool selects an existing ROI in an + // image. + POINT_TOOL(1), // The point tool draws a point on the image. + LINE_TOOL(2), // The line tool draws a line on the image. + RECTANGLE_TOOL(3), // The rectangle tool draws a rectangle on the image. + OVAL_TOOL(4), // The oval tool draws an oval on the image. + POLYGON_TOOL(5), // The polygon tool draws a polygon on the image. + CLOSED_FREEHAND_TOOL(6), // The closed freehand tool draws closed freehand + // shapes on the image. + ANNULUS_TOOL(7), // The annulus tool draws annuluses on the image. + ZOOM_TOOL(8), // The zoom tool controls the zoom of an image. + PAN_TOOL(9), // The pan tool shifts the view of the image. + POLYLINE_TOOL(10), // The polyline tool draws a series of connected straight + // lines on the image. + FREEHAND_TOOL(11), // The freehand tool draws freehand lines on the image. + ROTATED_RECT_TOOL(12), // The rotated rectangle tool draws rotated + // rectangles on the image. + ZOOM_OUT_TOOL(13), // The zoom out tool controls the zoom of an image. + ; + private final int value; + + private Tool(int value) { + this.value = value; + } + + public static Tool fromValue(int val) { + for (Tool v : values()) { + if (v.value == val) + return v; + } + return null; + } + + public int getValue() { + return value; + } + } + + public static enum TIFFCompressionType { + NO_COMPRESSION(0), // The function does not compress the TIFF file. + JPEG(1), // The function uses the JPEG compression algorithm to compress the + // TIFF file. + RUN_LENGTH(2), // The function uses a run length compression algorithm to + // compress the TIFF file. + ZIP(3), // The function uses the ZIP compression algorithm to compress the + // TIFF file. + ; + private final int value; + + private TIFFCompressionType(int value) { + this.value = value; + } + + public static TIFFCompressionType fromValue(int val) { + try { + return values()[val]; + } catch (ArrayIndexOutOfBoundsException e) { + return null; + } + } + + public int getValue() { + return value; + } + } + + public static enum ThresholdMethod { + THRESH_CLUSTERING(0), // The function uses a method that sorts the histogram + // of the image within a discrete number of classes + // corresponding to the number of phases perceived in + // an image. + THRESH_ENTROPY(1), // The function uses a method that is best for detecting + // particles that are present in minuscule proportions on + // the image. + THRESH_METRIC(2), // The function uses a method that is well-suited for + // images in which classes are not too disproportionate. + THRESH_MOMENTS(3), // The function uses a method that is suited for images + // that have poor contrast. + THRESH_INTERCLASS(4), // The function uses a method that is well-suited for + // images in which classes have well separated pixel + // value distributions. + ; + private final int value; + + private ThresholdMethod(int value) { + this.value = value; + } + + public static ThresholdMethod fromValue(int val) { + try { + return values()[val]; + } catch (ArrayIndexOutOfBoundsException e) { + return null; + } + } + + public int getValue() { + return value; + } + } + + public static enum TextAlignment { + LEFT(0), // Left aligns the text at the reference point. + CENTER(1), // Centers the text around the reference point. + RIGHT(2), // Right aligns the text at the reference point. + ; + private final int value; + + private TextAlignment(int value) { + this.value = value; + } + + public static TextAlignment fromValue(int val) { + try { + return values()[val]; + } catch (ArrayIndexOutOfBoundsException e) { + return null; + } + } + + public int getValue() { + return value; + } + } + + public static enum SpokeDirection { + OUTSIDE_TO_INSIDE(0), // The function searches from the outside of the + // search area to the inside of the search area. + INSIDE_TO_OUTSIDE(1), // The function searches from the inside of the search + // area to the outside of the search area. + ; + private final int value; + + private SpokeDirection(int value) { + this.value = value; + } + + public static SpokeDirection fromValue(int val) { + try { + return values()[val]; + } catch (ArrayIndexOutOfBoundsException e) { + return null; + } + } + + public int getValue() { + return value; + } + } + + public static enum SkeletonMethod { + SKELETON_L(0), // Uses an L-shaped structuring element in the skeleton + // function. + SKELETON_M(1), // Uses an M-shaped structuring element in the skeleton + // function. + SKELETON_INVERSE(2), // Uses an L-shaped structuring element on an inverse + // of the image in the skeleton function. + ; + private final int value; + + private SkeletonMethod(int value) { + this.value = value; + } + + public static SkeletonMethod fromValue(int val) { + try { + return values()[val]; + } catch (ArrayIndexOutOfBoundsException e) { + return null; + } + } + + public int getValue() { + return value; + } + } + + public static enum VerticalTextAlignment { + BOTTOM(0), // Aligns the bottom of the text at the reference point. + TOP(1), // Aligns the top of the text at the reference point. + BASELINE(2), // Aligns the baseline of the text at the reference point. + ; + private final int value; + + private VerticalTextAlignment(int value) { + this.value = value; + } + + public static VerticalTextAlignment fromValue(int val) { + try { + return values()[val]; + } catch (ArrayIndexOutOfBoundsException e) { + return null; + } + } + + public int getValue() { + return value; + } + } + + public static enum CalibrationROI { + FULL_IMAGE(0), // The correction function corrects the whole image, + // regardless of the user-defined or calibration-defined + // ROIs. + CALIBRATION_ROI(1), // The correction function corrects the area defined by + // the calibration ROI. + USER_ROI(2), // The correction function corrects the area defined by the + // user-defined ROI. + CALIBRATION_AND_USER_ROI(3), // The correction function corrects the area + // defined by the intersection of the + // user-defined ROI and the calibration ROI. + CALIBRATION_OR_USER_ROI(4), // The correction function corrects the area + // defined by the union of the user-defined ROI + // and the calibration ROI. + ; + private final int value; + + private CalibrationROI(int value) { + this.value = value; + } + + public static CalibrationROI fromValue(int val) { + try { + return values()[val]; + } catch (ArrayIndexOutOfBoundsException e) { + return null; + } + } + + public int getValue() { + return value; + } + } + + public static enum ContourType { + EMPTY_CONTOUR(0), // The contour is empty. + POINT(1), // The contour represents a point. + LINE(2), // The contour represents a line. + RECT(3), // The contour represents a rectangle. + OVAL(4), // The contour represents an oval. + CLOSED_CONTOUR(5), // The contour represents a series of connected points + // where the last point connects to the first. + OPEN_CONTOUR(6), // The contour represents a series of connected points + // where the last point does not connect to the first. + ANNULUS(7), // The contour represents an annulus. + ROTATED_RECT(8), // The contour represents a rotated rectangle. + ; + private final int value; + + private ContourType(int value) { + this.value = value; + } + + public static ContourType fromValue(int val) { + try { + return values()[val]; + } catch (ArrayIndexOutOfBoundsException e) { + return null; + } + } + + public int getValue() { + return value; + } + } + + public static enum MathTransformMethod { + TRANSFORM_LINEAR(0), // The function uses linear remapping. + TRANSFORM_LOG(1), // The function uses logarithmic remapping. + TRANSFORM_EXP(2), // The function uses exponential remapping. + TRANSFORM_SQR(3), // The function uses square remapping. + TRANSFORM_SQRT(4), // The function uses square root remapping. + TRANSFORM_POWX(5), // The function uses power X remapping. + TRANSFORM_POW1X(6), // The function uses power 1/X remapping. + ; + private final int value; + + private MathTransformMethod(int value) { + this.value = value; + } + + public static MathTransformMethod fromValue(int val) { + try { + return values()[val]; + } catch (ArrayIndexOutOfBoundsException e) { + return null; + } + } + + public int getValue() { + return value; + } + } + + public static enum ComplexPlane { + REAL(0), // The function operates on the real plane of the complex image. + IMAGINARY(1), // The function operates on the imaginary plane of the complex + // image. + MAGNITUDE(2), // The function operates on the magnitude plane of the complex + // image. + PHASE(3), // The function operates on the phase plane of the complex image. + ; + private final int value; + + private ComplexPlane(int value) { + this.value = value; + } + + public static ComplexPlane fromValue(int val) { + try { + return values()[val]; + } catch (ArrayIndexOutOfBoundsException e) { + return null; + } + } + + public int getValue() { + return value; + } + } + + public static enum PaletteType { + PALETTE_GRAY(0), // The function uses a palette that has a gradual + // gray-level variation from black to white. + PALETTE_BINARY(1), // The function uses a palette of 16 cycles of 16 + // different colors that is useful with binary images. + PALETTE_GRADIENT(2), // The function uses a palette that has a gradation + // from red to white with a prominent range of light + // blue in the upper value range. + PALETTE_RAINBOW(3), // The function uses a palette that has a gradation from + // blue to red with a prominent range of greens in the + // middle value range. + PALETTE_TEMPERATURE(4), // The function uses a palette that has a gradation + // from light brown to dark brown. + PALETTE_USER(5), // The function uses a palette defined by the user. + ; + private final int value; + + private PaletteType(int value) { + this.value = value; + } + + public static PaletteType fromValue(int val) { + try { + return values()[val]; + } catch (ArrayIndexOutOfBoundsException e) { + return null; + } + } + + public int getValue() { + return value; + } + } + + public static enum ColorSensitivity { + SENSITIVITY_LOW(0), // Instructs the algorithm to divide the hue plane into + // a low number of sectors, allowing for simple color + // analysis. + SENSITIVITY_MED(1), // Instructs the algorithm to divide the hue plane into + // a medium number of sectors, allowing for color + // analysis that balances sensitivity and complexity. + SENSITIVITY_HIGH(2), // Instructs the algorithm to divide the hue plane into + // a high number of sectors, allowing for complex, + // sensitive color analysis. + ; + private final int value; + + private ColorSensitivity(int value) { + this.value = value; + } + + public static ColorSensitivity fromValue(int val) { + try { + return values()[val]; + } catch (ArrayIndexOutOfBoundsException e) { + return null; + } + } + + public int getValue() { + return value; + } + } + + public static enum ColorMode { + RGB(0), // The function operates in the RGB (Red, Blue, Green) color space. + HSL(1), // The function operates in the HSL (Hue, Saturation, Luminance) + // color space. + HSV(2), // The function operates in the HSV (Hue, Saturation, Value) color + // space. + HSI(3), // The function operates in the HSI (Hue, Saturation, Intensity) + // color space. + CIE(4), // The function operates in the CIE L*a*b* color space. + CIEXYZ(5), // The function operates in the CIE XYZ color space. + ; + private final int value; + + private ColorMode(int value) { + this.value = value; + } + + public static ColorMode fromValue(int val) { + try { + return values()[val]; + } catch (ArrayIndexOutOfBoundsException e) { + return null; + } + } + + public int getValue() { + return value; + } + } + + public static enum DetectionMode { + DETECT_PEAKS(0), // The function detects peaks. + DETECT_VALLEYS(1), // The function detects valleys. + ; + private final int value; + + private DetectionMode(int value) { + this.value = value; + } + + public static DetectionMode fromValue(int val) { + try { + return values()[val]; + } catch (ArrayIndexOutOfBoundsException e) { + return null; + } + } + + public int getValue() { + return value; + } + } + + public static enum CalibrationUnit { + UNDEFINED(0), // The image does not have a defined unit of measurement. + ANGSTROM(1), // The unit of measure for the image is angstroms. + MICROMETER(2), // The unit of measure for the image is micrometers. + MILLIMETER(3), // The unit of measure for the image is millimeters. + CENTIMETER(4), // The unit of measure for the image is centimeters. + METER(5), // The unit of measure for the image is meters. + KILOMETER(6), // The unit of measure for the image is kilometers. + MICROINCH(7), // The unit of measure for the image is microinches. + INCH(8), // The unit of measure for the image is inches. + FOOT(9), // The unit of measure for the image is feet. + NAUTICMILE(10), // The unit of measure for the image is nautical miles. + GROUNDMILE(11), // The unit of measure for the image is ground miles. + STEP(12), // The unit of measure for the image is steps. + ; + private final int value; + + private CalibrationUnit(int value) { + this.value = value; + } + + public static CalibrationUnit fromValue(int val) { + try { + return values()[val]; + } catch (ArrayIndexOutOfBoundsException e) { + return null; + } + } + + public int getValue() { + return value; + } + } + + public static enum ConcentricRakeDirection { + COUNTER_CLOCKWISE(0), // The function searches the search area in a + // counter-clockwise direction. + CLOCKWISE(1), // The function searches the search area in a clockwise + // direction. + ; + private final int value; + + private ConcentricRakeDirection(int value) { + this.value = value; + } + + public static ConcentricRakeDirection fromValue(int val) { + try { + return values()[val]; + } catch (ArrayIndexOutOfBoundsException e) { + return null; + } + } + + public int getValue() { + return value; + } + } + + public static enum CalibrationMode { + PERSPECTIVE(0), // Functions correct for distortion caused by the camera's + // perspective. + NONLINEAR(1), // Functions correct for distortion caused by the camera's + // lens. + SIMPLE_CALIBRATION(2), // Functions do not correct for distortion. + CORRECTED_IMAGE(3), // The image is already corrected. + ; + private final int value; + + private CalibrationMode(int value) { + this.value = value; + } + + public static CalibrationMode fromValue(int val) { + try { + return values()[val]; + } catch (ArrayIndexOutOfBoundsException e) { + return null; + } + } + + public int getValue() { + return value; + } + } + + public static enum BrowserLocation { + INSERT_FIRST_FREE(0), // Inserts the thumbnail in the first available cell. + INSERT_END(1), // Inserts the thumbnail after the last occupied cell. + ; + private final int value; + + private BrowserLocation(int value) { + this.value = value; + } + + public static BrowserLocation fromValue(int val) { + try { + return values()[val]; + } catch (ArrayIndexOutOfBoundsException e) { + return null; + } + } + + public int getValue() { + return value; + } + } + + public static enum BrowserFrameStyle { + RAISED_FRAME(0), // Each thumbnail has a raised frame. + BEVELLED_FRAME(1), // Each thumbnail has a beveled frame. + OUTLINE_FRAME(2), // Each thumbnail has an outlined frame. + HIDDEN_FRAME(3), // Each thumbnail has a hidden frame. + STEP_FRAME(4), // Each thumbnail has a stepped frame. + RAISED_OUTLINE_FRAME(5), // Each thumbnail has a raised, outlined frame. + ; + private final int value; + + private BrowserFrameStyle(int value) { + this.value = value; + } + + public static BrowserFrameStyle fromValue(int val) { + try { + return values()[val]; + } catch (ArrayIndexOutOfBoundsException e) { + return null; + } + } + + public int getValue() { + return value; + } + } + + public static enum BorderMethod { + BORDER_MIRROR(0), // Symmetrically copies pixel values from the image into + // the border. + BORDER_COPY(1), // Copies the value of the pixel closest to the edge of the + // image into the border. + BORDER_CLEAR(2), // Sets all pixels in the border to 0. + ; + private final int value; + + private BorderMethod(int value) { + this.value = value; + } + + public static BorderMethod fromValue(int val) { + try { + return values()[val]; + } catch (ArrayIndexOutOfBoundsException e) { + return null; + } + } + + public int getValue() { + return value; + } + } + + public static enum BarcodeType { + INVALID(-1), // The barcode is not of a type known by NI Vision. + CODABAR(1), // The barcode is of type Codabar. + CODE39(2), // The barcode is of type Code 39. + CODE93(4), // The barcode is of type Code 93. + CODE128(8), // The barcode is of type Code 128. + EAN8(16), // The barcode is of type EAN 8. + EAN13(32), // The barcode is of type EAN 13. + I2_OF_5(64), // The barcode is of type Code 25. + MSI(128), // The barcode is of type MSI code. + UPCA(256), // The barcode is of type UPC A. + PHARMACODE(512), // The barcode is of type Pharmacode. + RSS_LIMITED(1024), // The barcode is of type RSS Limited. + ; + private final int value; + + private BarcodeType(int value) { + this.value = value; + } + + public static BarcodeType fromValue(int val) { + for (BarcodeType v : values()) { + if (v.value == val) + return v; + } + return null; + } + + public int getValue() { + return value; + } + } + + public static enum AxisOrientation { + DIRECT(0), // The y-axis direction corresponds to the y-axis direction of + // the Cartesian coordinate system. + INDIRECT(1), // The y-axis direction corresponds to the y-axis direction of + // an image. + ; + private final int value; + + private AxisOrientation(int value) { + this.value = value; + } + + public static AxisOrientation fromValue(int val) { + try { + return values()[val]; + } catch (ArrayIndexOutOfBoundsException e) { + return null; + } + } + + public int getValue() { + return value; + } + } + + public static enum ColorIgnoreMode { + IGNORE_NONE(0), // Specifies that the function does not ignore any pixels. + IGNORE_BLACK(1), // Specifies that the function ignores black pixels. + IGNORE_WHITE(2), // Specifies that the function ignores white pixels. + IGNORE_BLACK_AND_WHITE(3), // Specifies that the function ignores black + // pixels and white pixels. + ; + private final int value; + + private ColorIgnoreMode(int value) { + this.value = value; + } + + public static ColorIgnoreMode fromValue(int val) { + try { + return values()[val]; + } catch (ArrayIndexOutOfBoundsException e) { + return null; + } + } + + public int getValue() { + return value; + } + } + + public static enum LevelType { + ABSOLUTE(0), // The function evaluates the threshold and hysteresis values + // as absolute values. + RELATIVE(1), // The function evaluates the threshold and hysteresis values + // relative to the dynamic range of the given path. + ; + private final int value; + + private LevelType(int value) { + this.value = value; + } + + public static LevelType fromValue(int val) { + try { + return values()[val]; + } catch (ArrayIndexOutOfBoundsException e) { + return null; + } + } + + public int getValue() { + return value; + } + } + + public static enum MatchingMode { + MATCH_SHIFT_INVARIANT(1), // Searches for occurrences of the template image + // anywhere in the searchRect, assuming that the + // pattern is not rotated more than plus or minus + // 4 degrees. + MATCH_ROTATION_INVARIANT(2), // Searches for occurrences of the pattern in + // the image with no restriction on the + // rotation of the pattern. + ; + private final int value; + + private MatchingMode(int value) { + this.value = value; + } + + public static MatchingMode fromValue(int val) { + for (MatchingMode v : values()) { + if (v.value == val) + return v; + } + return null; + } + + public int getValue() { + return value; + } + } + + public static enum MappingMethod { + FULL_DYNAMIC(0), // (Obsolete) When the image bit depth is 0, the function + // maps the full dynamic range of the 16-bit image to an + // 8-bit scale. + DOWNSHIFT(1), // (Obsolete) When the image bit depth is 0, the function + // shifts the 16-bit image pixels to the right the number of + // times specified by the shiftCount element of the + // DisplayMapping structure. + RANGE(2), // (Obsolete) When the image bit depth is 0, the function maps the + // pixel values in the range specified by the minimumValue and + // maximumValue elements of the DisplayMapping structure to an + // 8-bit scale. + C90_PCT_DYNAMIC(3), // (Obsolete) When the image bit depth to 0, the + // function maps the dynamic range containing the middle + // 90 percent of the cumulated histogram of the image to + // an 8-bit (256 grayscale values) scale. + PERCENT_RANGE(4), // (Obsolete) When the image bit depth is 0, the function + // maps the pixel values in the relative percentage range + // (0 to 100) of the cumulated histogram specified by + // minimumValue and maximumValue to an 8-bit scale. + DEFAULT_MAPPING(10), // If the bit depth is 0, the function maps the 16-bit + // image to 8 bits by following the + // IMAQ_FULL_DYNAMIC_ALWAYS behavior; otherwise, the + // function shifts the image data to the right + // according to the IMAQ_MOST_SIGNIFICANT behavior. + MOST_SIGNIFICANT(11), // The function shifts the 16-bit image pixels to the + // right until the 8 most significant bits of the + // image data are remaining. + FULL_DYNAMIC_ALWAYS(12), // The function maps the full dynamic range of the + // 16-bit image to an 8-bit scale. + DOWNSHIFT_ALWAYS(13), // The function shifts the 16-bit image pixels to the + // right the number of times specified by the + // shiftCount element of the DisplayMapping structure. + RANGE_ALWAYS(14), // The function maps the pixel values in the range + // specified by the minimumValue and maximumValue elements + // of the DisplayMapping structure to an 8-bit scale. + C90_PCT_DYNAMIC_ALWAYS(15), // The function maps the dynamic range + // containing the middle 90 percent of the + // cumulated histogram of the image to an 8-bit + // (256 grayscale values) scale. + PERCENT_RANGE_ALWAYS(16), // The function maps the pixel values in the + // relative percentage range (0 to 100) of the + // cumulated histogram specified by minimumValue + // and maximumValue to an 8-bit scale. + ; + private final int value; + + private MappingMethod(int value) { + this.value = value; + } + + public static MappingMethod fromValue(int val) { + for (MappingMethod v : values()) { + if (v.value == val) + return v; + } + return null; + } + + public int getValue() { + return value; + } + } + + public static enum ComparisonFunction { + CLEAR_LESS(0), // The comparison is true if the source pixel value is less + // than the comparison image pixel value. + CLEAR_LESS_OR_EQUAL(1), // The comparison is true if the source pixel value + // is less than or equal to the comparison image + // pixel value. + CLEAR_EQUAL(2), // The comparison is true if the source pixel value is equal + // to the comparison image pixel value. + CLEAR_GREATER_OR_EQUAL(3), // The comparison is true if the source pixel + // value is greater than or equal to the + // comparison image pixel value. + CLEAR_GREATER(4), // The comparison is true if the source pixel value is + // greater than the comparison image pixel value. + ; + private final int value; + + private ComparisonFunction(int value) { + this.value = value; + } + + public static ComparisonFunction fromValue(int val) { + try { + return values()[val]; + } catch (ArrayIndexOutOfBoundsException e) { + return null; + } + } + + public int getValue() { + return value; + } + } + + public static enum LineGaugeMethod { + EDGE_TO_EDGE(0), // Measures from the first edge on the line to the last + // edge on the line. + EDGE_TO_POINT(1), // Measures from the first edge on the line to the end + // point of the line. + POINT_TO_EDGE(2), // Measures from the start point of the line to the first + // edge on the line. + POINT_TO_POINT(3), // Measures from the start point of the line to the end + // point of the line. + ; + private final int value; + + private LineGaugeMethod(int value) { + this.value = value; + } + + public static LineGaugeMethod fromValue(int val) { + try { + return values()[val]; + } catch (ArrayIndexOutOfBoundsException e) { + return null; + } + } + + public int getValue() { + return value; + } + } + + public static enum Direction3D { + C3D_NW(0), // The viewing angle for the 3D image is from the northwest. + C3D_SW(1), // The viewing angle for the 3D image is from the southwest. + C3D_SE(2), // The viewing angle for the 3D image is from the southeast. + C3D_NE(3), // The viewing angle for the 3D image is from the northeast. + ; + private final int value; + + private Direction3D(int value) { + this.value = value; + } + + public static Direction3D fromValue(int val) { + try { + return values()[val]; + } catch (ArrayIndexOutOfBoundsException e) { + return null; + } + } + + public int getValue() { + return value; + } + } + + public static enum LearningMode { + LEARN_ALL(0), // The function extracts information for shift- and + // rotation-invariant matching. + LEARN_SHIFT_INFORMATION(1), // The function extracts information for + // shift-invariant matching. + LEARN_ROTATION_INFORMATION(2), // The function extracts information for + // rotation-invariant matching. + ; + private final int value; + + private LearningMode(int value) { + this.value = value; + } + + public static LearningMode fromValue(int val) { + try { + return values()[val]; + } catch (ArrayIndexOutOfBoundsException e) { + return null; + } + } + + public int getValue() { + return value; + } + } + + public static enum KernelFamily { + GRADIENT_FAMILY(0), // The kernel is in the gradient family. + LAPLACIAN_FAMILY(1), // The kernel is in the Laplacian family. + SMOOTHING_FAMILY(2), // The kernel is in the smoothing family. + GAUSSIAN_FAMILY(3), // The kernel is in the Gaussian family. + ; + private final int value; + + private KernelFamily(int value) { + this.value = value; + } + + public static KernelFamily fromValue(int val) { + try { + return values()[val]; + } catch (ArrayIndexOutOfBoundsException e) { + return null; + } + } + + public int getValue() { + return value; + } + } + + public static enum InterpolationMethod { + ZERO_ORDER(0), // The function uses an interpolation method that + // interpolates new pixel values using the nearest valid + // neighboring pixel. + BILINEAR(1), // The function uses an interpolation method that interpolates + // new pixel values using a bidirectional average of the + // neighboring pixels. + QUADRATIC(2), // The function uses an interpolation method that interpolates + // new pixel values using a quadratic approximating + // polynomial. + CUBIC_SPLINE(3), // The function uses an interpolation method that + // interpolates new pixel values by fitting them to a cubic + // spline curve, where the curve is based on known pixel + // values from the image. + BILINEAR_FIXED(4), // The function uses an interpolation method that + // interpolates new pixel values using a bidirectional + // average of the neighboring pixels. + ; + private final int value; + + private InterpolationMethod(int value) { + this.value = value; + } + + public static InterpolationMethod fromValue(int val) { + try { + return values()[val]; + } catch (ArrayIndexOutOfBoundsException e) { + return null; + } + } + + public int getValue() { + return value; + } + } + + public static enum ImageType { + IMAGE_U8(0), // The image type is 8-bit unsigned integer grayscale. + IMAGE_U16(7), // The image type is 16-bit unsigned integer grayscale. + IMAGE_I16(1), // The image type is 16-bit signed integer grayscale. + IMAGE_SGL(2), // The image type is 32-bit floating-point grayscale. + IMAGE_COMPLEX(3), // The image type is complex. + IMAGE_RGB(4), // The image type is RGB color. + IMAGE_HSL(5), // The image type is HSL color. + IMAGE_RGB_U64(6), // The image type is 64-bit unsigned RGB color. + ; + private final int value; + + private ImageType(int value) { + this.value = value; + } + + public static ImageType fromValue(int val) { + for (ImageType v : values()) { + if (v.value == val) + return v; + } + return null; + } + + public int getValue() { + return value; + } + } + + public static enum ImageFeatureMode { + COLOR_AND_SHAPE_FEATURES(0), // Instructs the function to use the color and + // the shape features of the color pattern. + COLOR_FEATURES(1), // Instructs the function to use the color features of + // the color pattern. + SHAPE_FEATURES(2), // Instructs the function to use the shape features of + // the color pattern. + ; + private final int value; + + private ImageFeatureMode(int value) { + this.value = value; + } + + public static ImageFeatureMode fromValue(int val) { + try { + return values()[val]; + } catch (ArrayIndexOutOfBoundsException e) { + return null; + } + } + + public int getValue() { + return value; + } + } + + public static enum FontColor { + WHITE(0), // Draws text in white. + BLACK(1), // Draws text in black. + INVERT(2), // Inverts the text pixels. + BLACK_ON_WHITE(3), // Draws text in black with a white background. + WHITE_ON_BLACK(4), // Draws text in white with a black background. + ; + private final int value; + + private FontColor(int value) { + this.value = value; + } + + public static FontColor fromValue(int val) { + try { + return values()[val]; + } catch (ArrayIndexOutOfBoundsException e) { + return null; + } + } + + public int getValue() { + return value; + } + } + + public static enum FlipAxis { + HORIZONTAL_AXIS(0), // Flips the image over the central horizontal axis. + VERTICAL_AXIS(1), // Flips the image over the central vertical axis. + CENTER_AXIS(2), // Flips the image over both the central vertical and + // horizontal axes. + DIAG_L_TO_R_AXIS(3), // Flips the image over an axis from the upper left + // corner to lower right corner. + DIAG_R_TO_L_AXIS(4), // Flips the image over an axis from the upper right + // corner to lower left corner. + ; + private final int value; + + private FlipAxis(int value) { + this.value = value; + } + + public static FlipAxis fromValue(int val) { + try { + return values()[val]; + } catch (ArrayIndexOutOfBoundsException e) { + return null; + } + } + + public int getValue() { + return value; + } + } + + public static enum EdgeProcess { + FIRST(0), // The function looks for the first edge. + FIRST_AND_LAST(1), // The function looks for the first and last edge. + ALL(2), // The function looks for all edges. + BEST(3), // The function looks for the best edge. + ; + private final int value; + + private EdgeProcess(int value) { + this.value = value; + } + + public static EdgeProcess fromValue(int val) { + try { + return values()[val]; + } catch (ArrayIndexOutOfBoundsException e) { + return null; + } + } + + public int getValue() { + return value; + } + } + + public static enum DrawMode { + DRAW_VALUE(0), // Draws the boundary of the object with the specified pixel + // value. + DRAW_INVERT(2), // Inverts the pixel values of the boundary of the object. + PAINT_VALUE(1), // Fills the object with the given pixel value. + PAINT_INVERT(3), // Inverts the pixel values of the object. + HIGHLIGHT_VALUE(4), // The function fills the object by highlighting the + // enclosed pixels with the color of the object. + ; + private final int value; + + private DrawMode(int value) { + this.value = value; + } + + public static DrawMode fromValue(int val) { + for (DrawMode v : values()) { + if (v.value == val) + return v; + } + return null; + } + + public int getValue() { + return value; + } + } + + public static enum NearestNeighborMetric { + METRIC_MAXIMUM(0), // The maximum metric. + METRIC_SUM(1), // The sum metric. + METRIC_EUCLIDEAN(2), // The Euclidean metric. + ; + private final int value; + + private NearestNeighborMetric(int value) { + this.value = value; + } + + public static NearestNeighborMetric fromValue(int val) { + try { + return values()[val]; + } catch (ArrayIndexOutOfBoundsException e) { + return null; + } + } + + public int getValue() { + return value; + } + } + + public static enum ReadResolution { + LOW_RESOLUTION(0), // Configures NI Vision to use low resolution during the + // read process. + MEDIUM_RESOLUTION(1), // Configures NI Vision to use medium resolution + // during the read process. + HIGH_RESOLUTION(2), // Configures NI Vision to use high resolution during + // the read process. + ; + private final int value; + + private ReadResolution(int value) { + this.value = value; + } + + public static ReadResolution fromValue(int val) { + try { + return values()[val]; + } catch (ArrayIndexOutOfBoundsException e) { + return null; + } + } + + public int getValue() { + return value; + } + } + + public static enum ThresholdMode { + FIXED_RANGE(0), // Performs thresholding using the values you provide in the + // lowThreshold and highThreshold elements of + // OCRProcessingOptions. + COMPUTED_UNIFORM(1), // Calculates a single threshold value for the entire + // ROI. + COMPUTED_LINEAR(2), // Calculates a value on the left side of the ROI, + // calculates a value on the right side of the ROI, and + // linearly fills the middle values from left to right. + COMPUTED_NONLINEAR(3), // Divides the ROI into the number of blocks + // specified by the blockCount element of + // OCRProcessingOptions and calculates a threshold + // value for each block. + ; + private final int value; + + private ThresholdMode(int value) { + this.value = value; + } + + public static ThresholdMode fromValue(int val) { + try { + return values()[val]; + } catch (ArrayIndexOutOfBoundsException e) { + return null; + } + } + + public int getValue() { + return value; + } + } + + public static enum ReadStrategy { + READ_AGGRESSIVE(0), // Configures NI Vision to perform fewer checks when + // analyzing objects to determine if they match trained + // characters. + READ_CONSERVATIVE(1), // Configures NI Vision to perform more checks to + // determine if an object matches a trained character. + ; + private final int value; + + private ReadStrategy(int value) { + this.value = value; + } + + public static ReadStrategy fromValue(int val) { + try { + return values()[val]; + } catch (ArrayIndexOutOfBoundsException e) { + return null; + } + } + + public int getValue() { + return value; + } + } + + public static enum MeasurementType { + MT_CENTER_OF_MASS_X(0), // X-coordinate of the point representing the + // average position of the total particle mass, + // assuming every point in the particle has a + // constant density. + MT_CENTER_OF_MASS_Y(1), // Y-coordinate of the point representing the + // average position of the total particle mass, + // assuming every point in the particle has a + // constant density. + MT_FIRST_PIXEL_X(2), // X-coordinate of the highest, leftmost particle + // pixel. + MT_FIRST_PIXEL_Y(3), // Y-coordinate of the highest, leftmost particle + // pixel. + MT_BOUNDING_RECT_LEFT(4), // X-coordinate of the leftmost particle point. + MT_BOUNDING_RECT_TOP(5), // Y-coordinate of highest particle point. + MT_BOUNDING_RECT_RIGHT(6), // X-coordinate of the rightmost particle point. + MT_BOUNDING_RECT_BOTTOM(7), // Y-coordinate of the lowest particle point. + MT_MAX_FERET_DIAMETER_START_X(8), // X-coordinate of the start of the line + // segment connecting the two perimeter + // points that are the furthest apart. + MT_MAX_FERET_DIAMETER_START_Y(9), // Y-coordinate of the start of the line + // segment connecting the two perimeter + // points that are the furthest apart. + MT_MAX_FERET_DIAMETER_END_X(10), // X-coordinate of the end of the line + // segment connecting the two perimeter + // points that are the furthest apart. + MT_MAX_FERET_DIAMETER_END_Y(11), // Y-coordinate of the end of the line + // segment connecting the two perimeter + // points that are the furthest apart. + MT_MAX_HORIZ_SEGMENT_LENGTH_LEFT(12), // X-coordinate of the leftmost pixel + // in the longest row of contiguous + // pixels in the particle. + MT_MAX_HORIZ_SEGMENT_LENGTH_RIGHT(13), // X-coordinate of the rightmost + // pixel in the longest row of + // contiguous pixels in the particle. + MT_MAX_HORIZ_SEGMENT_LENGTH_ROW(14), // Y-coordinate of all of the pixels in + // the longest row of contiguous pixels + // in the particle. + MT_BOUNDING_RECT_WIDTH(16), // Distance between the x-coordinate of the + // leftmost particle point and the x-coordinate + // of the rightmost particle point. + MT_BOUNDING_RECT_HEIGHT(17), // Distance between the y-coordinate of highest + // particle point and the y-coordinate of the + // lowest particle point. + MT_BOUNDING_RECT_DIAGONAL(18), // Distance between opposite corners of the + // bounding rectangle. + MT_PERIMETER(19), // Length of the outer boundary of the particle. + MT_CONVEX_HULL_PERIMETER(20), // Perimeter of the smallest convex polygon + // containing all points in the particle. + MT_HOLES_PERIMETER(21), // Sum of the perimeters of each hole in the + // particle. + MT_MAX_FERET_DIAMETER(22), // Distance between the start and end of the line + // segment connecting the two perimeter points + // that are the furthest apart. + MT_EQUIVALENT_ELLIPSE_MAJOR_AXIS(23), // Length of the major axis of the + // ellipse with the same perimeter and + // area as the particle. + MT_EQUIVALENT_ELLIPSE_MINOR_AXIS(24), // Length of the minor axis of the + // ellipse with the same perimeter and + // area as the particle. + MT_EQUIVALENT_ELLIPSE_MINOR_AXIS_FERET(25), // Length of the minor axis of + // the ellipse with the same + // area as the particle, and + // Major Axis equal in length to + // the Max Feret Diameter. + MT_EQUIVALENT_RECT_LONG_SIDE(26), // Longest side of the rectangle with the + // same perimeter and area as the + // particle. + MT_EQUIVALENT_RECT_SHORT_SIDE(27), // Shortest side of the rectangle with + // the same perimeter and area as the + // particle. + MT_EQUIVALENT_RECT_DIAGONAL(28), // Distance between opposite corners of the + // rectangle with the same perimeter and + // area as the particle. + MT_EQUIVALENT_RECT_SHORT_SIDE_FERET(29), // Shortest side of the rectangle + // with the same area as the + // particle, and longest side equal + // in length to the Max Feret + // Diameter. + MT_AVERAGE_HORIZ_SEGMENT_LENGTH(30), // Average length of a horizontal + // segment in the particle. + MT_AVERAGE_VERT_SEGMENT_LENGTH(31), // Average length of a vertical segment + // in the particle. + MT_HYDRAULIC_RADIUS(32), // The particle area divided by the particle + // perimeter. + MT_WADDEL_DISK_DIAMETER(33), // Diameter of a disk with the same area as the + // particle. + MT_AREA(35), // Area of the particle. + MT_HOLES_AREA(36), // Sum of the areas of each hole in the particle. + MT_PARTICLE_AND_HOLES_AREA(37), // Area of a particle that completely covers + // the image. + MT_CONVEX_HULL_AREA(38), // Area of the smallest convex polygon containing + // all points in the particle. + MT_IMAGE_AREA(39), // Area of the image. + MT_NUMBER_OF_HOLES(41), // Number of holes in the particle. + MT_NUMBER_OF_HORIZ_SEGMENTS(42), // Number of horizontal segments in the + // particle. + MT_NUMBER_OF_VERT_SEGMENTS(43), // Number of vertical segments in the + // particle. + MT_ORIENTATION(45), // The angle of the line that passes through the + // particle Center of Mass about which the particle has + // the lowest moment of inertia. + MT_MAX_FERET_DIAMETER_ORIENTATION(46), // The angle of the line segment + // connecting the two perimeter + // points that are the furthest + // apart. + MT_AREA_BY_IMAGE_AREA(48), // Percentage of the particle Area covering the + // Image Area. + MT_AREA_BY_PARTICLE_AND_HOLES_AREA(49), // Percentage of the particle Area + // in relation to its Particle and + // Holes Area. + MT_RATIO_OF_EQUIVALENT_ELLIPSE_AXES(50), // Equivalent Ellipse Major Axis + // divided by Equivalent Ellipse + // Minor Axis. + MT_RATIO_OF_EQUIVALENT_RECT_SIDES(51), // Equivalent Rect Long Side divided + // by Equivalent Rect Short Side. + MT_ELONGATION_FACTOR(53), // Max Feret Diameter divided by Equivalent Rect + // Short Side (Feret). + MT_COMPACTNESS_FACTOR(54), // Area divided by the product of Bounding Rect + // Width and Bounding Rect Height. + MT_HEYWOOD_CIRCULARITY_FACTOR(55), // Perimeter divided by the circumference + // of a circle with the same area. + MT_TYPE_FACTOR(56), // Factor relating area to moment of inertia. + MT_SUM_X(58), // The sum of all x-coordinates in the particle. + MT_SUM_Y(59), // The sum of all y-coordinates in the particle. + MT_SUM_XX(60), // The sum of all x-coordinates squared in the particle. + MT_SUM_XY(61), // The sum of all x-coordinates times y-coordinates in the + // particle. + MT_SUM_YY(62), // The sum of all y-coordinates squared in the particle. + MT_SUM_XXX(63), // The sum of all x-coordinates cubed in the particle. + MT_SUM_XXY(64), // The sum of all x-coordinates squared times y-coordinates + // in the particle. + MT_SUM_XYY(65), // The sum of all x-coordinates times y-coordinates squared + // in the particle. + MT_SUM_YYY(66), // The sum of all y-coordinates cubed in the particle. + MT_MOMENT_OF_INERTIA_XX(68), // The moment of inertia in the x-direction + // twice. + MT_MOMENT_OF_INERTIA_XY(69), // The moment of inertia in the x and y + // directions. + MT_MOMENT_OF_INERTIA_YY(70), // The moment of inertia in the y-direction + // twice. + MT_MOMENT_OF_INERTIA_XXX(71), // The moment of inertia in the x-direction + // three times. + MT_MOMENT_OF_INERTIA_XXY(72), // The moment of inertia in the x-direction + // twice and the y-direction once. + MT_MOMENT_OF_INERTIA_XYY(73), // The moment of inertia in the x-direction + // once and the y-direction twice. + MT_MOMENT_OF_INERTIA_YYY(74), // The moment of inertia in the y-direction + // three times. + MT_NORM_MOMENT_OF_INERTIA_XX(75), // The normalized moment of inertia in the + // x-direction twice. + MT_NORM_MOMENT_OF_INERTIA_XY(76), // The normalized moment of inertia in the + // x- and y-directions. + MT_NORM_MOMENT_OF_INERTIA_YY(77), // The normalized moment of inertia in the + // y-direction twice. + MT_NORM_MOMENT_OF_INERTIA_XXX(78), // The normalized moment of inertia in + // the x-direction three times. + MT_NORM_MOMENT_OF_INERTIA_XXY(79), // The normalized moment of inertia in + // the x-direction twice and the + // y-direction once. + MT_NORM_MOMENT_OF_INERTIA_XYY(80), // The normalized moment of inertia in + // the x-direction once and the + // y-direction twice. + MT_NORM_MOMENT_OF_INERTIA_YYY(81), // The normalized moment of inertia in + // the y-direction three times. + MT_HU_MOMENT_1(82), // The first Hu moment. + MT_HU_MOMENT_2(83), // The second Hu moment. + MT_HU_MOMENT_3(84), // The third Hu moment. + MT_HU_MOMENT_4(85), // The fourth Hu moment. + MT_HU_MOMENT_5(86), // The fifth Hu moment. + MT_HU_MOMENT_6(87), // The sixth Hu moment. + MT_HU_MOMENT_7(88), // The seventh Hu moment. + ; + private final int value; + + private MeasurementType(int value) { + this.value = value; + } + + public static MeasurementType fromValue(int val) { + for (MeasurementType v : values()) { + if (v.value == val) + return v; + } + return null; + } + + public int getValue() { + return value; + } + } + + public static enum GeometricMatchingMode { + GEOMETRIC_MATCH_SHIFT_INVARIANT(0), // Searches for occurrences of the + // pattern in the image, assuming that + // the pattern is not rotated more than + // plus or minus 5 degrees. + GEOMETRIC_MATCH_ROTATION_INVARIANT(1), // Searches for occurrences of the + // pattern in the image with reduced + // restriction on the rotation of the + // pattern. + GEOMETRIC_MATCH_SCALE_INVARIANT(2), // Searches for occurrences of the + // pattern in the image with reduced + // restriction on the size of the + // pattern. + GEOMETRIC_MATCH_OCCLUSION_INVARIANT(4), // Searches for occurrences of the + // pattern in the image, allowing + // for a specified percentage of the + // pattern to be occluded. + ; + private final int value; + + private GeometricMatchingMode(int value) { + this.value = value; + } + + public static GeometricMatchingMode fromValue(int val) { + for (GeometricMatchingMode v : values()) { + if (v.value == val) + return v; + } + return null; + } + + public int getValue() { + return value; + } + } + + public static enum ButtonLabel { + BUTTON_OK(0), // The label "OK". + BUTTON_SAVE(1), // The label "Save". + BUTTON_SELECT(2), // The label "Select". + BUTTON_LOAD(3), // The label "Load". + ; + private final int value; + + private ButtonLabel(int value) { + this.value = value; + } + + public static ButtonLabel fromValue(int val) { + try { + return values()[val]; + } catch (ArrayIndexOutOfBoundsException e) { + return null; + } + } + + public int getValue() { + return value; + } + } + + public static enum NearestNeighborMethod { + MINIMUM_MEAN_DISTANCE(0), // The minimum mean distance method. + K_NEAREST_NEIGHBOR(1), // The k-nearest neighbor method. + NEAREST_PROTOTYPE(2), // The nearest prototype method. + ; + private final int value; + + private NearestNeighborMethod(int value) { + this.value = value; + } + + public static NearestNeighborMethod fromValue(int val) { + try { + return values()[val]; + } catch (ArrayIndexOutOfBoundsException e) { + return null; + } + } + + public int getValue() { + return value; + } + } + + public static enum QRMirrorMode { + QR_MIRROR_MODE_AUTO_DETECT(-2), // The function should determine if the QR + // code is mirrored. + QR_MIRROR_MODE_MIRRORED(1), // The function should expect the QR code to + // appear mirrored. + QR_MIRROR_MODE_NORMAL(0), // The function should expect the QR code to + // appear normal. + ; + private final int value; + + private QRMirrorMode(int value) { + this.value = value; + } + + public static QRMirrorMode fromValue(int val) { + for (QRMirrorMode v : values()) { + if (v.value == val) + return v; + } + return null; + } + + public int getValue() { + return value; + } + } + + public static enum ColumnProcessingMode { + AVERAGE_COLUMNS(0), // Averages the data extracted for edge detection. + MEDIAN_COLUMNS(1), // Takes the median of the data extracted for edge + // detection. + ; + private final int value; + + private ColumnProcessingMode(int value) { + this.value = value; + } + + public static ColumnProcessingMode fromValue(int val) { + try { + return values()[val]; + } catch (ArrayIndexOutOfBoundsException e) { + return null; + } + } + + public int getValue() { + return value; + } + } + + public static enum FindReferenceDirection { + LEFT_TO_RIGHT_DIRECT(0), // Searches from the left side of the search area + // to the right side of the search area for a + // direct axis. + LEFT_TO_RIGHT_INDIRECT(1), // Searches from the left side of the search area + // to the right side of the search area for an + // indirect axis. + TOP_TO_BOTTOM_DIRECT(2), // Searches from the top of the search area to the + // bottom of the search area for a direct axis. + TOP_TO_BOTTOM_INDIRECT(3), // Searches from the top of the search area to + // the bottom of the search area for an indirect + // axis. + RIGHT_TO_LEFT_DIRECT(4), // Searches from the right side of the search area + // to the left side of the search area for a direct + // axis. + RIGHT_TO_LEFT_INDIRECT(5), // Searches from the right side of the search + // area to the left side of the search area for + // an indirect axis. + BOTTOM_TO_TOP_DIRECT(6), // Searches from the bottom of the search area to + // the top of the search area for a direct axis. + BOTTOM_TO_TOP_INDIRECT(7), // Searches from the bottom of the search area to + // the top of the search area for an indirect + // axis. + ; + private final int value; + + private FindReferenceDirection(int value) { + this.value = value; + } + + public static FindReferenceDirection fromValue(int val) { + try { + return values()[val]; + } catch (ArrayIndexOutOfBoundsException e) { + return null; + } + } + + public int getValue() { + return value; + } + } + + public static enum MulticoreOperation { + GET_CORES(0), // The number of processor cores NI Vision is currently using. + SET_CORES(1), // The number of processor cores for NI Vision to use. + USE_MAX_AVAILABLE(2), // Use the maximum number of available processor + // cores. + ; + private final int value; + + private MulticoreOperation(int value) { + this.value = value; + } + + public static MulticoreOperation fromValue(int val) { + try { + return values()[val]; + } catch (ArrayIndexOutOfBoundsException e) { + return null; + } + } + + public int getValue() { + return value; + } + } + + public static enum GroupBehavior { + GROUP_CLEAR(0), // Sets the behavior of the overlay group to clear the + // current settings when an image is transformed. + GROUP_KEEP(1), // Sets the behavior of the overlay group to keep the current + // settings when an image is transformed. + GROUP_TRANSFORM(2), // Sets the behavior of the overlay group to transform + // with the image. + ; + private final int value; + + private GroupBehavior(int value) { + this.value = value; + } + + public static GroupBehavior fromValue(int val) { + try { + return values()[val]; + } catch (ArrayIndexOutOfBoundsException e) { + return null; + } + } + + public int getValue() { + return value; + } + } + + public static enum QRDimensions { + QR_DIMENSIONS_AUTO_DETECT(0), // The function will automatically determine + // the dimensions of the QR code. + QR_DIMENSIONS_11x11(11), // Specifies the dimensions of the QR code as 11 x + // 11. + QR_DIMENSIONS_13x13(13), // Specifies the dimensions of the QR code as 13 x + // 13. + QR_DIMENSIONS_15x15(15), // Specifies the dimensions of the QR code as 15 x + // 15. + QR_DIMENSIONS_17x17(17), // Specifies the dimensions of the QR code as 17 x + // 17. + QR_DIMENSIONS_21x21(21), // Specifies the dimensions of the QR code as 21 x + // 21. + QR_DIMENSIONS_25x25(25), // Specifies the dimensions of the QR code as 25 x + // 25. + QR_DIMENSIONS_29x29(29), // Specifies the dimensions of the QR code as 29 x + // 29. + QR_DIMENSIONS_33x33(33), // Specifies the dimensions of the QR code as 33 x + // 33. + QR_DIMENSIONS_37x37(37), // Specifies the dimensions of the QR code as 37 x + // 37. + QR_DIMENSIONS_41x41(41), // Specifies the dimensions of the QR code as 41 x + // 41. + QR_DIMENSIONS_45x45(45), // Specifies the dimensions of the QR code as 45 x + // 45. + QR_DIMENSIONS_49x49(49), // Specifies the dimensions of the QR code as 49 x + // 49. + QR_DIMENSIONS_53x53(53), // Specifies the dimensions of the QR code as 53 x + // 53. + QR_DIMENSIONS_57x57(57), // Specifies the dimensions of the QR code as 57 x + // 57. + QR_DIMENSIONS_61x61(61), // Specifies the dimensions of the QR code as 61 x + // 61. + QR_DIMENSIONS_65x65(65), // Specifies the dimensions of the QR code as 65 x + // 65. + QR_DIMENSIONS_69x69(69), // Specifies the dimensions of the QR code as 69 x + // 69. + QR_DIMENSIONS_73x73(73), // Specifies the dimensions of the QR code as 73 x + // 73. + QR_DIMENSIONS_77x77(77), // Specifies the dimensions of the QR code as 77 x + // 77. + QR_DIMENSIONS_81x81(81), // Specifies the dimensions of the QR code as 81 x + // 81. + QR_DIMENSIONS_85x85(85), // Specifies the dimensions of the QR code as 85 x + // 85. + QR_DIMENSIONS_89x89(89), // Specifies the dimensions of the QR code as 89 x + // 89. + QR_DIMENSIONS_93x93(93), // Specifies the dimensions of the QR code as 93 x + // 93. + QR_DIMENSIONS_97x97(97), // Specifies the dimensions of the QR code as 97 x + // 97. + QR_DIMENSIONS_101x101(101), // Specifies the dimensions of the QR code as + // 101 x 101. + QR_DIMENSIONS_105x105(105), // Specifies the dimensions of the QR code as + // 105 x 105. + QR_DIMENSIONS_109x109(109), // Specifies the dimensions of the QR code as + // 109 x 109. + QR_DIMENSIONS_113x113(113), // Specifies the dimensions of the QR code as + // 113 x 113. + QR_DIMENSIONS_117x117(117), // Specifies the dimensions of the QR code as + // 117 x 117. + QR_DIMENSIONS_121x121(121), // Specifies the dimensions of the QR code as + // 121 x 121. + QR_DIMENSIONS_125x125(125), // Specifies the dimensions of the QR code as + // 125 x 125. + QR_DIMENSIONS_129x129(129), // Specifies the dimensions of the QR code as + // 129 x 129. + QR_DIMENSIONS_133x133(133), // Specifies the dimensions of the QR code as + // 133 x 133. + QR_DIMENSIONS_137x137(137), // Specifies the dimensions of the QR code as + // 137 x 137. + QR_DIMENSIONS_141x141(141), // Specifies the dimensions of the QR code as + // 141 x 141. + QR_DIMENSIONS_145x145(145), // Specifies the dimensions of the QR code as + // 145 x 145. + QR_DIMENSIONS_149x149(149), // Specifies the dimensions of the QR code as + // 149 x 149. + QR_DIMENSIONS_153x153(153), // Specifies the dimensions of the QR code as + // 153 x 153. + QR_DIMENSIONS_157x157(157), // Specifies the dimensions of the QR code as + // 157 x 1537. + QR_DIMENSIONS_161x161(161), // Specifies the dimensions of the QR code as + // 161 x 161. + QR_DIMENSIONS_165x165(165), // Specifies the dimensions of the QR code as + // 165 x 165. + QR_DIMENSIONS_169x169(169), // Specifies the dimensions of the QR code as + // 169 x 169. + QR_DIMENSIONS_173x173(173), // Specifies the dimensions of the QR code as + // 173 x 173. + QR_DIMENSIONS_177x177(177), // Specifies the dimensions of the QR code as + // 177 x 177. + ; + private final int value; + + private QRDimensions(int value) { + this.value = value; + } + + public static QRDimensions fromValue(int val) { + for (QRDimensions v : values()) { + if (v.value == val) + return v; + } + return null; + } + + public int getValue() { + return value; + } + } + + public static enum QRCellFilterMode { + QR_CELL_FILTER_MODE_AUTO_DETECT(-2), // The function will try all filter + // modes and uses the one that decodes + // the QR code within the fewest + // iterations and utilizing the least + // amount of error correction. + QR_CELL_FILTER_MODE_AVERAGE(0), // The function sets the pixel value for the + // cell to the average of the sampled + // pixels. + QR_CELL_FILTER_MODE_MEDIAN(1), // The function sets the pixel value for the + // cell to the median of the sampled pixels. + QR_CELL_FILTER_MODE_CENTRAL_AVERAGE(2), // The function sets the pixel value + // for the cell to the average of + // the pixels in the center of the + // cell sample. + QR_CELL_FILTER_MODE_HIGH_AVERAGE(3), // The function sets the pixel value + // for the cell to the average value of + // the half of the sampled pixels with + // the highest pixel values. + QR_CELL_FILTER_MODE_LOW_AVERAGE(4), // The function sets the pixel value for + // the cell to the average value of the + // half of the sampled pixels with the + // lowest pixel values. + QR_CELL_FILTER_MODE_VERY_HIGH_AVERAGE(5), // The function sets the pixel + // value for the cell to the + // average value of the ninth of + // the sampled pixels with the + // highest pixel values. + QR_CELL_FILTER_MODE_VERY_LOW_AVERAGE(6), // The function sets the pixel + // value for the cell to the + // average value of the ninth of + // the sampled pixels with the + // lowest pixel values. + QR_CELL_FILTER_MODE_ALL(8), // The function tries each filter mode, starting + // with IMAQ_QR_CELL_FILTER_MODE_AVERAGE and + // ending with + // IMAQ_QR_CELL_FILTER_MODE_VERY_LOW_AVERAGE, + // stopping once a filter mode decodes + // correctly. + ; + private final int value; + + private QRCellFilterMode(int value) { + this.value = value; + } + + public static QRCellFilterMode fromValue(int val) { + for (QRCellFilterMode v : values()) { + if (v.value == val) + return v; + } + return null; + } + + public int getValue() { + return value; + } + } + + public static enum RoundingMode { + ROUNDING_MODE_OPTIMIZE(0), // Rounds the result of a division using the best + // available method. + ROUNDING_MODE_TRUNCATE(1), // Truncates the result of a division. + ; + private final int value; + + private RoundingMode(int value) { + this.value = value; + } + + public static RoundingMode fromValue(int val) { + try { + return values()[val]; + } catch (ArrayIndexOutOfBoundsException e) { + return null; + } + } + + public int getValue() { + return value; + } + } + + public static enum QRDemodulationMode { + QR_DEMODULATION_MODE_AUTO_DETECT(-2), // The function will try each + // demodulation mode and use the one + // which decodes the QR code within + // the fewest iterations and utilizing + // the least amount of error + // correction. + QR_DEMODULATION_MODE_HISTOGRAM(0), // The function uses a histogram of all + // of the QR cells to calculate a + // threshold. + QR_DEMODULATION_MODE_LOCAL_CONTRAST(1), // The function examines each of the + // cell's neighbors to determine if + // the cell is on or off. + QR_DEMODULATION_MODE_COMBINED(2), // The function uses the histogram of the + // QR code to calculate a threshold. + QR_DEMODULATION_MODE_ALL(3), // The function tries + // IMAQ_QR_DEMODULATION_MODE_HISTOGRAM, then + // IMAQ_QR_DEMODULATION_MODE_LOCAL_CONTRAST and + // then IMAQ_QR_DEMODULATION_MODE_COMBINED, + // stopping once one mode is successful. + ; + private final int value; + + private QRDemodulationMode(int value) { + this.value = value; + } + + public static QRDemodulationMode fromValue(int val) { + for (QRDemodulationMode v : values()) { + if (v.value == val) + return v; + } + return null; + } + + public int getValue() { + return value; + } + } + + public static enum ContrastMode { + ORIGINAL_CONTRAST(0), // Instructs the geometric matching algorithm to find + // matches with the same contrast as the template. + REVERSED_CONTRAST(1), // Instructs the geometric matching algorithm to find + // matches with the inverted contrast of the template. + BOTH_CONTRASTS(2), // Instructs the geometric matching algorithm to find + // matches with the same and inverted contrast of the + // template. + ; + private final int value; + + private ContrastMode(int value) { + this.value = value; + } + + public static ContrastMode fromValue(int val) { + try { + return values()[val]; + } catch (ArrayIndexOutOfBoundsException e) { + return null; + } + } + + public int getValue() { + return value; + } + } + + public static enum QRPolarities { + QR_POLARITY_AUTO_DETECT(-2), // The function should determine the polarity + // of the QR code. + QR_POLARITY_BLACK_ON_WHITE(0), // The function should search for a QR code + // with dark data on a bright background. + QR_POLARITY_WHITE_ON_BLACK(1), // The function should search for a QR code + // with bright data on a dark background. + ; + private final int value; + + private QRPolarities(int value) { + this.value = value; + } + + public static QRPolarities fromValue(int val) { + for (QRPolarities v : values()) { + if (v.value == val) + return v; + } + return null; + } + + public int getValue() { + return value; + } + } + + public static enum QRRotationMode { + QR_ROTATION_MODE_UNLIMITED(0), // The function allows for unlimited + // rotation. + QR_ROTATION_MODE_0_DEGREES(1), // The function allows for ??? 5 degrees of + // rotation. + QR_ROTATION_MODE_90_DEGREES(2), // The function allows for between 85 and 95 + // degrees of rotation. + QR_ROTATION_MODE_180_DEGREES(3), // The function allows for between 175 and + // 185 degrees of rotation. + QR_ROTATION_MODE_270_DEGREES(4), // The function allows for between 265 and + // 275 degrees of rotation. + ; + private final int value; + + private QRRotationMode(int value) { + this.value = value; + } + + public static QRRotationMode fromValue(int val) { + try { + return values()[val]; + } catch (ArrayIndexOutOfBoundsException e) { + return null; + } + } + + public int getValue() { + return value; + } + } + + public static enum QRGradingMode { + QR_NO_GRADING(0), // The function does not make any preparatory + // calculations. + ; + private final int value; + + private QRGradingMode(int value) { + this.value = value; + } + + public static QRGradingMode fromValue(int val) { + try { + return values()[val]; + } catch (ArrayIndexOutOfBoundsException e) { + return null; + } + } + + public int getValue() { + return value; + } + } + + public static enum StraightEdgeSearchMode { + USE_FIRST_RAKE_EDGES(0), // Fits a straight edge on the first points + // detected using a rake. + USE_BEST_RAKE_EDGES(1), // Fits a straight edge on the best points detected + // using a rake. + USE_BEST_HOUGH_LINE(2), // Finds the strongest straight edge using all + // points detected on a rake. + USE_FIRST_PROJECTION_EDGE(3), // Uses the location of the first projected + // edge as the straight edge. + USE_BEST_PROJECTION_EDGE(4), // Finds the strongest projected edge location + // to determine the straight edge. + ; + private final int value; + + private StraightEdgeSearchMode(int value) { + this.value = value; + } + + public static StraightEdgeSearchMode fromValue(int val) { + try { + return values()[val]; + } catch (ArrayIndexOutOfBoundsException e) { + return null; + } + } + + public int getValue() { + return value; + } + } + + public static enum SearchDirection { + SEARCH_DIRECTION_LEFT_TO_RIGHT(0), // Searches from the left side of the + // search area to the right side of the + // search area. + SEARCH_DIRECTION_RIGHT_TO_LEFT(1), // Searches from the right side of the + // search area to the left side of the + // search area. + SEARCH_DIRECTION_TOP_TO_BOTTOM(2), // Searches from the top side of the + // search area to the bottom side of the + // search area. + SEARCH_DIRECTION_BOTTOM_TO_TOP(3), // Searches from the bottom side of the + // search area to the top side of the + // search area. + ; + private final int value; + + private SearchDirection(int value) { + this.value = value; + } + + public static SearchDirection fromValue(int val) { + try { + return values()[val]; + } catch (ArrayIndexOutOfBoundsException e) { + return null; + } + } + + public int getValue() { + return value; + } + } + + public static enum QRStreamMode { + QR_MODE_NUMERIC(0), // Specifies that the data was encoded using numeric + // mode. + QR_MODE_ALPHANUMERIC(1), // Specifies that the data was encoded using + // alpha-numeric mode. + QR_MODE_RAW_BYTE(2), // Specifies that the data was not encoded but is only + // raw binary bytes, or encoded in JIS-8. + QR_MODE_EAN128_TOKEN(3), // Specifies that the data has a special meaning + // represented by the application ID. + QR_MODE_EAN128_DATA(4), // Specifies that the data has a special meaning + // represented by the application ID. + QR_MODE_ECI(5), // Specifies that the data was meant to be read using the + // language represented in the language ID. + QR_MODE_KANJI(6), // Specifies that the data was encoded in Shift-JIS16 + // Japanese. + ; + private final int value; + + private QRStreamMode(int value) { + this.value = value; + } + + public static QRStreamMode fromValue(int val) { + try { + return values()[val]; + } catch (ArrayIndexOutOfBoundsException e) { + return null; + } + } + + public int getValue() { + return value; + } + } + + public static enum ParticleClassifierType { + PARTICLE_LARGEST(0), // Use only the largest particle in the image. + PARTICLE_ALL(1), // Use all particles in the image. + ; + private final int value; + + private ParticleClassifierType(int value) { + this.value = value; + } + + public static ParticleClassifierType fromValue(int val) { + try { + return values()[val]; + } catch (ArrayIndexOutOfBoundsException e) { + return null; + } + } + + public int getValue() { + return value; + } + } + + public static enum QRCellSampleSize { + QR_CELL_SAMPLE_SIZE_AUTO_DETECT(-2), // The function will try each sample + // size and use the one which decodes + // the QR code within the fewest + // iterations and utilizing the least + // amount of error correction. + QR_CELL_SAMPLE_SIZE1X1(1), // The function will use a 1x1 sized sample from + // each cell. + QR_CELL_SAMPLE_SIZE2X2(2), // The function will use a 2x2 sized sample from + // each cell. + QR_CELL_SAMPLE_SIZE3X3(3), // The function will use a 3x3 sized sample from + // each cell. + QR_CELL_SAMPLE_SIZE4X4(4), // The function will use a 4x4 sized sample from + // each cell. + QR_CELL_SAMPLE_SIZE5X5(5), // The function will use a 5x5 sized sample from + // each cell. + QR_CELL_SAMPLE_SIZE6X6(6), // The function will use a 6x6 sized sample from + // each cell. + QR_CELL_SAMPLE_SIZE7X7(7), // The function will use a 7x7 sized sample from + // each cell. + ; + private final int value; + + private QRCellSampleSize(int value) { + this.value = value; + } + + public static QRCellSampleSize fromValue(int val) { + for (QRCellSampleSize v : values()) { + if (v.value == val) + return v; + } + return null; + } + + public int getValue() { + return value; + } + } + + public static enum RakeProcessType { + GET_FIRST_EDGES(0), GET_FIRST_AND_LAST_EDGES(1), GET_ALL_EDGES(2), GET_BEST_EDGES(3), ; + private final int value; + + private RakeProcessType(int value) { + this.value = value; + } + + public static RakeProcessType fromValue(int val) { + try { + return values()[val]; + } catch (ArrayIndexOutOfBoundsException e) { + return null; + } + } + + public int getValue() { + return value; + } + } + + public static enum GeometricSetupDataItem { + CURVE_EXTRACTION_MODE(0), // Specifies how the function identifies curves in + // the image. + CURVE_EDGE_THRSHOLD(1), // Specifies the minimum contrast an edge pixel must + // have for it to be considered part of a curve. + CURVE_EDGE_FILTER(2), // Specifies the width of the edge filter that the + // function uses to identify curves in the image. + MINIMUM_CURVE_LENGTH(3), // Specifies the length, in pixels, of the smallest + // curve that you want the function to identify. + CURVE_ROW_SEARCH_STEP_SIZE(4), // Specifies the distance, in the y + // direction, between the image rows that the + // algorithm inspects for curve seed points. + CURVE_COL_SEARCH_STEP_SIZE(5), // Specifies the distance, in the x + // direction, between the image columns that + // the algorithm inspects for curve seed + // points. + CURVE_MAX_END_POINT_GAP(6), // Specifies the maximum gap, in pixels, between + // the endpoints of a curve that the function + // identifies as a closed curve. + EXTRACT_CLOSED_CURVES(7), // Specifies whether to identify only closed + // curves in the image. + ENABLE_SUBPIXEL_CURVE_EXTRACTION(8), // The function ignores this option. + ENABLE_CORRELATION_SCORE(9), // Specifies that the function should calculate + // the Correlation Score and return it for each + // match result. + ENABLE_SUBPIXEL_ACCURACY(10), // Determines whether to return the match + // results with subpixel accuracy. + SUBPIXEL_ITERATIONS(11), // Specifies the maximum number of incremental + // improvements used to refine matches using + // subpixel information. + SUBPIXEL_TOLERANCE(12), // Specifies the maximum amount of change, in + // pixels, between consecutive incremental + // improvements in the match position before the + // function stops refining the match position. + INITIAL_MATCH_LIST_LENGTH(13), // Specifies the maximum size of the match + // list. + ENABLE_TARGET_TEMPLATE_CURVESCORE(14), // Specifies whether the function + // should calculate the match curve + // to template curve score and return + // it for each match result. + MINIMUM_MATCH_SEPARATION_DISTANCE(15), // Specifies the minimum separation + // distance, in pixels, between the + // origins of two matches that have + // unique positions. + MINIMUM_MATCH_SEPARATION_ANGLE(16), // Specifies the minimum angular + // difference, in degrees, between two + // matches that have unique angles. + MINIMUM_MATCH_SEPARATION_SCALE(17), // Specifies the minimum difference in + // scale, expressed as a percentage, + // between two matches that have unique + // scales. + MAXIMUM_MATCH_OVERLAP(18), // Specifies whether you want the algorithm to + // spend less time accurately estimating the + // location of a match. + ENABLE_COARSE_RESULT(19), // Specifies whether you want the algorithm to + // spend less time accurately estimating the + // location of a match. + ENABLE_CALIBRATION_SUPPORT(20), // Specifies whether or not the algorithm + // treat the inspection image as a + // calibrated image. + ENABLE_CONTRAST_REVERSAL(21), // Specifies the contrast of the matches to + // search for. + SEARCH_STRATEGY(22), // Specifies the aggressiveness of the strategy used to + // find matches in the image. + REFINEMENT_MATCH_FACTOR(23), // Specifies the factor applied to the number + // of matches requested to determine how many + // matches are refined in the pyramid stage. + SUBPIXEL_MATCH_FACTOR(24), // Specifies the factor applied to the number for + // matches requested to determine how many + // matches are used for the final (subpixel) + // stage. + MAX_REFINEMENT_ITERATIONS(25), // Specifies maximum refinement iteration. + ; + private final int value; + + private GeometricSetupDataItem(int value) { + this.value = value; + } + + public static GeometricSetupDataItem fromValue(int val) { + try { + return values()[val]; + } catch (ArrayIndexOutOfBoundsException e) { + return null; + } + } + + public int getValue() { + return value; + } + } + + public static enum DistortionModel { + POLYNOMIAL_MODEL(0), // Polynomial model. + DIVISION_MODEL(1), // Division Model. + NO_DISTORTION_MODEL(-1), // Not a distortion model. + ; + private final int value; + + private DistortionModel(int value) { + this.value = value; + } + + public static DistortionModel fromValue(int val) { + for (DistortionModel v : values()) { + if (v.value == val) + return v; + } + return null; + } + + public int getValue() { + return value; + } + } + + public static enum CalibrationThumbnailType { + CAMARA_MODEL_TYPE(0), // Camara model thumbnail type. + PERSPECTIVE_TYPE(1), // Perspective thumbnail type. + MICRO_PLANE_TYPE(2), // Micro Plane thumbnail type. + ; + private final int value; + + private CalibrationThumbnailType(int value) { + this.value = value; + } + + public static CalibrationThumbnailType fromValue(int val) { + try { + return values()[val]; + } catch (ArrayIndexOutOfBoundsException e) { + return null; + } + } + + public int getValue() { + return value; + } + } + + public static enum SettingType { + ROTATION_ANGLE_RANGE(0), // Set a range for this option to specify the + // angles at which you expect the Function to find + // template matches in the inspection image. + SCALE_RANGE(1), // Set a range for this option to specify the sizes at which + // you expect the Function to find template matches in the + // inspection image. + OCCLUSION_RANGE(2), // Set a range for this option to specify the amount of + // occlusion you expect for a match in the inspection + // image. + ; + private final int value; + + private SettingType(int value) { + this.value = value; + } + + public static SettingType fromValue(int val) { + try { + return values()[val]; + } catch (ArrayIndexOutOfBoundsException e) { + return null; + } + } + + public int getValue() { + return value; + } + } + + public static enum SegmentationDistanceLevel { + SEGMENTATION_LEVEL_CONSERVATIVE(0), // Uses extensive criteria to determine + // the Maximum Distance. + SEGMENTATION_LEVEL_AGGRESSIVE(1), // Uses few criteria to determine the + // Maximum Distance. + ; + private final int value; + + private SegmentationDistanceLevel(int value) { + this.value = value; + } + + public static SegmentationDistanceLevel fromValue(int val) { + try { + return values()[val]; + } catch (ArrayIndexOutOfBoundsException e) { + return null; + } + } + + public int getValue() { + return value; + } + } + + public static enum ExtractContourSelection { + CLOSEST(0), // Selects the curve closest to the ROI. + LONGEST(1), // Selects the longest curve. + STRONGEST(2), // Selects the curve with the highest edge strength averaged + // from each point on the curve. + ; + private final int value; + + private ExtractContourSelection(int value) { + this.value = value; + } + + public static ExtractContourSelection fromValue(int val) { + try { + return values()[val]; + } catch (ArrayIndexOutOfBoundsException e) { + return null; + } + } + + public int getValue() { + return value; + } + } + + public static enum FindTransformMode { + FIND_REFERENCE(0), // Update both parts of the coordinate system. + UPDATE_TRANSFORM(1), // Update only the new reference system. + ; + private final int value; + + private FindTransformMode(int value) { + this.value = value; + } + + public static FindTransformMode fromValue(int val) { + try { + return values()[val]; + } catch (ArrayIndexOutOfBoundsException e) { + return null; + } + } + + public int getValue() { + return value; + } + } + + public static enum ExtractContourDirection { + RECT_LEFT_RIGHT(0), // Searches the ROI from left to right. + RECT_RIGHT_LEFT(1), // Searches the ROI from right to left. + RECT_TOP_BOTTOM(2), // Searches the ROI from top to bottom. + RECT_BOTTOM_TOP(3), // Searches the ROI from bottom to top. + ANNULUS_INNER_OUTER(4), // Searches the ROI from the inner radius to the + // outer radius. + ANNULUS_OUTER_INNER(5), // Searches the ROI from the outer radius to the + // inner radius. + ANNULUS_START_STOP(6), // Searches the ROI from start angle to end angle. + ANNULUS_STOP_START(7), // Searches the ROI from end angle to start angle. + ; + private final int value; + + private ExtractContourDirection(int value) { + this.value = value; + } + + public static ExtractContourDirection fromValue(int val) { + try { + return values()[val]; + } catch (ArrayIndexOutOfBoundsException e) { + return null; + } + } + + public int getValue() { + return value; + } + } + + public static enum EdgePolaritySearchMode { + SEARCH_FOR_ALL_EDGES(0), // Searches for all edges. + SEARCH_FOR_RISING_EDGES(1), // Searches for rising edges only. + SEARCH_FOR_FALLING_EDGES(2), // Searches for falling edges only. + ; + private final int value; + + private EdgePolaritySearchMode(int value) { + this.value = value; + } + + public static EdgePolaritySearchMode fromValue(int val) { + try { + return values()[val]; + } catch (ArrayIndexOutOfBoundsException e) { + return null; + } + } + + public int getValue() { + return value; + } + } + + public static enum Connectivity { + FOUR_CONNECTED(0), // Morphological reconstruction is performed in + // connectivity mode 4. + EIGHT_CONNECTED(1), // Morphological reconstruction is performed in + // connectivity mode 8. + ; + private final int value; + + private Connectivity(int value) { + this.value = value; + } + + public static Connectivity fromValue(int val) { + try { + return values()[val]; + } catch (ArrayIndexOutOfBoundsException e) { + return null; + } + } + + public int getValue() { + return value; + } + } + + public static enum MorphologyReconstructOperation { + DILATE_RECONSTRUCT(0), // Performs Reconstruction by dilation. + ERODE_RECONSTRUCT(1), // Performs Reconstruction by erosion. + ; + private final int value; + + private MorphologyReconstructOperation(int value) { + this.value = value; + } + + public static MorphologyReconstructOperation fromValue(int val) { + try { + return values()[val]; + } catch (ArrayIndexOutOfBoundsException e) { + return null; + } + } + + public int getValue() { + return value; + } + } + + public static enum WaveletType { + DB02(0), DB03(1), DB04(2), // Specifies the Wavelet Type as DB02. + DB05(3), DB06(4), DB07(5), DB08(6), DB09(7), DB10(8), DB11(9), DB12(10), DB13(11), DB14(12), HAAR( + 13), BIOR1_3(14), BIOR1_5(15), BIOR2_2(16), BIOR2_4(17), BIOR2_6(18), BIOR2_8(19), BIOR3_1( + 20), BIOR3_3(21), BIOR3_5(22), BIOR3_7(23), BIOR3_9(24), BIOR4_4(25), COIF1(26), COIF2(27), COIF3( + 28), COIF4(29), COIF5(30), SYM2(31), SYM3(32), SYM4(33), SYM5(34), SYM6(35), SYM7(36), SYM8( + 37), BIOR5_5(38), BIOR6_8(39), ; + private final int value; + + private WaveletType(int value) { + this.value = value; + } + + public static WaveletType fromValue(int val) { + try { + return values()[val]; + } catch (ArrayIndexOutOfBoundsException e) { + return null; + } + } + + public int getValue() { + return value; + } + } + + public static enum ParticleClassifierThresholdType { + THRESHOLD_MANUAL(0), // The classifier performs a manual threshold on the + // image during preprocessing. + THRESHOLD_AUTO(1), // The classifier performs an auto threshold on the image + // during preprocessing. + THRESHOLD_LOCAL(2), // The classifier performs a local threshold on the + // image during preprocessing. + ; + private final int value; + + private ParticleClassifierThresholdType(int value) { + this.value = value; + } + + public static ParticleClassifierThresholdType fromValue(int val) { + try { + return values()[val]; + } catch (ArrayIndexOutOfBoundsException e) { + return null; + } + } + + public int getValue() { + return value; + } + } + + public static enum MeasureParticlesCalibrationMode { + CALIBRATION_MODE_PIXEL(0), // The function takes only pixel measurements on + // the particles in the image. + CALIBRATION_MODE_CALIBRATED(1), // The function takes only calibrated + // measurements on the particles in the + // image. + CALIBRATION_MODE_BOTH(2), // The function takes both pixel and calibrated + // measurements on the particles in the image. + ; + private final int value; + + private MeasureParticlesCalibrationMode(int value) { + this.value = value; + } + + public static MeasureParticlesCalibrationMode fromValue(int val) { + try { + return values()[val]; + } catch (ArrayIndexOutOfBoundsException e) { + return null; + } + } + + public int getValue() { + return value; + } + } + + public static enum GeometricMatchingSearchStrategy { + GEOMETRIC_MATCHING_CONSERVATIVE(0), // Instructs the pattern matching + // algorithm to use the largest possible + // amount of information from the image + // at the expense of slowing down the + // speed of the algorithm. + GEOMETRIC_MATCHING_BALANCED(1), // Instructs the pattern matching algorithm + // to balance the amount of information from + // the image it uses with the speed of the + // algorithm. + GEOMETRIC_MATCHING_AGGRESSIVE(2), // Instructs the pattern matching + // algorithm to use a lower amount of + // information from the image, which + // allows the algorithm to run quickly but + // at the expense of accuracy. + ; + private final int value; + + private GeometricMatchingSearchStrategy(int value) { + this.value = value; + } + + public static GeometricMatchingSearchStrategy fromValue(int val) { + try { + return values()[val]; + } catch (ArrayIndexOutOfBoundsException e) { + return null; + } + } + + public int getValue() { + return value; + } + } + + public static enum ColorClassificationResolution { + CLASSIFIER_LOW_RESOLUTION(0), // Low resolution version of the color + // classifier. + CLASSIFIER_MEDIUM_RESOLUTION(1), // Medium resolution version of the color + // classifier. + CLASSIFIER_HIGH_RESOLUTION(2), // High resolution version of the color + // classifier. + ; + private final int value; + + private ColorClassificationResolution(int value) { + this.value = value; + } + + public static ColorClassificationResolution fromValue(int val) { + try { + return values()[val]; + } catch (ArrayIndexOutOfBoundsException e) { + return null; + } + } + + public int getValue() { + return value; + } + } + + public static enum ConnectionConstraintType { + DISTANCE_CONSTRAINT(0), // Specifies the distance, in pixels, within which + // the end points of two curves must lie in order to + // be considered part of a contour. + ANGLE_CONSTRAINT(1), // Specifies the range, in degrees, within which the + // difference between the angle of two curves, measured + // at the end points, must lie in order for the two + // curves to be considered part of a contour. + CONNECTIVITY_CONSTRAINT(2), // Specifies the distance, in pixels, within + // which a line extended from the end point of a + // curve must pass the end point of another + // curve in order for the two curves to be + // considered part of a contour. + GRADIENT_CONSTRAINT(3), // Specifies the range, in degrees, within which the + // gradient angles of two curves, measured at the + // end points, must lie in order for the two curves + // to be considered part of a contour. + NUM_CONNECTION_CONSTRAINT_TYPES(4), // . + ; + private final int value; + + private ConnectionConstraintType(int value) { + this.value = value; + } + + public static ConnectionConstraintType fromValue(int val) { + try { + return values()[val]; + } catch (ArrayIndexOutOfBoundsException e) { + return null; + } + } + + public int getValue() { + return value; + } + } + + public static enum Barcode2DContrast { + ALL_BARCODE_2D_CONTRASTS(0), // The function searches for barcodes of each + // contrast type. + BLACK_ON_WHITE_BARCODE_2D(1), // The function searches for 2D barcodes + // containing black data on a white + // background. + WHITE_ON_BLACK_BARCODE_2D(2), // The function searches for 2D barcodes + // containing white data on a black + // background. + ; + private final int value; + + private Barcode2DContrast(int value) { + this.value = value; + } + + public static Barcode2DContrast fromValue(int val) { + try { + return values()[val]; + } catch (ArrayIndexOutOfBoundsException e) { + return null; + } + } + + public int getValue() { + return value; + } + } + + public static enum QRModelType { + QR_MODELTYPE_AUTO_DETECT(0), // Specifies that the function will auto-detect + // the type of QR code. + QR_MODELTYPE_MICRO(1), // Specifies the QR code is of a micro type. + QR_MODELTYPE_MODEL1(2), // Specifies the QR code is of a model1 type. + QR_MODELTYPE_MODEL2(3), // Specifies the QR code is of a model2 type. + ; + private final int value; + + private QRModelType(int value) { + this.value = value; + } + + public static QRModelType fromValue(int val) { + try { + return values()[val]; + } catch (ArrayIndexOutOfBoundsException e) { + return null; + } + } + + public int getValue() { + return value; + } + } + + public static enum WindowBackgroundFillStyle { + FILL_STYLE_SOLID(0), // Fill the display window with a solid color. + FILL_STYLE_HATCH(2), // Fill the display window with a pattern defined by + // WindowBackgroundHatchStyle. + FILL_STYLE_DEFAULT(3), // Fill the display window with the NI Vision default + // pattern. + ; + private final int value; + + private WindowBackgroundFillStyle(int value) { + this.value = value; + } + + public static WindowBackgroundFillStyle fromValue(int val) { + for (WindowBackgroundFillStyle v : values()) { + if (v.value == val) + return v; + } + return null; + } + + public int getValue() { + return value; + } + } + + public static enum ExtractionMode { + NORMAL_IMAGE(0), // Specifies that the function makes no assumptions about + // the uniformity of objects in the image or the image + // background. + UNIFORM_REGIONS(1), // Specifies that the function assumes that either the + // objects in the image or the image background consists + // of uniform pixel values. + ; + private final int value; + + private ExtractionMode(int value) { + this.value = value; + } + + public static ExtractionMode fromValue(int val) { + try { + return values()[val]; + } catch (ArrayIndexOutOfBoundsException e) { + return null; + } + } + + public int getValue() { + return value; + } + } + + public static enum EdgeFilterSize { + FINE(0), // Specifies that the function uses a fine (narrow) edge filter. + NORMAL(1), // Specifies that the function uses a normal edge filter. + CONTOUR_TRACING(2), // Sets the Edge Filter Size to contour tracing, which + // provides the best results for contour extraction but + // increases the time required to process the image. + ; + private final int value; + + private EdgeFilterSize(int value) { + this.value = value; + } + + public static EdgeFilterSize fromValue(int val) { + try { + return values()[val]; + } catch (ArrayIndexOutOfBoundsException e) { + return null; + } + } + + public int getValue() { + return value; + } + } + + public static enum Barcode2DSearchMode { + SEARCH_MULTIPLE(0), // The function searches for multiple 2D barcodes. + SEARCH_SINGLE_CONSERVATIVE(1), // The function searches for 2D barcodes + // using the same searching algorithm as + // IMAQ_SEARCH_MULTIPLE but stops searching + // after locating one valid barcode. + SEARCH_SINGLE_AGGRESSIVE(2), // The function searches for a single 2D + // barcode using a method that assumes the + // barcode occupies a majority of the search + // region. + ; + private final int value; + + private Barcode2DSearchMode(int value) { + this.value = value; + } + + public static Barcode2DSearchMode fromValue(int val) { + try { + return values()[val]; + } catch (ArrayIndexOutOfBoundsException e) { + return null; + } + } + + public int getValue() { + return value; + } + } + + public static enum DataMatrixSubtype { + ALL_DATA_MATRIX_SUBTYPES(0), // The function searches for Data Matrix + // barcodes of all subtypes. + DATA_MATRIX_SUBTYPES_ECC_000_ECC_140(1), // The function searches for Data + // Matrix barcodes of subtypes ECC + // 000, ECC 050, ECC 080, ECC 100 + // and ECC 140. + DATA_MATRIX_SUBTYPE_ECC_200(2), // The function searches for Data Matrix ECC + // 200 barcodes. + ; + private final int value; + + private DataMatrixSubtype(int value) { + this.value = value; + } + + public static DataMatrixSubtype fromValue(int val) { + try { + return values()[val]; + } catch (ArrayIndexOutOfBoundsException e) { + return null; + } + } + + public int getValue() { + return value; + } + } + + public static enum FeatureType { + NOT_FOUND_FEATURE(0), // Specifies the feature is not found. + CIRCLE_FEATURE(1), // Specifies the feature is a circle. + ELLIPSE_FEATURE(2), // Specifies the feature is an ellipse. + CONST_CURVE_FEATURE(3), // Specifies the features is a constant curve. + RECTANGLE_FEATURE(4), // Specifies the feature is a rectangle. + LEG_FEATURE(5), // Specifies the feature is a leg. + CORNER_FEATURE(6), // Specifies the feature is a corner. + PARALLEL_LINE_PAIR_FEATURE(7), // Specifies the feature is a parallel line + // pair. + PAIR_OF_PARALLEL_LINE_PAIRS_FEATURE(8), // Specifies the feature is a pair + // of parallel line pairs. + LINE_FEATURE(9), // Specifies the feature is a line. + CLOSED_CURVE_FEATURE(10), // Specifies the feature is a closed curve. + ; + private final int value; + + private FeatureType(int value) { + this.value = value; + } + + public static FeatureType fromValue(int val) { + try { + return values()[val]; + } catch (ArrayIndexOutOfBoundsException e) { + return null; + } + } + + public int getValue() { + return value; + } + } + + public static enum Barcode2DCellShape { + SQUARE_CELLS(0), // The function uses an algorithm for decoding the 2D + // barcode that works with square data cells. + ROUND_CELLS(1), // The function uses an algorithm for decoding the 2D + // barcode that works with round data cells. + ; + private final int value; + + private Barcode2DCellShape(int value) { + this.value = value; + } + + public static Barcode2DCellShape fromValue(int val) { + try { + return values()[val]; + } catch (ArrayIndexOutOfBoundsException e) { + return null; + } + } + + public int getValue() { + return value; + } + } + + public static enum LocalThresholdMethod { + NIBLACK(0), // The function computes thresholds for each pixel based on its + // local statistics using the Niblack local thresholding + // algorithm. + BACKGROUND_CORRECTION(1), // The function performs background correction + // first to eliminate non-uniform lighting + // effects, then performs thresholding using the + // Otsu thresholding algorithm. + ; + private final int value; + + private LocalThresholdMethod(int value) { + this.value = value; + } + + public static LocalThresholdMethod fromValue(int val) { + try { + return values()[val]; + } catch (ArrayIndexOutOfBoundsException e) { + return null; + } + } + + public int getValue() { + return value; + } + } + + public static enum Barcode2DType { + PDF417(0), // The 2D barcode is of type PDF417. + DATA_MATRIX_ECC_000(1), // The 2D barcode is of type Data Matrix ECC 000. + DATA_MATRIX_ECC_050(2), // The 2D barcode is of type Data Matrix ECC 050. + DATA_MATRIX_ECC_080(3), // The 2D barcode is of type Data Matrix ECC 080. + DATA_MATRIX_ECC_100(4), // The 2D barcode is of type Data Matrix ECC 100. + DATA_MATRIX_ECC_140(5), // The 2D barcode is of type Data Matrix ECC 140. + DATA_MATRIX_ECC_200(6), // The 2D barcode is of type Data Matrix ECC 200. + ; + private final int value; + + private Barcode2DType(int value) { + this.value = value; + } + + public static Barcode2DType fromValue(int val) { + try { + return values()[val]; + } catch (ArrayIndexOutOfBoundsException e) { + return null; + } + } + + public int getValue() { + return value; + } + } + + public static enum ClassifierEngineType { + ENGINE_NONE(0), // No engine has been set on this classifier session. + ENGINE_NEAREST_NEIGHBOR(1), // Nearest neighbor engine. + ENGINE_SUPPORT_VECTOR_MACHINE(2), ; + private final int value; + + private ClassifierEngineType(int value) { + this.value = value; + } + + public static ClassifierEngineType fromValue(int val) { + try { + return values()[val]; + } catch (ArrayIndexOutOfBoundsException e) { + return null; + } + } + + public int getValue() { + return value; + } + } + + public static enum ClassifierType { + CLASSIFIER_CUSTOM(0), // The classifier session classifies vectors of + // doubles. + CLASSIFIER_PARTICLE(1), // The classifier session classifies particles in + // binary images. + CLASSIFIER_COLOR(2), // The classifier session classifies an image based on + // its color. + CLASSIFIER_TEXTURE(3), // The classifier session classifies an image based + // on its texture. + ; + private final int value; + + private ClassifierType(int value) { + this.value = value; + } + + public static ClassifierType fromValue(int val) { + try { + return values()[val]; + } catch (ArrayIndexOutOfBoundsException e) { + return null; + } + } + + public int getValue() { + return value; + } + } + + public static enum ParticleType { + PARTICLE_BRIGHT(0), // Bright particles. + PARTICLE_DARK(1), // Dark particles. + ; + private final int value; + + private ParticleType(int value) { + this.value = value; + } + + public static ParticleType fromValue(int val) { + try { + return values()[val]; + } catch (ArrayIndexOutOfBoundsException e) { + return null; + } + } + + public int getValue() { + return value; + } + } + + public static enum VisionInfoType2 { + VISIONINFO_CALIBRATION(0x01), // Used to indicate interaction with the + // Calibration information in an image. + VISIONINFO_OVERLAY(0x02), // Used to indicate interaction with the Overlay + // information in an image. + VISIONINFO_GRAYTEMPLATE(0x04), // Used to indicate interaction with the + // grayscale template information in an + // image. + VISIONINFO_COLORTEMPLATE(0x08), // Used to indicate interaction with the + // color template information in an image. + VISIONINFO_GEOMETRICTEMPLATE(0x10), // Used to indicate interaction with the + // geometric template information in an + // image. + VISIONINFO_CUSTOMDATA(0x20), // Used to indicate interaction with the binary + // or text Custom Data in an image. + VISIONINFO_GOLDENTEMPLATE(0x40), // Used to indicate interaction with the + // golden template information in an image. + VISIONINFO_GEOMETRICTEMPLATE2(0x80), // Used to indicate interaction with + // the geometric template 2 information + // in an image. + VISIONINFO_ALL(0xFFFFFFFF), // Removes, checks for, or indicates the + // presence of all types of extra information in + // an image. + ; + private final int value; + + private VisionInfoType2(int value) { + this.value = value; + } + + public static VisionInfoType2 fromValue(int val) { + for (VisionInfoType2 v : values()) { + if (v.value == val) + return v; + } + return null; + } + + public int getValue() { + return value; + } + } + + public static enum ReadClassifierFileMode { + CLASSIFIER_READ_ALL(0), // Read all information from the classifier file. + CLASSIFIER_READ_SAMPLES(1), // Read only the samples from the classifier + // file. + CLASSIFIER_READ_PROPERTIES(2), // Read only the properties from the + // classifier file. + ; + private final int value; + + private ReadClassifierFileMode(int value) { + this.value = value; + } + + public static ReadClassifierFileMode fromValue(int val) { + try { + return values()[val]; + } catch (ArrayIndexOutOfBoundsException e) { + return null; + } + } + + public int getValue() { + return value; + } + } + + public static enum WriteClassifierFileMode { + CLASSIFIER_WRITE_ALL(0), // Writes all information to the classifier file. + CLASSIFIER_WRITE_CLASSIFY_ONLY(1), // Write only the information needed to + // classify to the classifier file. + ; + private final int value; + + private WriteClassifierFileMode(int value) { + this.value = value; + } + + public static WriteClassifierFileMode fromValue(int val) { + try { + return values()[val]; + } catch (ArrayIndexOutOfBoundsException e) { + return null; + } + } + + public int getValue() { + return value; + } + } + + public static enum Barcode2DShape { + SQUARE_BARCODE_2D(0), // The function searches for square 2D barcodes. + RECTANGULAR_BARCODE_2D(1), // The function searches for rectangular 2D + // barcodes. + ; + private final int value; + + private Barcode2DShape(int value) { + this.value = value; + } + + public static Barcode2DShape fromValue(int val) { + try { + return values()[val]; + } catch (ArrayIndexOutOfBoundsException e) { + return null; + } + } + + public int getValue() { + return value; + } + } + + public static enum DataMatrixRotationMode { + UNLIMITED_ROTATION(0), // The function allows for unlimited rotation. + C0_DEGREES(1), // The function allows for between -5 and 5 degrees of + // rotation. + C90_DEGREES(2), // The function allows for between 85 and 95 degrees of + // rotation. + C180_DEGREES(3), // The function allows for between 175 and 185 degrees of + // rotation. + C270_DEGREES(4), // The function allows for between 265 and 275 degrees of + // rotation. + ; + private final int value; + + private DataMatrixRotationMode(int value) { + this.value = value; + } + + public static DataMatrixRotationMode fromValue(int val) { + try { + return values()[val]; + } catch (ArrayIndexOutOfBoundsException e) { + return null; + } + } + + public int getValue() { + return value; + } + } + + public static enum AIMGrade { + AIM_GRADE_F(0), // The Data Matrix barcode received a grade of F. + AIM_GRADE_D(1), // The Data Matrix barcode received a grade of D. + AIM_GRADE_C(2), // The Data Matrix barcode received a grade of C. + AIM_GRADE_B(3), // The Data Matrix barcode received a grade of B. + AIM_GRADE_A(4), // The Data Matrix barcode received a grade of A. + ; + private final int value; + + private AIMGrade(int value) { + this.value = value; + } + + public static AIMGrade fromValue(int val) { + try { + return values()[val]; + } catch (ArrayIndexOutOfBoundsException e) { + return null; + } + } + + public int getValue() { + return value; + } + } + + public static enum DataMatrixCellFillMode { + AUTO_DETECT_CELL_FILL_MODE(-2), // Sets the function to determine the Data + // Matrix barcode cell fill percentage + // automatically. + LOW_FILL(0), // Sets the function to read Data Matrix barcodes with a cell + // fill percentage of less than 30 percent. + NORMAL_FILL(1), // Sets the function to read Data Matrix barcodes with a + // cell fill percentage greater than or equal to 30 percent. + ; + private final int value; + + private DataMatrixCellFillMode(int value) { + this.value = value; + } + + public static DataMatrixCellFillMode fromValue(int val) { + for (DataMatrixCellFillMode v : values()) { + if (v.value == val) + return v; + } + return null; + } + + public int getValue() { + return value; + } + } + + public static enum DataMatrixDemodulationMode { + AUTO_DETECT_DEMODULATION_MODE(-2), // The function will try each + // demodulation mode and use the one + // which decodes the Data Matrix barcode + // within the fewest iterations and + // utilizing the least amount of error + // correction. + HISTOGRAM(0), // The function uses a histogram of all of the Data Matrix + // cells to calculate a threshold. + LOCAL_CONTRAST(1), // The function examines each of the cell's neighbors to + // determine if the cell is on or off. + COMBINED(2), // The function uses the histogram of the Data Matrix barcode + // to calculate a threshold. + ALL_DEMODULATION_MODES(3), // The function tries IMAQ_HISTOGRAM, then + // IMAQ_LOCAL_CONTRAST and then IMAQ_COMBINATION, + // stopping once one mode is successful. + ; + private final int value; + + private DataMatrixDemodulationMode(int value) { + this.value = value; + } + + public static DataMatrixDemodulationMode fromValue(int val) { + for (DataMatrixDemodulationMode v : values()) { + if (v.value == val) + return v; + } + return null; + } + + public int getValue() { + return value; + } + } + + public static enum DataMatrixECC { + AUTO_DETECT_ECC(-2), // Sets the function to determine the Data Matrix + // barcode ECC automatically. + ECC_000(0), // Sets the function to read Data Matrix barcodes of ECC 000 + // only. + ECC_050(50), // Sets the function to read Data Matrix barcodes of ECC 050 + // only. + ECC_080(80), // Sets the function to read Data Matrix barcodes of ECC 080 + // only. + ECC_100(100), // Sets the function to read Data Matrix barcodes of ECC 100 + // only. + ECC_140(140), // Sets the function to read Data Matrix barcodes of ECC 140 + // only. + ECC_000_140(190), // Sets the function to read Data Matrix barcodes of ECC + // 000, ECC 050, ECC 080, ECC 100, and ECC 140 only. + ECC_200(200), // Sets the function to read Data Matrix barcodes of ECC 200 + // only. + ; + private final int value; + + private DataMatrixECC(int value) { + this.value = value; + } + + public static DataMatrixECC fromValue(int val) { + for (DataMatrixECC v : values()) { + if (v.value == val) + return v; + } + return null; + } + + public int getValue() { + return value; + } + } + + public static enum DataMatrixPolarity { + AUTO_DETECT_POLARITY(-2), // Sets the function to determine the Data Matrix + // barcode polarity automatically. + BLACK_DATA_ON_WHITE_BACKGROUND(0), // Sets the function to read Data Matrix + // barcodes with dark data on a bright + // background. + WHITE_DATA_ON_BLACK_BACKGROUND(1), // Sets the function to read Data Matrix + // barcodes with bright data on a dark + // background. + ; + private final int value; + + private DataMatrixPolarity(int value) { + this.value = value; + } + + public static DataMatrixPolarity fromValue(int val) { + for (DataMatrixPolarity v : values()) { + if (v.value == val) + return v; + } + return null; + } + + public int getValue() { + return value; + } + } + + public static enum DataMatrixCellFilterMode { + AUTO_DETECT_CELL_FILTER_MODE(-2), // The function will try all filter modes + // and uses the one that decodes the Data + // Matrix barcode within the fewest + // iterations and utilizing the least + // amount of error correction. + AVERAGE_FILTER(0), // The function sets the pixel value for the cell to the + // average of the sampled pixels. + MEDIAN_FILTER(1), // The function sets the pixel value for the cell to the + // median of the sampled pixels. + CENTRAL_AVERAGE_FILTER(2), // The function sets the pixel value for the cell + // to the average of the pixels in the center of + // the cell sample. + HIGH_AVERAGE_FILTER(3), // The function sets the pixel value for the cell to + // the average value of the half of the sampled + // pixels with the highest pixel values. + LOW_AVERAGE_FILTER(4), // The function sets the pixel value for the cell to + // the average value of the half of the sampled + // pixels with the lowest pixel values. + VERY_HIGH_AVERAGE_FILTER(5), // The function sets the pixel value for the + // cell to the average value of the ninth of + // the sampled pixels with the highest pixel + // values. + VERY_LOW_AVERAGE_FILTER(6), // The function sets the pixel value for the + // cell to the average value of the ninth of the + // sampled pixels with the lowest pixel values. + ALL_CELL_FILTERS(8), // The function tries each filter mode, starting with + // IMAQ_AVERAGE_FILTER and ending with + // IMAQ_VERY_LOW_AVERAGE_FILTER, stopping once a filter + // mode decodes correctly. + ; + private final int value; + + private DataMatrixCellFilterMode(int value) { + this.value = value; + } + + public static DataMatrixCellFilterMode fromValue(int val) { + for (DataMatrixCellFilterMode v : values()) { + if (v.value == val) + return v; + } + return null; + } + + public int getValue() { + return value; + } + } + + public static enum WindowBackgroundHatchStyle { + HATCH_STYLE_HORIZONTAL(0), // The background of the display window will be + // horizontal bars. + HATCH_STYLE_VERTICAL(1), // The background of the display window will be + // vertical bars. + HATCH_STYLE_FORWARD_DIAGONAL(2), // The background of the display window + // will be diagonal bars. + HATCH_STYLE_BACKWARD_DIAGONAL(3), // The background of the display window + // will be diagonal bars. + HATCH_STYLE_CROSS(4), // The background of the display window will be + // intersecting horizontal and vertical bars. + HATCH_STYLE_CROSS_HATCH(5), // The background of the display window will be + // intersecting forward and backward diagonal + // bars. + ; + private final int value; + + private WindowBackgroundHatchStyle(int value) { + this.value = value; + } + + public static WindowBackgroundHatchStyle fromValue(int val) { + try { + return values()[val]; + } catch (ArrayIndexOutOfBoundsException e) { + return null; + } + } + + public int getValue() { + return value; + } + } + + public static enum DataMatrixMirrorMode { + AUTO_DETECT_MIRROR(-2), // Specifies that the function should determine if + // the Data Matrix barcode is mirrored. + APPEARS_NORMAL(0), // Specifies that the function should expect the Data + // Matrix barcode to appear normal. + APPEARS_MIRRORED(1), // Specifies that the function should expect the Data + // Matrix barcode to appear mirrored. + ; + private final int value; + + private DataMatrixMirrorMode(int value) { + this.value = value; + } + + public static DataMatrixMirrorMode fromValue(int val) { + for (DataMatrixMirrorMode v : values()) { + if (v.value == val) + return v; + } + return null; + } + + public int getValue() { + return value; + } + } + + public static enum CalibrationMode2 { + PERSPECTIVE_MODE(0), // Functions correct for distortion caused by the + // camera's perspective. + MICROPLANE_MODE(1), // Functions correct for distortion caused by the + // camera's lens. + SIMPLE_CALIBRATION_MODE(2), // Functions do not correct for distortion. + CORRECTED_IMAGE_MODE(3), // The image is already corrected. + NO_CALIBRATION_MODE(4), // Image with No calibration. + ; + private final int value; + + private CalibrationMode2(int value) { + this.value = value; + } + + public static CalibrationMode2 fromValue(int val) { + try { + return values()[val]; + } catch (ArrayIndexOutOfBoundsException e) { + return null; + } + } + + public int getValue() { + return value; + } + } + + public static enum DataMatrixGradingMode { + NO_GRADING(0), // The function does not make any preparatory calculations. + PREPARE_FOR_AIM(1), // The function prepares the image for grading using the + // AIM Print Quality metrics. + ; + private final int value; + + private DataMatrixGradingMode(int value) { + this.value = value; + } + + public static DataMatrixGradingMode fromValue(int val) { + try { + return values()[val]; + } catch (ArrayIndexOutOfBoundsException e) { + return null; + } + } + + public int getValue() { + return value; + } + } + + public static enum WaveletTransformMode { + WAVELET_TRANSFORM_INTEGER(0), // Uses a 5-3 reversible integer transform. + WAVELET_TRANSFORM_FLOATING_POINT(1), // Performs a 9-7 irreversible + // floating-point transform. + ; + private final int value; + + private WaveletTransformMode(int value) { + this.value = value; + } + + public static WaveletTransformMode fromValue(int val) { + try { + return values()[val]; + } catch (ArrayIndexOutOfBoundsException e) { + return null; + } + } + + public int getValue() { + return value; + } + } + + public static enum NormalizationMethod { + NORMALIZATION_NONE(0), // No normalization. + NORMALIZATION_HISTOGRAM_MATCHING(1), // Adjust image so its histogram is + // similar to the golden template's + // histogram. + NORMALIZATION_AVERAGE_MATCHING(2), // Adjust image so its mean pixel value + // equals the golden template's mean + // pixel value. + ; + private final int value; + + private NormalizationMethod(int value) { + this.value = value; + } + + public static NormalizationMethod fromValue(int val) { + try { + return values()[val]; + } catch (ArrayIndexOutOfBoundsException e) { + return null; + } + } + + public int getValue() { + return value; + } + } + + public static enum RegistrationMethod { + REGISTRATION_NONE(0), // No registration. + REGISTRATION_PERSPECTIVE(1), // Adjust image to correct for minor variations + // in alignment or perspective. + ; + private final int value; + + private RegistrationMethod(int value) { + this.value = value; + } + + public static RegistrationMethod fromValue(int val) { + try { + return values()[val]; + } catch (ArrayIndexOutOfBoundsException e) { + return null; + } + } + + public int getValue() { + return value; + } + } + + public static enum LinearAveragesMode { + COLUMN_AVERAGES(1), // Specifies that the function calculates the mean pixel + // value of each column. + ROW_AVERAGES(2), // Specifies that the function calculates the mean pixel + // value of each row. + RISING_DIAGONAL_AVERAGES(4), // Specifies that the function calculates the + // mean pixel value of each diagonal running + // from the lower left to the upper right of + // the inspected area of the image. + FALLING_DIAGONAL_AVERAGES(8), // Specifies that the function calculates the + // mean pixel value of each diagonal running + // from the upper left to the lower right of + // the inspected area of the image. + ALL_LINEAR_AVERAGES(15), // Specifies that the function calculates all four + // linear mean pixel values. + ; + private final int value; + + private LinearAveragesMode(int value) { + this.value = value; + } + + public static LinearAveragesMode fromValue(int val) { + for (LinearAveragesMode v : values()) { + if (v.value == val) + return v; + } + return null; + } + + public int getValue() { + return value; + } + } + + public static enum CompressionType { + COMPRESSION_NONE(0), // Specifies that the function should not compress the + // image. + COMPRESSION_JPEG(1), // Specifies that the function should use lossy JPEG + // compression on the image. + COMPRESSION_PACKED_BINARY(2), // Specifies that the function should use + // lossless binary packing on the image. + ; + private final int value; + + private CompressionType(int value) { + this.value = value; + } + + public static CompressionType fromValue(int val) { + try { + return values()[val]; + } catch (ArrayIndexOutOfBoundsException e) { + return null; + } + } + + public int getValue() { + return value; + } + } + + public static enum FlattenType { + FLATTEN_IMAGE(0), // Flattens just the image data. + FLATTEN_IMAGE_AND_VISION_INFO(1), // Flattens the image data and any Vision + // information associated with the image. + ; + private final int value; + + private FlattenType(int value) { + this.value = value; + } + + public static FlattenType fromValue(int val) { + try { + return values()[val]; + } catch (ArrayIndexOutOfBoundsException e) { + return null; + } + } + + public int getValue() { + return value; + } + } + + public static enum DataMatrixCellSampleSize { + AUTO_DETECT_CELL_SAMPLE_SIZE(-2), // The function will try each sample size + // and use the one which decodes the Data + // Matrix barcode within the fewest + // iterations and utilizing the least + // amount of error correction. + C1x1(1), // The function will use a 1x1 sized sample from each cell. + C2x2(2), // The function will use a 2x2 sized sample from each cell. + C3x3(3), // The function will use a 3x3 sized sample from each cell. + C4x4(4), // The function will use a 4x4 sized sample from each cell. + C5x5(5), // The function will use a 5x5 sized sample from each cell. + C6x6(6), // The function will use a 6x6 sized sample from each cell. + C7x7(7), // The function will use a 7x7 sized sample from each cell. + ; + private final int value; + + private DataMatrixCellSampleSize(int value) { + this.value = value; + } + + public static DataMatrixCellSampleSize fromValue(int val) { + for (DataMatrixCellSampleSize v : values()) { + if (v.value == val) + return v; + } + return null; + } + + public int getValue() { + return value; + } + } + + /** + * Forward Declare Data Structures + */ + + /** + * Data Structures + */ + + public static class DivisionModel extends DisposedStruct { + public float kappa; // The learned kappa coefficient of division model. + + private void init() { + + } + + public DivisionModel() { + super(4); + init(); + } + + public DivisionModel(double kappa) { + super(4); + this.kappa = (float) kappa; + } + + protected DivisionModel(ByteBuffer backing, int offset) { + super(backing, offset, 4); + init(); + } + + protected DivisionModel(long nativeObj, boolean owned) { + super(nativeObj, owned, 4); + init(); + } + + protected void setBuffer(ByteBuffer backing, int offset) { + super.setBuffer(backing, offset, 4); + } + + public void read() { + kappa = backing.getFloat(0); + } + + public void write() { + backing.putFloat(0, kappa); + } + + public int size() { + return 4; + } + } + + public static class FocalLength extends DisposedStruct { + public float fx; // Focal length in X direction. + public float fy; // Focal length in Y direction. + + private void init() { + + } + + public FocalLength() { + super(8); + init(); + } + + public FocalLength(double fx, double fy) { + super(8); + this.fx = (float) fx; + this.fy = (float) fy; + } + + protected FocalLength(ByteBuffer backing, int offset) { + super(backing, offset, 8); + init(); + } + + protected FocalLength(long nativeObj, boolean owned) { + super(nativeObj, owned, 8); + init(); + } + + protected void setBuffer(ByteBuffer backing, int offset) { + super.setBuffer(backing, offset, 8); + } + + public void read() { + fx = backing.getFloat(0); + fy = backing.getFloat(4); + } + + public void write() { + backing.putFloat(0, fx); + backing.putFloat(4, fy); + } + + public int size() { + return 8; + } + } + + public static class PolyModel extends DisposedStruct { + public float[] kCoeffs; // The learned radial coefficients of polynomial + // model. + public float p1; // The P1(learned tangential coefficients of polynomial + // model). + public float p2; // The P2(learned tangential coefficients of polynomial + // model). + private ByteBuffer kCoeffs_buf; + + private void init() { + kCoeffs = new float[0]; + } + + public PolyModel() { + super(16); + init(); + } + + public PolyModel(float[] kCoeffs, double p1, double p2) { + super(16); + this.kCoeffs = kCoeffs; + this.p1 = (float) p1; + this.p2 = (float) p2; + } + + protected PolyModel(ByteBuffer backing, int offset) { + super(backing, offset, 16); + init(); + } + + protected PolyModel(long nativeObj, boolean owned) { + super(nativeObj, owned, 16); + init(); + } + + protected void setBuffer(ByteBuffer backing, int offset) { + super.setBuffer(backing, offset, 16); + } + + public void read() { + int kCoeffs_numKCoeffs = backing.getInt(4); + long kCoeffs_addr = getPointer(backing, 0); + kCoeffs = new float[kCoeffs_numKCoeffs]; + if (kCoeffs_numKCoeffs > 0 && kCoeffs_addr != 0) { + newDirectByteBuffer(kCoeffs_addr, kCoeffs_numKCoeffs * 4).asFloatBuffer().get(kCoeffs); + } + p1 = backing.getFloat(8); + p2 = backing.getFloat(12); + } + + public void write() { + kCoeffs_buf = ByteBuffer.allocateDirect(kCoeffs.length * 4).order(ByteOrder.nativeOrder()); + kCoeffs_buf.asFloatBuffer().put(kCoeffs).rewind(); + backing.putInt(4, kCoeffs.length); + putPointer(backing, 0, kCoeffs_buf); + backing.putFloat(8, p1); + backing.putFloat(12, p2); + } + + public int size() { + return 16; + } + } + + public static class DistortionModelParams extends DisposedStruct { + public DistortionModel distortionModel; // Type of learned distortion model. + public PolyModel polyModel; // The learned coefficients of polynomial model. + public DivisionModel divisionModel; // The learned coefficient of division + // model. + + private void init() { + polyModel = new PolyModel(backing, 4); + divisionModel = new DivisionModel(backing, 20); + } + + public DistortionModelParams() { + super(24); + init(); + } + + public DistortionModelParams(DistortionModel distortionModel, PolyModel polyModel, + DivisionModel divisionModel) { + super(24); + this.distortionModel = distortionModel; + this.polyModel = polyModel; + this.divisionModel = divisionModel; + } + + protected DistortionModelParams(ByteBuffer backing, int offset) { + super(backing, offset, 24); + init(); + } + + protected DistortionModelParams(long nativeObj, boolean owned) { + super(nativeObj, owned, 24); + init(); + } + + protected void setBuffer(ByteBuffer backing, int offset) { + super.setBuffer(backing, offset, 24); + } + + public void read() { + distortionModel = DistortionModel.fromValue(backing.getInt(0)); + polyModel.read(); + divisionModel.read(); + } + + public void write() { + if (distortionModel != null) + backing.putInt(0, distortionModel.getValue()); + polyModel.write(); + divisionModel.write(); + } + + public int size() { + return 24; + } + } + + public static class PointFloat extends DisposedStruct { + public float x; // The x-coordinate of the point. + public float y; // The y-coordinate of the point. + + private void init() { + + } + + public PointFloat() { + super(8); + init(); + } + + public PointFloat(double x, double y) { + super(8); + this.x = (float) x; + this.y = (float) y; + } + + protected PointFloat(ByteBuffer backing, int offset) { + super(backing, offset, 8); + init(); + } + + protected PointFloat(long nativeObj, boolean owned) { + super(nativeObj, owned, 8); + init(); + } + + protected void setBuffer(ByteBuffer backing, int offset) { + super.setBuffer(backing, offset, 8); + } + + public void read() { + x = backing.getFloat(0); + y = backing.getFloat(4); + } + + public void write() { + backing.putFloat(0, x); + backing.putFloat(4, y); + } + + public int size() { + return 8; + } + } + + public static class InternalParameters extends DisposedStruct { + public byte isInsufficientData; + public FocalLength focalLength; + public PointFloat opticalCenter; + + private void init() { + focalLength = new FocalLength(backing, 4); + opticalCenter = new PointFloat(backing, 12); + } + + public InternalParameters() { + super(20); + init(); + } + + public InternalParameters(byte isInsufficientData, FocalLength focalLength, + PointFloat opticalCenter) { + super(20); + this.isInsufficientData = isInsufficientData; + this.focalLength = focalLength; + this.opticalCenter = opticalCenter; + } + + protected InternalParameters(ByteBuffer backing, int offset) { + super(backing, offset, 20); + init(); + } + + protected InternalParameters(long nativeObj, boolean owned) { + super(nativeObj, owned, 20); + init(); + } + + protected void setBuffer(ByteBuffer backing, int offset) { + super.setBuffer(backing, offset, 20); + } + + public void read() { + isInsufficientData = backing.get(0); + focalLength.read(); + opticalCenter.read(); + } + + public void write() { + backing.put(0, isInsufficientData); + focalLength.write(); + opticalCenter.write(); + } + + public int size() { + return 20; + } + } + + public static class MaxGridSize extends DisposedStruct { + public int xMax; // Maximum x limit for the grid size. + public int yMax; // Maximum y limit for the grid size. + + private void init() { + + } + + public MaxGridSize() { + super(8); + init(); + } + + public MaxGridSize(int xMax, int yMax) { + super(8); + this.xMax = xMax; + this.yMax = yMax; + } + + protected MaxGridSize(ByteBuffer backing, int offset) { + super(backing, offset, 8); + init(); + } + + protected MaxGridSize(long nativeObj, boolean owned) { + super(nativeObj, owned, 8); + init(); + } + + protected void setBuffer(ByteBuffer backing, int offset) { + super.setBuffer(backing, offset, 8); + } + + public void read() { + xMax = backing.getInt(0); + yMax = backing.getInt(4); + } + + public void write() { + backing.putInt(0, xMax); + backing.putInt(4, yMax); + } + + public int size() { + return 8; + } + } + + public static class ImageSize extends DisposedStruct { + public int xRes; // X resolution of the image. + public int yRes; // Y resolution of the image. + + private void init() { + + } + + public ImageSize() { + super(8); + init(); + } + + public ImageSize(int xRes, int yRes) { + super(8); + this.xRes = xRes; + this.yRes = yRes; + } + + protected ImageSize(ByteBuffer backing, int offset) { + super(backing, offset, 8); + init(); + } + + protected ImageSize(long nativeObj, boolean owned) { + super(nativeObj, owned, 8); + init(); + } + + protected void setBuffer(ByteBuffer backing, int offset) { + super.setBuffer(backing, offset, 8); + } + + public void read() { + xRes = backing.getInt(0); + yRes = backing.getInt(4); + } + + public void write() { + backing.putInt(0, xRes); + backing.putInt(4, yRes); + } + + public int size() { + return 8; + } + } + + public static class CalibrationReferencePoints extends DisposedStruct { + public PointDouble[] pixelCoords; // Specifies the coordinates of the pixel + // reference points. + public PointDouble[] realCoords; // Specifies the measuring unit associated + // with the image. + public CalibrationUnit units; // Specifies the units of X Step and Y Step. + public ImageSize imageSize; // Specifies the size of calibration template + // image. + private ByteBuffer pixelCoords_buf; + private ByteBuffer realCoords_buf; + + private void init() { + pixelCoords = new PointDouble[0]; + realCoords = new PointDouble[0]; + imageSize = new ImageSize(backing, 20); + } + + public CalibrationReferencePoints() { + super(28); + init(); + } + + public CalibrationReferencePoints(PointDouble[] pixelCoords, PointDouble[] realCoords, + CalibrationUnit units, ImageSize imageSize) { + super(28); + this.pixelCoords = pixelCoords; + this.realCoords = realCoords; + this.units = units; + this.imageSize = imageSize; + } + + protected CalibrationReferencePoints(ByteBuffer backing, int offset) { + super(backing, offset, 28); + init(); + } + + protected CalibrationReferencePoints(long nativeObj, boolean owned) { + super(nativeObj, owned, 28); + init(); + } + + protected void setBuffer(ByteBuffer backing, int offset) { + super.setBuffer(backing, offset, 28); + } + + public void read() { + int pixelCoords_numPixelCoords = backing.getInt(4); + long pixelCoords_addr = getPointer(backing, 0); + pixelCoords = new PointDouble[pixelCoords_numPixelCoords]; + if (pixelCoords_numPixelCoords > 0 && pixelCoords_addr != 0) { + ByteBuffer bb = newDirectByteBuffer(pixelCoords_addr, pixelCoords_numPixelCoords * 16); + for (int i = 0, off = 0; i < pixelCoords_numPixelCoords; i++, off += 16) { + pixelCoords[i] = new PointDouble(bb, off); + pixelCoords[i].read(); + } + } + int realCoords_numRealCoords = backing.getInt(12); + long realCoords_addr = getPointer(backing, 8); + realCoords = new PointDouble[realCoords_numRealCoords]; + if (realCoords_numRealCoords > 0 && realCoords_addr != 0) { + ByteBuffer bb = newDirectByteBuffer(realCoords_addr, realCoords_numRealCoords * 16); + for (int i = 0, off = 0; i < realCoords_numRealCoords; i++, off += 16) { + realCoords[i] = new PointDouble(bb, off); + realCoords[i].read(); + } + } + units = CalibrationUnit.fromValue(backing.getInt(16)); + imageSize.read(); + } + + public void write() { + pixelCoords_buf = + ByteBuffer.allocateDirect(pixelCoords.length * 16).order(ByteOrder.nativeOrder()); + for (int i = 0, off = 0; i < pixelCoords.length; i++, off += 16) { + pixelCoords[i].setBuffer(pixelCoords_buf, off); + pixelCoords[i].write(); + } + backing.putInt(4, pixelCoords.length); + putPointer(backing, 0, pixelCoords_buf); + realCoords_buf = + ByteBuffer.allocateDirect(realCoords.length * 16).order(ByteOrder.nativeOrder()); + for (int i = 0, off = 0; i < realCoords.length; i++, off += 16) { + realCoords[i].setBuffer(realCoords_buf, off); + realCoords[i].write(); + } + backing.putInt(12, realCoords.length); + putPointer(backing, 8, realCoords_buf); + if (units != null) + backing.putInt(16, units.getValue()); + imageSize.write(); + } + + public int size() { + return 28; + } + } + + public static class GetCameraParametersReport extends DisposedStruct { + public int projectionMatrixRows; // Number of rows in projection matrix. + public int projectionMatrixCols; // Number of columns in projection matrix. + public DistortionModelParams distortion; // Distortion model Coefficients. + public InternalParameters internalParams; // The learned internal paramters + // of camera model such as focal + // length and optical center. + + private void init() { + distortion = new DistortionModelParams(backing, 12); + internalParams = new InternalParameters(backing, 36); + } + + public GetCameraParametersReport() { + super(56); + init(); + } + + public GetCameraParametersReport(int projectionMatrixRows, int projectionMatrixCols, + DistortionModelParams distortion, InternalParameters internalParams) { + super(56); + this.projectionMatrixRows = projectionMatrixRows; + this.projectionMatrixCols = projectionMatrixCols; + this.distortion = distortion; + this.internalParams = internalParams; + } + + protected GetCameraParametersReport(ByteBuffer backing, int offset) { + super(backing, offset, 56); + init(); + } + + protected GetCameraParametersReport(long nativeObj, boolean owned) { + super(nativeObj, owned, 56); + init(); + } + + protected void setBuffer(ByteBuffer backing, int offset) { + super.setBuffer(backing, offset, 56); + } + + public void read() { + projectionMatrixRows = backing.getInt(4); + projectionMatrixCols = backing.getInt(8); + distortion.read(); + internalParams.read(); + } + + public void write() { + backing.putInt(4, projectionMatrixRows); + backing.putInt(8, projectionMatrixCols); + distortion.write(); + internalParams.write(); + } + + public int size() { + return 56; + } + } + + public static class CalibrationAxisInfo extends DisposedStruct { + public PointFloat center; // The origin of the reference coordinate system, + // expressed in pixel units. + public float rotationAngle; // The angle of the x-axis of the real-world + // coordinate system, in relation to the + // horizontal. + public AxisOrientation axisDirection; // Specifies the direction of the + // calibraiton axis which is either + // Direct or Indirect. + + private void init() { + center = new PointFloat(backing, 0); + } + + public CalibrationAxisInfo() { + super(16); + init(); + } + + public CalibrationAxisInfo(PointFloat center, double rotationAngle, + AxisOrientation axisDirection) { + super(16); + this.center = center; + this.rotationAngle = (float) rotationAngle; + this.axisDirection = axisDirection; + } + + protected CalibrationAxisInfo(ByteBuffer backing, int offset) { + super(backing, offset, 16); + init(); + } + + protected CalibrationAxisInfo(long nativeObj, boolean owned) { + super(nativeObj, owned, 16); + init(); + } + + protected void setBuffer(ByteBuffer backing, int offset) { + super.setBuffer(backing, offset, 16); + } + + public void read() { + center.read(); + rotationAngle = backing.getFloat(8); + axisDirection = AxisOrientation.fromValue(backing.getInt(12)); + } + + public void write() { + center.write(); + backing.putFloat(8, rotationAngle); + if (axisDirection != null) + backing.putInt(12, axisDirection.getValue()); + } + + public int size() { + return 16; + } + } + + public static class CalibrationLearnSetupInfo extends DisposedStruct { + public CalibrationMode2 calibrationMethod; // Type of calibration method + // used. + public DistortionModel distortionModel; // Type of learned distortion model. + public ScalingMethod scaleMode; // The aspect scaling to use when correcting + // an image. + public CalibrationROI roiMode; // The ROI to use when correcting an image. + public byte learnCorrectionTable; // Set this input to true value if you + // want the correction table to be + // determined and stored. + + private void init() { + + } + + public CalibrationLearnSetupInfo() { + super(20); + init(); + } + + public CalibrationLearnSetupInfo(CalibrationMode2 calibrationMethod, + DistortionModel distortionModel, ScalingMethod scaleMode, CalibrationROI roiMode, + byte learnCorrectionTable) { + super(20); + this.calibrationMethod = calibrationMethod; + this.distortionModel = distortionModel; + this.scaleMode = scaleMode; + this.roiMode = roiMode; + this.learnCorrectionTable = learnCorrectionTable; + } + + protected CalibrationLearnSetupInfo(ByteBuffer backing, int offset) { + super(backing, offset, 20); + init(); + } + + protected CalibrationLearnSetupInfo(long nativeObj, boolean owned) { + super(nativeObj, owned, 20); + init(); + } + + protected void setBuffer(ByteBuffer backing, int offset) { + super.setBuffer(backing, offset, 20); + } + + public void read() { + calibrationMethod = CalibrationMode2.fromValue(backing.getInt(0)); + distortionModel = DistortionModel.fromValue(backing.getInt(4)); + scaleMode = ScalingMethod.fromValue(backing.getInt(8)); + roiMode = CalibrationROI.fromValue(backing.getInt(12)); + learnCorrectionTable = backing.get(16); + } + + public void write() { + if (calibrationMethod != null) + backing.putInt(0, calibrationMethod.getValue()); + if (distortionModel != null) + backing.putInt(4, distortionModel.getValue()); + if (scaleMode != null) + backing.putInt(8, scaleMode.getValue()); + if (roiMode != null) + backing.putInt(12, roiMode.getValue()); + backing.put(16, learnCorrectionTable); + } + + public int size() { + return 20; + } + } + + public static class GridDescriptor extends DisposedStruct { + public float xStep; // The distance in the x direction between two adjacent + // pixels in units specified by unit. + public float yStep; // The distance in the y direction between two adjacent + // pixels in units specified by unit. + public CalibrationUnit unit; // The unit of measure for the image. + + private void init() { + + } + + public GridDescriptor() { + super(12); + init(); + } + + public GridDescriptor(double xStep, double yStep, CalibrationUnit unit) { + super(12); + this.xStep = (float) xStep; + this.yStep = (float) yStep; + this.unit = unit; + } + + protected GridDescriptor(ByteBuffer backing, int offset) { + super(backing, offset, 12); + init(); + } + + protected GridDescriptor(long nativeObj, boolean owned) { + super(nativeObj, owned, 12); + init(); + } + + protected void setBuffer(ByteBuffer backing, int offset) { + super.setBuffer(backing, offset, 12); + } + + public void read() { + xStep = backing.getFloat(0); + yStep = backing.getFloat(4); + unit = CalibrationUnit.fromValue(backing.getInt(8)); + } + + public void write() { + backing.putFloat(0, xStep); + backing.putFloat(4, yStep); + if (unit != null) + backing.putInt(8, unit.getValue()); + } + + public int size() { + return 12; + } + } + + public static class ErrorStatistics extends DisposedStruct { + public double mean; // Mean error statistics value. + public double maximum; // Maximum value of error. + public double standardDeviation; // The standard deviation error statistiscs + // value. + public double distortion; // The distortion error statistics value. + + private void init() { + + } + + public ErrorStatistics() { + super(32); + init(); + } + + public ErrorStatistics(double mean, double maximum, double standardDeviation, double distortion) { + super(32); + this.mean = mean; + this.maximum = maximum; + this.standardDeviation = standardDeviation; + this.distortion = distortion; + } + + protected ErrorStatistics(ByteBuffer backing, int offset) { + super(backing, offset, 32); + init(); + } + + protected ErrorStatistics(long nativeObj, boolean owned) { + super(nativeObj, owned, 32); + init(); + } + + protected void setBuffer(ByteBuffer backing, int offset) { + super.setBuffer(backing, offset, 32); + } + + public void read() { + mean = backing.getDouble(0); + maximum = backing.getDouble(8); + standardDeviation = backing.getDouble(16); + distortion = backing.getDouble(24); + } + + public void write() { + backing.putDouble(0, mean); + backing.putDouble(8, maximum); + backing.putDouble(16, standardDeviation); + backing.putDouble(24, distortion); + } + + public int size() { + return 32; + } + } + + public static class GetCalibrationInfoReport extends DisposedStruct { + public ROI userRoi; // Specifies the ROI the user provided when learning the + // calibration. + public ROI calibrationRoi; // Specifies the ROI that corresponds to the + // region of the image where the calibration + // information is accurate. + public CalibrationAxisInfo axisInfo; // Reference Coordinate System for the + // real-world coordinates. + public CalibrationLearnSetupInfo learnSetupInfo; // Calibration learn setup + // information. + public GridDescriptor gridDescriptor; // Specifies scaling constants used to + // calibrate the image. + public int errorMapRows; // Number of rows in error map. + public int errorMapCols; // Number of Columns in error map. + public ErrorStatistics errorStatistics; // Error statistics of the + // calibration. + + private void init() { + axisInfo = new CalibrationAxisInfo(backing, 8); + learnSetupInfo = new CalibrationLearnSetupInfo(backing, 24); + gridDescriptor = new GridDescriptor(backing, 44); + errorStatistics = new ErrorStatistics(backing, 72); + } + + public GetCalibrationInfoReport() { + super(104); + init(); + } + + public GetCalibrationInfoReport(ROI userRoi, ROI calibrationRoi, CalibrationAxisInfo axisInfo, + CalibrationLearnSetupInfo learnSetupInfo, GridDescriptor gridDescriptor, int errorMapRows, + int errorMapCols, ErrorStatistics errorStatistics) { + super(104); + this.userRoi = userRoi; + this.calibrationRoi = calibrationRoi; + this.axisInfo = axisInfo; + this.learnSetupInfo = learnSetupInfo; + this.gridDescriptor = gridDescriptor; + this.errorMapRows = errorMapRows; + this.errorMapCols = errorMapCols; + this.errorStatistics = errorStatistics; + } + + protected GetCalibrationInfoReport(ByteBuffer backing, int offset) { + super(backing, offset, 104); + init(); + } + + protected GetCalibrationInfoReport(long nativeObj, boolean owned) { + super(nativeObj, owned, 104); + init(); + } + + protected void setBuffer(ByteBuffer backing, int offset) { + super.setBuffer(backing, offset, 104); + } + + public void read() { + long userRoi_addr = getPointer(backing, 0); + if (userRoi_addr == 0) + userRoi = null; + else + userRoi = new ROI(userRoi_addr, false); + long calibrationRoi_addr = getPointer(backing, 4); + if (calibrationRoi_addr == 0) + calibrationRoi = null; + else + calibrationRoi = new ROI(calibrationRoi_addr, false); + axisInfo.read(); + learnSetupInfo.read(); + gridDescriptor.read(); + errorMapRows = backing.getInt(60); + errorMapCols = backing.getInt(64); + errorStatistics.read(); + } + + public void write() { + putPointer(backing, 0, userRoi); + putPointer(backing, 4, calibrationRoi); + axisInfo.write(); + learnSetupInfo.write(); + gridDescriptor.write(); + backing.putInt(60, errorMapRows); + backing.putInt(64, errorMapCols); + errorStatistics.write(); + } + + public int size() { + return 104; + } + } + + public static class EdgePolarity extends DisposedStruct { + public EdgePolaritySearchMode start; + public EdgePolaritySearchMode end; + + private void init() { + + } + + public EdgePolarity() { + super(8); + init(); + } + + public EdgePolarity(EdgePolaritySearchMode start, EdgePolaritySearchMode end) { + super(8); + this.start = start; + this.end = end; + } + + protected EdgePolarity(ByteBuffer backing, int offset) { + super(backing, offset, 8); + init(); + } + + protected EdgePolarity(long nativeObj, boolean owned) { + super(nativeObj, owned, 8); + init(); + } + + protected void setBuffer(ByteBuffer backing, int offset) { + super.setBuffer(backing, offset, 8); + } + + public void read() { + start = EdgePolaritySearchMode.fromValue(backing.getInt(0)); + end = EdgePolaritySearchMode.fromValue(backing.getInt(4)); + } + + public void write() { + if (start != null) + backing.putInt(0, start.getValue()); + if (end != null) + backing.putInt(4, end.getValue()); + } + + public int size() { + return 8; + } + } + + public static class ClampSettings extends DisposedStruct { + public double angleRange; // Specifies the angle range. + public EdgePolarity edgePolarity; // Specifies the edge polarity. + + private void init() { + edgePolarity = new EdgePolarity(backing, 8); + } + + public ClampSettings() { + super(16); + init(); + } + + public ClampSettings(double angleRange, EdgePolarity edgePolarity) { + super(16); + this.angleRange = angleRange; + this.edgePolarity = edgePolarity; + } + + protected ClampSettings(ByteBuffer backing, int offset) { + super(backing, offset, 16); + init(); + } + + protected ClampSettings(long nativeObj, boolean owned) { + super(nativeObj, owned, 16); + init(); + } + + protected void setBuffer(ByteBuffer backing, int offset) { + super.setBuffer(backing, offset, 16); + } + + public void read() { + angleRange = backing.getDouble(0); + edgePolarity.read(); + } + + public void write() { + backing.putDouble(0, angleRange); + edgePolarity.write(); + } + + public int size() { + return 16; + } + } + + public static class PointDouble extends DisposedStruct { + public double x; // The x-coordinate of the point. + public double y; // The y-coordinate of the point. + + private void init() { + + } + + public PointDouble() { + super(16); + init(); + } + + public PointDouble(double x, double y) { + super(16); + this.x = x; + this.y = y; + } + + protected PointDouble(ByteBuffer backing, int offset) { + super(backing, offset, 16); + init(); + } + + protected PointDouble(long nativeObj, boolean owned) { + super(nativeObj, owned, 16); + init(); + } + + protected void setBuffer(ByteBuffer backing, int offset) { + super.setBuffer(backing, offset, 16); + } + + public void read() { + x = backing.getDouble(0); + y = backing.getDouble(8); + } + + public void write() { + backing.putDouble(0, x); + backing.putDouble(8, y); + } + + public int size() { + return 16; + } + } + + public static class PointDoublePair extends DisposedStruct { + public PointDouble start; // The Start co-ordinate of the pair. + public PointDouble end; // The End co-ordinate of the pair. + + private void init() { + start = new PointDouble(backing, 0); + end = new PointDouble(backing, 16); + } + + public PointDoublePair() { + super(32); + init(); + } + + public PointDoublePair(PointDouble start, PointDouble end) { + super(32); + this.start = start; + this.end = end; + } + + protected PointDoublePair(ByteBuffer backing, int offset) { + super(backing, offset, 32); + init(); + } + + protected PointDoublePair(long nativeObj, boolean owned) { + super(nativeObj, owned, 32); + init(); + } + + protected void setBuffer(ByteBuffer backing, int offset) { + super.setBuffer(backing, offset, 32); + } + + public void read() { + start.read(); + end.read(); + } + + public void write() { + start.write(); + end.write(); + } + + public int size() { + return 32; + } + } + + public static class ClampResults extends DisposedStruct { + public double distancePix; // Defines the Pixel world distance. + public double distanceRealWorld; // Defines the real world distance. + public double angleAbs; // Defines the absolute angle. + public double angleRelative; // Defines the relative angle. + + private void init() { + + } + + public ClampResults() { + super(32); + init(); + } + + public ClampResults(double distancePix, double distanceRealWorld, double angleAbs, + double angleRelative) { + super(32); + this.distancePix = distancePix; + this.distanceRealWorld = distanceRealWorld; + this.angleAbs = angleAbs; + this.angleRelative = angleRelative; + } + + protected ClampResults(ByteBuffer backing, int offset) { + super(backing, offset, 32); + init(); + } + + protected ClampResults(long nativeObj, boolean owned) { + super(nativeObj, owned, 32); + init(); + } + + protected void setBuffer(ByteBuffer backing, int offset) { + super.setBuffer(backing, offset, 32); + } + + public void read() { + distancePix = backing.getDouble(0); + distanceRealWorld = backing.getDouble(8); + angleAbs = backing.getDouble(16); + angleRelative = backing.getDouble(24); + } + + public void write() { + backing.putDouble(0, distancePix); + backing.putDouble(8, distanceRealWorld); + backing.putDouble(16, angleAbs); + backing.putDouble(24, angleRelative); + } + + public int size() { + return 32; + } + } + + public static class ClampPoints extends DisposedStruct { + public PointDoublePair pixel; // Specifies the pixel world point pair for + // clamp. + public PointDoublePair realWorld; // Specifies the real world point pair for + // clamp. + + private void init() { + pixel = new PointDoublePair(backing, 0); + realWorld = new PointDoublePair(backing, 32); + } + + public ClampPoints() { + super(64); + init(); + } + + public ClampPoints(PointDoublePair pixel, PointDoublePair realWorld) { + super(64); + this.pixel = pixel; + this.realWorld = realWorld; + } + + protected ClampPoints(ByteBuffer backing, int offset) { + super(backing, offset, 64); + init(); + } + + protected ClampPoints(long nativeObj, boolean owned) { + super(nativeObj, owned, 64); + init(); + } + + protected void setBuffer(ByteBuffer backing, int offset) { + super.setBuffer(backing, offset, 64); + } + + public void read() { + pixel.read(); + realWorld.read(); + } + + public void write() { + pixel.write(); + realWorld.write(); + } + + public int size() { + return 64; + } + } + + public static class RGBValue extends DisposedStruct { + public short B; // The blue value of the color. + public short G; // The green value of the color. + public short R; // The red value of the color. + public short alpha; // The alpha value of the color, which represents extra + // information about a color image, such as gamma + // correction. + + private void init() { + + } + + public RGBValue() { + super(4); + init(); + } + + public RGBValue(int B, int G, int R, int alpha) { + super(4); + this.B = (short) B; + this.G = (short) G; + this.R = (short) R; + this.alpha = (short) alpha; + } + + protected RGBValue(ByteBuffer backing, int offset) { + super(backing, offset, 4); + init(); + } + + protected RGBValue(long nativeObj, boolean owned) { + super(nativeObj, owned, 4); + init(); + } + + protected void setBuffer(ByteBuffer backing, int offset) { + super.setBuffer(backing, offset, 4); + } + + public void read() { + B = (short) (backing.get(0) & 0xff); + G = (short) (backing.get(1) & 0xff); + R = (short) (backing.get(2) & 0xff); + alpha = (short) (backing.get(3) & 0xff); + } + + public void write() { + backing.put(0, (byte) (B & 0xff)); + backing.put(1, (byte) (G & 0xff)); + backing.put(2, (byte) (R & 0xff)); + backing.put(3, (byte) (alpha & 0xff)); + } + + public int size() { + return 4; + } + } + + public static class ClampOverlaySettings extends DisposedStruct { + public int showSearchArea; // If TRUE, the function overlays the search area + // on the image. + public int showCurves; // If TRUE, the function overlays the curves on the + // image. + public int showClampLocation; // If TRUE, the function overlays the clamp + // location on the image. + public int showResult; // If TRUE, the function overlays the hit lines to + // the object and the edge used to generate the hit + // line on the result image. + public RGBValue searchAreaColor; // Specifies the RGB color value to use to + // overlay the search area. + public RGBValue curvesColor; // Specifies the RGB color value to use to + // overlay the curves. + public RGBValue clampLocationsColor; // Specifies the RGB color value to use + // to overlay the clamp locations. + public RGBValue resultColor; // Specifies the RGB color value to use to + // overlay the results. + public String overlayGroupName; // Specifies the group overlay name for the + // step overlays. + private ByteBuffer overlayGroupName_buf; + + private void init() { + searchAreaColor = new RGBValue(backing, 16); + curvesColor = new RGBValue(backing, 20); + clampLocationsColor = new RGBValue(backing, 24); + resultColor = new RGBValue(backing, 28); + } + + public ClampOverlaySettings() { + super(36); + init(); + } + + public ClampOverlaySettings(int showSearchArea, int showCurves, int showClampLocation, + int showResult, RGBValue searchAreaColor, RGBValue curvesColor, + RGBValue clampLocationsColor, RGBValue resultColor, String overlayGroupName) { + super(36); + this.showSearchArea = showSearchArea; + this.showCurves = showCurves; + this.showClampLocation = showClampLocation; + this.showResult = showResult; + this.searchAreaColor = searchAreaColor; + this.curvesColor = curvesColor; + this.clampLocationsColor = clampLocationsColor; + this.resultColor = resultColor; + this.overlayGroupName = overlayGroupName; + } + + protected ClampOverlaySettings(ByteBuffer backing, int offset) { + super(backing, offset, 36); + init(); + } + + protected ClampOverlaySettings(long nativeObj, boolean owned) { + super(nativeObj, owned, 36); + init(); + } + + protected void setBuffer(ByteBuffer backing, int offset) { + super.setBuffer(backing, offset, 36); + } + + public void read() { + showSearchArea = backing.getInt(0); + showCurves = backing.getInt(4); + showClampLocation = backing.getInt(8); + showResult = backing.getInt(12); + searchAreaColor.read(); + curvesColor.read(); + clampLocationsColor.read(); + resultColor.read(); + long overlayGroupName_addr = getPointer(backing, 32); + if (overlayGroupName_addr == 0) + overlayGroupName = null; + else { + ByteBuffer bb = newDirectByteBuffer(overlayGroupName_addr, 1000); // FIXME + while (bb.get() != 0) { + } + byte[] bytes = new byte[bb.position() - 1]; + getBytes(bb, bytes, 0, bytes.length); try { - Class[] cArg = new Class[2]; - cArg[0] = long.class; - cArg[1] = int.class; - constructDirectByteBuffer = Class.forName("java.nio.DirectByteBuffer").getDeclaredConstructor(cArg); - constructDirectByteBuffer.setAccessible(true); - - bufferAddressField = Buffer.class.getDeclaredField("address"); - bufferAddressField.setAccessible(true); - } catch (ReflectiveOperationException e) { - throw new ExceptionInInitializerError(e); - } - } - - private static ByteBuffer newDirectByteBuffer(long addr, int cap) { - try { - return ((ByteBuffer)(constructDirectByteBuffer.newInstance(addr, cap))).order(ByteOrder.nativeOrder()); - } catch (ReflectiveOperationException e) { - throw new ExceptionInInitializerError(e); - } - } - - private static long getByteBufferAddress(ByteBuffer bb) { - try { - return bufferAddressField.getLong(bb); - } catch (IllegalAccessException e) { - return 0; - } - } - - public static ByteBuffer sliceByteBuffer(ByteBuffer bb, int offset, int size) { - int pos = bb.position(); - int lim = bb.limit(); - bb.position(offset); - bb.limit(offset+size); - ByteBuffer new_bb = bb.slice().order(ByteOrder.nativeOrder()); - bb.position(pos); - bb.limit(lim); - return new_bb; - } - - public static ByteBuffer getBytes(ByteBuffer bb, byte[] dst, int offset, int size) { - int pos = bb.position(); - bb.position(offset); - bb.get(dst, 0, size); - bb.position(pos); - return bb; - } - - public static ByteBuffer putBytes(ByteBuffer bb, byte[] src, int offset, int size) { - int pos = bb.position(); - bb.position(offset); - bb.put(src, 0, size); - bb.position(pos); - return bb; - } - - private static abstract class DisposedStruct { - protected ByteBuffer backing; - private boolean owned; - protected DisposedStruct(int size) { - backing = ByteBuffer.allocateDirect(size); - backing.order(ByteOrder.nativeOrder()); - owned = false; - } - protected DisposedStruct(ByteBuffer backing, int offset, int size) { - this.backing = sliceByteBuffer(backing, offset, size); - owned = false; - } - private DisposedStruct(long nativeObj, boolean owned, int size) { - backing = newDirectByteBuffer(nativeObj, size); - this.owned = owned; - } - public void free() { - if (owned) { - imaqDispose(getByteBufferAddress(backing)); - owned = false; - backing = null; - } - } - @Override - protected void finalize() throws Throwable { - if (owned) - imaqDispose(getByteBufferAddress(backing)); - super.finalize(); - } - public long getAddress() { - if (backing == null) - return 0; - write(); - return getByteBufferAddress(backing); - } - protected void setBuffer(ByteBuffer backing, int offset, int size) { - this.backing = sliceByteBuffer(backing, offset, size); - } - - abstract public void read(); - abstract public void write(); - abstract public int size(); - } - - private static abstract class OpaqueStruct { - private long nativeObj; - private boolean owned; - protected OpaqueStruct() { - nativeObj = 0; - owned = false; - } - protected OpaqueStruct(long nativeObj, boolean owned) { - this.nativeObj = nativeObj; - this.owned = owned; - } - public void free() { - if (owned && nativeObj != 0) { - imaqDispose(nativeObj); - owned = false; - nativeObj = 0; - } - } - @Override - protected void finalize() throws Throwable { - if (owned && nativeObj != 0) - imaqDispose(nativeObj); - super.finalize(); - } - public long getAddress() { - return nativeObj; - } - } - - public static class RawData { - private ByteBuffer buf; - private boolean owned; - public RawData() { - owned = false; - } - public RawData(ByteBuffer buf) { - this.buf = buf; - owned = false; - } - private RawData(long nativeObj, boolean owned, int size) { - buf = newDirectByteBuffer(nativeObj, size); - this.owned = owned; - } - public void free() { - if (owned) { - imaqDispose(getByteBufferAddress(buf)); - owned = false; - buf = null; - } - } - @Override - protected void finalize() throws Throwable { - if (owned) - imaqDispose(getByteBufferAddress(buf)); - super.finalize(); - } - public long getAddress() { - if (buf == null) - return 0; - return getByteBufferAddress(buf); - } - public ByteBuffer getBuffer() { - return buf; - } - public void setBuffer(ByteBuffer buf) { - if (owned) - free(); - this.buf = buf; - } - } - - private static long getPointer(ByteBuffer bb, int offset) { - return (long)bb.getInt(offset); - } - private static void putPointer(ByteBuffer bb, int offset, long address) { - bb.putInt(offset, (int)address); - } - private static void putPointer(ByteBuffer bb, int offset, ByteBuffer buf) { - if (buf == null) - bb.putInt(offset, 0); - else - bb.putInt(offset, (int)getByteBufferAddress(buf)); - } - private static void putPointer(ByteBuffer bb, int offset, DisposedStruct struct) { - if (struct == null) - bb.putInt(offset, 0); - else - bb.putInt(offset, (int)struct.getAddress()); - } - private static void putPointer(ByteBuffer bb, int offset, OpaqueStruct struct) { - if (struct == null) - bb.putInt(offset, 0); - else - bb.putInt(offset, (int)struct.getAddress()); - } - - /** - * Opaque Structures - */ - - public static class CharSet extends OpaqueStruct { - private CharSet() {} - private CharSet(long nativeObj, boolean owned) { - super(nativeObj, owned); - } - } - - public static class ClassifierSession extends OpaqueStruct { - private ClassifierSession() {} - private ClassifierSession(long nativeObj, boolean owned) { - super(nativeObj, owned); - } - } - - public static class Image extends OpaqueStruct { - private Image() {} - private Image(long nativeObj, boolean owned) { - super(nativeObj, owned); - } - } - - public static class MultipleGeometricPattern extends OpaqueStruct { - private MultipleGeometricPattern() {} - private MultipleGeometricPattern(long nativeObj, boolean owned) { - super(nativeObj, owned); - } - } - - public static class Overlay extends OpaqueStruct { - private Overlay() {} - private Overlay(long nativeObj, boolean owned) { - super(nativeObj, owned); - } - } - - public static class ROI extends OpaqueStruct { - private ROI() {} - private ROI(long nativeObj, boolean owned) { - super(nativeObj, owned); - } - } - - /** - * Manifest Constants - */ - public static final boolean DEFAULT_SHOW_COORDINATES = true; - public static final int DEFAULT_MAX_ICONS_PER_LINE = 4; - public static final boolean DEFAULT_BMP_COMPRESS = false; - public static final int DEFAULT_PNG_QUALITY = 750; - public static final int DEFAULT_JPEG_QUALITY = 750; - public static final int ALL_CONTOURS = -1; - public static final int ALL_WINDOWS = -1; - public static final int SHIFT = 1; - public static final int ALT = 2; - public static final int CTRL = 4; - public static final int CAPS_LOCK = 8; - public static final int MODAL_DIALOG = -1; - public static final int USE_DEFAULT_QUALITY = -1; - public static final int ALL_SAMPLES = -1; - public static final int ALL_OBJECTS = -1; - public static final int ALL_CHARACTERS = -1; - - /** - * Predefined Valid Characters - */ - public static final byte[] ANY_CHARACTER = { 0 }; - public static final byte[] ALPHABETIC = { 0x41,0x42,0x43,0x44,0x45,0x46,0x47,0x48,0x49,0x4a,0x4b,0x4c,0x4d,0x4e,0x4f,0x50,0x51,0x52,0x53,0x54,0x55,0x56,0x57,0x58,0x59,0x5a,0x61,0x62,0x63,0x64,0x65,0x66,0x67,0x68,0x69,0x6a,0x6b,0x6c,0x6d,0x6e,0x6f,0x70,0x71,0x72,0x73,0x74,0x75,0x76,0x77,0x78,0x79,0x7a,0 }; - public static final byte[] ALPHANUMERIC = { 0x41,0x42,0x43,0x44,0x45,0x46,0x47,0x48,0x49,0x4a,0x4b,0x4c,0x4d,0x4e,0x4f,0x50,0x51,0x52,0x53,0x54,0x55,0x56,0x57,0x58,0x59,0x5a,0x61,0x62,0x63,0x64,0x65,0x66,0x67,0x68,0x69,0x6a,0x6b,0x6c,0x6d,0x6e,0x6f,0x70,0x71,0x72,0x73,0x74,0x75,0x76,0x77,0x78,0x79,0x7a,0x30,0x31,0x32,0x33,0x34,0x35,0x36,0x37,0x38,0x39,0 }; - public static final byte[] UPPERCASE_LETTERS = { 0x41,0x42,0x43,0x44,0x45,0x46,0x47,0x48,0x49,0x4a,0x4b,0x4c,0x4d,0x4e,0x4f,0x50,0x51,0x52,0x53,0x54,0x55,0x56,0x57,0x58,0x59,0x5a,0 }; - public static final byte[] LOWERCASE_LETTERS = { 0x61,0x62,0x63,0x64,0x65,0x66,0x67,0x68,0x69,0x6a,0x6b,0x6c,0x6d,0x6e,0x6f,0x70,0x71,0x72,0x73,0x74,0x75,0x76,0x77,0x78,0x79,0x7a,0 }; - public static final byte[] DECIMAL_DIGITS = { 0x30,0x31,0x32,0x33,0x34,0x35,0x36,0x37,0x38,0x39,0 }; - public static final byte[] HEXADECIMAL_DIGITS = { 0x30,0x31,0x32,0x33,0x34,0x35,0x36,0x37,0x38,0x39,0x41,0x42,0x43,0x44,0x45,0x46,0x61,0x62,0x63,0x64,0x65,0x66,0 }; - public static final byte[] PATTERN = { 0x5c,0x78,0x46,0x46,0 }; - public static final byte[] FORCE_SPACE = { 0x20,0 }; - - /** - * Enumerated Types - */ - - public static enum PointSymbol { - POINT_AS_PIXEL(0), // A single pixel represents a point in the overlay. - POINT_AS_CROSS(1), // A cross represents a point in the overlay. - POINT_USER_DEFINED(2), // The pattern supplied by the user represents a point in the overlay. - ; - private final int value; - private PointSymbol(int value) { - this.value = value; - } - public static PointSymbol fromValue(int val) { - try { - return values()[val]; - } catch (ArrayIndexOutOfBoundsException e) { - return null; - } - } - public int getValue() { - return value; - } - } - - public static enum MeasurementValue { - AREA(0), // Surface area of the particle in pixels. - AREA_CALIBRATED(1), // Surface area of the particle in calibrated units. - NUM_HOLES(2), // Number of holes in the particle. - AREA_OF_HOLES(3), // Surface area of the holes in calibrated units. - TOTAL_AREA(4), // Total surface area (holes and particle) in calibrated units. - IMAGE_AREA(5), // Surface area of the entire image in calibrated units. - PARTICLE_TO_IMAGE(6), // Ratio, expressed as a percentage, of the surface area of a particle in relation to the total area of the particle. - PARTICLE_TO_TOTAL(7), // Ratio, expressed as a percentage, of the surface area of a particle in relation to the total area of the particle. - CENTER_MASS_X(8), // X-coordinate of the center of mass. - CENTER_MASS_Y(9), // Y-coordinate of the center of mass. - LEFT_COLUMN(10), // Left edge of the bounding rectangle. - TOP_ROW(11), // Top edge of the bounding rectangle. - RIGHT_COLUMN(12), // Right edge of the bounding rectangle. - BOTTOM_ROW(13), // Bottom edge of bounding rectangle. - WIDTH(14), // Width of bounding rectangle in calibrated units. - HEIGHT(15), // Height of bounding rectangle in calibrated units. - MAX_SEGMENT_LENGTH(16), // Length of longest horizontal line segment. - MAX_SEGMENT_LEFT_COLUMN(17), // Leftmost x-coordinate of longest horizontal line segment. - MAX_SEGMENT_TOP_ROW(18), // Y-coordinate of longest horizontal line segment. - PERIMETER(19), // Outer perimeter of the particle. - PERIMETER_OF_HOLES(20), // Perimeter of all holes within the particle. - SIGMA_X(21), // Sum of the particle pixels on the x-axis. - SIGMA_Y(22), // Sum of the particle pixels on the y-axis. - SIGMA_XX(23), // Sum of the particle pixels on the x-axis squared. - SIGMA_YY(24), // Sum of the particle pixels on the y-axis squared. - SIGMA_XY(25), // Sum of the particle pixels on the x-axis and y-axis. - PROJ_X(26), // Projection corrected in X. - PROJ_Y(27), // Projection corrected in Y. - INERTIA_XX(28), // Inertia matrix coefficient in XX. - INERTIA_YY(29), // Inertia matrix coefficient in YY. - INERTIA_XY(30), // Inertia matrix coefficient in XY. - MEAN_H(31), // Mean length of horizontal segments. - MEAN_V(32), // Mean length of vertical segments. - MAX_INTERCEPT(33), // Length of longest segment of the convex hull. - MEAN_INTERCEPT(34), // Mean length of the chords in an object perpendicular to its max intercept. - ORIENTATION(35), // The orientation based on the inertia of the pixels in the particle. - EQUIV_ELLIPSE_MINOR(36), // Total length of the axis of the ellipse having the same area as the particle and a major axis equal to half the max intercept. - ELLIPSE_MAJOR(37), // Total length of major axis having the same area and perimeter as the particle in calibrated units. - ELLIPSE_MINOR(38), // Total length of minor axis having the same area and perimeter as the particle in calibrated units. - ELLIPSE_RATIO(39), // Fraction of major axis to minor axis. - RECT_LONG_SIDE(40), // Length of the long side of a rectangle having the same area and perimeter as the particle in calibrated units. - RECT_SHORT_SIDE(41), // Length of the short side of a rectangle having the same area and perimeter as the particle in calibrated units. - RECT_RATIO(42), // Ratio of rectangle long side to rectangle short side. - ELONGATION(43), // Max intercept/mean perpendicular intercept. - COMPACTNESS(44), // Particle area/(height x width). - HEYWOOD(45), // Particle perimeter/perimeter of the circle having the same area as the particle. - TYPE_FACTOR(46), // A complex factor relating the surface area to the moment of inertia. - HYDRAULIC(47), // Particle area/particle perimeter. - WADDLE_DISK(48), // Diameter of the disk having the same area as the particle in user units. - DIAGONAL(49), // Diagonal of an equivalent rectangle in user units. - ; - private final int value; - private MeasurementValue(int value) { - this.value = value; - } - public static MeasurementValue fromValue(int val) { - try { - return values()[val]; - } catch (ArrayIndexOutOfBoundsException e) { - return null; - } - } - public int getValue() { - return value; - } - } - - public static enum ScalingMode { - SCALE_LARGER(0), // The function duplicates pixels to make the image larger. - SCALE_SMALLER(1), // The function subsamples pixels to make the image smaller. - ; - private final int value; - private ScalingMode(int value) { - this.value = value; - } - public static ScalingMode fromValue(int val) { - try { - return values()[val]; - } catch (ArrayIndexOutOfBoundsException e) { - return null; - } - } - public int getValue() { - return value; - } - } - - public static enum ScalingMethod { - SCALE_TO_PRESERVE_AREA(0), // Correction functions scale the image such that the features in the corrected image have the same area as the features in the input image. - SCALE_TO_FIT(1), // Correction functions scale the image such that the corrected image is the same size as the input image. - ; - private final int value; - private ScalingMethod(int value) { - this.value = value; - } - public static ScalingMethod fromValue(int val) { - try { - return values()[val]; - } catch (ArrayIndexOutOfBoundsException e) { - return null; - } - } - public int getValue() { - return value; - } - } - - public static enum ReferenceMode { - COORD_X_Y(0), // This method requires three elements in the points array. - COORD_ORIGIN_X(1), // This method requires two elements in the points array. - ; - private final int value; - private ReferenceMode(int value) { - this.value = value; - } - public static ReferenceMode fromValue(int val) { - try { - return values()[val]; - } catch (ArrayIndexOutOfBoundsException e) { - return null; - } - } - public int getValue() { - return value; - } - } - - public static enum RectOrientation { - BASE_INSIDE(0), // Specifies that the base of the rectangular image lies along the inside edge of the annulus. - BASE_OUTSIDE(1), // Specifies that the base of the rectangular image lies along the outside edge of the annulus. - ; - private final int value; - private RectOrientation(int value) { - this.value = value; - } - public static RectOrientation fromValue(int val) { - try { - return values()[val]; - } catch (ArrayIndexOutOfBoundsException e) { - return null; - } - } - public int getValue() { - return value; - } - } - - public static enum ShapeMode { - SHAPE_RECT(1), // The function draws a rectangle. - SHAPE_OVAL(2), // The function draws an oval. - ; - private final int value; - private ShapeMode(int value) { - this.value = value; - } - public static ShapeMode fromValue(int val) { - for (ShapeMode v : values()) { - if (v.value == val) - return v; - } - return null; - } - public int getValue() { - return value; - } - } - - public static enum PolarityType { - EDGE_RISING(1), // The edge is a rising edge. - EDGE_FALLING(-1), // The edge is a falling edge. - ; - private final int value; - private PolarityType(int value) { - this.value = value; - } - public static PolarityType fromValue(int val) { - for (PolarityType v : values()) { - if (v.value == val) - return v; - } - return null; - } - public int getValue() { - return value; - } - } - - public static enum SizeType { - KEEP_LARGE(0), // The function keeps large particles remaining after the erosion. - KEEP_SMALL(1), // The function keeps small particles eliminated by the erosion. - ; - private final int value; - private SizeType(int value) { - this.value = value; - } - public static SizeType fromValue(int val) { - try { - return values()[val]; - } catch (ArrayIndexOutOfBoundsException e) { - return null; - } - } - public int getValue() { - return value; - } - } - - public static enum Plane3D { - C3D_REAL(0), // The function shows the real part of complex images. - C3D_IMAGINARY(1), // The function shows the imaginary part of complex images. - C3D_MAGNITUDE(2), // The function shows the magnitude part of complex images. - C3D_PHASE(3), // The function shows the phase part of complex images. - ; - private final int value; - private Plane3D(int value) { - this.value = value; - } - public static Plane3D fromValue(int val) { - try { - return values()[val]; - } catch (ArrayIndexOutOfBoundsException e) { - return null; - } - } - public int getValue() { - return value; - } - } - - public static enum PhotometricMode { - WHITE_IS_ZERO(0), // The function interprets zero-value pixels as white. - BLACK_IS_ZERO(1), // The function interprets zero-value pixels as black. - ; - private final int value; - private PhotometricMode(int value) { - this.value = value; - } - public static PhotometricMode fromValue(int val) { - try { - return values()[val]; - } catch (ArrayIndexOutOfBoundsException e) { - return null; - } - } - public int getValue() { - return value; - } - } - - public static enum ParticleInfoMode { - BASIC_INFO(0), // The function returns only the following elements of each report: area, calibratedArea, boundingRect. - ALL_INFO(1), // The function returns all the information about each particle. - ; - private final int value; - private ParticleInfoMode(int value) { - this.value = value; - } - public static ParticleInfoMode fromValue(int val) { - try { - return values()[val]; - } catch (ArrayIndexOutOfBoundsException e) { - return null; - } - } - public int getValue() { - return value; - } - } - - public static enum OutlineMethod { - EDGE_DIFFERENCE(0), // The function uses a method that produces continuous contours by highlighting each pixel where an intensity variation occurs between itself and its three upper-left neighbors. - EDGE_GRADIENT(1), // The function uses a method that outlines contours where an intensity variation occurs along the vertical axis. - EDGE_PREWITT(2), // The function uses a method that extracts the outer contours of objects. - EDGE_ROBERTS(3), // The function uses a method that outlines the contours that highlight pixels where an intensity variation occurs along the diagonal axes. - EDGE_SIGMA(4), // The function uses a method that outlines contours and details by setting pixels to the mean value found in their neighborhood, if their deviation from this value is not significant. - EDGE_SOBEL(5), // The function uses a method that extracts the outer contours of objects. - ; - private final int value; - private OutlineMethod(int value) { - this.value = value; - } - public static OutlineMethod fromValue(int val) { - try { - return values()[val]; - } catch (ArrayIndexOutOfBoundsException e) { - return null; - } - } - public int getValue() { - return value; - } - } - - public static enum MorphologyMethod { - AUTOM(0), // The function uses a transformation that generates simpler particles that contain fewer details. - CLOSE(1), // The function uses a transformation that fills tiny holes and smooths boundaries. - DILATE(2), // The function uses a transformation that eliminates tiny holes isolated in particles and expands the contour of the particles according to the template defined by the structuring element. - ERODE(3), // The function uses a transformation that eliminates pixels isolated in the background and erodes the contour of particles according to the template defined by the structuring element. - GRADIENT(4), // The function uses a transformation that leaves only the pixels that would be added by the dilation process or eliminated by the erosion process. - GRADIENTOUT(5), // The function uses a transformation that leaves only the pixels that would be added by the dilation process. - GRADIENTIN(6), // The function uses a transformation that leaves only the pixels that would be eliminated by the erosion process. - HITMISS(7), // The function uses a transformation that extracts each pixel located in a neighborhood exactly matching the template defined by the structuring element. - OPEN(8), // The function uses a transformation that removes small particles and smooths boundaries. - PCLOSE(9), // The function uses a transformation that fills tiny holes and smooths the inner contour of particles according to the template defined by the structuring element. - POPEN(10), // The function uses a transformation that removes small particles and smooths the contour of particles according to the template defined by the structuring element. - THICK(11), // The function uses a transformation that adds to an image those pixels located in a neighborhood that matches a template specified by the structuring element. - THIN(12), // The function uses a transformation that eliminates pixels that are located in a neighborhood matching a template specified by the structuring element. - ; - private final int value; - private MorphologyMethod(int value) { - this.value = value; - } - public static MorphologyMethod fromValue(int val) { - try { - return values()[val]; - } catch (ArrayIndexOutOfBoundsException e) { - return null; - } - } - public int getValue() { - return value; - } - } - - public static enum MeterArcMode { - METER_ARC_ROI(0), // The function uses the roi parameter and ignores the base, start, and end parameters. - METER_ARC_POINTS(1), // The function uses the base,start, and end parameters and ignores the roi parameter. - ; - private final int value; - private MeterArcMode(int value) { - this.value = value; - } - public static MeterArcMode fromValue(int val) { - try { - return values()[val]; - } catch (ArrayIndexOutOfBoundsException e) { - return null; - } - } - public int getValue() { - return value; - } - } - - public static enum RakeDirection { - LEFT_TO_RIGHT(0), // The function searches from the left side of the search area to the right side of the search area. - RIGHT_TO_LEFT(1), // The function searches from the right side of the search area to the left side of the search area. - TOP_TO_BOTTOM(2), // The function searches from the top side of the search area to the bottom side of the search area. - BOTTOM_TO_TOP(3), // The function searches from the bottom side of the search area to the top side of the search area. - ; - private final int value; - private RakeDirection(int value) { - this.value = value; - } - public static RakeDirection fromValue(int val) { - try { - return values()[val]; - } catch (ArrayIndexOutOfBoundsException e) { - return null; - } - } - public int getValue() { - return value; - } - } - - public static enum TruncateMode { - TRUNCATE_LOW(0), // The function truncates low frequencies. - TRUNCATE_HIGH(1), // The function truncates high frequencies. - ; - private final int value; - private TruncateMode(int value) { - this.value = value; - } - public static TruncateMode fromValue(int val) { - try { - return values()[val]; - } catch (ArrayIndexOutOfBoundsException e) { - return null; - } - } - public int getValue() { - return value; - } - } - - public static enum AttenuateMode { - ATTENUATE_LOW(0), // The function attenuates low frequencies. - ATTENUATE_HIGH(1), // The function attenuates high frequencies. - ; - private final int value; - private AttenuateMode(int value) { - this.value = value; - } - public static AttenuateMode fromValue(int val) { - try { - return values()[val]; - } catch (ArrayIndexOutOfBoundsException e) { - return null; - } - } - public int getValue() { - return value; - } - } - - public static enum WindowThreadPolicy { - CALLING_THREAD(0), // Using this policy, NI Vision creates windows in the thread that makes the first display function call for a given window number. - SEPARATE_THREAD(1), // Using this policy, NI Vision creates windows in a separate thread and processes messages for the windows automatically. - ; - private final int value; - private WindowThreadPolicy(int value) { - this.value = value; - } - public static WindowThreadPolicy fromValue(int val) { - try { - return values()[val]; - } catch (ArrayIndexOutOfBoundsException e) { - return null; - } - } - public int getValue() { - return value; - } - } - - public static enum WindowOptions { - WIND_RESIZABLE(1), // When present, the user may resize the window interactively. - WIND_TITLEBAR(2), // When present, the title bar on the window is visible. - WIND_CLOSEABLE(4), // When present, the close box is available. - WIND_TOPMOST(8), // When present, the window is always on top. - ; - private final int value; - private WindowOptions(int value) { - this.value = value; - } - public static WindowOptions fromValue(int val) { - for (WindowOptions v : values()) { - if (v.value == val) - return v; - } - return null; - } - public int getValue() { - return value; - } - } - - public static enum WindowEventType { - NO_EVENT(0), // No event occurred since the last call to imaqGetLastEvent(). - CLICK_EVENT(1), // The user clicked on a window. - DRAW_EVENT(2), // The user drew an ROI in a window. - MOVE_EVENT(3), // The user moved a window. - SIZE_EVENT(4), // The user sized a window. - SCROLL_EVENT(5), // The user scrolled a window. - ACTIVATE_EVENT(6), // The user activated a window. - CLOSE_EVENT(7), // The user closed a window. - DOUBLE_CLICK_EVENT(8), // The user double-clicked in a window. - ; - private final int value; - private WindowEventType(int value) { - this.value = value; - } - public static WindowEventType fromValue(int val) { - try { - return values()[val]; - } catch (ArrayIndexOutOfBoundsException e) { - return null; - } - } - public int getValue() { - return value; - } - } - - public static enum VisionInfoType { - ANY_VISION_INFO(0), // The function checks if any extra vision information is associated with the image. - PATTERN_MATCHING_INFO(1), // The function checks if any pattern matching template information is associated with the image. - CALIBRATION_INFO(2), // The function checks if any calibration information is associated with the image. - OVERLAY_INFO(3), // The function checks if any overlay information is associated with the image. - ; - private final int value; - private VisionInfoType(int value) { - this.value = value; - } - public static VisionInfoType fromValue(int val) { - try { - return values()[val]; - } catch (ArrayIndexOutOfBoundsException e) { - return null; - } - } - public int getValue() { - return value; - } - } - - public static enum SearchStrategy { - CONSERVATIVE(1), // Instructs the pattern matching algorithm to use the largest possible amount of information from the image at the expense of slowing down the speed of the algorithm. - BALANCED(2), // Instructs the pattern matching algorithm to balance the amount of information from the image it uses with the speed of the algorithm. - AGGRESSIVE(3), // Instructs the pattern matching algorithm to use a lower amount of information from the image, which allows the algorithm to run quickly but at the expense of accuracy. - VERY_AGGRESSIVE(4), // Instructs the pattern matching algorithm to use the smallest possible amount of information from the image, which allows the algorithm to run at the highest speed possible but at the expense of accuracy. - ; - private final int value; - private SearchStrategy(int value) { - this.value = value; - } - public static SearchStrategy fromValue(int val) { - for (SearchStrategy v : values()) { - if (v.value == val) - return v; - } - return null; - } - public int getValue() { - return value; - } - } - - public static enum TwoEdgePolarityType { - NONE(0), // The function ignores the polarity of the edges. - RISING_FALLING(1), // The polarity of the first edge is rising (dark to light) and the polarity of the second edge is falling (light to dark). - FALLING_RISING(2), // The polarity of the first edge is falling (light to dark) and the polarity of the second edge is rising (dark to light). - RISING_RISING(3), // The polarity of the first edge is rising (dark to light) and the polarity of the second edge is rising (dark to light). - FALLING_FALLING(4), // The polarity of the first edge is falling (light to dark) and the polarity of the second edge is falling (light to dark). - ; - private final int value; - private TwoEdgePolarityType(int value) { - this.value = value; - } - public static TwoEdgePolarityType fromValue(int val) { - try { - return values()[val]; - } catch (ArrayIndexOutOfBoundsException e) { - return null; - } - } - public int getValue() { - return value; - } - } - - public static enum ObjectType { - BRIGHT_OBJECTS(0), // The function detects bright objects. - DARK_OBJECTS(1), // The function detects dark objects. - ; - private final int value; - private ObjectType(int value) { - this.value = value; - } - public static ObjectType fromValue(int val) { - try { - return values()[val]; - } catch (ArrayIndexOutOfBoundsException e) { - return null; - } - } - public int getValue() { - return value; - } - } - - public static enum Tool { - NO_TOOL(-1), // No tool is in the selected state. - SELECTION_TOOL(0), // The selection tool selects an existing ROI in an image. - POINT_TOOL(1), // The point tool draws a point on the image. - LINE_TOOL(2), // The line tool draws a line on the image. - RECTANGLE_TOOL(3), // The rectangle tool draws a rectangle on the image. - OVAL_TOOL(4), // The oval tool draws an oval on the image. - POLYGON_TOOL(5), // The polygon tool draws a polygon on the image. - CLOSED_FREEHAND_TOOL(6), // The closed freehand tool draws closed freehand shapes on the image. - ANNULUS_TOOL(7), // The annulus tool draws annuluses on the image. - ZOOM_TOOL(8), // The zoom tool controls the zoom of an image. - PAN_TOOL(9), // The pan tool shifts the view of the image. - POLYLINE_TOOL(10), // The polyline tool draws a series of connected straight lines on the image. - FREEHAND_TOOL(11), // The freehand tool draws freehand lines on the image. - ROTATED_RECT_TOOL(12), // The rotated rectangle tool draws rotated rectangles on the image. - ZOOM_OUT_TOOL(13), // The zoom out tool controls the zoom of an image. - ; - private final int value; - private Tool(int value) { - this.value = value; - } - public static Tool fromValue(int val) { - for (Tool v : values()) { - if (v.value == val) - return v; - } - return null; - } - public int getValue() { - return value; - } - } - - public static enum TIFFCompressionType { - NO_COMPRESSION(0), // The function does not compress the TIFF file. - JPEG(1), // The function uses the JPEG compression algorithm to compress the TIFF file. - RUN_LENGTH(2), // The function uses a run length compression algorithm to compress the TIFF file. - ZIP(3), // The function uses the ZIP compression algorithm to compress the TIFF file. - ; - private final int value; - private TIFFCompressionType(int value) { - this.value = value; - } - public static TIFFCompressionType fromValue(int val) { - try { - return values()[val]; - } catch (ArrayIndexOutOfBoundsException e) { - return null; - } - } - public int getValue() { - return value; - } - } - - public static enum ThresholdMethod { - THRESH_CLUSTERING(0), // The function uses a method that sorts the histogram of the image within a discrete number of classes corresponding to the number of phases perceived in an image. - THRESH_ENTROPY(1), // The function uses a method that is best for detecting particles that are present in minuscule proportions on the image. - THRESH_METRIC(2), // The function uses a method that is well-suited for images in which classes are not too disproportionate. - THRESH_MOMENTS(3), // The function uses a method that is suited for images that have poor contrast. - THRESH_INTERCLASS(4), // The function uses a method that is well-suited for images in which classes have well separated pixel value distributions. - ; - private final int value; - private ThresholdMethod(int value) { - this.value = value; - } - public static ThresholdMethod fromValue(int val) { - try { - return values()[val]; - } catch (ArrayIndexOutOfBoundsException e) { - return null; - } - } - public int getValue() { - return value; - } - } - - public static enum TextAlignment { - LEFT(0), // Left aligns the text at the reference point. - CENTER(1), // Centers the text around the reference point. - RIGHT(2), // Right aligns the text at the reference point. - ; - private final int value; - private TextAlignment(int value) { - this.value = value; - } - public static TextAlignment fromValue(int val) { - try { - return values()[val]; - } catch (ArrayIndexOutOfBoundsException e) { - return null; - } - } - public int getValue() { - return value; - } - } - - public static enum SpokeDirection { - OUTSIDE_TO_INSIDE(0), // The function searches from the outside of the search area to the inside of the search area. - INSIDE_TO_OUTSIDE(1), // The function searches from the inside of the search area to the outside of the search area. - ; - private final int value; - private SpokeDirection(int value) { - this.value = value; - } - public static SpokeDirection fromValue(int val) { - try { - return values()[val]; - } catch (ArrayIndexOutOfBoundsException e) { - return null; - } - } - public int getValue() { - return value; - } - } - - public static enum SkeletonMethod { - SKELETON_L(0), // Uses an L-shaped structuring element in the skeleton function. - SKELETON_M(1), // Uses an M-shaped structuring element in the skeleton function. - SKELETON_INVERSE(2), // Uses an L-shaped structuring element on an inverse of the image in the skeleton function. - ; - private final int value; - private SkeletonMethod(int value) { - this.value = value; - } - public static SkeletonMethod fromValue(int val) { - try { - return values()[val]; - } catch (ArrayIndexOutOfBoundsException e) { - return null; - } - } - public int getValue() { - return value; - } - } - - public static enum VerticalTextAlignment { - BOTTOM(0), // Aligns the bottom of the text at the reference point. - TOP(1), // Aligns the top of the text at the reference point. - BASELINE(2), // Aligns the baseline of the text at the reference point. - ; - private final int value; - private VerticalTextAlignment(int value) { - this.value = value; - } - public static VerticalTextAlignment fromValue(int val) { - try { - return values()[val]; - } catch (ArrayIndexOutOfBoundsException e) { - return null; - } - } - public int getValue() { - return value; - } - } - - public static enum CalibrationROI { - FULL_IMAGE(0), // The correction function corrects the whole image, regardless of the user-defined or calibration-defined ROIs. - CALIBRATION_ROI(1), // The correction function corrects the area defined by the calibration ROI. - USER_ROI(2), // The correction function corrects the area defined by the user-defined ROI. - CALIBRATION_AND_USER_ROI(3), // The correction function corrects the area defined by the intersection of the user-defined ROI and the calibration ROI. - CALIBRATION_OR_USER_ROI(4), // The correction function corrects the area defined by the union of the user-defined ROI and the calibration ROI. - ; - private final int value; - private CalibrationROI(int value) { - this.value = value; - } - public static CalibrationROI fromValue(int val) { - try { - return values()[val]; - } catch (ArrayIndexOutOfBoundsException e) { - return null; - } - } - public int getValue() { - return value; - } - } - - public static enum ContourType { - EMPTY_CONTOUR(0), // The contour is empty. - POINT(1), // The contour represents a point. - LINE(2), // The contour represents a line. - RECT(3), // The contour represents a rectangle. - OVAL(4), // The contour represents an oval. - CLOSED_CONTOUR(5), // The contour represents a series of connected points where the last point connects to the first. - OPEN_CONTOUR(6), // The contour represents a series of connected points where the last point does not connect to the first. - ANNULUS(7), // The contour represents an annulus. - ROTATED_RECT(8), // The contour represents a rotated rectangle. - ; - private final int value; - private ContourType(int value) { - this.value = value; - } - public static ContourType fromValue(int val) { - try { - return values()[val]; - } catch (ArrayIndexOutOfBoundsException e) { - return null; - } - } - public int getValue() { - return value; - } - } - - public static enum MathTransformMethod { - TRANSFORM_LINEAR(0), // The function uses linear remapping. - TRANSFORM_LOG(1), // The function uses logarithmic remapping. - TRANSFORM_EXP(2), // The function uses exponential remapping. - TRANSFORM_SQR(3), // The function uses square remapping. - TRANSFORM_SQRT(4), // The function uses square root remapping. - TRANSFORM_POWX(5), // The function uses power X remapping. - TRANSFORM_POW1X(6), // The function uses power 1/X remapping. - ; - private final int value; - private MathTransformMethod(int value) { - this.value = value; - } - public static MathTransformMethod fromValue(int val) { - try { - return values()[val]; - } catch (ArrayIndexOutOfBoundsException e) { - return null; - } - } - public int getValue() { - return value; - } - } - - public static enum ComplexPlane { - REAL(0), // The function operates on the real plane of the complex image. - IMAGINARY(1), // The function operates on the imaginary plane of the complex image. - MAGNITUDE(2), // The function operates on the magnitude plane of the complex image. - PHASE(3), // The function operates on the phase plane of the complex image. - ; - private final int value; - private ComplexPlane(int value) { - this.value = value; - } - public static ComplexPlane fromValue(int val) { - try { - return values()[val]; - } catch (ArrayIndexOutOfBoundsException e) { - return null; - } - } - public int getValue() { - return value; - } - } - - public static enum PaletteType { - PALETTE_GRAY(0), // The function uses a palette that has a gradual gray-level variation from black to white. - PALETTE_BINARY(1), // The function uses a palette of 16 cycles of 16 different colors that is useful with binary images. - PALETTE_GRADIENT(2), // The function uses a palette that has a gradation from red to white with a prominent range of light blue in the upper value range. - PALETTE_RAINBOW(3), // The function uses a palette that has a gradation from blue to red with a prominent range of greens in the middle value range. - PALETTE_TEMPERATURE(4), // The function uses a palette that has a gradation from light brown to dark brown. - PALETTE_USER(5), // The function uses a palette defined by the user. - ; - private final int value; - private PaletteType(int value) { - this.value = value; - } - public static PaletteType fromValue(int val) { - try { - return values()[val]; - } catch (ArrayIndexOutOfBoundsException e) { - return null; - } - } - public int getValue() { - return value; - } - } - - public static enum ColorSensitivity { - SENSITIVITY_LOW(0), // Instructs the algorithm to divide the hue plane into a low number of sectors, allowing for simple color analysis. - SENSITIVITY_MED(1), // Instructs the algorithm to divide the hue plane into a medium number of sectors, allowing for color analysis that balances sensitivity and complexity. - SENSITIVITY_HIGH(2), // Instructs the algorithm to divide the hue plane into a high number of sectors, allowing for complex, sensitive color analysis. - ; - private final int value; - private ColorSensitivity(int value) { - this.value = value; - } - public static ColorSensitivity fromValue(int val) { - try { - return values()[val]; - } catch (ArrayIndexOutOfBoundsException e) { - return null; - } - } - public int getValue() { - return value; - } - } - - public static enum ColorMode { - RGB(0), // The function operates in the RGB (Red, Blue, Green) color space. - HSL(1), // The function operates in the HSL (Hue, Saturation, Luminance) color space. - HSV(2), // The function operates in the HSV (Hue, Saturation, Value) color space. - HSI(3), // The function operates in the HSI (Hue, Saturation, Intensity) color space. - CIE(4), // The function operates in the CIE L*a*b* color space. - CIEXYZ(5), // The function operates in the CIE XYZ color space. - ; - private final int value; - private ColorMode(int value) { - this.value = value; - } - public static ColorMode fromValue(int val) { - try { - return values()[val]; - } catch (ArrayIndexOutOfBoundsException e) { - return null; - } - } - public int getValue() { - return value; - } - } - - public static enum DetectionMode { - DETECT_PEAKS(0), // The function detects peaks. - DETECT_VALLEYS(1), // The function detects valleys. - ; - private final int value; - private DetectionMode(int value) { - this.value = value; - } - public static DetectionMode fromValue(int val) { - try { - return values()[val]; - } catch (ArrayIndexOutOfBoundsException e) { - return null; - } - } - public int getValue() { - return value; - } - } - - public static enum CalibrationUnit { - UNDEFINED(0), // The image does not have a defined unit of measurement. - ANGSTROM(1), // The unit of measure for the image is angstroms. - MICROMETER(2), // The unit of measure for the image is micrometers. - MILLIMETER(3), // The unit of measure for the image is millimeters. - CENTIMETER(4), // The unit of measure for the image is centimeters. - METER(5), // The unit of measure for the image is meters. - KILOMETER(6), // The unit of measure for the image is kilometers. - MICROINCH(7), // The unit of measure for the image is microinches. - INCH(8), // The unit of measure for the image is inches. - FOOT(9), // The unit of measure for the image is feet. - NAUTICMILE(10), // The unit of measure for the image is nautical miles. - GROUNDMILE(11), // The unit of measure for the image is ground miles. - STEP(12), // The unit of measure for the image is steps. - ; - private final int value; - private CalibrationUnit(int value) { - this.value = value; - } - public static CalibrationUnit fromValue(int val) { - try { - return values()[val]; - } catch (ArrayIndexOutOfBoundsException e) { - return null; - } - } - public int getValue() { - return value; - } - } - - public static enum ConcentricRakeDirection { - COUNTER_CLOCKWISE(0), // The function searches the search area in a counter-clockwise direction. - CLOCKWISE(1), // The function searches the search area in a clockwise direction. - ; - private final int value; - private ConcentricRakeDirection(int value) { - this.value = value; - } - public static ConcentricRakeDirection fromValue(int val) { - try { - return values()[val]; - } catch (ArrayIndexOutOfBoundsException e) { - return null; - } - } - public int getValue() { - return value; - } - } - - public static enum CalibrationMode { - PERSPECTIVE(0), // Functions correct for distortion caused by the camera's perspective. - NONLINEAR(1), // Functions correct for distortion caused by the camera's lens. - SIMPLE_CALIBRATION(2), // Functions do not correct for distortion. - CORRECTED_IMAGE(3), // The image is already corrected. - ; - private final int value; - private CalibrationMode(int value) { - this.value = value; - } - public static CalibrationMode fromValue(int val) { - try { - return values()[val]; - } catch (ArrayIndexOutOfBoundsException e) { - return null; - } - } - public int getValue() { - return value; - } - } - - public static enum BrowserLocation { - INSERT_FIRST_FREE(0), // Inserts the thumbnail in the first available cell. - INSERT_END(1), // Inserts the thumbnail after the last occupied cell. - ; - private final int value; - private BrowserLocation(int value) { - this.value = value; - } - public static BrowserLocation fromValue(int val) { - try { - return values()[val]; - } catch (ArrayIndexOutOfBoundsException e) { - return null; - } - } - public int getValue() { - return value; - } - } - - public static enum BrowserFrameStyle { - RAISED_FRAME(0), // Each thumbnail has a raised frame. - BEVELLED_FRAME(1), // Each thumbnail has a beveled frame. - OUTLINE_FRAME(2), // Each thumbnail has an outlined frame. - HIDDEN_FRAME(3), // Each thumbnail has a hidden frame. - STEP_FRAME(4), // Each thumbnail has a stepped frame. - RAISED_OUTLINE_FRAME(5), // Each thumbnail has a raised, outlined frame. - ; - private final int value; - private BrowserFrameStyle(int value) { - this.value = value; - } - public static BrowserFrameStyle fromValue(int val) { - try { - return values()[val]; - } catch (ArrayIndexOutOfBoundsException e) { - return null; - } - } - public int getValue() { - return value; - } - } - - public static enum BorderMethod { - BORDER_MIRROR(0), // Symmetrically copies pixel values from the image into the border. - BORDER_COPY(1), // Copies the value of the pixel closest to the edge of the image into the border. - BORDER_CLEAR(2), // Sets all pixels in the border to 0. - ; - private final int value; - private BorderMethod(int value) { - this.value = value; - } - public static BorderMethod fromValue(int val) { - try { - return values()[val]; - } catch (ArrayIndexOutOfBoundsException e) { - return null; - } - } - public int getValue() { - return value; - } - } - - public static enum BarcodeType { - INVALID(-1), // The barcode is not of a type known by NI Vision. - CODABAR(1), // The barcode is of type Codabar. - CODE39(2), // The barcode is of type Code 39. - CODE93(4), // The barcode is of type Code 93. - CODE128(8), // The barcode is of type Code 128. - EAN8(16), // The barcode is of type EAN 8. - EAN13(32), // The barcode is of type EAN 13. - I2_OF_5(64), // The barcode is of type Code 25. - MSI(128), // The barcode is of type MSI code. - UPCA(256), // The barcode is of type UPC A. - PHARMACODE(512), // The barcode is of type Pharmacode. - RSS_LIMITED(1024), // The barcode is of type RSS Limited. - ; - private final int value; - private BarcodeType(int value) { - this.value = value; - } - public static BarcodeType fromValue(int val) { - for (BarcodeType v : values()) { - if (v.value == val) - return v; - } - return null; - } - public int getValue() { - return value; - } - } - - public static enum AxisOrientation { - DIRECT(0), // The y-axis direction corresponds to the y-axis direction of the Cartesian coordinate system. - INDIRECT(1), // The y-axis direction corresponds to the y-axis direction of an image. - ; - private final int value; - private AxisOrientation(int value) { - this.value = value; - } - public static AxisOrientation fromValue(int val) { - try { - return values()[val]; - } catch (ArrayIndexOutOfBoundsException e) { - return null; - } - } - public int getValue() { - return value; - } - } - - public static enum ColorIgnoreMode { - IGNORE_NONE(0), // Specifies that the function does not ignore any pixels. - IGNORE_BLACK(1), // Specifies that the function ignores black pixels. - IGNORE_WHITE(2), // Specifies that the function ignores white pixels. - IGNORE_BLACK_AND_WHITE(3), // Specifies that the function ignores black pixels and white pixels. - ; - private final int value; - private ColorIgnoreMode(int value) { - this.value = value; - } - public static ColorIgnoreMode fromValue(int val) { - try { - return values()[val]; - } catch (ArrayIndexOutOfBoundsException e) { - return null; - } - } - public int getValue() { - return value; - } - } - - public static enum LevelType { - ABSOLUTE(0), // The function evaluates the threshold and hysteresis values as absolute values. - RELATIVE(1), // The function evaluates the threshold and hysteresis values relative to the dynamic range of the given path. - ; - private final int value; - private LevelType(int value) { - this.value = value; - } - public static LevelType fromValue(int val) { - try { - return values()[val]; - } catch (ArrayIndexOutOfBoundsException e) { - return null; - } - } - public int getValue() { - return value; - } - } - - public static enum MatchingMode { - MATCH_SHIFT_INVARIANT(1), // Searches for occurrences of the template image anywhere in the searchRect, assuming that the pattern is not rotated more than plus or minus 4 degrees. - MATCH_ROTATION_INVARIANT(2), // Searches for occurrences of the pattern in the image with no restriction on the rotation of the pattern. - ; - private final int value; - private MatchingMode(int value) { - this.value = value; - } - public static MatchingMode fromValue(int val) { - for (MatchingMode v : values()) { - if (v.value == val) - return v; - } - return null; - } - public int getValue() { - return value; - } - } - - public static enum MappingMethod { - FULL_DYNAMIC(0), // (Obsolete) When the image bit depth is 0, the function maps the full dynamic range of the 16-bit image to an 8-bit scale. - DOWNSHIFT(1), // (Obsolete) When the image bit depth is 0, the function shifts the 16-bit image pixels to the right the number of times specified by the shiftCount element of the DisplayMapping structure. - RANGE(2), // (Obsolete) When the image bit depth is 0, the function maps the pixel values in the range specified by the minimumValue and maximumValue elements of the DisplayMapping structure to an 8-bit scale. - C90_PCT_DYNAMIC(3), // (Obsolete) When the image bit depth to 0, the function maps the dynamic range containing the middle 90 percent of the cumulated histogram of the image to an 8-bit (256 grayscale values) scale. - PERCENT_RANGE(4), // (Obsolete) When the image bit depth is 0, the function maps the pixel values in the relative percentage range (0 to 100) of the cumulated histogram specified by minimumValue and maximumValue to an 8-bit scale. - DEFAULT_MAPPING(10), // If the bit depth is 0, the function maps the 16-bit image to 8 bits by following the IMAQ_FULL_DYNAMIC_ALWAYS behavior; otherwise, the function shifts the image data to the right according to the IMAQ_MOST_SIGNIFICANT behavior. - MOST_SIGNIFICANT(11), // The function shifts the 16-bit image pixels to the right until the 8 most significant bits of the image data are remaining. - FULL_DYNAMIC_ALWAYS(12), // The function maps the full dynamic range of the 16-bit image to an 8-bit scale. - DOWNSHIFT_ALWAYS(13), // The function shifts the 16-bit image pixels to the right the number of times specified by the shiftCount element of the DisplayMapping structure. - RANGE_ALWAYS(14), // The function maps the pixel values in the range specified by the minimumValue and maximumValue elements of the DisplayMapping structure to an 8-bit scale. - C90_PCT_DYNAMIC_ALWAYS(15), // The function maps the dynamic range containing the middle 90 percent of the cumulated histogram of the image to an 8-bit (256 grayscale values) scale. - PERCENT_RANGE_ALWAYS(16), // The function maps the pixel values in the relative percentage range (0 to 100) of the cumulated histogram specified by minimumValue and maximumValue to an 8-bit scale. - ; - private final int value; - private MappingMethod(int value) { - this.value = value; - } - public static MappingMethod fromValue(int val) { - for (MappingMethod v : values()) { - if (v.value == val) - return v; - } - return null; - } - public int getValue() { - return value; - } - } - - public static enum ComparisonFunction { - CLEAR_LESS(0), // The comparison is true if the source pixel value is less than the comparison image pixel value. - CLEAR_LESS_OR_EQUAL(1), // The comparison is true if the source pixel value is less than or equal to the comparison image pixel value. - CLEAR_EQUAL(2), // The comparison is true if the source pixel value is equal to the comparison image pixel value. - CLEAR_GREATER_OR_EQUAL(3), // The comparison is true if the source pixel value is greater than or equal to the comparison image pixel value. - CLEAR_GREATER(4), // The comparison is true if the source pixel value is greater than the comparison image pixel value. - ; - private final int value; - private ComparisonFunction(int value) { - this.value = value; - } - public static ComparisonFunction fromValue(int val) { - try { - return values()[val]; - } catch (ArrayIndexOutOfBoundsException e) { - return null; - } - } - public int getValue() { - return value; - } - } - - public static enum LineGaugeMethod { - EDGE_TO_EDGE(0), // Measures from the first edge on the line to the last edge on the line. - EDGE_TO_POINT(1), // Measures from the first edge on the line to the end point of the line. - POINT_TO_EDGE(2), // Measures from the start point of the line to the first edge on the line. - POINT_TO_POINT(3), // Measures from the start point of the line to the end point of the line. - ; - private final int value; - private LineGaugeMethod(int value) { - this.value = value; - } - public static LineGaugeMethod fromValue(int val) { - try { - return values()[val]; - } catch (ArrayIndexOutOfBoundsException e) { - return null; - } - } - public int getValue() { - return value; - } - } - - public static enum Direction3D { - C3D_NW(0), // The viewing angle for the 3D image is from the northwest. - C3D_SW(1), // The viewing angle for the 3D image is from the southwest. - C3D_SE(2), // The viewing angle for the 3D image is from the southeast. - C3D_NE(3), // The viewing angle for the 3D image is from the northeast. - ; - private final int value; - private Direction3D(int value) { - this.value = value; - } - public static Direction3D fromValue(int val) { - try { - return values()[val]; - } catch (ArrayIndexOutOfBoundsException e) { - return null; - } - } - public int getValue() { - return value; - } - } - - public static enum LearningMode { - LEARN_ALL(0), // The function extracts information for shift- and rotation-invariant matching. - LEARN_SHIFT_INFORMATION(1), // The function extracts information for shift-invariant matching. - LEARN_ROTATION_INFORMATION(2), // The function extracts information for rotation-invariant matching. - ; - private final int value; - private LearningMode(int value) { - this.value = value; - } - public static LearningMode fromValue(int val) { - try { - return values()[val]; - } catch (ArrayIndexOutOfBoundsException e) { - return null; - } - } - public int getValue() { - return value; - } - } - - public static enum KernelFamily { - GRADIENT_FAMILY(0), // The kernel is in the gradient family. - LAPLACIAN_FAMILY(1), // The kernel is in the Laplacian family. - SMOOTHING_FAMILY(2), // The kernel is in the smoothing family. - GAUSSIAN_FAMILY(3), // The kernel is in the Gaussian family. - ; - private final int value; - private KernelFamily(int value) { - this.value = value; - } - public static KernelFamily fromValue(int val) { - try { - return values()[val]; - } catch (ArrayIndexOutOfBoundsException e) { - return null; - } - } - public int getValue() { - return value; - } - } - - public static enum InterpolationMethod { - ZERO_ORDER(0), // The function uses an interpolation method that interpolates new pixel values using the nearest valid neighboring pixel. - BILINEAR(1), // The function uses an interpolation method that interpolates new pixel values using a bidirectional average of the neighboring pixels. - QUADRATIC(2), // The function uses an interpolation method that interpolates new pixel values using a quadratic approximating polynomial. - CUBIC_SPLINE(3), // The function uses an interpolation method that interpolates new pixel values by fitting them to a cubic spline curve, where the curve is based on known pixel values from the image. - BILINEAR_FIXED(4), // The function uses an interpolation method that interpolates new pixel values using a bidirectional average of the neighboring pixels. - ; - private final int value; - private InterpolationMethod(int value) { - this.value = value; - } - public static InterpolationMethod fromValue(int val) { - try { - return values()[val]; - } catch (ArrayIndexOutOfBoundsException e) { - return null; - } - } - public int getValue() { - return value; - } - } - - public static enum ImageType { - IMAGE_U8(0), // The image type is 8-bit unsigned integer grayscale. - IMAGE_U16(7), // The image type is 16-bit unsigned integer grayscale. - IMAGE_I16(1), // The image type is 16-bit signed integer grayscale. - IMAGE_SGL(2), // The image type is 32-bit floating-point grayscale. - IMAGE_COMPLEX(3), // The image type is complex. - IMAGE_RGB(4), // The image type is RGB color. - IMAGE_HSL(5), // The image type is HSL color. - IMAGE_RGB_U64(6), // The image type is 64-bit unsigned RGB color. - ; - private final int value; - private ImageType(int value) { - this.value = value; - } - public static ImageType fromValue(int val) { - for (ImageType v : values()) { - if (v.value == val) - return v; - } - return null; - } - public int getValue() { - return value; - } - } - - public static enum ImageFeatureMode { - COLOR_AND_SHAPE_FEATURES(0), // Instructs the function to use the color and the shape features of the color pattern. - COLOR_FEATURES(1), // Instructs the function to use the color features of the color pattern. - SHAPE_FEATURES(2), // Instructs the function to use the shape features of the color pattern. - ; - private final int value; - private ImageFeatureMode(int value) { - this.value = value; - } - public static ImageFeatureMode fromValue(int val) { - try { - return values()[val]; - } catch (ArrayIndexOutOfBoundsException e) { - return null; - } - } - public int getValue() { - return value; - } - } - - public static enum FontColor { - WHITE(0), // Draws text in white. - BLACK(1), // Draws text in black. - INVERT(2), // Inverts the text pixels. - BLACK_ON_WHITE(3), // Draws text in black with a white background. - WHITE_ON_BLACK(4), // Draws text in white with a black background. - ; - private final int value; - private FontColor(int value) { - this.value = value; - } - public static FontColor fromValue(int val) { - try { - return values()[val]; - } catch (ArrayIndexOutOfBoundsException e) { - return null; - } - } - public int getValue() { - return value; - } - } - - public static enum FlipAxis { - HORIZONTAL_AXIS(0), // Flips the image over the central horizontal axis. - VERTICAL_AXIS(1), // Flips the image over the central vertical axis. - CENTER_AXIS(2), // Flips the image over both the central vertical and horizontal axes. - DIAG_L_TO_R_AXIS(3), // Flips the image over an axis from the upper left corner to lower right corner. - DIAG_R_TO_L_AXIS(4), // Flips the image over an axis from the upper right corner to lower left corner. - ; - private final int value; - private FlipAxis(int value) { - this.value = value; - } - public static FlipAxis fromValue(int val) { - try { - return values()[val]; - } catch (ArrayIndexOutOfBoundsException e) { - return null; - } - } - public int getValue() { - return value; - } - } - - public static enum EdgeProcess { - FIRST(0), // The function looks for the first edge. - FIRST_AND_LAST(1), // The function looks for the first and last edge. - ALL(2), // The function looks for all edges. - BEST(3), // The function looks for the best edge. - ; - private final int value; - private EdgeProcess(int value) { - this.value = value; - } - public static EdgeProcess fromValue(int val) { - try { - return values()[val]; - } catch (ArrayIndexOutOfBoundsException e) { - return null; - } - } - public int getValue() { - return value; - } - } - - public static enum DrawMode { - DRAW_VALUE(0), // Draws the boundary of the object with the specified pixel value. - DRAW_INVERT(2), // Inverts the pixel values of the boundary of the object. - PAINT_VALUE(1), // Fills the object with the given pixel value. - PAINT_INVERT(3), // Inverts the pixel values of the object. - HIGHLIGHT_VALUE(4), // The function fills the object by highlighting the enclosed pixels with the color of the object. - ; - private final int value; - private DrawMode(int value) { - this.value = value; - } - public static DrawMode fromValue(int val) { - for (DrawMode v : values()) { - if (v.value == val) - return v; - } - return null; - } - public int getValue() { - return value; - } - } - - public static enum NearestNeighborMetric { - METRIC_MAXIMUM(0), // The maximum metric. - METRIC_SUM(1), // The sum metric. - METRIC_EUCLIDEAN(2), // The Euclidean metric. - ; - private final int value; - private NearestNeighborMetric(int value) { - this.value = value; - } - public static NearestNeighborMetric fromValue(int val) { - try { - return values()[val]; - } catch (ArrayIndexOutOfBoundsException e) { - return null; - } - } - public int getValue() { - return value; - } - } - - public static enum ReadResolution { - LOW_RESOLUTION(0), // Configures NI Vision to use low resolution during the read process. - MEDIUM_RESOLUTION(1), // Configures NI Vision to use medium resolution during the read process. - HIGH_RESOLUTION(2), // Configures NI Vision to use high resolution during the read process. - ; - private final int value; - private ReadResolution(int value) { - this.value = value; - } - public static ReadResolution fromValue(int val) { - try { - return values()[val]; - } catch (ArrayIndexOutOfBoundsException e) { - return null; - } - } - public int getValue() { - return value; - } - } - - public static enum ThresholdMode { - FIXED_RANGE(0), // Performs thresholding using the values you provide in the lowThreshold and highThreshold elements of OCRProcessingOptions. - COMPUTED_UNIFORM(1), // Calculates a single threshold value for the entire ROI. - COMPUTED_LINEAR(2), // Calculates a value on the left side of the ROI, calculates a value on the right side of the ROI, and linearly fills the middle values from left to right. - COMPUTED_NONLINEAR(3), // Divides the ROI into the number of blocks specified by the blockCount element of OCRProcessingOptions and calculates a threshold value for each block. - ; - private final int value; - private ThresholdMode(int value) { - this.value = value; - } - public static ThresholdMode fromValue(int val) { - try { - return values()[val]; - } catch (ArrayIndexOutOfBoundsException e) { - return null; - } - } - public int getValue() { - return value; - } - } - - public static enum ReadStrategy { - READ_AGGRESSIVE(0), // Configures NI Vision to perform fewer checks when analyzing objects to determine if they match trained characters. - READ_CONSERVATIVE(1), // Configures NI Vision to perform more checks to determine if an object matches a trained character. - ; - private final int value; - private ReadStrategy(int value) { - this.value = value; - } - public static ReadStrategy fromValue(int val) { - try { - return values()[val]; - } catch (ArrayIndexOutOfBoundsException e) { - return null; - } - } - public int getValue() { - return value; - } - } - - public static enum MeasurementType { - MT_CENTER_OF_MASS_X(0), // X-coordinate of the point representing the average position of the total particle mass, assuming every point in the particle has a constant density. - MT_CENTER_OF_MASS_Y(1), // Y-coordinate of the point representing the average position of the total particle mass, assuming every point in the particle has a constant density. - MT_FIRST_PIXEL_X(2), // X-coordinate of the highest, leftmost particle pixel. - MT_FIRST_PIXEL_Y(3), // Y-coordinate of the highest, leftmost particle pixel. - MT_BOUNDING_RECT_LEFT(4), // X-coordinate of the leftmost particle point. - MT_BOUNDING_RECT_TOP(5), // Y-coordinate of highest particle point. - MT_BOUNDING_RECT_RIGHT(6), // X-coordinate of the rightmost particle point. - MT_BOUNDING_RECT_BOTTOM(7), // Y-coordinate of the lowest particle point. - MT_MAX_FERET_DIAMETER_START_X(8), // X-coordinate of the start of the line segment connecting the two perimeter points that are the furthest apart. - MT_MAX_FERET_DIAMETER_START_Y(9), // Y-coordinate of the start of the line segment connecting the two perimeter points that are the furthest apart. - MT_MAX_FERET_DIAMETER_END_X(10), // X-coordinate of the end of the line segment connecting the two perimeter points that are the furthest apart. - MT_MAX_FERET_DIAMETER_END_Y(11), // Y-coordinate of the end of the line segment connecting the two perimeter points that are the furthest apart. - MT_MAX_HORIZ_SEGMENT_LENGTH_LEFT(12), // X-coordinate of the leftmost pixel in the longest row of contiguous pixels in the particle. - MT_MAX_HORIZ_SEGMENT_LENGTH_RIGHT(13), // X-coordinate of the rightmost pixel in the longest row of contiguous pixels in the particle. - MT_MAX_HORIZ_SEGMENT_LENGTH_ROW(14), // Y-coordinate of all of the pixels in the longest row of contiguous pixels in the particle. - MT_BOUNDING_RECT_WIDTH(16), // Distance between the x-coordinate of the leftmost particle point and the x-coordinate of the rightmost particle point. - MT_BOUNDING_RECT_HEIGHT(17), // Distance between the y-coordinate of highest particle point and the y-coordinate of the lowest particle point. - MT_BOUNDING_RECT_DIAGONAL(18), // Distance between opposite corners of the bounding rectangle. - MT_PERIMETER(19), // Length of the outer boundary of the particle. - MT_CONVEX_HULL_PERIMETER(20), // Perimeter of the smallest convex polygon containing all points in the particle. - MT_HOLES_PERIMETER(21), // Sum of the perimeters of each hole in the particle. - MT_MAX_FERET_DIAMETER(22), // Distance between the start and end of the line segment connecting the two perimeter points that are the furthest apart. - MT_EQUIVALENT_ELLIPSE_MAJOR_AXIS(23), // Length of the major axis of the ellipse with the same perimeter and area as the particle. - MT_EQUIVALENT_ELLIPSE_MINOR_AXIS(24), // Length of the minor axis of the ellipse with the same perimeter and area as the particle. - MT_EQUIVALENT_ELLIPSE_MINOR_AXIS_FERET(25), // Length of the minor axis of the ellipse with the same area as the particle, and Major Axis equal in length to the Max Feret Diameter. - MT_EQUIVALENT_RECT_LONG_SIDE(26), // Longest side of the rectangle with the same perimeter and area as the particle. - MT_EQUIVALENT_RECT_SHORT_SIDE(27), // Shortest side of the rectangle with the same perimeter and area as the particle. - MT_EQUIVALENT_RECT_DIAGONAL(28), // Distance between opposite corners of the rectangle with the same perimeter and area as the particle. - MT_EQUIVALENT_RECT_SHORT_SIDE_FERET(29), // Shortest side of the rectangle with the same area as the particle, and longest side equal in length to the Max Feret Diameter. - MT_AVERAGE_HORIZ_SEGMENT_LENGTH(30), // Average length of a horizontal segment in the particle. - MT_AVERAGE_VERT_SEGMENT_LENGTH(31), // Average length of a vertical segment in the particle. - MT_HYDRAULIC_RADIUS(32), // The particle area divided by the particle perimeter. - MT_WADDEL_DISK_DIAMETER(33), // Diameter of a disk with the same area as the particle. - MT_AREA(35), // Area of the particle. - MT_HOLES_AREA(36), // Sum of the areas of each hole in the particle. - MT_PARTICLE_AND_HOLES_AREA(37), // Area of a particle that completely covers the image. - MT_CONVEX_HULL_AREA(38), // Area of the smallest convex polygon containing all points in the particle. - MT_IMAGE_AREA(39), // Area of the image. - MT_NUMBER_OF_HOLES(41), // Number of holes in the particle. - MT_NUMBER_OF_HORIZ_SEGMENTS(42), // Number of horizontal segments in the particle. - MT_NUMBER_OF_VERT_SEGMENTS(43), // Number of vertical segments in the particle. - MT_ORIENTATION(45), // The angle of the line that passes through the particle Center of Mass about which the particle has the lowest moment of inertia. - MT_MAX_FERET_DIAMETER_ORIENTATION(46), // The angle of the line segment connecting the two perimeter points that are the furthest apart. - MT_AREA_BY_IMAGE_AREA(48), // Percentage of the particle Area covering the Image Area. - MT_AREA_BY_PARTICLE_AND_HOLES_AREA(49), // Percentage of the particle Area in relation to its Particle and Holes Area. - MT_RATIO_OF_EQUIVALENT_ELLIPSE_AXES(50), // Equivalent Ellipse Major Axis divided by Equivalent Ellipse Minor Axis. - MT_RATIO_OF_EQUIVALENT_RECT_SIDES(51), // Equivalent Rect Long Side divided by Equivalent Rect Short Side. - MT_ELONGATION_FACTOR(53), // Max Feret Diameter divided by Equivalent Rect Short Side (Feret). - MT_COMPACTNESS_FACTOR(54), // Area divided by the product of Bounding Rect Width and Bounding Rect Height. - MT_HEYWOOD_CIRCULARITY_FACTOR(55), // Perimeter divided by the circumference of a circle with the same area. - MT_TYPE_FACTOR(56), // Factor relating area to moment of inertia. - MT_SUM_X(58), // The sum of all x-coordinates in the particle. - MT_SUM_Y(59), // The sum of all y-coordinates in the particle. - MT_SUM_XX(60), // The sum of all x-coordinates squared in the particle. - MT_SUM_XY(61), // The sum of all x-coordinates times y-coordinates in the particle. - MT_SUM_YY(62), // The sum of all y-coordinates squared in the particle. - MT_SUM_XXX(63), // The sum of all x-coordinates cubed in the particle. - MT_SUM_XXY(64), // The sum of all x-coordinates squared times y-coordinates in the particle. - MT_SUM_XYY(65), // The sum of all x-coordinates times y-coordinates squared in the particle. - MT_SUM_YYY(66), // The sum of all y-coordinates cubed in the particle. - MT_MOMENT_OF_INERTIA_XX(68), // The moment of inertia in the x-direction twice. - MT_MOMENT_OF_INERTIA_XY(69), // The moment of inertia in the x and y directions. - MT_MOMENT_OF_INERTIA_YY(70), // The moment of inertia in the y-direction twice. - MT_MOMENT_OF_INERTIA_XXX(71), // The moment of inertia in the x-direction three times. - MT_MOMENT_OF_INERTIA_XXY(72), // The moment of inertia in the x-direction twice and the y-direction once. - MT_MOMENT_OF_INERTIA_XYY(73), // The moment of inertia in the x-direction once and the y-direction twice. - MT_MOMENT_OF_INERTIA_YYY(74), // The moment of inertia in the y-direction three times. - MT_NORM_MOMENT_OF_INERTIA_XX(75), // The normalized moment of inertia in the x-direction twice. - MT_NORM_MOMENT_OF_INERTIA_XY(76), // The normalized moment of inertia in the x- and y-directions. - MT_NORM_MOMENT_OF_INERTIA_YY(77), // The normalized moment of inertia in the y-direction twice. - MT_NORM_MOMENT_OF_INERTIA_XXX(78), // The normalized moment of inertia in the x-direction three times. - MT_NORM_MOMENT_OF_INERTIA_XXY(79), // The normalized moment of inertia in the x-direction twice and the y-direction once. - MT_NORM_MOMENT_OF_INERTIA_XYY(80), // The normalized moment of inertia in the x-direction once and the y-direction twice. - MT_NORM_MOMENT_OF_INERTIA_YYY(81), // The normalized moment of inertia in the y-direction three times. - MT_HU_MOMENT_1(82), // The first Hu moment. - MT_HU_MOMENT_2(83), // The second Hu moment. - MT_HU_MOMENT_3(84), // The third Hu moment. - MT_HU_MOMENT_4(85), // The fourth Hu moment. - MT_HU_MOMENT_5(86), // The fifth Hu moment. - MT_HU_MOMENT_6(87), // The sixth Hu moment. - MT_HU_MOMENT_7(88), // The seventh Hu moment. - ; - private final int value; - private MeasurementType(int value) { - this.value = value; - } - public static MeasurementType fromValue(int val) { - for (MeasurementType v : values()) { - if (v.value == val) - return v; - } - return null; - } - public int getValue() { - return value; - } - } - - public static enum GeometricMatchingMode { - GEOMETRIC_MATCH_SHIFT_INVARIANT(0), // Searches for occurrences of the pattern in the image, assuming that the pattern is not rotated more than plus or minus 5 degrees. - GEOMETRIC_MATCH_ROTATION_INVARIANT(1), // Searches for occurrences of the pattern in the image with reduced restriction on the rotation of the pattern. - GEOMETRIC_MATCH_SCALE_INVARIANT(2), // Searches for occurrences of the pattern in the image with reduced restriction on the size of the pattern. - GEOMETRIC_MATCH_OCCLUSION_INVARIANT(4), // Searches for occurrences of the pattern in the image, allowing for a specified percentage of the pattern to be occluded. - ; - private final int value; - private GeometricMatchingMode(int value) { - this.value = value; - } - public static GeometricMatchingMode fromValue(int val) { - for (GeometricMatchingMode v : values()) { - if (v.value == val) - return v; - } - return null; - } - public int getValue() { - return value; - } - } - - public static enum ButtonLabel { - BUTTON_OK(0), // The label "OK". - BUTTON_SAVE(1), // The label "Save". - BUTTON_SELECT(2), // The label "Select". - BUTTON_LOAD(3), // The label "Load". - ; - private final int value; - private ButtonLabel(int value) { - this.value = value; - } - public static ButtonLabel fromValue(int val) { - try { - return values()[val]; - } catch (ArrayIndexOutOfBoundsException e) { - return null; - } - } - public int getValue() { - return value; - } - } - - public static enum NearestNeighborMethod { - MINIMUM_MEAN_DISTANCE(0), // The minimum mean distance method. - K_NEAREST_NEIGHBOR(1), // The k-nearest neighbor method. - NEAREST_PROTOTYPE(2), // The nearest prototype method. - ; - private final int value; - private NearestNeighborMethod(int value) { - this.value = value; - } - public static NearestNeighborMethod fromValue(int val) { - try { - return values()[val]; - } catch (ArrayIndexOutOfBoundsException e) { - return null; - } - } - public int getValue() { - return value; - } - } - - public static enum QRMirrorMode { - QR_MIRROR_MODE_AUTO_DETECT(-2), // The function should determine if the QR code is mirrored. - QR_MIRROR_MODE_MIRRORED(1), // The function should expect the QR code to appear mirrored. - QR_MIRROR_MODE_NORMAL(0), // The function should expect the QR code to appear normal. - ; - private final int value; - private QRMirrorMode(int value) { - this.value = value; - } - public static QRMirrorMode fromValue(int val) { - for (QRMirrorMode v : values()) { - if (v.value == val) - return v; - } - return null; - } - public int getValue() { - return value; - } - } - - public static enum ColumnProcessingMode { - AVERAGE_COLUMNS(0), // Averages the data extracted for edge detection. - MEDIAN_COLUMNS(1), // Takes the median of the data extracted for edge detection. - ; - private final int value; - private ColumnProcessingMode(int value) { - this.value = value; - } - public static ColumnProcessingMode fromValue(int val) { - try { - return values()[val]; - } catch (ArrayIndexOutOfBoundsException e) { - return null; - } - } - public int getValue() { - return value; - } - } - - public static enum FindReferenceDirection { - LEFT_TO_RIGHT_DIRECT(0), // Searches from the left side of the search area to the right side of the search area for a direct axis. - LEFT_TO_RIGHT_INDIRECT(1), // Searches from the left side of the search area to the right side of the search area for an indirect axis. - TOP_TO_BOTTOM_DIRECT(2), // Searches from the top of the search area to the bottom of the search area for a direct axis. - TOP_TO_BOTTOM_INDIRECT(3), // Searches from the top of the search area to the bottom of the search area for an indirect axis. - RIGHT_TO_LEFT_DIRECT(4), // Searches from the right side of the search area to the left side of the search area for a direct axis. - RIGHT_TO_LEFT_INDIRECT(5), // Searches from the right side of the search area to the left side of the search area for an indirect axis. - BOTTOM_TO_TOP_DIRECT(6), // Searches from the bottom of the search area to the top of the search area for a direct axis. - BOTTOM_TO_TOP_INDIRECT(7), // Searches from the bottom of the search area to the top of the search area for an indirect axis. - ; - private final int value; - private FindReferenceDirection(int value) { - this.value = value; - } - public static FindReferenceDirection fromValue(int val) { - try { - return values()[val]; - } catch (ArrayIndexOutOfBoundsException e) { - return null; - } - } - public int getValue() { - return value; - } - } - - public static enum MulticoreOperation { - GET_CORES(0), // The number of processor cores NI Vision is currently using. - SET_CORES(1), // The number of processor cores for NI Vision to use. - USE_MAX_AVAILABLE(2), // Use the maximum number of available processor cores. - ; - private final int value; - private MulticoreOperation(int value) { - this.value = value; - } - public static MulticoreOperation fromValue(int val) { - try { - return values()[val]; - } catch (ArrayIndexOutOfBoundsException e) { - return null; - } - } - public int getValue() { - return value; - } - } - - public static enum GroupBehavior { - GROUP_CLEAR(0), // Sets the behavior of the overlay group to clear the current settings when an image is transformed. - GROUP_KEEP(1), // Sets the behavior of the overlay group to keep the current settings when an image is transformed. - GROUP_TRANSFORM(2), // Sets the behavior of the overlay group to transform with the image. - ; - private final int value; - private GroupBehavior(int value) { - this.value = value; - } - public static GroupBehavior fromValue(int val) { - try { - return values()[val]; - } catch (ArrayIndexOutOfBoundsException e) { - return null; - } - } - public int getValue() { - return value; - } - } - - public static enum QRDimensions { - QR_DIMENSIONS_AUTO_DETECT(0), // The function will automatically determine the dimensions of the QR code. - QR_DIMENSIONS_11x11(11), // Specifies the dimensions of the QR code as 11 x 11. - QR_DIMENSIONS_13x13(13), // Specifies the dimensions of the QR code as 13 x 13. - QR_DIMENSIONS_15x15(15), // Specifies the dimensions of the QR code as 15 x 15. - QR_DIMENSIONS_17x17(17), // Specifies the dimensions of the QR code as 17 x 17. - QR_DIMENSIONS_21x21(21), // Specifies the dimensions of the QR code as 21 x 21. - QR_DIMENSIONS_25x25(25), // Specifies the dimensions of the QR code as 25 x 25. - QR_DIMENSIONS_29x29(29), // Specifies the dimensions of the QR code as 29 x 29. - QR_DIMENSIONS_33x33(33), // Specifies the dimensions of the QR code as 33 x 33. - QR_DIMENSIONS_37x37(37), // Specifies the dimensions of the QR code as 37 x 37. - QR_DIMENSIONS_41x41(41), // Specifies the dimensions of the QR code as 41 x 41. - QR_DIMENSIONS_45x45(45), // Specifies the dimensions of the QR code as 45 x 45. - QR_DIMENSIONS_49x49(49), // Specifies the dimensions of the QR code as 49 x 49. - QR_DIMENSIONS_53x53(53), // Specifies the dimensions of the QR code as 53 x 53. - QR_DIMENSIONS_57x57(57), // Specifies the dimensions of the QR code as 57 x 57. - QR_DIMENSIONS_61x61(61), // Specifies the dimensions of the QR code as 61 x 61. - QR_DIMENSIONS_65x65(65), // Specifies the dimensions of the QR code as 65 x 65. - QR_DIMENSIONS_69x69(69), // Specifies the dimensions of the QR code as 69 x 69. - QR_DIMENSIONS_73x73(73), // Specifies the dimensions of the QR code as 73 x 73. - QR_DIMENSIONS_77x77(77), // Specifies the dimensions of the QR code as 77 x 77. - QR_DIMENSIONS_81x81(81), // Specifies the dimensions of the QR code as 81 x 81. - QR_DIMENSIONS_85x85(85), // Specifies the dimensions of the QR code as 85 x 85. - QR_DIMENSIONS_89x89(89), // Specifies the dimensions of the QR code as 89 x 89. - QR_DIMENSIONS_93x93(93), // Specifies the dimensions of the QR code as 93 x 93. - QR_DIMENSIONS_97x97(97), // Specifies the dimensions of the QR code as 97 x 97. - QR_DIMENSIONS_101x101(101), // Specifies the dimensions of the QR code as 101 x 101. - QR_DIMENSIONS_105x105(105), // Specifies the dimensions of the QR code as 105 x 105. - QR_DIMENSIONS_109x109(109), // Specifies the dimensions of the QR code as 109 x 109. - QR_DIMENSIONS_113x113(113), // Specifies the dimensions of the QR code as 113 x 113. - QR_DIMENSIONS_117x117(117), // Specifies the dimensions of the QR code as 117 x 117. - QR_DIMENSIONS_121x121(121), // Specifies the dimensions of the QR code as 121 x 121. - QR_DIMENSIONS_125x125(125), // Specifies the dimensions of the QR code as 125 x 125. - QR_DIMENSIONS_129x129(129), // Specifies the dimensions of the QR code as 129 x 129. - QR_DIMENSIONS_133x133(133), // Specifies the dimensions of the QR code as 133 x 133. - QR_DIMENSIONS_137x137(137), // Specifies the dimensions of the QR code as 137 x 137. - QR_DIMENSIONS_141x141(141), // Specifies the dimensions of the QR code as 141 x 141. - QR_DIMENSIONS_145x145(145), // Specifies the dimensions of the QR code as 145 x 145. - QR_DIMENSIONS_149x149(149), // Specifies the dimensions of the QR code as 149 x 149. - QR_DIMENSIONS_153x153(153), // Specifies the dimensions of the QR code as 153 x 153. - QR_DIMENSIONS_157x157(157), // Specifies the dimensions of the QR code as 157 x 1537. - QR_DIMENSIONS_161x161(161), // Specifies the dimensions of the QR code as 161 x 161. - QR_DIMENSIONS_165x165(165), // Specifies the dimensions of the QR code as 165 x 165. - QR_DIMENSIONS_169x169(169), // Specifies the dimensions of the QR code as 169 x 169. - QR_DIMENSIONS_173x173(173), // Specifies the dimensions of the QR code as 173 x 173. - QR_DIMENSIONS_177x177(177), // Specifies the dimensions of the QR code as 177 x 177. - ; - private final int value; - private QRDimensions(int value) { - this.value = value; - } - public static QRDimensions fromValue(int val) { - for (QRDimensions v : values()) { - if (v.value == val) - return v; - } - return null; - } - public int getValue() { - return value; - } - } - - public static enum QRCellFilterMode { - QR_CELL_FILTER_MODE_AUTO_DETECT(-2), // The function will try all filter modes and uses the one that decodes the QR code within the fewest iterations and utilizing the least amount of error correction. - QR_CELL_FILTER_MODE_AVERAGE(0), // The function sets the pixel value for the cell to the average of the sampled pixels. - QR_CELL_FILTER_MODE_MEDIAN(1), // The function sets the pixel value for the cell to the median of the sampled pixels. - QR_CELL_FILTER_MODE_CENTRAL_AVERAGE(2), // The function sets the pixel value for the cell to the average of the pixels in the center of the cell sample. - QR_CELL_FILTER_MODE_HIGH_AVERAGE(3), // The function sets the pixel value for the cell to the average value of the half of the sampled pixels with the highest pixel values. - QR_CELL_FILTER_MODE_LOW_AVERAGE(4), // The function sets the pixel value for the cell to the average value of the half of the sampled pixels with the lowest pixel values. - QR_CELL_FILTER_MODE_VERY_HIGH_AVERAGE(5), // The function sets the pixel value for the cell to the average value of the ninth of the sampled pixels with the highest pixel values. - QR_CELL_FILTER_MODE_VERY_LOW_AVERAGE(6), // The function sets the pixel value for the cell to the average value of the ninth of the sampled pixels with the lowest pixel values. - QR_CELL_FILTER_MODE_ALL(8), // The function tries each filter mode, starting with IMAQ_QR_CELL_FILTER_MODE_AVERAGE and ending with IMAQ_QR_CELL_FILTER_MODE_VERY_LOW_AVERAGE, stopping once a filter mode decodes correctly. - ; - private final int value; - private QRCellFilterMode(int value) { - this.value = value; - } - public static QRCellFilterMode fromValue(int val) { - for (QRCellFilterMode v : values()) { - if (v.value == val) - return v; - } - return null; - } - public int getValue() { - return value; - } - } - - public static enum RoundingMode { - ROUNDING_MODE_OPTIMIZE(0), // Rounds the result of a division using the best available method. - ROUNDING_MODE_TRUNCATE(1), // Truncates the result of a division. - ; - private final int value; - private RoundingMode(int value) { - this.value = value; - } - public static RoundingMode fromValue(int val) { - try { - return values()[val]; - } catch (ArrayIndexOutOfBoundsException e) { - return null; - } - } - public int getValue() { - return value; - } - } - - public static enum QRDemodulationMode { - QR_DEMODULATION_MODE_AUTO_DETECT(-2), // The function will try each demodulation mode and use the one which decodes the QR code within the fewest iterations and utilizing the least amount of error correction. - QR_DEMODULATION_MODE_HISTOGRAM(0), // The function uses a histogram of all of the QR cells to calculate a threshold. - QR_DEMODULATION_MODE_LOCAL_CONTRAST(1), // The function examines each of the cell's neighbors to determine if the cell is on or off. - QR_DEMODULATION_MODE_COMBINED(2), // The function uses the histogram of the QR code to calculate a threshold. - QR_DEMODULATION_MODE_ALL(3), // The function tries IMAQ_QR_DEMODULATION_MODE_HISTOGRAM, then IMAQ_QR_DEMODULATION_MODE_LOCAL_CONTRAST and then IMAQ_QR_DEMODULATION_MODE_COMBINED, stopping once one mode is successful. - ; - private final int value; - private QRDemodulationMode(int value) { - this.value = value; - } - public static QRDemodulationMode fromValue(int val) { - for (QRDemodulationMode v : values()) { - if (v.value == val) - return v; - } - return null; - } - public int getValue() { - return value; - } - } - - public static enum ContrastMode { - ORIGINAL_CONTRAST(0), // Instructs the geometric matching algorithm to find matches with the same contrast as the template. - REVERSED_CONTRAST(1), // Instructs the geometric matching algorithm to find matches with the inverted contrast of the template. - BOTH_CONTRASTS(2), // Instructs the geometric matching algorithm to find matches with the same and inverted contrast of the template. - ; - private final int value; - private ContrastMode(int value) { - this.value = value; - } - public static ContrastMode fromValue(int val) { - try { - return values()[val]; - } catch (ArrayIndexOutOfBoundsException e) { - return null; - } - } - public int getValue() { - return value; - } - } - - public static enum QRPolarities { - QR_POLARITY_AUTO_DETECT(-2), // The function should determine the polarity of the QR code. - QR_POLARITY_BLACK_ON_WHITE(0), // The function should search for a QR code with dark data on a bright background. - QR_POLARITY_WHITE_ON_BLACK(1), // The function should search for a QR code with bright data on a dark background. - ; - private final int value; - private QRPolarities(int value) { - this.value = value; - } - public static QRPolarities fromValue(int val) { - for (QRPolarities v : values()) { - if (v.value == val) - return v; - } - return null; - } - public int getValue() { - return value; - } - } - - public static enum QRRotationMode { - QR_ROTATION_MODE_UNLIMITED(0), // The function allows for unlimited rotation. - QR_ROTATION_MODE_0_DEGREES(1), // The function allows for ??? 5 degrees of rotation. - QR_ROTATION_MODE_90_DEGREES(2), // The function allows for between 85 and 95 degrees of rotation. - QR_ROTATION_MODE_180_DEGREES(3), // The function allows for between 175 and 185 degrees of rotation. - QR_ROTATION_MODE_270_DEGREES(4), // The function allows for between 265 and 275 degrees of rotation. - ; - private final int value; - private QRRotationMode(int value) { - this.value = value; - } - public static QRRotationMode fromValue(int val) { - try { - return values()[val]; - } catch (ArrayIndexOutOfBoundsException e) { - return null; - } - } - public int getValue() { - return value; - } - } - - public static enum QRGradingMode { - QR_NO_GRADING(0), // The function does not make any preparatory calculations. - ; - private final int value; - private QRGradingMode(int value) { - this.value = value; - } - public static QRGradingMode fromValue(int val) { - try { - return values()[val]; - } catch (ArrayIndexOutOfBoundsException e) { - return null; - } - } - public int getValue() { - return value; - } - } - - public static enum StraightEdgeSearchMode { - USE_FIRST_RAKE_EDGES(0), // Fits a straight edge on the first points detected using a rake. - USE_BEST_RAKE_EDGES(1), // Fits a straight edge on the best points detected using a rake. - USE_BEST_HOUGH_LINE(2), // Finds the strongest straight edge using all points detected on a rake. - USE_FIRST_PROJECTION_EDGE(3), // Uses the location of the first projected edge as the straight edge. - USE_BEST_PROJECTION_EDGE(4), // Finds the strongest projected edge location to determine the straight edge. - ; - private final int value; - private StraightEdgeSearchMode(int value) { - this.value = value; - } - public static StraightEdgeSearchMode fromValue(int val) { - try { - return values()[val]; - } catch (ArrayIndexOutOfBoundsException e) { - return null; - } - } - public int getValue() { - return value; - } - } - - public static enum SearchDirection { - SEARCH_DIRECTION_LEFT_TO_RIGHT(0), // Searches from the left side of the search area to the right side of the search area. - SEARCH_DIRECTION_RIGHT_TO_LEFT(1), // Searches from the right side of the search area to the left side of the search area. - SEARCH_DIRECTION_TOP_TO_BOTTOM(2), // Searches from the top side of the search area to the bottom side of the search area. - SEARCH_DIRECTION_BOTTOM_TO_TOP(3), // Searches from the bottom side of the search area to the top side of the search area. - ; - private final int value; - private SearchDirection(int value) { - this.value = value; - } - public static SearchDirection fromValue(int val) { - try { - return values()[val]; - } catch (ArrayIndexOutOfBoundsException e) { - return null; - } - } - public int getValue() { - return value; - } - } - - public static enum QRStreamMode { - QR_MODE_NUMERIC(0), // Specifies that the data was encoded using numeric mode. - QR_MODE_ALPHANUMERIC(1), // Specifies that the data was encoded using alpha-numeric mode. - QR_MODE_RAW_BYTE(2), // Specifies that the data was not encoded but is only raw binary bytes, or encoded in JIS-8. - QR_MODE_EAN128_TOKEN(3), // Specifies that the data has a special meaning represented by the application ID. - QR_MODE_EAN128_DATA(4), // Specifies that the data has a special meaning represented by the application ID. - QR_MODE_ECI(5), // Specifies that the data was meant to be read using the language represented in the language ID. - QR_MODE_KANJI(6), // Specifies that the data was encoded in Shift-JIS16 Japanese. - ; - private final int value; - private QRStreamMode(int value) { - this.value = value; - } - public static QRStreamMode fromValue(int val) { - try { - return values()[val]; - } catch (ArrayIndexOutOfBoundsException e) { - return null; - } - } - public int getValue() { - return value; - } - } - - public static enum ParticleClassifierType { - PARTICLE_LARGEST(0), // Use only the largest particle in the image. - PARTICLE_ALL(1), // Use all particles in the image. - ; - private final int value; - private ParticleClassifierType(int value) { - this.value = value; - } - public static ParticleClassifierType fromValue(int val) { - try { - return values()[val]; - } catch (ArrayIndexOutOfBoundsException e) { - return null; - } - } - public int getValue() { - return value; - } - } - - public static enum QRCellSampleSize { - QR_CELL_SAMPLE_SIZE_AUTO_DETECT(-2), // The function will try each sample size and use the one which decodes the QR code within the fewest iterations and utilizing the least amount of error correction. - QR_CELL_SAMPLE_SIZE1X1(1), // The function will use a 1x1 sized sample from each cell. - QR_CELL_SAMPLE_SIZE2X2(2), // The function will use a 2x2 sized sample from each cell. - QR_CELL_SAMPLE_SIZE3X3(3), // The function will use a 3x3 sized sample from each cell. - QR_CELL_SAMPLE_SIZE4X4(4), // The function will use a 4x4 sized sample from each cell. - QR_CELL_SAMPLE_SIZE5X5(5), // The function will use a 5x5 sized sample from each cell. - QR_CELL_SAMPLE_SIZE6X6(6), // The function will use a 6x6 sized sample from each cell. - QR_CELL_SAMPLE_SIZE7X7(7), // The function will use a 7x7 sized sample from each cell. - ; - private final int value; - private QRCellSampleSize(int value) { - this.value = value; - } - public static QRCellSampleSize fromValue(int val) { - for (QRCellSampleSize v : values()) { - if (v.value == val) - return v; - } - return null; - } - public int getValue() { - return value; - } - } - - public static enum RakeProcessType { - GET_FIRST_EDGES(0), - GET_FIRST_AND_LAST_EDGES(1), - GET_ALL_EDGES(2), - GET_BEST_EDGES(3), - ; - private final int value; - private RakeProcessType(int value) { - this.value = value; - } - public static RakeProcessType fromValue(int val) { - try { - return values()[val]; - } catch (ArrayIndexOutOfBoundsException e) { - return null; - } - } - public int getValue() { - return value; - } - } - - public static enum GeometricSetupDataItem { - CURVE_EXTRACTION_MODE(0), // Specifies how the function identifies curves in the image. - CURVE_EDGE_THRSHOLD(1), // Specifies the minimum contrast an edge pixel must have for it to be considered part of a curve. - CURVE_EDGE_FILTER(2), // Specifies the width of the edge filter that the function uses to identify curves in the image. - MINIMUM_CURVE_LENGTH(3), // Specifies the length, in pixels, of the smallest curve that you want the function to identify. - CURVE_ROW_SEARCH_STEP_SIZE(4), // Specifies the distance, in the y direction, between the image rows that the algorithm inspects for curve seed points. - CURVE_COL_SEARCH_STEP_SIZE(5), // Specifies the distance, in the x direction, between the image columns that the algorithm inspects for curve seed points. - CURVE_MAX_END_POINT_GAP(6), // Specifies the maximum gap, in pixels, between the endpoints of a curve that the function identifies as a closed curve. - EXTRACT_CLOSED_CURVES(7), // Specifies whether to identify only closed curves in the image. - ENABLE_SUBPIXEL_CURVE_EXTRACTION(8), // The function ignores this option. - ENABLE_CORRELATION_SCORE(9), // Specifies that the function should calculate the Correlation Score and return it for each match result. - ENABLE_SUBPIXEL_ACCURACY(10), // Determines whether to return the match results with subpixel accuracy. - SUBPIXEL_ITERATIONS(11), // Specifies the maximum number of incremental improvements used to refine matches using subpixel information. - SUBPIXEL_TOLERANCE(12), // Specifies the maximum amount of change, in pixels, between consecutive incremental improvements in the match position before the function stops refining the match position. - INITIAL_MATCH_LIST_LENGTH(13), // Specifies the maximum size of the match list. - ENABLE_TARGET_TEMPLATE_CURVESCORE(14), // Specifies whether the function should calculate the match curve to template curve score and return it for each match result. - MINIMUM_MATCH_SEPARATION_DISTANCE(15), // Specifies the minimum separation distance, in pixels, between the origins of two matches that have unique positions. - MINIMUM_MATCH_SEPARATION_ANGLE(16), // Specifies the minimum angular difference, in degrees, between two matches that have unique angles. - MINIMUM_MATCH_SEPARATION_SCALE(17), // Specifies the minimum difference in scale, expressed as a percentage, between two matches that have unique scales. - MAXIMUM_MATCH_OVERLAP(18), // Specifies whether you want the algorithm to spend less time accurately estimating the location of a match. - ENABLE_COARSE_RESULT(19), // Specifies whether you want the algorithm to spend less time accurately estimating the location of a match. - ENABLE_CALIBRATION_SUPPORT(20), // Specifies whether or not the algorithm treat the inspection image as a calibrated image. - ENABLE_CONTRAST_REVERSAL(21), // Specifies the contrast of the matches to search for. - SEARCH_STRATEGY(22), // Specifies the aggressiveness of the strategy used to find matches in the image. - REFINEMENT_MATCH_FACTOR(23), // Specifies the factor applied to the number of matches requested to determine how many matches are refined in the pyramid stage. - SUBPIXEL_MATCH_FACTOR(24), // Specifies the factor applied to the number for matches requested to determine how many matches are used for the final (subpixel) stage. - MAX_REFINEMENT_ITERATIONS(25), // Specifies maximum refinement iteration. - ; - private final int value; - private GeometricSetupDataItem(int value) { - this.value = value; - } - public static GeometricSetupDataItem fromValue(int val) { - try { - return values()[val]; - } catch (ArrayIndexOutOfBoundsException e) { - return null; - } - } - public int getValue() { - return value; - } - } - - public static enum DistortionModel { - POLYNOMIAL_MODEL(0), // Polynomial model. - DIVISION_MODEL(1), // Division Model. - NO_DISTORTION_MODEL(-1), // Not a distortion model. - ; - private final int value; - private DistortionModel(int value) { - this.value = value; - } - public static DistortionModel fromValue(int val) { - for (DistortionModel v : values()) { - if (v.value == val) - return v; - } - return null; - } - public int getValue() { - return value; - } - } - - public static enum CalibrationThumbnailType { - CAMARA_MODEL_TYPE(0), // Camara model thumbnail type. - PERSPECTIVE_TYPE(1), // Perspective thumbnail type. - MICRO_PLANE_TYPE(2), // Micro Plane thumbnail type. - ; - private final int value; - private CalibrationThumbnailType(int value) { - this.value = value; - } - public static CalibrationThumbnailType fromValue(int val) { - try { - return values()[val]; - } catch (ArrayIndexOutOfBoundsException e) { - return null; - } - } - public int getValue() { - return value; - } - } - - public static enum SettingType { - ROTATION_ANGLE_RANGE(0), // Set a range for this option to specify the angles at which you expect the Function to find template matches in the inspection image. - SCALE_RANGE(1), // Set a range for this option to specify the sizes at which you expect the Function to find template matches in the inspection image. - OCCLUSION_RANGE(2), // Set a range for this option to specify the amount of occlusion you expect for a match in the inspection image. - ; - private final int value; - private SettingType(int value) { - this.value = value; - } - public static SettingType fromValue(int val) { - try { - return values()[val]; - } catch (ArrayIndexOutOfBoundsException e) { - return null; - } - } - public int getValue() { - return value; - } - } - - public static enum SegmentationDistanceLevel { - SEGMENTATION_LEVEL_CONSERVATIVE(0), // Uses extensive criteria to determine the Maximum Distance. - SEGMENTATION_LEVEL_AGGRESSIVE(1), // Uses few criteria to determine the Maximum Distance. - ; - private final int value; - private SegmentationDistanceLevel(int value) { - this.value = value; - } - public static SegmentationDistanceLevel fromValue(int val) { - try { - return values()[val]; - } catch (ArrayIndexOutOfBoundsException e) { - return null; - } - } - public int getValue() { - return value; - } - } - - public static enum ExtractContourSelection { - CLOSEST(0), // Selects the curve closest to the ROI. - LONGEST(1), // Selects the longest curve. - STRONGEST(2), // Selects the curve with the highest edge strength averaged from each point on the curve. - ; - private final int value; - private ExtractContourSelection(int value) { - this.value = value; - } - public static ExtractContourSelection fromValue(int val) { - try { - return values()[val]; - } catch (ArrayIndexOutOfBoundsException e) { - return null; - } - } - public int getValue() { - return value; - } - } - - public static enum FindTransformMode { - FIND_REFERENCE(0), // Update both parts of the coordinate system. - UPDATE_TRANSFORM(1), // Update only the new reference system. - ; - private final int value; - private FindTransformMode(int value) { - this.value = value; - } - public static FindTransformMode fromValue(int val) { - try { - return values()[val]; - } catch (ArrayIndexOutOfBoundsException e) { - return null; - } - } - public int getValue() { - return value; - } - } - - public static enum ExtractContourDirection { - RECT_LEFT_RIGHT(0), // Searches the ROI from left to right. - RECT_RIGHT_LEFT(1), // Searches the ROI from right to left. - RECT_TOP_BOTTOM(2), // Searches the ROI from top to bottom. - RECT_BOTTOM_TOP(3), // Searches the ROI from bottom to top. - ANNULUS_INNER_OUTER(4), // Searches the ROI from the inner radius to the outer radius. - ANNULUS_OUTER_INNER(5), // Searches the ROI from the outer radius to the inner radius. - ANNULUS_START_STOP(6), // Searches the ROI from start angle to end angle. - ANNULUS_STOP_START(7), // Searches the ROI from end angle to start angle. - ; - private final int value; - private ExtractContourDirection(int value) { - this.value = value; - } - public static ExtractContourDirection fromValue(int val) { - try { - return values()[val]; - } catch (ArrayIndexOutOfBoundsException e) { - return null; - } - } - public int getValue() { - return value; - } - } - - public static enum EdgePolaritySearchMode { - SEARCH_FOR_ALL_EDGES(0), // Searches for all edges. - SEARCH_FOR_RISING_EDGES(1), // Searches for rising edges only. - SEARCH_FOR_FALLING_EDGES(2), // Searches for falling edges only. - ; - private final int value; - private EdgePolaritySearchMode(int value) { - this.value = value; - } - public static EdgePolaritySearchMode fromValue(int val) { - try { - return values()[val]; - } catch (ArrayIndexOutOfBoundsException e) { - return null; - } - } - public int getValue() { - return value; - } - } - - public static enum Connectivity { - FOUR_CONNECTED(0), // Morphological reconstruction is performed in connectivity mode 4. - EIGHT_CONNECTED(1), // Morphological reconstruction is performed in connectivity mode 8. - ; - private final int value; - private Connectivity(int value) { - this.value = value; - } - public static Connectivity fromValue(int val) { - try { - return values()[val]; - } catch (ArrayIndexOutOfBoundsException e) { - return null; - } - } - public int getValue() { - return value; - } - } - - public static enum MorphologyReconstructOperation { - DILATE_RECONSTRUCT(0), // Performs Reconstruction by dilation. - ERODE_RECONSTRUCT(1), // Performs Reconstruction by erosion. - ; - private final int value; - private MorphologyReconstructOperation(int value) { - this.value = value; - } - public static MorphologyReconstructOperation fromValue(int val) { - try { - return values()[val]; - } catch (ArrayIndexOutOfBoundsException e) { - return null; - } - } - public int getValue() { - return value; - } - } - - public static enum WaveletType { - DB02(0), - DB03(1), - DB04(2), // Specifies the Wavelet Type as DB02. - DB05(3), - DB06(4), - DB07(5), - DB08(6), - DB09(7), - DB10(8), - DB11(9), - DB12(10), - DB13(11), - DB14(12), - HAAR(13), - BIOR1_3(14), - BIOR1_5(15), - BIOR2_2(16), - BIOR2_4(17), - BIOR2_6(18), - BIOR2_8(19), - BIOR3_1(20), - BIOR3_3(21), - BIOR3_5(22), - BIOR3_7(23), - BIOR3_9(24), - BIOR4_4(25), - COIF1(26), - COIF2(27), - COIF3(28), - COIF4(29), - COIF5(30), - SYM2(31), - SYM3(32), - SYM4(33), - SYM5(34), - SYM6(35), - SYM7(36), - SYM8(37), - BIOR5_5(38), - BIOR6_8(39), - ; - private final int value; - private WaveletType(int value) { - this.value = value; - } - public static WaveletType fromValue(int val) { - try { - return values()[val]; - } catch (ArrayIndexOutOfBoundsException e) { - return null; - } - } - public int getValue() { - return value; - } - } - - public static enum ParticleClassifierThresholdType { - THRESHOLD_MANUAL(0), // The classifier performs a manual threshold on the image during preprocessing. - THRESHOLD_AUTO(1), // The classifier performs an auto threshold on the image during preprocessing. - THRESHOLD_LOCAL(2), // The classifier performs a local threshold on the image during preprocessing. - ; - private final int value; - private ParticleClassifierThresholdType(int value) { - this.value = value; - } - public static ParticleClassifierThresholdType fromValue(int val) { - try { - return values()[val]; - } catch (ArrayIndexOutOfBoundsException e) { - return null; - } - } - public int getValue() { - return value; - } - } - - public static enum MeasureParticlesCalibrationMode { - CALIBRATION_MODE_PIXEL(0), // The function takes only pixel measurements on the particles in the image. - CALIBRATION_MODE_CALIBRATED(1), // The function takes only calibrated measurements on the particles in the image. - CALIBRATION_MODE_BOTH(2), // The function takes both pixel and calibrated measurements on the particles in the image. - ; - private final int value; - private MeasureParticlesCalibrationMode(int value) { - this.value = value; - } - public static MeasureParticlesCalibrationMode fromValue(int val) { - try { - return values()[val]; - } catch (ArrayIndexOutOfBoundsException e) { - return null; - } - } - public int getValue() { - return value; - } - } - - public static enum GeometricMatchingSearchStrategy { - GEOMETRIC_MATCHING_CONSERVATIVE(0), // Instructs the pattern matching algorithm to use the largest possible amount of information from the image at the expense of slowing down the speed of the algorithm. - GEOMETRIC_MATCHING_BALANCED(1), // Instructs the pattern matching algorithm to balance the amount of information from the image it uses with the speed of the algorithm. - GEOMETRIC_MATCHING_AGGRESSIVE(2), // Instructs the pattern matching algorithm to use a lower amount of information from the image, which allows the algorithm to run quickly but at the expense of accuracy. - ; - private final int value; - private GeometricMatchingSearchStrategy(int value) { - this.value = value; - } - public static GeometricMatchingSearchStrategy fromValue(int val) { - try { - return values()[val]; - } catch (ArrayIndexOutOfBoundsException e) { - return null; - } - } - public int getValue() { - return value; - } - } - - public static enum ColorClassificationResolution { - CLASSIFIER_LOW_RESOLUTION(0), // Low resolution version of the color classifier. - CLASSIFIER_MEDIUM_RESOLUTION(1), // Medium resolution version of the color classifier. - CLASSIFIER_HIGH_RESOLUTION(2), // High resolution version of the color classifier. - ; - private final int value; - private ColorClassificationResolution(int value) { - this.value = value; - } - public static ColorClassificationResolution fromValue(int val) { - try { - return values()[val]; - } catch (ArrayIndexOutOfBoundsException e) { - return null; - } - } - public int getValue() { - return value; - } - } - - public static enum ConnectionConstraintType { - DISTANCE_CONSTRAINT(0), // Specifies the distance, in pixels, within which the end points of two curves must lie in order to be considered part of a contour. - ANGLE_CONSTRAINT(1), // Specifies the range, in degrees, within which the difference between the angle of two curves, measured at the end points, must lie in order for the two curves to be considered part of a contour. - CONNECTIVITY_CONSTRAINT(2), // Specifies the distance, in pixels, within which a line extended from the end point of a curve must pass the end point of another curve in order for the two curves to be considered part of a contour. - GRADIENT_CONSTRAINT(3), // Specifies the range, in degrees, within which the gradient angles of two curves, measured at the end points, must lie in order for the two curves to be considered part of a contour. - NUM_CONNECTION_CONSTRAINT_TYPES(4), // . - ; - private final int value; - private ConnectionConstraintType(int value) { - this.value = value; - } - public static ConnectionConstraintType fromValue(int val) { - try { - return values()[val]; - } catch (ArrayIndexOutOfBoundsException e) { - return null; - } - } - public int getValue() { - return value; - } - } - - public static enum Barcode2DContrast { - ALL_BARCODE_2D_CONTRASTS(0), // The function searches for barcodes of each contrast type. - BLACK_ON_WHITE_BARCODE_2D(1), // The function searches for 2D barcodes containing black data on a white background. - WHITE_ON_BLACK_BARCODE_2D(2), // The function searches for 2D barcodes containing white data on a black background. - ; - private final int value; - private Barcode2DContrast(int value) { - this.value = value; - } - public static Barcode2DContrast fromValue(int val) { - try { - return values()[val]; - } catch (ArrayIndexOutOfBoundsException e) { - return null; - } - } - public int getValue() { - return value; - } - } - - public static enum QRModelType { - QR_MODELTYPE_AUTO_DETECT(0), // Specifies that the function will auto-detect the type of QR code. - QR_MODELTYPE_MICRO(1), // Specifies the QR code is of a micro type. - QR_MODELTYPE_MODEL1(2), // Specifies the QR code is of a model1 type. - QR_MODELTYPE_MODEL2(3), // Specifies the QR code is of a model2 type. - ; - private final int value; - private QRModelType(int value) { - this.value = value; - } - public static QRModelType fromValue(int val) { - try { - return values()[val]; - } catch (ArrayIndexOutOfBoundsException e) { - return null; - } - } - public int getValue() { - return value; - } - } - - public static enum WindowBackgroundFillStyle { - FILL_STYLE_SOLID(0), // Fill the display window with a solid color. - FILL_STYLE_HATCH(2), // Fill the display window with a pattern defined by WindowBackgroundHatchStyle. - FILL_STYLE_DEFAULT(3), // Fill the display window with the NI Vision default pattern. - ; - private final int value; - private WindowBackgroundFillStyle(int value) { - this.value = value; - } - public static WindowBackgroundFillStyle fromValue(int val) { - for (WindowBackgroundFillStyle v : values()) { - if (v.value == val) - return v; - } - return null; - } - public int getValue() { - return value; - } - } - - public static enum ExtractionMode { - NORMAL_IMAGE(0), // Specifies that the function makes no assumptions about the uniformity of objects in the image or the image background. - UNIFORM_REGIONS(1), // Specifies that the function assumes that either the objects in the image or the image background consists of uniform pixel values. - ; - private final int value; - private ExtractionMode(int value) { - this.value = value; - } - public static ExtractionMode fromValue(int val) { - try { - return values()[val]; - } catch (ArrayIndexOutOfBoundsException e) { - return null; - } - } - public int getValue() { - return value; - } - } - - public static enum EdgeFilterSize { - FINE(0), // Specifies that the function uses a fine (narrow) edge filter. - NORMAL(1), // Specifies that the function uses a normal edge filter. - CONTOUR_TRACING(2), // Sets the Edge Filter Size to contour tracing, which provides the best results for contour extraction but increases the time required to process the image. - ; - private final int value; - private EdgeFilterSize(int value) { - this.value = value; - } - public static EdgeFilterSize fromValue(int val) { - try { - return values()[val]; - } catch (ArrayIndexOutOfBoundsException e) { - return null; - } - } - public int getValue() { - return value; - } - } - - public static enum Barcode2DSearchMode { - SEARCH_MULTIPLE(0), // The function searches for multiple 2D barcodes. - SEARCH_SINGLE_CONSERVATIVE(1), // The function searches for 2D barcodes using the same searching algorithm as IMAQ_SEARCH_MULTIPLE but stops searching after locating one valid barcode. - SEARCH_SINGLE_AGGRESSIVE(2), // The function searches for a single 2D barcode using a method that assumes the barcode occupies a majority of the search region. - ; - private final int value; - private Barcode2DSearchMode(int value) { - this.value = value; - } - public static Barcode2DSearchMode fromValue(int val) { - try { - return values()[val]; - } catch (ArrayIndexOutOfBoundsException e) { - return null; - } - } - public int getValue() { - return value; - } - } - - public static enum DataMatrixSubtype { - ALL_DATA_MATRIX_SUBTYPES(0), // The function searches for Data Matrix barcodes of all subtypes. - DATA_MATRIX_SUBTYPES_ECC_000_ECC_140(1), // The function searches for Data Matrix barcodes of subtypes ECC 000, ECC 050, ECC 080, ECC 100 and ECC 140. - DATA_MATRIX_SUBTYPE_ECC_200(2), // The function searches for Data Matrix ECC 200 barcodes. - ; - private final int value; - private DataMatrixSubtype(int value) { - this.value = value; - } - public static DataMatrixSubtype fromValue(int val) { - try { - return values()[val]; - } catch (ArrayIndexOutOfBoundsException e) { - return null; - } - } - public int getValue() { - return value; - } - } - - public static enum FeatureType { - NOT_FOUND_FEATURE(0), // Specifies the feature is not found. - CIRCLE_FEATURE(1), // Specifies the feature is a circle. - ELLIPSE_FEATURE(2), // Specifies the feature is an ellipse. - CONST_CURVE_FEATURE(3), // Specifies the features is a constant curve. - RECTANGLE_FEATURE(4), // Specifies the feature is a rectangle. - LEG_FEATURE(5), // Specifies the feature is a leg. - CORNER_FEATURE(6), // Specifies the feature is a corner. - PARALLEL_LINE_PAIR_FEATURE(7), // Specifies the feature is a parallel line pair. - PAIR_OF_PARALLEL_LINE_PAIRS_FEATURE(8), // Specifies the feature is a pair of parallel line pairs. - LINE_FEATURE(9), // Specifies the feature is a line. - CLOSED_CURVE_FEATURE(10), // Specifies the feature is a closed curve. - ; - private final int value; - private FeatureType(int value) { - this.value = value; - } - public static FeatureType fromValue(int val) { - try { - return values()[val]; - } catch (ArrayIndexOutOfBoundsException e) { - return null; - } - } - public int getValue() { - return value; - } - } - - public static enum Barcode2DCellShape { - SQUARE_CELLS(0), // The function uses an algorithm for decoding the 2D barcode that works with square data cells. - ROUND_CELLS(1), // The function uses an algorithm for decoding the 2D barcode that works with round data cells. - ; - private final int value; - private Barcode2DCellShape(int value) { - this.value = value; - } - public static Barcode2DCellShape fromValue(int val) { - try { - return values()[val]; - } catch (ArrayIndexOutOfBoundsException e) { - return null; - } - } - public int getValue() { - return value; - } - } - - public static enum LocalThresholdMethod { - NIBLACK(0), // The function computes thresholds for each pixel based on its local statistics using the Niblack local thresholding algorithm. - BACKGROUND_CORRECTION(1), // The function performs background correction first to eliminate non-uniform lighting effects, then performs thresholding using the Otsu thresholding algorithm. - ; - private final int value; - private LocalThresholdMethod(int value) { - this.value = value; - } - public static LocalThresholdMethod fromValue(int val) { - try { - return values()[val]; - } catch (ArrayIndexOutOfBoundsException e) { - return null; - } - } - public int getValue() { - return value; - } - } - - public static enum Barcode2DType { - PDF417(0), // The 2D barcode is of type PDF417. - DATA_MATRIX_ECC_000(1), // The 2D barcode is of type Data Matrix ECC 000. - DATA_MATRIX_ECC_050(2), // The 2D barcode is of type Data Matrix ECC 050. - DATA_MATRIX_ECC_080(3), // The 2D barcode is of type Data Matrix ECC 080. - DATA_MATRIX_ECC_100(4), // The 2D barcode is of type Data Matrix ECC 100. - DATA_MATRIX_ECC_140(5), // The 2D barcode is of type Data Matrix ECC 140. - DATA_MATRIX_ECC_200(6), // The 2D barcode is of type Data Matrix ECC 200. - ; - private final int value; - private Barcode2DType(int value) { - this.value = value; - } - public static Barcode2DType fromValue(int val) { - try { - return values()[val]; - } catch (ArrayIndexOutOfBoundsException e) { - return null; - } - } - public int getValue() { - return value; - } - } - - public static enum ClassifierEngineType { - ENGINE_NONE(0), // No engine has been set on this classifier session. - ENGINE_NEAREST_NEIGHBOR(1), // Nearest neighbor engine. - ENGINE_SUPPORT_VECTOR_MACHINE(2), - ; - private final int value; - private ClassifierEngineType(int value) { - this.value = value; - } - public static ClassifierEngineType fromValue(int val) { - try { - return values()[val]; - } catch (ArrayIndexOutOfBoundsException e) { - return null; - } - } - public int getValue() { - return value; - } - } - - public static enum ClassifierType { - CLASSIFIER_CUSTOM(0), // The classifier session classifies vectors of doubles. - CLASSIFIER_PARTICLE(1), // The classifier session classifies particles in binary images. - CLASSIFIER_COLOR(2), // The classifier session classifies an image based on its color. - CLASSIFIER_TEXTURE(3), // The classifier session classifies an image based on its texture. - ; - private final int value; - private ClassifierType(int value) { - this.value = value; - } - public static ClassifierType fromValue(int val) { - try { - return values()[val]; - } catch (ArrayIndexOutOfBoundsException e) { - return null; - } - } - public int getValue() { - return value; - } - } - - public static enum ParticleType { - PARTICLE_BRIGHT(0), // Bright particles. - PARTICLE_DARK(1), // Dark particles. - ; - private final int value; - private ParticleType(int value) { - this.value = value; - } - public static ParticleType fromValue(int val) { - try { - return values()[val]; - } catch (ArrayIndexOutOfBoundsException e) { - return null; - } - } - public int getValue() { - return value; - } - } - - public static enum VisionInfoType2 { - VISIONINFO_CALIBRATION(0x01), // Used to indicate interaction with the Calibration information in an image. - VISIONINFO_OVERLAY(0x02), // Used to indicate interaction with the Overlay information in an image. - VISIONINFO_GRAYTEMPLATE(0x04), // Used to indicate interaction with the grayscale template information in an image. - VISIONINFO_COLORTEMPLATE(0x08), // Used to indicate interaction with the color template information in an image. - VISIONINFO_GEOMETRICTEMPLATE(0x10), // Used to indicate interaction with the geometric template information in an image. - VISIONINFO_CUSTOMDATA(0x20), // Used to indicate interaction with the binary or text Custom Data in an image. - VISIONINFO_GOLDENTEMPLATE(0x40), // Used to indicate interaction with the golden template information in an image. - VISIONINFO_GEOMETRICTEMPLATE2(0x80), // Used to indicate interaction with the geometric template 2 information in an image. - VISIONINFO_ALL(0xFFFFFFFF), // Removes, checks for, or indicates the presence of all types of extra information in an image. - ; - private final int value; - private VisionInfoType2(int value) { - this.value = value; - } - public static VisionInfoType2 fromValue(int val) { - for (VisionInfoType2 v : values()) { - if (v.value == val) - return v; - } - return null; - } - public int getValue() { - return value; - } - } - - public static enum ReadClassifierFileMode { - CLASSIFIER_READ_ALL(0), // Read all information from the classifier file. - CLASSIFIER_READ_SAMPLES(1), // Read only the samples from the classifier file. - CLASSIFIER_READ_PROPERTIES(2), // Read only the properties from the classifier file. - ; - private final int value; - private ReadClassifierFileMode(int value) { - this.value = value; - } - public static ReadClassifierFileMode fromValue(int val) { - try { - return values()[val]; - } catch (ArrayIndexOutOfBoundsException e) { - return null; - } - } - public int getValue() { - return value; - } - } - - public static enum WriteClassifierFileMode { - CLASSIFIER_WRITE_ALL(0), // Writes all information to the classifier file. - CLASSIFIER_WRITE_CLASSIFY_ONLY(1), // Write only the information needed to classify to the classifier file. - ; - private final int value; - private WriteClassifierFileMode(int value) { - this.value = value; - } - public static WriteClassifierFileMode fromValue(int val) { - try { - return values()[val]; - } catch (ArrayIndexOutOfBoundsException e) { - return null; - } - } - public int getValue() { - return value; - } - } - - public static enum Barcode2DShape { - SQUARE_BARCODE_2D(0), // The function searches for square 2D barcodes. - RECTANGULAR_BARCODE_2D(1), // The function searches for rectangular 2D barcodes. - ; - private final int value; - private Barcode2DShape(int value) { - this.value = value; - } - public static Barcode2DShape fromValue(int val) { - try { - return values()[val]; - } catch (ArrayIndexOutOfBoundsException e) { - return null; - } - } - public int getValue() { - return value; - } - } - - public static enum DataMatrixRotationMode { - UNLIMITED_ROTATION(0), // The function allows for unlimited rotation. - C0_DEGREES(1), // The function allows for between -5 and 5 degrees of rotation. - C90_DEGREES(2), // The function allows for between 85 and 95 degrees of rotation. - C180_DEGREES(3), // The function allows for between 175 and 185 degrees of rotation. - C270_DEGREES(4), // The function allows for between 265 and 275 degrees of rotation. - ; - private final int value; - private DataMatrixRotationMode(int value) { - this.value = value; - } - public static DataMatrixRotationMode fromValue(int val) { - try { - return values()[val]; - } catch (ArrayIndexOutOfBoundsException e) { - return null; - } - } - public int getValue() { - return value; - } - } - - public static enum AIMGrade { - AIM_GRADE_F(0), // The Data Matrix barcode received a grade of F. - AIM_GRADE_D(1), // The Data Matrix barcode received a grade of D. - AIM_GRADE_C(2), // The Data Matrix barcode received a grade of C. - AIM_GRADE_B(3), // The Data Matrix barcode received a grade of B. - AIM_GRADE_A(4), // The Data Matrix barcode received a grade of A. - ; - private final int value; - private AIMGrade(int value) { - this.value = value; - } - public static AIMGrade fromValue(int val) { - try { - return values()[val]; - } catch (ArrayIndexOutOfBoundsException e) { - return null; - } - } - public int getValue() { - return value; - } - } - - public static enum DataMatrixCellFillMode { - AUTO_DETECT_CELL_FILL_MODE(-2), // Sets the function to determine the Data Matrix barcode cell fill percentage automatically. - LOW_FILL(0), // Sets the function to read Data Matrix barcodes with a cell fill percentage of less than 30 percent. - NORMAL_FILL(1), // Sets the function to read Data Matrix barcodes with a cell fill percentage greater than or equal to 30 percent. - ; - private final int value; - private DataMatrixCellFillMode(int value) { - this.value = value; - } - public static DataMatrixCellFillMode fromValue(int val) { - for (DataMatrixCellFillMode v : values()) { - if (v.value == val) - return v; - } - return null; - } - public int getValue() { - return value; - } - } - - public static enum DataMatrixDemodulationMode { - AUTO_DETECT_DEMODULATION_MODE(-2), // The function will try each demodulation mode and use the one which decodes the Data Matrix barcode within the fewest iterations and utilizing the least amount of error correction. - HISTOGRAM(0), // The function uses a histogram of all of the Data Matrix cells to calculate a threshold. - LOCAL_CONTRAST(1), // The function examines each of the cell's neighbors to determine if the cell is on or off. - COMBINED(2), // The function uses the histogram of the Data Matrix barcode to calculate a threshold. - ALL_DEMODULATION_MODES(3), // The function tries IMAQ_HISTOGRAM, then IMAQ_LOCAL_CONTRAST and then IMAQ_COMBINATION, stopping once one mode is successful. - ; - private final int value; - private DataMatrixDemodulationMode(int value) { - this.value = value; - } - public static DataMatrixDemodulationMode fromValue(int val) { - for (DataMatrixDemodulationMode v : values()) { - if (v.value == val) - return v; - } - return null; - } - public int getValue() { - return value; - } - } - - public static enum DataMatrixECC { - AUTO_DETECT_ECC(-2), // Sets the function to determine the Data Matrix barcode ECC automatically. - ECC_000(0), // Sets the function to read Data Matrix barcodes of ECC 000 only. - ECC_050(50), // Sets the function to read Data Matrix barcodes of ECC 050 only. - ECC_080(80), // Sets the function to read Data Matrix barcodes of ECC 080 only. - ECC_100(100), // Sets the function to read Data Matrix barcodes of ECC 100 only. - ECC_140(140), // Sets the function to read Data Matrix barcodes of ECC 140 only. - ECC_000_140(190), // Sets the function to read Data Matrix barcodes of ECC 000, ECC 050, ECC 080, ECC 100, and ECC 140 only. - ECC_200(200), // Sets the function to read Data Matrix barcodes of ECC 200 only. - ; - private final int value; - private DataMatrixECC(int value) { - this.value = value; - } - public static DataMatrixECC fromValue(int val) { - for (DataMatrixECC v : values()) { - if (v.value == val) - return v; - } - return null; - } - public int getValue() { - return value; - } - } - - public static enum DataMatrixPolarity { - AUTO_DETECT_POLARITY(-2), // Sets the function to determine the Data Matrix barcode polarity automatically. - BLACK_DATA_ON_WHITE_BACKGROUND(0), // Sets the function to read Data Matrix barcodes with dark data on a bright background. - WHITE_DATA_ON_BLACK_BACKGROUND(1), // Sets the function to read Data Matrix barcodes with bright data on a dark background. - ; - private final int value; - private DataMatrixPolarity(int value) { - this.value = value; - } - public static DataMatrixPolarity fromValue(int val) { - for (DataMatrixPolarity v : values()) { - if (v.value == val) - return v; - } - return null; - } - public int getValue() { - return value; - } - } - - public static enum DataMatrixCellFilterMode { - AUTO_DETECT_CELL_FILTER_MODE(-2), // The function will try all filter modes and uses the one that decodes the Data Matrix barcode within the fewest iterations and utilizing the least amount of error correction. - AVERAGE_FILTER(0), // The function sets the pixel value for the cell to the average of the sampled pixels. - MEDIAN_FILTER(1), // The function sets the pixel value for the cell to the median of the sampled pixels. - CENTRAL_AVERAGE_FILTER(2), // The function sets the pixel value for the cell to the average of the pixels in the center of the cell sample. - HIGH_AVERAGE_FILTER(3), // The function sets the pixel value for the cell to the average value of the half of the sampled pixels with the highest pixel values. - LOW_AVERAGE_FILTER(4), // The function sets the pixel value for the cell to the average value of the half of the sampled pixels with the lowest pixel values. - VERY_HIGH_AVERAGE_FILTER(5), // The function sets the pixel value for the cell to the average value of the ninth of the sampled pixels with the highest pixel values. - VERY_LOW_AVERAGE_FILTER(6), // The function sets the pixel value for the cell to the average value of the ninth of the sampled pixels with the lowest pixel values. - ALL_CELL_FILTERS(8), // The function tries each filter mode, starting with IMAQ_AVERAGE_FILTER and ending with IMAQ_VERY_LOW_AVERAGE_FILTER, stopping once a filter mode decodes correctly. - ; - private final int value; - private DataMatrixCellFilterMode(int value) { - this.value = value; - } - public static DataMatrixCellFilterMode fromValue(int val) { - for (DataMatrixCellFilterMode v : values()) { - if (v.value == val) - return v; - } - return null; - } - public int getValue() { - return value; - } - } - - public static enum WindowBackgroundHatchStyle { - HATCH_STYLE_HORIZONTAL(0), // The background of the display window will be horizontal bars. - HATCH_STYLE_VERTICAL(1), // The background of the display window will be vertical bars. - HATCH_STYLE_FORWARD_DIAGONAL(2), // The background of the display window will be diagonal bars. - HATCH_STYLE_BACKWARD_DIAGONAL(3), // The background of the display window will be diagonal bars. - HATCH_STYLE_CROSS(4), // The background of the display window will be intersecting horizontal and vertical bars. - HATCH_STYLE_CROSS_HATCH(5), // The background of the display window will be intersecting forward and backward diagonal bars. - ; - private final int value; - private WindowBackgroundHatchStyle(int value) { - this.value = value; - } - public static WindowBackgroundHatchStyle fromValue(int val) { - try { - return values()[val]; - } catch (ArrayIndexOutOfBoundsException e) { - return null; - } - } - public int getValue() { - return value; - } - } - - public static enum DataMatrixMirrorMode { - AUTO_DETECT_MIRROR(-2), // Specifies that the function should determine if the Data Matrix barcode is mirrored. - APPEARS_NORMAL(0), // Specifies that the function should expect the Data Matrix barcode to appear normal. - APPEARS_MIRRORED(1), // Specifies that the function should expect the Data Matrix barcode to appear mirrored. - ; - private final int value; - private DataMatrixMirrorMode(int value) { - this.value = value; - } - public static DataMatrixMirrorMode fromValue(int val) { - for (DataMatrixMirrorMode v : values()) { - if (v.value == val) - return v; - } - return null; - } - public int getValue() { - return value; - } - } - - public static enum CalibrationMode2 { - PERSPECTIVE_MODE(0), // Functions correct for distortion caused by the camera's perspective. - MICROPLANE_MODE(1), // Functions correct for distortion caused by the camera's lens. - SIMPLE_CALIBRATION_MODE(2), // Functions do not correct for distortion. - CORRECTED_IMAGE_MODE(3), // The image is already corrected. - NO_CALIBRATION_MODE(4), // Image with No calibration. - ; - private final int value; - private CalibrationMode2(int value) { - this.value = value; - } - public static CalibrationMode2 fromValue(int val) { - try { - return values()[val]; - } catch (ArrayIndexOutOfBoundsException e) { - return null; - } - } - public int getValue() { - return value; - } - } - - public static enum DataMatrixGradingMode { - NO_GRADING(0), // The function does not make any preparatory calculations. - PREPARE_FOR_AIM(1), // The function prepares the image for grading using the AIM Print Quality metrics. - ; - private final int value; - private DataMatrixGradingMode(int value) { - this.value = value; - } - public static DataMatrixGradingMode fromValue(int val) { - try { - return values()[val]; - } catch (ArrayIndexOutOfBoundsException e) { - return null; - } - } - public int getValue() { - return value; - } - } - - public static enum WaveletTransformMode { - WAVELET_TRANSFORM_INTEGER(0), // Uses a 5-3 reversible integer transform. - WAVELET_TRANSFORM_FLOATING_POINT(1), // Performs a 9-7 irreversible floating-point transform. - ; - private final int value; - private WaveletTransformMode(int value) { - this.value = value; - } - public static WaveletTransformMode fromValue(int val) { - try { - return values()[val]; - } catch (ArrayIndexOutOfBoundsException e) { - return null; - } - } - public int getValue() { - return value; - } - } - - public static enum NormalizationMethod { - NORMALIZATION_NONE(0), // No normalization. - NORMALIZATION_HISTOGRAM_MATCHING(1), // Adjust image so its histogram is similar to the golden template's histogram. - NORMALIZATION_AVERAGE_MATCHING(2), // Adjust image so its mean pixel value equals the golden template's mean pixel value. - ; - private final int value; - private NormalizationMethod(int value) { - this.value = value; - } - public static NormalizationMethod fromValue(int val) { - try { - return values()[val]; - } catch (ArrayIndexOutOfBoundsException e) { - return null; - } - } - public int getValue() { - return value; - } - } - - public static enum RegistrationMethod { - REGISTRATION_NONE(0), // No registration. - REGISTRATION_PERSPECTIVE(1), // Adjust image to correct for minor variations in alignment or perspective. - ; - private final int value; - private RegistrationMethod(int value) { - this.value = value; - } - public static RegistrationMethod fromValue(int val) { - try { - return values()[val]; - } catch (ArrayIndexOutOfBoundsException e) { - return null; - } - } - public int getValue() { - return value; - } - } - - public static enum LinearAveragesMode { - COLUMN_AVERAGES(1), // Specifies that the function calculates the mean pixel value of each column. - ROW_AVERAGES(2), // Specifies that the function calculates the mean pixel value of each row. - RISING_DIAGONAL_AVERAGES(4), // Specifies that the function calculates the mean pixel value of each diagonal running from the lower left to the upper right of the inspected area of the image. - FALLING_DIAGONAL_AVERAGES(8), // Specifies that the function calculates the mean pixel value of each diagonal running from the upper left to the lower right of the inspected area of the image. - ALL_LINEAR_AVERAGES(15), // Specifies that the function calculates all four linear mean pixel values. - ; - private final int value; - private LinearAveragesMode(int value) { - this.value = value; - } - public static LinearAveragesMode fromValue(int val) { - for (LinearAveragesMode v : values()) { - if (v.value == val) - return v; - } - return null; - } - public int getValue() { - return value; - } - } - - public static enum CompressionType { - COMPRESSION_NONE(0), // Specifies that the function should not compress the image. - COMPRESSION_JPEG(1), // Specifies that the function should use lossy JPEG compression on the image. - COMPRESSION_PACKED_BINARY(2), // Specifies that the function should use lossless binary packing on the image. - ; - private final int value; - private CompressionType(int value) { - this.value = value; - } - public static CompressionType fromValue(int val) { - try { - return values()[val]; - } catch (ArrayIndexOutOfBoundsException e) { - return null; - } - } - public int getValue() { - return value; - } - } - - public static enum FlattenType { - FLATTEN_IMAGE(0), // Flattens just the image data. - FLATTEN_IMAGE_AND_VISION_INFO(1), // Flattens the image data and any Vision information associated with the image. - ; - private final int value; - private FlattenType(int value) { - this.value = value; - } - public static FlattenType fromValue(int val) { - try { - return values()[val]; - } catch (ArrayIndexOutOfBoundsException e) { - return null; - } - } - public int getValue() { - return value; - } - } - - public static enum DataMatrixCellSampleSize { - AUTO_DETECT_CELL_SAMPLE_SIZE(-2), // The function will try each sample size and use the one which decodes the Data Matrix barcode within the fewest iterations and utilizing the least amount of error correction. - C1x1(1), // The function will use a 1x1 sized sample from each cell. - C2x2(2), // The function will use a 2x2 sized sample from each cell. - C3x3(3), // The function will use a 3x3 sized sample from each cell. - C4x4(4), // The function will use a 4x4 sized sample from each cell. - C5x5(5), // The function will use a 5x5 sized sample from each cell. - C6x6(6), // The function will use a 6x6 sized sample from each cell. - C7x7(7), // The function will use a 7x7 sized sample from each cell. - ; - private final int value; - private DataMatrixCellSampleSize(int value) { - this.value = value; - } - public static DataMatrixCellSampleSize fromValue(int val) { - for (DataMatrixCellSampleSize v : values()) { - if (v.value == val) - return v; - } - return null; - } - public int getValue() { - return value; - } - } - - /** - * Forward Declare Data Structures - */ - - /** - * Data Structures - */ - - public static class DivisionModel extends DisposedStruct { - public float kappa; // The learned kappa coefficient of division model. - - private void init() { - - } - public DivisionModel() { - super(4); - init(); - } - public DivisionModel(double kappa) { - super(4); - this.kappa = (float)kappa; - } - protected DivisionModel(ByteBuffer backing, int offset) { - super(backing, offset, 4); - init(); - } - protected DivisionModel(long nativeObj, boolean owned) { - super(nativeObj, owned, 4); - init(); - } - protected void setBuffer(ByteBuffer backing, int offset) { - super.setBuffer(backing, offset, 4); - } - public void read() { - kappa = backing.getFloat(0); - } - public void write() { - backing.putFloat(0, kappa); - } - public int size() { - return 4; - } - } - - public static class FocalLength extends DisposedStruct { - public float fx; // Focal length in X direction. - public float fy; // Focal length in Y direction. - - private void init() { - - } - public FocalLength() { - super(8); - init(); - } - public FocalLength(double fx, double fy) { - super(8); - this.fx = (float)fx; - this.fy = (float)fy; - } - protected FocalLength(ByteBuffer backing, int offset) { - super(backing, offset, 8); - init(); - } - protected FocalLength(long nativeObj, boolean owned) { - super(nativeObj, owned, 8); - init(); - } - protected void setBuffer(ByteBuffer backing, int offset) { - super.setBuffer(backing, offset, 8); - } - public void read() { - fx = backing.getFloat(0); - fy = backing.getFloat(4); - } - public void write() { - backing.putFloat(0, fx); - backing.putFloat(4, fy); - } - public int size() { - return 8; - } - } - - public static class PolyModel extends DisposedStruct { - public float[] kCoeffs; // The learned radial coefficients of polynomial model. - public float p1; // The P1(learned tangential coefficients of polynomial model). - public float p2; // The P2(learned tangential coefficients of polynomial model). - private ByteBuffer kCoeffs_buf; - - private void init() { - kCoeffs = new float[0]; - } - public PolyModel() { - super(16); - init(); - } - public PolyModel(float[] kCoeffs, double p1, double p2) { - super(16); - this.kCoeffs = kCoeffs; - this.p1 = (float)p1; - this.p2 = (float)p2; - } - protected PolyModel(ByteBuffer backing, int offset) { - super(backing, offset, 16); - init(); - } - protected PolyModel(long nativeObj, boolean owned) { - super(nativeObj, owned, 16); - init(); - } - protected void setBuffer(ByteBuffer backing, int offset) { - super.setBuffer(backing, offset, 16); - } - public void read() { - int kCoeffs_numKCoeffs = backing.getInt(4); - long kCoeffs_addr = getPointer(backing, 0); - kCoeffs = new float[kCoeffs_numKCoeffs]; - if (kCoeffs_numKCoeffs > 0 && kCoeffs_addr != 0) { - newDirectByteBuffer(kCoeffs_addr, kCoeffs_numKCoeffs*4).asFloatBuffer().get(kCoeffs); - } - p1 = backing.getFloat(8); - p2 = backing.getFloat(12); - } - public void write() { - kCoeffs_buf = ByteBuffer.allocateDirect(kCoeffs.length*4).order(ByteOrder.nativeOrder()); - kCoeffs_buf.asFloatBuffer().put(kCoeffs).rewind(); - backing.putInt(4, kCoeffs.length); - putPointer(backing, 0, kCoeffs_buf); - backing.putFloat(8, p1); - backing.putFloat(12, p2); - } - public int size() { - return 16; - } - } - - public static class DistortionModelParams extends DisposedStruct { - public DistortionModel distortionModel; // Type of learned distortion model. - public PolyModel polyModel; // The learned coefficients of polynomial model. - public DivisionModel divisionModel; // The learned coefficient of division model. - - private void init() { - polyModel = new PolyModel(backing, 4); - divisionModel = new DivisionModel(backing, 20); - } - public DistortionModelParams() { - super(24); - init(); - } - public DistortionModelParams(DistortionModel distortionModel, PolyModel polyModel, DivisionModel divisionModel) { - super(24); - this.distortionModel = distortionModel; - this.polyModel = polyModel; - this.divisionModel = divisionModel; - } - protected DistortionModelParams(ByteBuffer backing, int offset) { - super(backing, offset, 24); - init(); - } - protected DistortionModelParams(long nativeObj, boolean owned) { - super(nativeObj, owned, 24); - init(); - } - protected void setBuffer(ByteBuffer backing, int offset) { - super.setBuffer(backing, offset, 24); - } - public void read() { - distortionModel = DistortionModel.fromValue(backing.getInt(0)); - polyModel.read(); - divisionModel.read(); - } - public void write() { - if (distortionModel != null) - backing.putInt(0, distortionModel.getValue()); - polyModel.write(); - divisionModel.write(); - } - public int size() { - return 24; - } - } - - public static class PointFloat extends DisposedStruct { - public float x; // The x-coordinate of the point. - public float y; // The y-coordinate of the point. - - private void init() { - - } - public PointFloat() { - super(8); - init(); - } - public PointFloat(double x, double y) { - super(8); - this.x = (float)x; - this.y = (float)y; - } - protected PointFloat(ByteBuffer backing, int offset) { - super(backing, offset, 8); - init(); - } - protected PointFloat(long nativeObj, boolean owned) { - super(nativeObj, owned, 8); - init(); - } - protected void setBuffer(ByteBuffer backing, int offset) { - super.setBuffer(backing, offset, 8); - } - public void read() { - x = backing.getFloat(0); - y = backing.getFloat(4); - } - public void write() { - backing.putFloat(0, x); - backing.putFloat(4, y); - } - public int size() { - return 8; - } - } - - public static class InternalParameters extends DisposedStruct { - public byte isInsufficientData; - public FocalLength focalLength; - public PointFloat opticalCenter; - - private void init() { - focalLength = new FocalLength(backing, 4); - opticalCenter = new PointFloat(backing, 12); - } - public InternalParameters() { - super(20); - init(); - } - public InternalParameters(byte isInsufficientData, FocalLength focalLength, PointFloat opticalCenter) { - super(20); - this.isInsufficientData = isInsufficientData; - this.focalLength = focalLength; - this.opticalCenter = opticalCenter; - } - protected InternalParameters(ByteBuffer backing, int offset) { - super(backing, offset, 20); - init(); - } - protected InternalParameters(long nativeObj, boolean owned) { - super(nativeObj, owned, 20); - init(); - } - protected void setBuffer(ByteBuffer backing, int offset) { - super.setBuffer(backing, offset, 20); - } - public void read() { - isInsufficientData = backing.get(0); - focalLength.read(); - opticalCenter.read(); - } - public void write() { - backing.put(0, isInsufficientData); - focalLength.write(); - opticalCenter.write(); - } - public int size() { - return 20; - } - } - - public static class MaxGridSize extends DisposedStruct { - public int xMax; // Maximum x limit for the grid size. - public int yMax; // Maximum y limit for the grid size. - - private void init() { - - } - public MaxGridSize() { - super(8); - init(); - } - public MaxGridSize(int xMax, int yMax) { - super(8); - this.xMax = xMax; - this.yMax = yMax; - } - protected MaxGridSize(ByteBuffer backing, int offset) { - super(backing, offset, 8); - init(); - } - protected MaxGridSize(long nativeObj, boolean owned) { - super(nativeObj, owned, 8); - init(); - } - protected void setBuffer(ByteBuffer backing, int offset) { - super.setBuffer(backing, offset, 8); - } - public void read() { - xMax = backing.getInt(0); - yMax = backing.getInt(4); - } - public void write() { - backing.putInt(0, xMax); - backing.putInt(4, yMax); - } - public int size() { - return 8; - } - } - - public static class ImageSize extends DisposedStruct { - public int xRes; // X resolution of the image. - public int yRes; // Y resolution of the image. - - private void init() { - - } - public ImageSize() { - super(8); - init(); - } - public ImageSize(int xRes, int yRes) { - super(8); - this.xRes = xRes; - this.yRes = yRes; - } - protected ImageSize(ByteBuffer backing, int offset) { - super(backing, offset, 8); - init(); - } - protected ImageSize(long nativeObj, boolean owned) { - super(nativeObj, owned, 8); - init(); - } - protected void setBuffer(ByteBuffer backing, int offset) { - super.setBuffer(backing, offset, 8); - } - public void read() { - xRes = backing.getInt(0); - yRes = backing.getInt(4); - } - public void write() { - backing.putInt(0, xRes); - backing.putInt(4, yRes); - } - public int size() { - return 8; - } - } - - public static class CalibrationReferencePoints extends DisposedStruct { - public PointDouble[] pixelCoords; // Specifies the coordinates of the pixel reference points. - public PointDouble[] realCoords; // Specifies the measuring unit associated with the image. - public CalibrationUnit units; // Specifies the units of X Step and Y Step. - public ImageSize imageSize; // Specifies the size of calibration template image. - private ByteBuffer pixelCoords_buf; - private ByteBuffer realCoords_buf; - - private void init() { - pixelCoords = new PointDouble[0]; - realCoords = new PointDouble[0]; - imageSize = new ImageSize(backing, 20); - } - public CalibrationReferencePoints() { - super(28); - init(); - } - public CalibrationReferencePoints(PointDouble[] pixelCoords, PointDouble[] realCoords, CalibrationUnit units, ImageSize imageSize) { - super(28); - this.pixelCoords = pixelCoords; - this.realCoords = realCoords; - this.units = units; - this.imageSize = imageSize; - } - protected CalibrationReferencePoints(ByteBuffer backing, int offset) { - super(backing, offset, 28); - init(); - } - protected CalibrationReferencePoints(long nativeObj, boolean owned) { - super(nativeObj, owned, 28); - init(); - } - protected void setBuffer(ByteBuffer backing, int offset) { - super.setBuffer(backing, offset, 28); - } - public void read() { - int pixelCoords_numPixelCoords = backing.getInt(4); - long pixelCoords_addr = getPointer(backing, 0); - pixelCoords = new PointDouble[pixelCoords_numPixelCoords]; - if (pixelCoords_numPixelCoords > 0 && pixelCoords_addr != 0) { - ByteBuffer bb = newDirectByteBuffer(pixelCoords_addr, pixelCoords_numPixelCoords*16); - for (int i=0, off=0; i 0 && realCoords_addr != 0) { - ByteBuffer bb = newDirectByteBuffer(realCoords_addr, realCoords_numRealCoords*16); - for (int i=0, off=0; i 0 && points_addr != 0) { - ByteBuffer bb = newDirectByteBuffer(points_addr, points_numberOfPoints*16); - for (int i=0, off=0; i 0 && bestFit_addr != 0) { - ByteBuffer bb = newDirectByteBuffer(bestFit_addr, bestFit_numberOfPoints*16); - for (int i=0, off=0; i 0 && polynomialCoefficients_addr != 0) { - newDirectByteBuffer(polynomialCoefficients_addr, polynomialCoefficients_numberOfCoefficients*8).asDoubleBuffer().get(polynomialCoefficients); - } - } - public void write() { - bestFit_buf = ByteBuffer.allocateDirect(bestFit.length*16).order(ByteOrder.nativeOrder()); - for (int i=0, off=0; i 0 && matchSetupData_addr != 0) { - getBytes(newDirectByteBuffer(matchSetupData_addr, matchSetupData_numMatchSetupData), matchSetupData, 0, matchSetupData_numMatchSetupData); - } - } - public void write() { - matchSetupData_buf = ByteBuffer.allocateDirect(matchSetupData.length); - putBytes(matchSetupData_buf, matchSetupData, 0, matchSetupData.length); - backing.putInt(4, matchSetupData.length); - putPointer(backing, 0, matchSetupData_buf); - } - public int size() { - return 8; - } - } - - public static class RangeSettingDouble extends DisposedStruct { - public SettingType settingType; // Match Constraints specifies the match option whose values you want to constrain by the given range. - public double min; // Min is the minimum value of the range for a given Match Constraint. - public double max; // Max is the maximum value of the range for a given Match Constraint. - - private void init() { - - } - public RangeSettingDouble() { - super(24); - init(); - } - public RangeSettingDouble(SettingType settingType, double min, double max) { - super(24); - this.settingType = settingType; - this.min = min; - this.max = max; - } - protected RangeSettingDouble(ByteBuffer backing, int offset) { - super(backing, offset, 24); - init(); - } - protected RangeSettingDouble(long nativeObj, boolean owned) { - super(nativeObj, owned, 24); - init(); - } - protected void setBuffer(ByteBuffer backing, int offset) { - super.setBuffer(backing, offset, 24); - } - public void read() { - settingType = SettingType.fromValue(backing.getInt(0)); - min = backing.getDouble(8); - max = backing.getDouble(16); - } - public void write() { - if (settingType != null) - backing.putInt(0, settingType.getValue()); - backing.putDouble(8, min); - backing.putDouble(16, max); - } - public int size() { - return 24; - } - } - - public static class GeometricAdvancedSetupDataOption extends DisposedStruct { - public GeometricSetupDataItem type; // It determines the option you want to use during the matching phase. - public double value; // Value is the value for the option you want to use during the matching phase. - - private void init() { - - } - public GeometricAdvancedSetupDataOption() { - super(16); - init(); - } - public GeometricAdvancedSetupDataOption(GeometricSetupDataItem type, double value) { - super(16); - this.type = type; - this.value = value; - } - protected GeometricAdvancedSetupDataOption(ByteBuffer backing, int offset) { - super(backing, offset, 16); - init(); - } - protected GeometricAdvancedSetupDataOption(long nativeObj, boolean owned) { - super(nativeObj, owned, 16); - init(); - } - protected void setBuffer(ByteBuffer backing, int offset) { - super.setBuffer(backing, offset, 16); - } - public void read() { - type = GeometricSetupDataItem.fromValue(backing.getInt(0)); - value = backing.getDouble(8); - } - public void write() { - if (type != null) - backing.putInt(0, type.getValue()); - backing.putDouble(8, value); - } - public int size() { - return 16; - } - } - - public static class ContourInfoReport extends DisposedStruct { - public PointDouble[] pointsPixel; // Points (pixel) specifies the location of every point detected on the curve, in pixels. - public PointDouble[] pointsReal; // Points (real) specifies the location of every point detected on the curve, in calibrated units. - public double[] curvaturePixel; // Curvature Pixel displays the curvature profile for the selected contour, in pixels. - public double[] curvatureReal; // Curvature Real displays the curvature profile for the selected contour, in calibrated units. - public double length; // Length (pixel) specifies the length, in pixels, of the curves in the image. - public double lengthReal; // Length (real) specifies the length, in calibrated units, of the curves within the curvature range. - public int hasEquation; // Has Equation specifies whether the contour has a fitted equation. - private ByteBuffer pointsPixel_buf; - private ByteBuffer pointsReal_buf; - private ByteBuffer curvaturePixel_buf; - private ByteBuffer curvatureReal_buf; - - private void init() { - pointsPixel = new PointDouble[0]; - pointsReal = new PointDouble[0]; - curvaturePixel = new double[0]; - curvatureReal = new double[0]; - } - public ContourInfoReport() { - super(56); - init(); - } - public ContourInfoReport(PointDouble[] pointsPixel, PointDouble[] pointsReal, double[] curvaturePixel, double[] curvatureReal, double length, double lengthReal, int hasEquation) { - super(56); - this.pointsPixel = pointsPixel; - this.pointsReal = pointsReal; - this.curvaturePixel = curvaturePixel; - this.curvatureReal = curvatureReal; - this.length = length; - this.lengthReal = lengthReal; - this.hasEquation = hasEquation; - } - protected ContourInfoReport(ByteBuffer backing, int offset) { - super(backing, offset, 56); - init(); - } - protected ContourInfoReport(long nativeObj, boolean owned) { - super(nativeObj, owned, 56); - init(); - } - protected void setBuffer(ByteBuffer backing, int offset) { - super.setBuffer(backing, offset, 56); - } - public void read() { - int pointsPixel_numPointsPixel = backing.getInt(4); - long pointsPixel_addr = getPointer(backing, 0); - pointsPixel = new PointDouble[pointsPixel_numPointsPixel]; - if (pointsPixel_numPointsPixel > 0 && pointsPixel_addr != 0) { - ByteBuffer bb = newDirectByteBuffer(pointsPixel_addr, pointsPixel_numPointsPixel*16); - for (int i=0, off=0; i 0 && pointsReal_addr != 0) { - ByteBuffer bb = newDirectByteBuffer(pointsReal_addr, pointsReal_numPointsReal*16); - for (int i=0, off=0; i 0 && curvaturePixel_addr != 0) { - newDirectByteBuffer(curvaturePixel_addr, curvaturePixel_numCurvaturePixel*8).asDoubleBuffer().get(curvaturePixel); - } - int curvatureReal_numCurvatureReal = backing.getInt(28); - long curvatureReal_addr = getPointer(backing, 24); - curvatureReal = new double[curvatureReal_numCurvatureReal]; - if (curvatureReal_numCurvatureReal > 0 && curvatureReal_addr != 0) { - newDirectByteBuffer(curvatureReal_addr, curvatureReal_numCurvatureReal*8).asDoubleBuffer().get(curvatureReal); - } - length = backing.getDouble(32); - lengthReal = backing.getDouble(40); - hasEquation = backing.getInt(48); - } - public void write() { - pointsPixel_buf = ByteBuffer.allocateDirect(pointsPixel.length*16).order(ByteOrder.nativeOrder()); - for (int i=0, off=0; i 0 && labelOut_addr != 0) { - ByteBuffer bb = newDirectByteBuffer(labelOut_addr, labelOut_numLabelOut*8); - for (int i=0, off=0; i 0 && roiArray_addr != 0) { - ByteBuffer bb = newDirectByteBuffer(roiArray_addr, roiArray_numOfROIs*4); - for (int i=0, off=0; i 0 && labelsOutArray_addr != 0) { - newDirectByteBuffer(labelsOutArray_addr, labelsOutArray_numOfLabels*4).asIntBuffer().get(labelsOutArray); - } - int isTooManyVectorsArray_isTooManyVectorsArraySize = backing.getInt(20); - long isTooManyVectorsArray_addr = getPointer(backing, 16); - isTooManyVectorsArray = new int[isTooManyVectorsArray_isTooManyVectorsArraySize]; - if (isTooManyVectorsArray_isTooManyVectorsArraySize > 0 && isTooManyVectorsArray_addr != 0) { - newDirectByteBuffer(isTooManyVectorsArray_addr, isTooManyVectorsArray_isTooManyVectorsArraySize*4).asIntBuffer().get(isTooManyVectorsArray); - } - } - public void write() { - roiArray_buf = ByteBuffer.allocateDirect(roiArray.length*4).order(ByteOrder.nativeOrder()); - for (int i=0, off=0; i 0 && curvePoints_addr != 0) { - ByteBuffer bb = newDirectByteBuffer(curvePoints_addr, curvePoints_numCurvePoints*16); - for (int i=0, off=0; i 0 && curves_addr != 0) { - ByteBuffer bb = newDirectByteBuffer(curves_addr, curves_numCurves*48); - for (int i=0, off=0; i 0 && distances_addr != 0) { - ByteBuffer bb = newDirectByteBuffer(distances_addr, distances_numDistances*40); - for (int i=0, off=0; i 0 && distancesReal_addr != 0) { - ByteBuffer bb = newDirectByteBuffer(distancesReal_addr, distancesReal_numDistancesReal*40); - for (int i=0, off=0; i 0 && templateSubsection_addr != 0) { - ByteBuffer bb = newDirectByteBuffer(templateSubsection_addr, templateSubsection_numTemplateSubsection*16); - for (int i=0, off=0; i 0 && targetSubsection_addr != 0) { - ByteBuffer bb = newDirectByteBuffer(targetSubsection_addr, targetSubsection_numTargetSubsection*16); - for (int i=0, off=0; i 0 && classifiedDistances_addr != 0) { - ByteBuffer bb = newDirectByteBuffer(classifiedDistances_addr, classifiedDistances_numClassifiedDistances*56); - for (int i=0, off=0; i 0 && curvaturePixel_addr != 0) { - newDirectByteBuffer(curvaturePixel_addr, curvaturePixel_numCurvaturePixel*8).asDoubleBuffer().get(curvaturePixel); - } - int curvatureReal_numCurvatureReal = backing.getInt(12); - long curvatureReal_addr = getPointer(backing, 8); - curvatureReal = new double[curvatureReal_numCurvatureReal]; - if (curvatureReal_numCurvatureReal > 0 && curvatureReal_addr != 0) { - newDirectByteBuffer(curvatureReal_addr, curvatureReal_numCurvatureReal*8).asDoubleBuffer().get(curvatureReal); - } - } - public void write() { - curvaturePixel_buf = ByteBuffer.allocateDirect(curvaturePixel.length*8).order(ByteOrder.nativeOrder()); - curvaturePixel_buf.asDoubleBuffer().put(curvaturePixel).rewind(); - backing.putInt(4, curvaturePixel.length); - putPointer(backing, 0, curvaturePixel_buf); - curvatureReal_buf = ByteBuffer.allocateDirect(curvatureReal.length*8).order(ByteOrder.nativeOrder()); - curvatureReal_buf.asDoubleBuffer().put(curvatureReal).rewind(); - backing.putInt(12, curvatureReal.length); - putPointer(backing, 8, curvatureReal_buf); - } - public int size() { - return 16; - } - } - - public static class ContourOverlaySettings extends DisposedStruct { - public int overlay; // Overlay specifies whether to display the overlay on the image. - public RGBValue color; // Color is the color of the overlay. - public int width; // Width specifies the width of the overlay in pixels. - public int maintainWidth; // Maintain Width? specifies whether you want the overlay measured in screen pixels or image pixels. - - private void init() { - color = new RGBValue(backing, 4); - } - public ContourOverlaySettings() { - super(16); - init(); - } - public ContourOverlaySettings(int overlay, RGBValue color, int width, int maintainWidth) { - super(16); - this.overlay = overlay; - this.color = color; - this.width = width; - this.maintainWidth = maintainWidth; - } - protected ContourOverlaySettings(ByteBuffer backing, int offset) { - super(backing, offset, 16); - init(); - } - protected ContourOverlaySettings(long nativeObj, boolean owned) { - super(nativeObj, owned, 16); - init(); - } - protected void setBuffer(ByteBuffer backing, int offset) { - super.setBuffer(backing, offset, 16); - } - public void read() { - overlay = backing.getInt(0); - color.read(); - width = backing.getInt(8); - maintainWidth = backing.getInt(12); - } - public void write() { - backing.putInt(0, overlay); - color.write(); - backing.putInt(8, width); - backing.putInt(12, maintainWidth); - } - public int size() { - return 16; - } - } - - public static class CurveParameters extends DisposedStruct { - public ExtractionMode extractionMode; // Specifies the method the function uses to identify curves in the image. - public int threshold; // Specifies the minimum contrast a seed point must have in order to begin a curve. - public EdgeFilterSize filterSize; // Specifies the width of the edge filter the function uses to identify curves in the image. - public int minLength; // Specifies the length, in pixels, of the smallest curve the function will extract. - public int searchStep; // Search Step Size specifies the distance, in the y direction, between the image rows that the algorithm inspects for curve seed points. - public int maxEndPointGap; // Specifies the maximum gap, in pixels, between the endpoints of a curve that the function identifies as a closed curve. - public int subpixel; // Subpixel specifies whether to detect curve points with subpixel accuracy. - - private void init() { - - } - public CurveParameters() { - super(28); - init(); - } - public CurveParameters(ExtractionMode extractionMode, int threshold, EdgeFilterSize filterSize, int minLength, int searchStep, int maxEndPointGap, int subpixel) { - super(28); - this.extractionMode = extractionMode; - this.threshold = threshold; - this.filterSize = filterSize; - this.minLength = minLength; - this.searchStep = searchStep; - this.maxEndPointGap = maxEndPointGap; - this.subpixel = subpixel; - } - protected CurveParameters(ByteBuffer backing, int offset) { - super(backing, offset, 28); - init(); - } - protected CurveParameters(long nativeObj, boolean owned) { - super(nativeObj, owned, 28); - init(); - } - protected void setBuffer(ByteBuffer backing, int offset) { - super.setBuffer(backing, offset, 28); - } - public void read() { - extractionMode = ExtractionMode.fromValue(backing.getInt(0)); - threshold = backing.getInt(4); - filterSize = EdgeFilterSize.fromValue(backing.getInt(8)); - minLength = backing.getInt(12); - searchStep = backing.getInt(16); - maxEndPointGap = backing.getInt(20); - subpixel = backing.getInt(24); - } - public void write() { - if (extractionMode != null) - backing.putInt(0, extractionMode.getValue()); - backing.putInt(4, threshold); - if (filterSize != null) - backing.putInt(8, filterSize.getValue()); - backing.putInt(12, minLength); - backing.putInt(16, searchStep); - backing.putInt(20, maxEndPointGap); - backing.putInt(24, subpixel); - } - public int size() { - return 28; - } - } - - public static class ExtractContourReport extends DisposedStruct { - public PointDouble[] contourPoints; // Contour Points specifies every point found on the contour. - public PointDouble[] sourcePoints; // Source Image Points specifies every point found on the contour in the source image. - private ByteBuffer contourPoints_buf; - private ByteBuffer sourcePoints_buf; - - private void init() { - contourPoints = new PointDouble[0]; - sourcePoints = new PointDouble[0]; - } - public ExtractContourReport() { - super(16); - init(); - } - public ExtractContourReport(PointDouble[] contourPoints, PointDouble[] sourcePoints) { - super(16); - this.contourPoints = contourPoints; - this.sourcePoints = sourcePoints; - } - protected ExtractContourReport(ByteBuffer backing, int offset) { - super(backing, offset, 16); - init(); - } - protected ExtractContourReport(long nativeObj, boolean owned) { - super(nativeObj, owned, 16); - init(); - } - protected void setBuffer(ByteBuffer backing, int offset) { - super.setBuffer(backing, offset, 16); - } - public void read() { - int contourPoints_numContourPoints = backing.getInt(4); - long contourPoints_addr = getPointer(backing, 0); - contourPoints = new PointDouble[contourPoints_numContourPoints]; - if (contourPoints_numContourPoints > 0 && contourPoints_addr != 0) { - ByteBuffer bb = newDirectByteBuffer(contourPoints_addr, contourPoints_numContourPoints*16); - for (int i=0, off=0; i 0 && sourcePoints_addr != 0) { - ByteBuffer bb = newDirectByteBuffer(sourcePoints_addr, sourcePoints_numSourcePoints*16); - for (int i=0, off=0; i 0 && waveletBands_addr != 0) { - newDirectByteBuffer(waveletBands_addr, waveletBands_numWaveletBands*4).asIntBuffer().get(waveletBands); - } - textureFeaturesRows = backing.getInt(12); - textureFeaturesCols = backing.getInt(16); - } - public void write() { - waveletBands_buf = ByteBuffer.allocateDirect(waveletBands.length*4).order(ByteOrder.nativeOrder()); - waveletBands_buf.asIntBuffer().put(waveletBands).rewind(); - backing.putInt(4, waveletBands.length); - putPointer(backing, 0, waveletBands_buf); - backing.putInt(12, textureFeaturesRows); - backing.putInt(16, textureFeaturesCols); - } - public int size() { - return 20; - } - } - - public static class WaveletBandsReport extends DisposedStruct { - public float LHLBand; // 2-D array for LHL Band. - public int rows; // Number of Rows for each of the 2-D arrays. - public int cols; // Number of Columns for each of the 2-D arrays. - - private void init() { - - } - public WaveletBandsReport() { - super(40); - init(); - } - public WaveletBandsReport(double LHLBand, int rows, int cols) { - super(40); - this.LHLBand = (float)LHLBand; - this.rows = rows; - this.cols = cols; - } - protected WaveletBandsReport(ByteBuffer backing, int offset) { - super(backing, offset, 40); - init(); - } - protected WaveletBandsReport(long nativeObj, boolean owned) { - super(nativeObj, owned, 40); - init(); - } - protected void setBuffer(ByteBuffer backing, int offset) { - super.setBuffer(backing, offset, 40); - } - public void read() { - LHLBand = backing.getFloat(24); - rows = backing.getInt(32); - cols = backing.getInt(36); - } - public void write() { - backing.putFloat(24, LHLBand); - backing.putInt(32, rows); - backing.putInt(36, cols); - } - public int size() { - return 40; - } - } - - public static class CircleFitOptions extends DisposedStruct { - public int maxRadius; // Specifies the acceptable distance, in pixels, that a point determined to belong to the circle can be from the perimeter of the circle. - public double stepSize; // Step Size is the angle, in degrees, between each radial line in the annular region. - public RakeProcessType processType; // Method used to process the data extracted for edge detection. - - private void init() { - - } - public CircleFitOptions() { - super(24); - init(); - } - public CircleFitOptions(int maxRadius, double stepSize, RakeProcessType processType) { - super(24); - this.maxRadius = maxRadius; - this.stepSize = stepSize; - this.processType = processType; - } - protected CircleFitOptions(ByteBuffer backing, int offset) { - super(backing, offset, 24); - init(); - } - protected CircleFitOptions(long nativeObj, boolean owned) { - super(nativeObj, owned, 24); - init(); - } - protected void setBuffer(ByteBuffer backing, int offset) { - super.setBuffer(backing, offset, 24); - } - public void read() { - maxRadius = backing.getInt(0); - stepSize = backing.getDouble(8); - processType = RakeProcessType.fromValue(backing.getInt(16)); - } - public void write() { - backing.putInt(0, maxRadius); - backing.putDouble(8, stepSize); - if (processType != null) - backing.putInt(16, processType.getValue()); - } - public int size() { - return 24; - } - } - - public static class EdgeOptions2 extends DisposedStruct { - public EdgePolaritySearchMode polarity; // Specifies the polarity of the edges to be found. - public int kernelSize; // Specifies the size of the edge detection kernel. - public int width; // Specifies the number of pixels averaged perpendicular to the search direction to compute the edge profile strength at each point along the search ROI. - public float minThreshold; // Specifies the minimum edge strength (gradient magnitude) required for a detected edge. - public InterpolationMethod interpolationType; // Specifies the interpolation method used to locate the edge position. - public ColumnProcessingMode columnProcessingMode; // Specifies the method used to find the straight edge. - - private void init() { - - } - public EdgeOptions2() { - super(24); - init(); - } - public EdgeOptions2(EdgePolaritySearchMode polarity, int kernelSize, int width, double minThreshold, InterpolationMethod interpolationType, ColumnProcessingMode columnProcessingMode) { - super(24); - this.polarity = polarity; - this.kernelSize = kernelSize; - this.width = width; - this.minThreshold = (float)minThreshold; - this.interpolationType = interpolationType; - this.columnProcessingMode = columnProcessingMode; - } - protected EdgeOptions2(ByteBuffer backing, int offset) { - super(backing, offset, 24); - init(); - } - protected EdgeOptions2(long nativeObj, boolean owned) { - super(nativeObj, owned, 24); - init(); - } - protected void setBuffer(ByteBuffer backing, int offset) { - super.setBuffer(backing, offset, 24); - } - public void read() { - polarity = EdgePolaritySearchMode.fromValue(backing.getInt(0)); - kernelSize = backing.getInt(4); - width = backing.getInt(8); - minThreshold = backing.getFloat(12); - interpolationType = InterpolationMethod.fromValue(backing.getInt(16)); - columnProcessingMode = ColumnProcessingMode.fromValue(backing.getInt(20)); - } - public void write() { - if (polarity != null) - backing.putInt(0, polarity.getValue()); - backing.putInt(4, kernelSize); - backing.putInt(8, width); - backing.putFloat(12, minThreshold); - if (interpolationType != null) - backing.putInt(16, interpolationType.getValue()); - if (columnProcessingMode != null) - backing.putInt(20, columnProcessingMode.getValue()); - } - public int size() { - return 24; - } - } - - public static class FindCircularEdgeOptions extends DisposedStruct { - public SpokeDirection direction; // Specifies the Spoke direction to search in the ROI. - public int showSearchArea; // If TRUE, the function overlays the search area on the image. - public int showSearchLines; // If TRUE, the function overlays the search lines used to locate the edges on the image. - public int showEdgesFound; // If TRUE, the function overlays the locations of the edges found on the image. - public int showResult; // If TRUE, the function overlays the hit lines to the object and the edge used to generate the hit line on the result image. - public RGBValue searchAreaColor; // Specifies the RGB color value to use to overlay the search area. - public RGBValue searchLinesColor; // Specifies the RGB color value to use to overlay the search lines. - public RGBValue searchEdgesColor; // Specifies the RGB color value to use to overlay the search edges. - public RGBValue resultColor; // Specifies the RGB color value to use to overlay the results. - public String overlayGroupName; // Specifies the overlay group name to assign to the overlays. - public EdgeOptions2 edgeOptions; // Specifies the edge detection options along a single search line. - private ByteBuffer overlayGroupName_buf; - - private void init() { - searchAreaColor = new RGBValue(backing, 20); - searchLinesColor = new RGBValue(backing, 24); - searchEdgesColor = new RGBValue(backing, 28); - resultColor = new RGBValue(backing, 32); - edgeOptions = new EdgeOptions2(backing, 40); - } - public FindCircularEdgeOptions() { - super(64); - init(); - } - public FindCircularEdgeOptions(SpokeDirection direction, int showSearchArea, int showSearchLines, int showEdgesFound, int showResult, RGBValue searchAreaColor, RGBValue searchLinesColor, RGBValue searchEdgesColor, RGBValue resultColor, String overlayGroupName, EdgeOptions2 edgeOptions) { - super(64); - this.direction = direction; - this.showSearchArea = showSearchArea; - this.showSearchLines = showSearchLines; - this.showEdgesFound = showEdgesFound; - this.showResult = showResult; - this.searchAreaColor = searchAreaColor; - this.searchLinesColor = searchLinesColor; - this.searchEdgesColor = searchEdgesColor; - this.resultColor = resultColor; - this.overlayGroupName = overlayGroupName; - this.edgeOptions = edgeOptions; - } - protected FindCircularEdgeOptions(ByteBuffer backing, int offset) { - super(backing, offset, 64); - init(); - } - protected FindCircularEdgeOptions(long nativeObj, boolean owned) { - super(nativeObj, owned, 64); - init(); - } - protected void setBuffer(ByteBuffer backing, int offset) { - super.setBuffer(backing, offset, 64); - } - public void read() { - direction = SpokeDirection.fromValue(backing.getInt(0)); - showSearchArea = backing.getInt(4); - showSearchLines = backing.getInt(8); - showEdgesFound = backing.getInt(12); - showResult = backing.getInt(16); - searchAreaColor.read(); - searchLinesColor.read(); - searchEdgesColor.read(); - resultColor.read(); - long overlayGroupName_addr = getPointer(backing, 36); - if (overlayGroupName_addr == 0) - overlayGroupName = null; - else { - ByteBuffer bb = newDirectByteBuffer(overlayGroupName_addr, 1000); // FIXME - while (bb.get() != 0) {} - byte[] bytes = new byte[bb.position()-1]; - getBytes(bb, bytes, 0, bytes.length); - try { - overlayGroupName = new String(bytes, "UTF-8"); - } catch (UnsupportedEncodingException e) { - overlayGroupName = ""; - } - } - - edgeOptions.read(); - } - public void write() { - if (direction != null) - backing.putInt(0, direction.getValue()); - backing.putInt(4, showSearchArea); - backing.putInt(8, showSearchLines); - backing.putInt(12, showEdgesFound); - backing.putInt(16, showResult); - searchAreaColor.write(); - searchLinesColor.write(); - searchEdgesColor.write(); - resultColor.write(); - if (overlayGroupName != null) { - byte[] overlayGroupName_bytes; - try { - overlayGroupName_bytes = overlayGroupName.getBytes("UTF-8"); - } catch (UnsupportedEncodingException e) { - overlayGroupName_bytes = new byte[0]; - } - overlayGroupName_buf = ByteBuffer.allocateDirect(overlayGroupName_bytes.length+1); - putBytes(overlayGroupName_buf, overlayGroupName_bytes, 0, overlayGroupName_bytes.length).put(overlayGroupName_bytes.length, (byte)0); - } - putPointer(backing, 36, overlayGroupName == null ? 0 : getByteBufferAddress(overlayGroupName_buf)); - edgeOptions.write(); - } - public int size() { - return 64; - } - } - - public static class FindConcentricEdgeOptions extends DisposedStruct { - public ConcentricRakeDirection direction; // Specifies the Concentric Rake direction. - public int showSearchArea; // If TRUE, the function overlays the search area on the image. - public int showSearchLines; // If TRUE, the function overlays the search lines used to locate the edges on the image. - public int showEdgesFound; // If TRUE, the function overlays the locations of the edges found on the image. - public int showResult; // If TRUE, the function overlays the hit lines to the object and the edge used to generate the hit line on the result image. - public RGBValue searchAreaColor; // Specifies the RGB color value to use to overlay the search area. - public RGBValue searchLinesColor; // Specifies the RGB color value to use to overlay the search lines. - public RGBValue searchEdgesColor; // Specifies the RGB color value to use to overlay the search edges. - public RGBValue resultColor; // Specifies the RGB color value to use to overlay the results. - public String overlayGroupName; // Specifies the overlay group name to assign to the overlays. - public EdgeOptions2 edgeOptions; // Specifies the edge detection options along a single search line. - private ByteBuffer overlayGroupName_buf; - - private void init() { - searchAreaColor = new RGBValue(backing, 20); - searchLinesColor = new RGBValue(backing, 24); - searchEdgesColor = new RGBValue(backing, 28); - resultColor = new RGBValue(backing, 32); - edgeOptions = new EdgeOptions2(backing, 40); - } - public FindConcentricEdgeOptions() { - super(64); - init(); - } - public FindConcentricEdgeOptions(ConcentricRakeDirection direction, int showSearchArea, int showSearchLines, int showEdgesFound, int showResult, RGBValue searchAreaColor, RGBValue searchLinesColor, RGBValue searchEdgesColor, RGBValue resultColor, String overlayGroupName, EdgeOptions2 edgeOptions) { - super(64); - this.direction = direction; - this.showSearchArea = showSearchArea; - this.showSearchLines = showSearchLines; - this.showEdgesFound = showEdgesFound; - this.showResult = showResult; - this.searchAreaColor = searchAreaColor; - this.searchLinesColor = searchLinesColor; - this.searchEdgesColor = searchEdgesColor; - this.resultColor = resultColor; - this.overlayGroupName = overlayGroupName; - this.edgeOptions = edgeOptions; - } - protected FindConcentricEdgeOptions(ByteBuffer backing, int offset) { - super(backing, offset, 64); - init(); - } - protected FindConcentricEdgeOptions(long nativeObj, boolean owned) { - super(nativeObj, owned, 64); - init(); - } - protected void setBuffer(ByteBuffer backing, int offset) { - super.setBuffer(backing, offset, 64); - } - public void read() { - direction = ConcentricRakeDirection.fromValue(backing.getInt(0)); - showSearchArea = backing.getInt(4); - showSearchLines = backing.getInt(8); - showEdgesFound = backing.getInt(12); - showResult = backing.getInt(16); - searchAreaColor.read(); - searchLinesColor.read(); - searchEdgesColor.read(); - resultColor.read(); - long overlayGroupName_addr = getPointer(backing, 36); - if (overlayGroupName_addr == 0) - overlayGroupName = null; - else { - ByteBuffer bb = newDirectByteBuffer(overlayGroupName_addr, 1000); // FIXME - while (bb.get() != 0) {} - byte[] bytes = new byte[bb.position()-1]; - getBytes(bb, bytes, 0, bytes.length); - try { - overlayGroupName = new String(bytes, "UTF-8"); - } catch (UnsupportedEncodingException e) { - overlayGroupName = ""; - } - } - - edgeOptions.read(); - } - public void write() { - if (direction != null) - backing.putInt(0, direction.getValue()); - backing.putInt(4, showSearchArea); - backing.putInt(8, showSearchLines); - backing.putInt(12, showEdgesFound); - backing.putInt(16, showResult); - searchAreaColor.write(); - searchLinesColor.write(); - searchEdgesColor.write(); - resultColor.write(); - if (overlayGroupName != null) { - byte[] overlayGroupName_bytes; - try { - overlayGroupName_bytes = overlayGroupName.getBytes("UTF-8"); - } catch (UnsupportedEncodingException e) { - overlayGroupName_bytes = new byte[0]; - } - overlayGroupName_buf = ByteBuffer.allocateDirect(overlayGroupName_bytes.length+1); - putBytes(overlayGroupName_buf, overlayGroupName_bytes, 0, overlayGroupName_bytes.length).put(overlayGroupName_bytes.length, (byte)0); - } - putPointer(backing, 36, overlayGroupName == null ? 0 : getByteBufferAddress(overlayGroupName_buf)); - edgeOptions.write(); - } - public int size() { - return 64; - } - } - - public static class ConcentricEdgeFitOptions extends DisposedStruct { - public int maxRadius; // Specifies the acceptable distance, in pixels, that a point determined to belong to the circle can be from the perimeter of the circle. - public double stepSize; // The sampling factor that determines the gap between the rake lines. - public RakeProcessType processType; // Method used to process the data extracted for edge detection. - - private void init() { - - } - public ConcentricEdgeFitOptions() { - super(24); - init(); - } - public ConcentricEdgeFitOptions(int maxRadius, double stepSize, RakeProcessType processType) { - super(24); - this.maxRadius = maxRadius; - this.stepSize = stepSize; - this.processType = processType; - } - protected ConcentricEdgeFitOptions(ByteBuffer backing, int offset) { - super(backing, offset, 24); - init(); - } - protected ConcentricEdgeFitOptions(long nativeObj, boolean owned) { - super(nativeObj, owned, 24); - init(); - } - protected void setBuffer(ByteBuffer backing, int offset) { - super.setBuffer(backing, offset, 24); - } - public void read() { - maxRadius = backing.getInt(0); - stepSize = backing.getDouble(8); - processType = RakeProcessType.fromValue(backing.getInt(16)); - } - public void write() { - backing.putInt(0, maxRadius); - backing.putDouble(8, stepSize); - if (processType != null) - backing.putInt(16, processType.getValue()); - } - public int size() { - return 24; - } - } - - public static class FindConcentricEdgeReport extends DisposedStruct { - public PointFloat startPt; // Pixel Coordinates for starting point of the edge. - public PointFloat endPt; // Pixel Coordinates for end point of the edge. - public PointFloat startPtCalibrated; // Real world Coordinates for starting point of the edge. - public PointFloat endPtCalibrated; // Real world Coordinates for end point of the edge. - public double angle; // Angle of the edge found. - public double angleCalibrated; // Calibrated angle of the edge found. - public double straightness; // The straightness value of the detected straight edge. - public double avgStrength; // Average strength of the egde found. - public double avgSNR; // Average SNR(Signal to Noise Ratio) for the edge found. - public int lineFound; // If the edge is found or not. - - private void init() { - startPt = new PointFloat(backing, 0); - endPt = new PointFloat(backing, 8); - startPtCalibrated = new PointFloat(backing, 16); - endPtCalibrated = new PointFloat(backing, 24); - } - public FindConcentricEdgeReport() { - super(80); - init(); - } - public FindConcentricEdgeReport(PointFloat startPt, PointFloat endPt, PointFloat startPtCalibrated, PointFloat endPtCalibrated, double angle, double angleCalibrated, double straightness, double avgStrength, double avgSNR, int lineFound) { - super(80); - this.startPt = startPt; - this.endPt = endPt; - this.startPtCalibrated = startPtCalibrated; - this.endPtCalibrated = endPtCalibrated; - this.angle = angle; - this.angleCalibrated = angleCalibrated; - this.straightness = straightness; - this.avgStrength = avgStrength; - this.avgSNR = avgSNR; - this.lineFound = lineFound; - } - protected FindConcentricEdgeReport(ByteBuffer backing, int offset) { - super(backing, offset, 80); - init(); - } - protected FindConcentricEdgeReport(long nativeObj, boolean owned) { - super(nativeObj, owned, 80); - init(); - } - protected void setBuffer(ByteBuffer backing, int offset) { - super.setBuffer(backing, offset, 80); - } - public void read() { - startPt.read(); - endPt.read(); - startPtCalibrated.read(); - endPtCalibrated.read(); - angle = backing.getDouble(32); - angleCalibrated = backing.getDouble(40); - straightness = backing.getDouble(48); - avgStrength = backing.getDouble(56); - avgSNR = backing.getDouble(64); - lineFound = backing.getInt(72); - } - public void write() { - startPt.write(); - endPt.write(); - startPtCalibrated.write(); - endPtCalibrated.write(); - backing.putDouble(32, angle); - backing.putDouble(40, angleCalibrated); - backing.putDouble(48, straightness); - backing.putDouble(56, avgStrength); - backing.putDouble(64, avgSNR); - backing.putInt(72, lineFound); - } - public int size() { - return 80; - } - } - - public static class FindCircularEdgeReport extends DisposedStruct { - public PointFloat centerCalibrated; // Real world Coordinates of the Center. - public double radiusCalibrated; // Real world radius of the Circular Edge found. - public PointFloat center; // Pixel Coordinates of the Center. - public double radius; // Radius in pixels of the Circular Edge found. - public double roundness; // The roundness of the calculated circular edge. - public double avgStrength; // Average strength of the egde found. - public double avgSNR; // Average SNR(Signal to Noise Ratio) for the edge found. - public int circleFound; // If the circlular edge is found or not. - - private void init() { - centerCalibrated = new PointFloat(backing, 0); - center = new PointFloat(backing, 16); - } - public FindCircularEdgeReport() { - super(64); - init(); - } - public FindCircularEdgeReport(PointFloat centerCalibrated, double radiusCalibrated, PointFloat center, double radius, double roundness, double avgStrength, double avgSNR, int circleFound) { - super(64); - this.centerCalibrated = centerCalibrated; - this.radiusCalibrated = radiusCalibrated; - this.center = center; - this.radius = radius; - this.roundness = roundness; - this.avgStrength = avgStrength; - this.avgSNR = avgSNR; - this.circleFound = circleFound; - } - protected FindCircularEdgeReport(ByteBuffer backing, int offset) { - super(backing, offset, 64); - init(); - } - protected FindCircularEdgeReport(long nativeObj, boolean owned) { - super(nativeObj, owned, 64); - init(); - } - protected void setBuffer(ByteBuffer backing, int offset) { - super.setBuffer(backing, offset, 64); - } - public void read() { - centerCalibrated.read(); - radiusCalibrated = backing.getDouble(8); - center.read(); - radius = backing.getDouble(24); - roundness = backing.getDouble(32); - avgStrength = backing.getDouble(40); - avgSNR = backing.getDouble(48); - circleFound = backing.getInt(56); - } - public void write() { - centerCalibrated.write(); - backing.putDouble(8, radiusCalibrated); - center.write(); - backing.putDouble(24, radius); - backing.putDouble(32, roundness); - backing.putDouble(40, avgStrength); - backing.putDouble(48, avgSNR); - backing.putInt(56, circleFound); - } - public int size() { - return 64; - } - } - - public static class WindowSize extends DisposedStruct { - public int x; // Window lenght on X direction. - public int y; // Window lenght on Y direction. - public int stepSize; // Distance between windows. - - private void init() { - - } - public WindowSize() { - super(12); - init(); - } - public WindowSize(int x, int y, int stepSize) { - super(12); - this.x = x; - this.y = y; - this.stepSize = stepSize; - } - protected WindowSize(ByteBuffer backing, int offset) { - super(backing, offset, 12); - init(); - } - protected WindowSize(long nativeObj, boolean owned) { - super(nativeObj, owned, 12); - init(); - } - protected void setBuffer(ByteBuffer backing, int offset) { - super.setBuffer(backing, offset, 12); - } - public void read() { - x = backing.getInt(0); - y = backing.getInt(4); - stepSize = backing.getInt(8); - } - public void write() { - backing.putInt(0, x); - backing.putInt(4, y); - backing.putInt(8, stepSize); - } - public int size() { - return 12; - } - } - - public static class DisplacementVector extends DisposedStruct { - public int x; // length on X direction. - public int y; // length on Y direction. - - private void init() { - - } - public DisplacementVector() { - super(8); - init(); - } - public DisplacementVector(int x, int y) { - super(8); - this.x = x; - this.y = y; - } - protected DisplacementVector(ByteBuffer backing, int offset) { - super(backing, offset, 8); - init(); - } - protected DisplacementVector(long nativeObj, boolean owned) { - super(nativeObj, owned, 8); - init(); - } - protected void setBuffer(ByteBuffer backing, int offset) { - super.setBuffer(backing, offset, 8); - } - public void read() { - x = backing.getInt(0); - y = backing.getInt(4); - } - public void write() { - backing.putInt(0, x); - backing.putInt(4, y); - } - public int size() { - return 8; - } - } - - public static class WaveletOptions extends DisposedStruct { - public WaveletType typeOfWavelet; // Type of wavelet(db, bior. - public float minEnergy; // Minimum Energy in the bands to consider for texture defect detection. - - private void init() { - - } - public WaveletOptions() { - super(8); - init(); - } - public WaveletOptions(WaveletType typeOfWavelet, double minEnergy) { - super(8); - this.typeOfWavelet = typeOfWavelet; - this.minEnergy = (float)minEnergy; - } - protected WaveletOptions(ByteBuffer backing, int offset) { - super(backing, offset, 8); - init(); - } - protected WaveletOptions(long nativeObj, boolean owned) { - super(nativeObj, owned, 8); - init(); - } - protected void setBuffer(ByteBuffer backing, int offset) { - super.setBuffer(backing, offset, 8); - } - public void read() { - typeOfWavelet = WaveletType.fromValue(backing.getInt(0)); - minEnergy = backing.getFloat(4); - } - public void write() { - if (typeOfWavelet != null) - backing.putInt(0, typeOfWavelet.getValue()); - backing.putFloat(4, minEnergy); - } - public int size() { - return 8; - } - } - - public static class CooccurrenceOptions extends DisposedStruct { - public int level; // Level/size of matrix. - public DisplacementVector displacement; // Displacemnet between pixels to accumulate the matrix. - - private void init() { - displacement = new DisplacementVector(backing, 4); - } - public CooccurrenceOptions() { - super(12); - init(); - } - public CooccurrenceOptions(int level, DisplacementVector displacement) { - super(12); - this.level = level; - this.displacement = displacement; - } - protected CooccurrenceOptions(ByteBuffer backing, int offset) { - super(backing, offset, 12); - init(); - } - protected CooccurrenceOptions(long nativeObj, boolean owned) { - super(nativeObj, owned, 12); - init(); - } - protected void setBuffer(ByteBuffer backing, int offset) { - super.setBuffer(backing, offset, 12); - } - public void read() { - level = backing.getInt(0); - displacement.read(); - } - public void write() { - backing.putInt(0, level); - displacement.write(); - } - public int size() { - return 12; - } - } - - public static class ParticleClassifierLocalThresholdOptions extends DisposedStruct { - public LocalThresholdMethod method; // Specifies the local thresholding method the function uses. - public ParticleType particleType; // Specifies what kind of particles to look for. - public int windowWidth; // The width of the rectangular window around the pixel on which the function performs the local threshold. - public int windowHeight; // The height of the rectangular window around the pixel on which the function performs the local threshold. - public double deviationWeight; // Specifies the k constant used in the Niblack local thresholding algorithm, which determines the weight applied to the variance calculation. - - private void init() { - - } - public ParticleClassifierLocalThresholdOptions() { - super(24); - init(); - } - public ParticleClassifierLocalThresholdOptions(LocalThresholdMethod method, ParticleType particleType, int windowWidth, int windowHeight, double deviationWeight) { - super(24); - this.method = method; - this.particleType = particleType; - this.windowWidth = windowWidth; - this.windowHeight = windowHeight; - this.deviationWeight = deviationWeight; - } - protected ParticleClassifierLocalThresholdOptions(ByteBuffer backing, int offset) { - super(backing, offset, 24); - init(); - } - protected ParticleClassifierLocalThresholdOptions(long nativeObj, boolean owned) { - super(nativeObj, owned, 24); - init(); - } - protected void setBuffer(ByteBuffer backing, int offset) { - super.setBuffer(backing, offset, 24); - } - public void read() { - method = LocalThresholdMethod.fromValue(backing.getInt(0)); - particleType = ParticleType.fromValue(backing.getInt(4)); - windowWidth = backing.getInt(8); - windowHeight = backing.getInt(12); - deviationWeight = backing.getDouble(16); - } - public void write() { - if (method != null) - backing.putInt(0, method.getValue()); - if (particleType != null) - backing.putInt(4, particleType.getValue()); - backing.putInt(8, windowWidth); - backing.putInt(12, windowHeight); - backing.putDouble(16, deviationWeight); - } - public int size() { - return 24; - } - } - - public static class RangeFloat extends DisposedStruct { - public float minValue; // The minimum value of the range. - public float maxValue; // The maximum value of the range. - - private void init() { - - } - public RangeFloat() { - super(8); - init(); - } - public RangeFloat(double minValue, double maxValue) { - super(8); - this.minValue = (float)minValue; - this.maxValue = (float)maxValue; - } - protected RangeFloat(ByteBuffer backing, int offset) { - super(backing, offset, 8); - init(); - } - protected RangeFloat(long nativeObj, boolean owned) { - super(nativeObj, owned, 8); - init(); - } - protected void setBuffer(ByteBuffer backing, int offset) { - super.setBuffer(backing, offset, 8); - } - public void read() { - minValue = backing.getFloat(0); - maxValue = backing.getFloat(4); - } - public void write() { - backing.putFloat(0, minValue); - backing.putFloat(4, maxValue); - } - public int size() { - return 8; - } - } - - public static class ParticleClassifierAutoThresholdOptions extends DisposedStruct { - public ThresholdMethod method; // The method for binary thresholding, which specifies how to calculate the classes. - public ParticleType particleType; // Specifies what kind of particles to look for. - public RangeFloat limits; // The limits on the automatic threshold range. - - private void init() { - limits = new RangeFloat(backing, 8); - } - public ParticleClassifierAutoThresholdOptions() { - super(16); - init(); - } - public ParticleClassifierAutoThresholdOptions(ThresholdMethod method, ParticleType particleType, RangeFloat limits) { - super(16); - this.method = method; - this.particleType = particleType; - this.limits = limits; - } - protected ParticleClassifierAutoThresholdOptions(ByteBuffer backing, int offset) { - super(backing, offset, 16); - init(); - } - protected ParticleClassifierAutoThresholdOptions(long nativeObj, boolean owned) { - super(nativeObj, owned, 16); - init(); - } - protected void setBuffer(ByteBuffer backing, int offset) { - super.setBuffer(backing, offset, 16); - } - public void read() { - method = ThresholdMethod.fromValue(backing.getInt(0)); - particleType = ParticleType.fromValue(backing.getInt(4)); - limits.read(); - } - public void write() { - if (method != null) - backing.putInt(0, method.getValue()); - if (particleType != null) - backing.putInt(4, particleType.getValue()); - limits.write(); - } - public int size() { - return 16; - } - } - - public static class ParticleClassifierPreprocessingOptions2 extends DisposedStruct { - public ParticleClassifierThresholdType thresholdType; // The type of threshold to perform on the image. - public RangeFloat manualThresholdRange; // The range of pixels to keep if manually thresholding the image. - public ParticleClassifierAutoThresholdOptions autoThresholdOptions; // The options used to auto threshold the image. - public ParticleClassifierLocalThresholdOptions localThresholdOptions; // The options used to local threshold the image. - public int rejectBorder; // Set this element to TRUE to reject border particles. - public int numErosions; // The number of erosions to perform. - - private void init() { - manualThresholdRange = new RangeFloat(backing, 4); - autoThresholdOptions = new ParticleClassifierAutoThresholdOptions(backing, 12); - localThresholdOptions = new ParticleClassifierLocalThresholdOptions(backing, 32); - } - public ParticleClassifierPreprocessingOptions2() { - super(64); - init(); - } - public ParticleClassifierPreprocessingOptions2(ParticleClassifierThresholdType thresholdType, RangeFloat manualThresholdRange, ParticleClassifierAutoThresholdOptions autoThresholdOptions, ParticleClassifierLocalThresholdOptions localThresholdOptions, int rejectBorder, int numErosions) { - super(64); - this.thresholdType = thresholdType; - this.manualThresholdRange = manualThresholdRange; - this.autoThresholdOptions = autoThresholdOptions; - this.localThresholdOptions = localThresholdOptions; - this.rejectBorder = rejectBorder; - this.numErosions = numErosions; - } - protected ParticleClassifierPreprocessingOptions2(ByteBuffer backing, int offset) { - super(backing, offset, 64); - init(); - } - protected ParticleClassifierPreprocessingOptions2(long nativeObj, boolean owned) { - super(nativeObj, owned, 64); - init(); - } - protected void setBuffer(ByteBuffer backing, int offset) { - super.setBuffer(backing, offset, 64); - } - public void read() { - thresholdType = ParticleClassifierThresholdType.fromValue(backing.getInt(0)); - manualThresholdRange.read(); - autoThresholdOptions.read(); - localThresholdOptions.read(); - rejectBorder = backing.getInt(56); - numErosions = backing.getInt(60); - } - public void write() { - if (thresholdType != null) - backing.putInt(0, thresholdType.getValue()); - manualThresholdRange.write(); - autoThresholdOptions.write(); - localThresholdOptions.write(); - backing.putInt(56, rejectBorder); - backing.putInt(60, numErosions); - } - public int size() { - return 64; - } - } - - public static class MeasureParticlesReport extends DisposedStruct { - public int numParticles; // The number of particles on which measurements were taken. - public int numMeasurements; // The number of measurements taken. - - private void init() { - - } - public MeasureParticlesReport() { - super(16); - init(); - } - public MeasureParticlesReport(int numParticles, int numMeasurements) { - super(16); - this.numParticles = numParticles; - this.numMeasurements = numMeasurements; - } - protected MeasureParticlesReport(ByteBuffer backing, int offset) { - super(backing, offset, 16); - init(); - } - protected MeasureParticlesReport(long nativeObj, boolean owned) { - super(nativeObj, owned, 16); - init(); - } - protected void setBuffer(ByteBuffer backing, int offset) { - super.setBuffer(backing, offset, 16); - } - public void read() { - numParticles = backing.getInt(8); - numMeasurements = backing.getInt(12); - } - public void write() { - backing.putInt(8, numParticles); - backing.putInt(12, numMeasurements); - } - public int size() { - return 16; - } - } - - public static class GeometricPatternMatch3 extends DisposedStruct { - public PointFloat position; // The location of the origin of the template in the match. - public float rotation; // The rotation of the match relative to the template image, in degrees. - public float scale; // The size of the match relative to the size of the template image, expressed as a percentage. - public float score; // The accuracy of the match. - public PointFloat[] corner; // An array of four points describing the rectangle surrounding the template image. - public int inverse; // This element is TRUE if the match is an inverse of the template image. - public float occlusion; // The percentage of the match that is occluded. - public float templateMatchCurveScore; // The accuracy of the match obtained by comparing the template curves to the curves in the match region. - public float matchTemplateCurveScore; // The accuracy of the match obtained by comparing the curves in the match region to the template curves. - public float correlationScore; // The accuracy of the match obtained by comparing the template image to the match region using a correlation metric that compares the two regions as a function of their pixel values. - public PointFloat calibratedPosition; // The location of the origin of the template in the match. - public float calibratedRotation; // The rotation of the match relative to the template image, in degrees. - public PointFloat[] calibratedCorner; // An array of four points describing the rectangle surrounding the template image. - - private void init() { - position = new PointFloat(backing, 0); - corner = new PointFloat[4]; - - for (int i=0, off=20; i<4; i++, off += 8) - corner[i] = new PointFloat(backing, off); - calibratedPosition = new PointFloat(backing, 72); - calibratedCorner = new PointFloat[4]; - - for (int i=0, off=84; i<4; i++, off += 8) - calibratedCorner[i] = new PointFloat(backing, off); - } - public GeometricPatternMatch3() { - super(116); - init(); - } - public GeometricPatternMatch3(PointFloat position, double rotation, double scale, double score, PointFloat[] corner, int inverse, double occlusion, double templateMatchCurveScore, double matchTemplateCurveScore, double correlationScore, PointFloat calibratedPosition, double calibratedRotation, PointFloat[] calibratedCorner) { - super(116); - this.position = position; - this.rotation = (float)rotation; - this.scale = (float)scale; - this.score = (float)score; - this.corner = corner; - this.inverse = inverse; - this.occlusion = (float)occlusion; - this.templateMatchCurveScore = (float)templateMatchCurveScore; - this.matchTemplateCurveScore = (float)matchTemplateCurveScore; - this.correlationScore = (float)correlationScore; - this.calibratedPosition = calibratedPosition; - this.calibratedRotation = (float)calibratedRotation; - this.calibratedCorner = calibratedCorner; - } - protected GeometricPatternMatch3(ByteBuffer backing, int offset) { - super(backing, offset, 116); - init(); - } - protected GeometricPatternMatch3(long nativeObj, boolean owned) { - super(nativeObj, owned, 116); - init(); - } - protected void setBuffer(ByteBuffer backing, int offset) { - super.setBuffer(backing, offset, 116); - } - public void read() { - position.read(); - rotation = backing.getFloat(8); - scale = backing.getFloat(12); - score = backing.getFloat(16); - for (PointFloat it : corner) { - it.read(); - } - inverse = backing.getInt(52); - occlusion = backing.getFloat(56); - templateMatchCurveScore = backing.getFloat(60); - matchTemplateCurveScore = backing.getFloat(64); - correlationScore = backing.getFloat(68); - calibratedPosition.read(); - calibratedRotation = backing.getFloat(80); - for (PointFloat it : calibratedCorner) { - it.read(); - } - } - public void write() { - position.write(); - backing.putFloat(8, rotation); - backing.putFloat(12, scale); - backing.putFloat(16, score); - for (PointFloat it : corner) { - it.write(); - } - backing.putInt(52, inverse); - backing.putFloat(56, occlusion); - backing.putFloat(60, templateMatchCurveScore); - backing.putFloat(64, matchTemplateCurveScore); - backing.putFloat(68, correlationScore); - calibratedPosition.write(); - backing.putFloat(80, calibratedRotation); - for (PointFloat it : calibratedCorner) { - it.write(); - } - } - public int size() { - return 116; - } - } - - public static class MatchGeometricPatternAdvancedOptions3 extends DisposedStruct { - public int subpixelIterations; // Specifies the maximum number of incremental improvements used to refine matches with subpixel information. - public double subpixelTolerance; // Specifies the maximum amount of change, in pixels, between consecutive incremental improvements in the match position before the function stops refining the match position. - public int initialMatchListLength; // Specifies the maximum size of the match list. - public int targetTemplateCurveScore; // Set this element to TRUE to specify that the function should calculate the match curve to template curve score and return it for each match result. - public int correlationScore; // Set this element to TRUE to specify that the function should calculate the correlation score and return it for each match result. - public double minMatchSeparationDistance; // Specifies the minimum separation distance, in pixels, between the origins of two matches that have unique positions. - public double minMatchSeparationAngle; // Specifies the minimum angular difference, in degrees, between two matches that have unique angles. - public double minMatchSeparationScale; // Specifies the minimum difference in scale, expressed as a percentage, between two matches that have unique scales. - public double maxMatchOverlap; // Specifies the maximum amount of overlap, expressed as a percentage, allowed between the bounding rectangles of two unique matches. - public int coarseResult; // Specifies whether you want the function to spend less time accurately estimating the location of a match. - public int enableCalibrationSupport; // Set this element to TRUE to specify the algorithm treat the inspection image as a calibrated image. - public ContrastMode enableContrastReversal; // Use this element to specify the contrast of the matches to search for in the image. - public GeometricMatchingSearchStrategy matchStrategy; // Specifies the aggressiveness of the search strategy. - public int refineMatchFactor; // Specifies the factor that is applied to the number of matches requested by the user to determine the number of matches that are refined at the initial matching stage. - public int subpixelMatchFactor; // Specifies the factor that is applied to the number of matches requested by the user to determine the number of matches that are evaluated at the final subpixel matching stage. - - private void init() { - - } - public MatchGeometricPatternAdvancedOptions3() { - super(88); - init(); - } - public MatchGeometricPatternAdvancedOptions3(int subpixelIterations, double subpixelTolerance, int initialMatchListLength, int targetTemplateCurveScore, int correlationScore, double minMatchSeparationDistance, double minMatchSeparationAngle, double minMatchSeparationScale, double maxMatchOverlap, int coarseResult, int enableCalibrationSupport, ContrastMode enableContrastReversal, GeometricMatchingSearchStrategy matchStrategy, int refineMatchFactor, int subpixelMatchFactor) { - super(88); - this.subpixelIterations = subpixelIterations; - this.subpixelTolerance = subpixelTolerance; - this.initialMatchListLength = initialMatchListLength; - this.targetTemplateCurveScore = targetTemplateCurveScore; - this.correlationScore = correlationScore; - this.minMatchSeparationDistance = minMatchSeparationDistance; - this.minMatchSeparationAngle = minMatchSeparationAngle; - this.minMatchSeparationScale = minMatchSeparationScale; - this.maxMatchOverlap = maxMatchOverlap; - this.coarseResult = coarseResult; - this.enableCalibrationSupport = enableCalibrationSupport; - this.enableContrastReversal = enableContrastReversal; - this.matchStrategy = matchStrategy; - this.refineMatchFactor = refineMatchFactor; - this.subpixelMatchFactor = subpixelMatchFactor; - } - protected MatchGeometricPatternAdvancedOptions3(ByteBuffer backing, int offset) { - super(backing, offset, 88); - init(); - } - protected MatchGeometricPatternAdvancedOptions3(long nativeObj, boolean owned) { - super(nativeObj, owned, 88); - init(); - } - protected void setBuffer(ByteBuffer backing, int offset) { - super.setBuffer(backing, offset, 88); - } - public void read() { - subpixelIterations = backing.getInt(0); - subpixelTolerance = backing.getDouble(8); - initialMatchListLength = backing.getInt(16); - targetTemplateCurveScore = backing.getInt(20); - correlationScore = backing.getInt(24); - minMatchSeparationDistance = backing.getDouble(32); - minMatchSeparationAngle = backing.getDouble(40); - minMatchSeparationScale = backing.getDouble(48); - maxMatchOverlap = backing.getDouble(56); - coarseResult = backing.getInt(64); - enableCalibrationSupport = backing.getInt(68); - enableContrastReversal = ContrastMode.fromValue(backing.getInt(72)); - matchStrategy = GeometricMatchingSearchStrategy.fromValue(backing.getInt(76)); - refineMatchFactor = backing.getInt(80); - subpixelMatchFactor = backing.getInt(84); - } - public void write() { - backing.putInt(0, subpixelIterations); - backing.putDouble(8, subpixelTolerance); - backing.putInt(16, initialMatchListLength); - backing.putInt(20, targetTemplateCurveScore); - backing.putInt(24, correlationScore); - backing.putDouble(32, minMatchSeparationDistance); - backing.putDouble(40, minMatchSeparationAngle); - backing.putDouble(48, minMatchSeparationScale); - backing.putDouble(56, maxMatchOverlap); - backing.putInt(64, coarseResult); - backing.putInt(68, enableCalibrationSupport); - if (enableContrastReversal != null) - backing.putInt(72, enableContrastReversal.getValue()); - if (matchStrategy != null) - backing.putInt(76, matchStrategy.getValue()); - backing.putInt(80, refineMatchFactor); - backing.putInt(84, subpixelMatchFactor); - } - public int size() { - return 88; - } - } - - public static class ColorOptions extends DisposedStruct { - public ColorClassificationResolution colorClassificationResolution; // Specifies the color resolution of the classifier. - public int useLuminance; // Specifies if the luminance band is going to be used in the feature vector. - public ColorMode colorMode; // Specifies the color mode of the classifier. - - private void init() { - - } - public ColorOptions() { - super(12); - init(); - } - public ColorOptions(ColorClassificationResolution colorClassificationResolution, int useLuminance, ColorMode colorMode) { - super(12); - this.colorClassificationResolution = colorClassificationResolution; - this.useLuminance = useLuminance; - this.colorMode = colorMode; - } - protected ColorOptions(ByteBuffer backing, int offset) { - super(backing, offset, 12); - init(); - } - protected ColorOptions(long nativeObj, boolean owned) { - super(nativeObj, owned, 12); - init(); - } - protected void setBuffer(ByteBuffer backing, int offset) { - super.setBuffer(backing, offset, 12); - } - public void read() { - colorClassificationResolution = ColorClassificationResolution.fromValue(backing.getInt(0)); - useLuminance = backing.getInt(4); - colorMode = ColorMode.fromValue(backing.getInt(8)); - } - public void write() { - if (colorClassificationResolution != null) - backing.putInt(0, colorClassificationResolution.getValue()); - backing.putInt(4, useLuminance); - if (colorMode != null) - backing.putInt(8, colorMode.getValue()); - } - public int size() { - return 12; - } - } - - public static class SampleScore extends DisposedStruct { - public String className; // The name of the class. - public float distance; // The distance from the item to this class. - public int index; // index of this sample. - private ByteBuffer className_buf; - - private void init() { - - } - public SampleScore() { - super(12); - init(); - } - public SampleScore(String className, double distance, int index) { - super(12); - this.className = className; - this.distance = (float)distance; - this.index = index; - } - protected SampleScore(ByteBuffer backing, int offset) { - super(backing, offset, 12); - init(); - } - protected SampleScore(long nativeObj, boolean owned) { - super(nativeObj, owned, 12); - init(); - } - protected void setBuffer(ByteBuffer backing, int offset) { - super.setBuffer(backing, offset, 12); - } - public void read() { - long className_addr = getPointer(backing, 0); - if (className_addr == 0) - className = null; - else { - ByteBuffer bb = newDirectByteBuffer(className_addr, 1000); // FIXME - while (bb.get() != 0) {} - byte[] bytes = new byte[bb.position()-1]; - getBytes(bb, bytes, 0, bytes.length); - try { - className = new String(bytes, "UTF-8"); - } catch (UnsupportedEncodingException e) { - className = ""; - } - } - - distance = backing.getFloat(4); - index = backing.getInt(8); - } - public void write() { - if (className != null) { - byte[] className_bytes; - try { - className_bytes = className.getBytes("UTF-8"); - } catch (UnsupportedEncodingException e) { - className_bytes = new byte[0]; - } - className_buf = ByteBuffer.allocateDirect(className_bytes.length+1); - putBytes(className_buf, className_bytes, 0, className_bytes.length).put(className_bytes.length, (byte)0); - } - putPointer(backing, 0, className == null ? 0 : getByteBufferAddress(className_buf)); - backing.putFloat(4, distance); - backing.putInt(8, index); - } - public int size() { - return 12; - } - } - - public static class ClassifierReportAdvanced extends DisposedStruct { - public String bestClassName; // The name of the best class for the sample. - public float classificationScore; // The similarity of the sample and the two closest classes in the classifier. - public float identificationScore; // The similarity of the sample and the assigned class. - public ClassScore[] allScores; // All classes and their scores. - public SampleScore[] sampleScores; // All samples and their scores. - private ByteBuffer bestClassName_buf; - private ByteBuffer allScores_buf; - private ByteBuffer sampleScores_buf; - - private void init() { - allScores = new ClassScore[0]; - sampleScores = new SampleScore[0]; - } - public ClassifierReportAdvanced() { - super(28); - init(); - } - public ClassifierReportAdvanced(String bestClassName, double classificationScore, double identificationScore, ClassScore[] allScores, SampleScore[] sampleScores) { - super(28); - this.bestClassName = bestClassName; - this.classificationScore = (float)classificationScore; - this.identificationScore = (float)identificationScore; - this.allScores = allScores; - this.sampleScores = sampleScores; - } - protected ClassifierReportAdvanced(ByteBuffer backing, int offset) { - super(backing, offset, 28); - init(); - } - protected ClassifierReportAdvanced(long nativeObj, boolean owned) { - super(nativeObj, owned, 28); - init(); - } - protected void setBuffer(ByteBuffer backing, int offset) { - super.setBuffer(backing, offset, 28); - } - public void read() { - long bestClassName_addr = getPointer(backing, 0); - if (bestClassName_addr == 0) - bestClassName = null; - else { - ByteBuffer bb = newDirectByteBuffer(bestClassName_addr, 1000); // FIXME - while (bb.get() != 0) {} - byte[] bytes = new byte[bb.position()-1]; - getBytes(bb, bytes, 0, bytes.length); - try { - bestClassName = new String(bytes, "UTF-8"); - } catch (UnsupportedEncodingException e) { - bestClassName = ""; - } - } - - classificationScore = backing.getFloat(4); - identificationScore = backing.getFloat(8); - int allScores_allScoresSize = backing.getInt(16); - long allScores_addr = getPointer(backing, 12); - allScores = new ClassScore[allScores_allScoresSize]; - if (allScores_allScoresSize > 0 && allScores_addr != 0) { - ByteBuffer bb = newDirectByteBuffer(allScores_addr, allScores_allScoresSize*8); - for (int i=0, off=0; i 0 && sampleScores_addr != 0) { - ByteBuffer bb = newDirectByteBuffer(sampleScores_addr, sampleScores_sampleScoresSize*12); - for (int i=0, off=0; i 0 && straightEdges_addr != 0) { - ByteBuffer bb = newDirectByteBuffer(straightEdges_addr, straightEdges_numStraightEdges*88); - for (int i=0, off=0; i 0 && characterReport_addr != 0) { - ByteBuffer bb = newDirectByteBuffer(characterReport_addr, characterReport_numCharacterReports*44); - for (int i=0, off=0; i 0 && edges_addr != 0) { - ByteBuffer bb = newDirectByteBuffer(edges_addr, edges_numEdges*56); - for (int i=0, off=0; i 0 && gradientInfo_addr != 0) { - newDirectByteBuffer(gradientInfo_addr, gradientInfo_numGradientInfo*8).asDoubleBuffer().get(gradientInfo); - } - calibrationValid = backing.getInt(16); - } - public void write() { - edges_buf = ByteBuffer.allocateDirect(edges.length*56).order(ByteOrder.nativeOrder()); - for (int i=0, off=0; i 0 && firstEdges_addr != 0) { - ByteBuffer bb = newDirectByteBuffer(firstEdges_addr, firstEdges_numFirstEdges*56); - for (int i=0, off=0; i 0 && lastEdges_addr != 0) { - ByteBuffer bb = newDirectByteBuffer(lastEdges_addr, lastEdges_numLastEdges*56); - for (int i=0, off=0; i 0 && searchArcs_addr != 0) { - ByteBuffer bb = newDirectByteBuffer(searchArcs_addr, searchArcs_numSearchArcs*56); - for (int i=0, off=0; i 0 && firstEdges_addr != 0) { - ByteBuffer bb = newDirectByteBuffer(firstEdges_addr, firstEdges_numFirstEdges*56); - for (int i=0, off=0; i 0 && lastEdges_addr != 0) { - ByteBuffer bb = newDirectByteBuffer(lastEdges_addr, lastEdges_numLastEdges*56); - for (int i=0, off=0; i 0 && searchLines_addr != 0) { - ByteBuffer bb = newDirectByteBuffer(searchLines_addr, searchLines_numSearchLines*36); - for (int i=0, off=0; i 0 && firstEdges_addr != 0) { - ByteBuffer bb = newDirectByteBuffer(firstEdges_addr, firstEdges_numFirstEdges*56); - for (int i=0, off=0; i 0 && lastEdges_addr != 0) { - ByteBuffer bb = newDirectByteBuffer(lastEdges_addr, lastEdges_numLastEdges*56); - for (int i=0, off=0; i 0 && searchLines_addr != 0) { - ByteBuffer bb = newDirectByteBuffer(searchLines_addr, searchLines_numSearchLines*36); - for (int i=0, off=0; i 0 && data_addr != 0) { - getBytes(newDirectByteBuffer(data_addr, data_dataLength), data, 0, data_dataLength); - } - } - public void write() { - if (mode != null) - backing.putInt(0, mode.getValue()); - backing.putInt(4, modeData); - data_buf = ByteBuffer.allocateDirect(data.length); - putBytes(data_buf, data, 0, data.length); - backing.putInt(12, data.length); - putPointer(backing, 8, data_buf); - } - public int size() { - return 16; - } - } - - public static class ParticleFilterOptions extends DisposedStruct { - public int rejectMatches; // Set this parameter to TRUE to transfer only those particles that do not meet all the criteria. - public int rejectBorder; // Set this element to TRUE to reject border particles. - public int connectivity8; // Set this parameter to TRUE to use connectivity-8 to determine whether particles are touching. - - private void init() { - - } - public ParticleFilterOptions() { - super(12); - init(); - } - public ParticleFilterOptions(int rejectMatches, int rejectBorder, int connectivity8) { - super(12); - this.rejectMatches = rejectMatches; - this.rejectBorder = rejectBorder; - this.connectivity8 = connectivity8; - } - protected ParticleFilterOptions(ByteBuffer backing, int offset) { - super(backing, offset, 12); - init(); - } - protected ParticleFilterOptions(long nativeObj, boolean owned) { - super(nativeObj, owned, 12); - init(); - } - protected void setBuffer(ByteBuffer backing, int offset) { - super.setBuffer(backing, offset, 12); - } - public void read() { - rejectMatches = backing.getInt(0); - rejectBorder = backing.getInt(4); - connectivity8 = backing.getInt(8); - } - public void write() { - backing.putInt(0, rejectMatches); - backing.putInt(4, rejectBorder); - backing.putInt(8, connectivity8); - } - public int size() { - return 12; - } - } - - public static class StraightEdgeReport2 extends DisposedStruct { - public StraightEdge[] straightEdges; // Contains an array of found straight edges. - public SearchLineInfo[] searchLines; // Contains an array of all search lines used in the detection. - private ByteBuffer straightEdges_buf; - private ByteBuffer searchLines_buf; - - private void init() { - straightEdges = new StraightEdge[0]; - searchLines = new SearchLineInfo[0]; - } - public StraightEdgeReport2() { - super(16); - init(); - } - public StraightEdgeReport2(StraightEdge[] straightEdges, SearchLineInfo[] searchLines) { - super(16); - this.straightEdges = straightEdges; - this.searchLines = searchLines; - } - protected StraightEdgeReport2(ByteBuffer backing, int offset) { - super(backing, offset, 16); - init(); - } - protected StraightEdgeReport2(long nativeObj, boolean owned) { - super(nativeObj, owned, 16); - init(); - } - protected void setBuffer(ByteBuffer backing, int offset) { - super.setBuffer(backing, offset, 16); - } - public void read() { - int straightEdges_numStraightEdges = backing.getInt(4); - long straightEdges_addr = getPointer(backing, 0); - straightEdges = new StraightEdge[straightEdges_numStraightEdges]; - if (straightEdges_numStraightEdges > 0 && straightEdges_addr != 0) { - ByteBuffer bb = newDirectByteBuffer(straightEdges_addr, straightEdges_numStraightEdges*88); - for (int i=0, off=0; i 0 && searchLines_addr != 0) { - ByteBuffer bb = newDirectByteBuffer(searchLines_addr, searchLines_numSearchLines*36); - for (int i=0, off=0; i 0 && usedEdges_addr != 0) { - ByteBuffer bb = newDirectByteBuffer(usedEdges_addr, usedEdges_numUsedEdges*56); - for (int i=0, off=0; i 0 && data_addr != 0) { - getBytes(newDirectByteBuffer(data_addr, data_dataLength), data, 0, data_dataLength); - } - for (PointFloat it : boundingBox) { - it.read(); - } - int tokenizedData_sizeOfTokenizedData = backing.getInt(48); - long tokenizedData_addr = getPointer(backing, 44); - tokenizedData = new QRCodeDataToken[tokenizedData_sizeOfTokenizedData]; - if (tokenizedData_sizeOfTokenizedData > 0 && tokenizedData_addr != 0) { - ByteBuffer bb = newDirectByteBuffer(tokenizedData_addr, tokenizedData_sizeOfTokenizedData*16); - for (int i=0, off=0; i 0 && data_addr != 0) { - getBytes(newDirectByteBuffer(data_addr, data_dataLength), data, 0, data_dataLength); - } - for (PointFloat it : boundingBox) { - it.read(); - } - numErrorsCorrected = backing.getInt(48); - numErasuresCorrected = backing.getInt(52); - aspectRatio = backing.getFloat(56); - rows = backing.getInt(60); - columns = backing.getInt(64); - ecc = DataMatrixECC.fromValue(backing.getInt(72)); - polarity = DataMatrixPolarity.fromValue(backing.getInt(80)); - cellFill = DataMatrixCellFillMode.fromValue(backing.getInt(88)); - borderIntegrity = backing.getFloat(96); - mirrored = backing.getInt(100); - minimumEdgeStrength = backing.getInt(104); - demodulationMode = DataMatrixDemodulationMode.fromValue(backing.getInt(112)); - cellSampleSize = DataMatrixCellSampleSize.fromValue(backing.getInt(120)); - cellFilterMode = DataMatrixCellFilterMode.fromValue(backing.getInt(128)); - iterations = backing.getInt(136); - } - public void write() { - backing.putInt(0, found); - backing.putInt(4, binary); - data_buf = ByteBuffer.allocateDirect(data.length); - putBytes(data_buf, data, 0, data.length); - backing.putInt(12, data.length); - putPointer(backing, 8, data_buf); - for (PointFloat it : boundingBox) { - it.write(); - } - backing.putInt(48, numErrorsCorrected); - backing.putInt(52, numErasuresCorrected); - backing.putFloat(56, aspectRatio); - backing.putInt(60, rows); - backing.putInt(64, columns); - if (ecc != null) - backing.putInt(72, ecc.getValue()); - if (polarity != null) - backing.putInt(80, polarity.getValue()); - if (cellFill != null) - backing.putInt(88, cellFill.getValue()); - backing.putFloat(96, borderIntegrity); - backing.putInt(100, mirrored); - backing.putInt(104, minimumEdgeStrength); - if (demodulationMode != null) - backing.putInt(112, demodulationMode.getValue()); - if (cellSampleSize != null) - backing.putInt(120, cellSampleSize.getValue()); - if (cellFilterMode != null) - backing.putInt(128, cellFilterMode.getValue()); - backing.putInt(136, iterations); - } - public int size() { - return 144; - } - } - - public static class JPEG2000FileAdvancedOptions extends DisposedStruct { - public WaveletTransformMode waveletMode; // Determines which wavelet transform to use when writing the file. - public int useMultiComponentTransform; // Set this parameter to TRUE to use an additional transform on RGB images. - public int maxWaveletTransformLevel; // Specifies the maximum allowed level of wavelet transform. - public float quantizationStepSize; // Specifies the absolute base quantization step size for derived quantization mode. - - private void init() { - - } - public JPEG2000FileAdvancedOptions() { - super(16); - init(); - } - public JPEG2000FileAdvancedOptions(WaveletTransformMode waveletMode, int useMultiComponentTransform, int maxWaveletTransformLevel, double quantizationStepSize) { - super(16); - this.waveletMode = waveletMode; - this.useMultiComponentTransform = useMultiComponentTransform; - this.maxWaveletTransformLevel = maxWaveletTransformLevel; - this.quantizationStepSize = (float)quantizationStepSize; - } - protected JPEG2000FileAdvancedOptions(ByteBuffer backing, int offset) { - super(backing, offset, 16); - init(); - } - protected JPEG2000FileAdvancedOptions(long nativeObj, boolean owned) { - super(nativeObj, owned, 16); - init(); - } - protected void setBuffer(ByteBuffer backing, int offset) { - super.setBuffer(backing, offset, 16); - } - public void read() { - waveletMode = WaveletTransformMode.fromValue(backing.getInt(0)); - useMultiComponentTransform = backing.getInt(4); - maxWaveletTransformLevel = backing.getInt(8); - quantizationStepSize = backing.getFloat(12); - } - public void write() { - if (waveletMode != null) - backing.putInt(0, waveletMode.getValue()); - backing.putInt(4, useMultiComponentTransform); - backing.putInt(8, maxWaveletTransformLevel); - backing.putFloat(12, quantizationStepSize); - } - public int size() { - return 16; - } - } - - public static class MatchGeometricPatternAdvancedOptions2 extends DisposedStruct { - public int minFeaturesUsed; // Specifies the minimum number of features the function uses when matching. - public int maxFeaturesUsed; // Specifies the maximum number of features the function uses when matching. - public int subpixelIterations; // Specifies the maximum number of incremental improvements used to refine matches with subpixel information. - public double subpixelTolerance; // Specifies the maximum amount of change, in pixels, between consecutive incremental improvements in the match position before the function stops refining the match position. - public int initialMatchListLength; // Specifies the maximum size of the match list. - public float matchTemplateCurveScore; // Set this element to TRUE to specify that the function should calculate the match curve to template curve score and return it for each match result. - public int correlationScore; // Set this element to TRUE to specify that the function should calculate the correlation score and return it for each match result. - public double minMatchSeparationDistance; // Specifies the minimum separation distance, in pixels, between the origins of two matches that have unique positions. - public double minMatchSeparationAngle; // Specifies the minimum angular difference, in degrees, between two matches that have unique angles. - public double minMatchSeparationScale; // Specifies the minimum difference in scale, expressed as a percentage, between two matches that have unique scales. - public double maxMatchOverlap; // Specifies the maximum amount of overlap, expressed as a percentage, allowed between the bounding rectangles of two unique matches. - public int coarseResult; // Specifies whether you want the function to spend less time accurately estimating the location of a match. - public int smoothContours; // Set this element to TRUE to specify smoothing be done on the contours of the inspection image before feature extraction. - public int enableCalibrationSupport; // Set this element to TRUE to specify the algorithm treat the inspection image as a calibrated image. - - private void init() { - - } - public MatchGeometricPatternAdvancedOptions2() { - super(88); - init(); - } - public MatchGeometricPatternAdvancedOptions2(int minFeaturesUsed, int maxFeaturesUsed, int subpixelIterations, double subpixelTolerance, int initialMatchListLength, double matchTemplateCurveScore, int correlationScore, double minMatchSeparationDistance, double minMatchSeparationAngle, double minMatchSeparationScale, double maxMatchOverlap, int coarseResult, int smoothContours, int enableCalibrationSupport) { - super(88); - this.minFeaturesUsed = minFeaturesUsed; - this.maxFeaturesUsed = maxFeaturesUsed; - this.subpixelIterations = subpixelIterations; - this.subpixelTolerance = subpixelTolerance; - this.initialMatchListLength = initialMatchListLength; - this.matchTemplateCurveScore = (float)matchTemplateCurveScore; - this.correlationScore = correlationScore; - this.minMatchSeparationDistance = minMatchSeparationDistance; - this.minMatchSeparationAngle = minMatchSeparationAngle; - this.minMatchSeparationScale = minMatchSeparationScale; - this.maxMatchOverlap = maxMatchOverlap; - this.coarseResult = coarseResult; - this.smoothContours = smoothContours; - this.enableCalibrationSupport = enableCalibrationSupport; - } - protected MatchGeometricPatternAdvancedOptions2(ByteBuffer backing, int offset) { - super(backing, offset, 88); - init(); - } - protected MatchGeometricPatternAdvancedOptions2(long nativeObj, boolean owned) { - super(nativeObj, owned, 88); - init(); - } - protected void setBuffer(ByteBuffer backing, int offset) { - super.setBuffer(backing, offset, 88); - } - public void read() { - minFeaturesUsed = backing.getInt(0); - maxFeaturesUsed = backing.getInt(4); - subpixelIterations = backing.getInt(8); - subpixelTolerance = backing.getDouble(16); - initialMatchListLength = backing.getInt(24); - matchTemplateCurveScore = backing.getFloat(28); - correlationScore = backing.getInt(32); - minMatchSeparationDistance = backing.getDouble(40); - minMatchSeparationAngle = backing.getDouble(48); - minMatchSeparationScale = backing.getDouble(56); - maxMatchOverlap = backing.getDouble(64); - coarseResult = backing.getInt(72); - smoothContours = backing.getInt(76); - enableCalibrationSupport = backing.getInt(80); - } - public void write() { - backing.putInt(0, minFeaturesUsed); - backing.putInt(4, maxFeaturesUsed); - backing.putInt(8, subpixelIterations); - backing.putDouble(16, subpixelTolerance); - backing.putInt(24, initialMatchListLength); - backing.putFloat(28, matchTemplateCurveScore); - backing.putInt(32, correlationScore); - backing.putDouble(40, minMatchSeparationDistance); - backing.putDouble(48, minMatchSeparationAngle); - backing.putDouble(56, minMatchSeparationScale); - backing.putDouble(64, maxMatchOverlap); - backing.putInt(72, coarseResult); - backing.putInt(76, smoothContours); - backing.putInt(80, enableCalibrationSupport); - } - public int size() { - return 88; - } - } - - public static class InspectionAlignment extends DisposedStruct { - public PointFloat position; // The location of the center of the golden template in the image under inspection. - public float rotation; // The rotation of the golden template in the image under inspection, in degrees. - public float scale; // The percentage of the size of the area under inspection compared to the size of the golden template. - - private void init() { - position = new PointFloat(backing, 0); - } - public InspectionAlignment() { - super(16); - init(); - } - public InspectionAlignment(PointFloat position, double rotation, double scale) { - super(16); - this.position = position; - this.rotation = (float)rotation; - this.scale = (float)scale; - } - protected InspectionAlignment(ByteBuffer backing, int offset) { - super(backing, offset, 16); - init(); - } - protected InspectionAlignment(long nativeObj, boolean owned) { - super(nativeObj, owned, 16); - init(); - } - protected void setBuffer(ByteBuffer backing, int offset) { - super.setBuffer(backing, offset, 16); - } - public void read() { - position.read(); - rotation = backing.getFloat(8); - scale = backing.getFloat(12); - } - public void write() { - position.write(); - backing.putFloat(8, rotation); - backing.putFloat(12, scale); - } - public int size() { - return 16; - } - } - - public static class InspectionOptions extends DisposedStruct { - public RegistrationMethod registrationMethod; // Specifies how the function registers the golden template and the target image. - public NormalizationMethod normalizationMethod; // Specifies how the function normalizes the golden template to the target image. - public int edgeThicknessToIgnore; // Specifies desired thickness of edges to be ignored. - public float brightThreshold; // Specifies the threshold for areas where the target image is brighter than the golden template. - public float darkThreshold; // Specifies the threshold for areas where the target image is darker than the golden template. - public int binary; // Specifies whether the function should return a binary image giving the location of defects, or a grayscale image giving the intensity of defects. - - private void init() { - - } - public InspectionOptions() { - super(24); - init(); - } - public InspectionOptions(RegistrationMethod registrationMethod, NormalizationMethod normalizationMethod, int edgeThicknessToIgnore, double brightThreshold, double darkThreshold, int binary) { - super(24); - this.registrationMethod = registrationMethod; - this.normalizationMethod = normalizationMethod; - this.edgeThicknessToIgnore = edgeThicknessToIgnore; - this.brightThreshold = (float)brightThreshold; - this.darkThreshold = (float)darkThreshold; - this.binary = binary; - } - protected InspectionOptions(ByteBuffer backing, int offset) { - super(backing, offset, 24); - init(); - } - protected InspectionOptions(long nativeObj, boolean owned) { - super(nativeObj, owned, 24); - init(); - } - protected void setBuffer(ByteBuffer backing, int offset) { - super.setBuffer(backing, offset, 24); - } - public void read() { - registrationMethod = RegistrationMethod.fromValue(backing.getInt(0)); - normalizationMethod = NormalizationMethod.fromValue(backing.getInt(4)); - edgeThicknessToIgnore = backing.getInt(8); - brightThreshold = backing.getFloat(12); - darkThreshold = backing.getFloat(16); - binary = backing.getInt(20); - } - public void write() { - if (registrationMethod != null) - backing.putInt(0, registrationMethod.getValue()); - if (normalizationMethod != null) - backing.putInt(4, normalizationMethod.getValue()); - backing.putInt(8, edgeThicknessToIgnore); - backing.putFloat(12, brightThreshold); - backing.putFloat(16, darkThreshold); - backing.putInt(20, binary); - } - public int size() { - return 24; - } - } - - public static class CharReport2 extends DisposedStruct { - public String character; // The character value. - public PointFloat[] corner; // An array of four points that describes the rectangle that surrounds the character. - public int lowThreshold; // The minimum value of the threshold range used for this character. - public int highThreshold; // The maximum value of the threshold range used for this character. - public int classificationScore; // The degree to which the assigned character class represents the object better than the other character classes in the character set. - public int verificationScore; // The similarity of the character and the reference character for the character class. - public int verified; // This element is TRUE if a reference character was found for the character class and FALSE if a reference character was not found. - private ByteBuffer character_buf; - - private void init() { - corner = new PointFloat[4]; - - for (int i=0, off=4; i<4; i++, off += 8) - corner[i] = new PointFloat(backing, off); - } - public CharReport2() { - super(56); - init(); - } - public CharReport2(String character, PointFloat[] corner, int lowThreshold, int highThreshold, int classificationScore, int verificationScore, int verified) { - super(56); - this.character = character; - this.corner = corner; - this.lowThreshold = lowThreshold; - this.highThreshold = highThreshold; - this.classificationScore = classificationScore; - this.verificationScore = verificationScore; - this.verified = verified; - } - protected CharReport2(ByteBuffer backing, int offset) { - super(backing, offset, 56); - init(); - } - protected CharReport2(long nativeObj, boolean owned) { - super(nativeObj, owned, 56); - init(); - } - protected void setBuffer(ByteBuffer backing, int offset) { - super.setBuffer(backing, offset, 56); - } - public void read() { - long character_addr = getPointer(backing, 0); - if (character_addr == 0) - character = null; - else { - ByteBuffer bb = newDirectByteBuffer(character_addr, 1000); // FIXME - while (bb.get() != 0) {} - byte[] bytes = new byte[bb.position()-1]; - getBytes(bb, bytes, 0, bytes.length); - try { - character = new String(bytes, "UTF-8"); - } catch (UnsupportedEncodingException e) { - character = ""; - } - } - - for (PointFloat it : corner) { - it.read(); - } - lowThreshold = backing.getInt(36); - highThreshold = backing.getInt(40); - classificationScore = backing.getInt(44); - verificationScore = backing.getInt(48); - verified = backing.getInt(52); - } - public void write() { - if (character != null) { - byte[] character_bytes; - try { - character_bytes = character.getBytes("UTF-8"); - } catch (UnsupportedEncodingException e) { - character_bytes = new byte[0]; - } - character_buf = ByteBuffer.allocateDirect(character_bytes.length+1); - putBytes(character_buf, character_bytes, 0, character_bytes.length).put(character_bytes.length, (byte)0); - } - putPointer(backing, 0, character == null ? 0 : getByteBufferAddress(character_buf)); - for (PointFloat it : corner) { - it.write(); - } - backing.putInt(36, lowThreshold); - backing.putInt(40, highThreshold); - backing.putInt(44, classificationScore); - backing.putInt(48, verificationScore); - backing.putInt(52, verified); - } - public int size() { - return 56; - } - } - - public static class CharInfo2 extends DisposedStruct { - public String charValue; // Retrieves the character value of the corresponding character in the character set. - public Image charImage; // The image you used to train this character. - public Image internalImage; // The internal representation that NI Vision uses to match objects to this character. - public int isReferenceChar; // This element is TRUE if the character is the reference character for the character class. - private ByteBuffer charValue_buf; - - private void init() { - - } - public CharInfo2() { - super(16); - init(); - } - public CharInfo2(String charValue, Image charImage, Image internalImage, int isReferenceChar) { - super(16); - this.charValue = charValue; - this.charImage = charImage; - this.internalImage = internalImage; - this.isReferenceChar = isReferenceChar; - } - protected CharInfo2(ByteBuffer backing, int offset) { - super(backing, offset, 16); - init(); - } - protected CharInfo2(long nativeObj, boolean owned) { - super(nativeObj, owned, 16); - init(); - } - protected void setBuffer(ByteBuffer backing, int offset) { - super.setBuffer(backing, offset, 16); - } - public void read() { - long charValue_addr = getPointer(backing, 0); - if (charValue_addr == 0) - charValue = null; - else { - ByteBuffer bb = newDirectByteBuffer(charValue_addr, 1000); // FIXME - while (bb.get() != 0) {} - byte[] bytes = new byte[bb.position()-1]; - getBytes(bb, bytes, 0, bytes.length); - try { - charValue = new String(bytes, "UTF-8"); - } catch (UnsupportedEncodingException e) { - charValue = ""; - } - } - - long charImage_addr = getPointer(backing, 4); - if (charImage_addr == 0) - charImage = null; - else - charImage = new Image(charImage_addr, false); - long internalImage_addr = getPointer(backing, 8); - if (internalImage_addr == 0) - internalImage = null; - else - internalImage = new Image(internalImage_addr, false); - isReferenceChar = backing.getInt(12); - } - public void write() { - if (charValue != null) { - byte[] charValue_bytes; - try { - charValue_bytes = charValue.getBytes("UTF-8"); - } catch (UnsupportedEncodingException e) { - charValue_bytes = new byte[0]; - } - charValue_buf = ByteBuffer.allocateDirect(charValue_bytes.length+1); - putBytes(charValue_buf, charValue_bytes, 0, charValue_bytes.length).put(charValue_bytes.length, (byte)0); - } - putPointer(backing, 0, charValue == null ? 0 : getByteBufferAddress(charValue_buf)); - putPointer(backing, 4, charImage); - putPointer(backing, 8, internalImage); - backing.putInt(12, isReferenceChar); - } - public int size() { - return 16; - } - } - - public static class ReadTextReport2 extends DisposedStruct { - public String readString; // The read string. - public CharReport2[] characterReport; // An array of reports describing the properties of each identified character. - private ByteBuffer readString_buf; - private ByteBuffer characterReport_buf; - - private void init() { - characterReport = new CharReport2[0]; - } - public ReadTextReport2() { - super(12); - init(); - } - public ReadTextReport2(String readString, CharReport2[] characterReport) { - super(12); - this.readString = readString; - this.characterReport = characterReport; - } - protected ReadTextReport2(ByteBuffer backing, int offset) { - super(backing, offset, 12); - init(); - } - protected ReadTextReport2(long nativeObj, boolean owned) { - super(nativeObj, owned, 12); - init(); - } - protected void setBuffer(ByteBuffer backing, int offset) { - super.setBuffer(backing, offset, 12); - } - public void read() { - long readString_addr = getPointer(backing, 0); - if (readString_addr == 0) - readString = null; - else { - ByteBuffer bb = newDirectByteBuffer(readString_addr, 1000); // FIXME - while (bb.get() != 0) {} - byte[] bytes = new byte[bb.position()-1]; - getBytes(bb, bytes, 0, bytes.length); - try { - readString = new String(bytes, "UTF-8"); - } catch (UnsupportedEncodingException e) { - readString = ""; - } - } - - int characterReport_numCharacterReports = backing.getInt(8); - long characterReport_addr = getPointer(backing, 4); - characterReport = new CharReport2[characterReport_numCharacterReports]; - if (characterReport_numCharacterReports > 0 && characterReport_addr != 0) { - ByteBuffer bb = newDirectByteBuffer(characterReport_addr, characterReport_numCharacterReports*56); - for (int i=0, off=0; i 0 && contourPoints_addr != 0) { - ByteBuffer bb = newDirectByteBuffer(contourPoints_addr, contourPoints_numContourPoints*8); - for (int i=0, off=0; i 0 && featureData_addr != 0) { - ByteBuffer bb = newDirectByteBuffer(featureData_addr, featureData_numFeatureData*16); - for (int i=0, off=0; i 0 && angleRanges_addr != 0) { - ByteBuffer bb = newDirectByteBuffer(angleRanges_addr, angleRanges_numAngleRanges*8); - for (int i=0, off=0; i 0 && points_addr != 0) { - ByteBuffer bb = newDirectByteBuffer(points_addr, points_numPoints*8); - for (int i=0, off=0; i 0 && data_addr != 0) { - getBytes(newDirectByteBuffer(data_addr, data_dataLength), data, 0, data_dataLength); - } - for (PointFloat it : boundingBox) { - it.read(); - } - numErrorsCorrected = backing.getInt(48); - numErasuresCorrected = backing.getInt(52); - rows = backing.getInt(56); - columns = backing.getInt(60); - } - public void write() { - if (type != null) - backing.putInt(0, type.getValue()); - backing.putInt(4, binary); - data_buf = ByteBuffer.allocateDirect(data.length); - putBytes(data_buf, data, 0, data.length); - backing.putInt(12, data.length); - putPointer(backing, 8, data_buf); - for (PointFloat it : boundingBox) { - it.write(); - } - backing.putInt(48, numErrorsCorrected); - backing.putInt(52, numErasuresCorrected); - backing.putInt(56, rows); - backing.putInt(60, columns); - } - public int size() { - return 64; - } - } - - public static class DataMatrixOptions extends DisposedStruct { - public Barcode2DSearchMode searchMode; // Specifies the mode the function uses to search for barcodes. - public Barcode2DContrast contrast; // Specifies the contrast of the barcodes that the function searches for. - public Barcode2DCellShape cellShape; // Specifies the shape of the barcode data cells, which affects how the function decodes the barcode. - public Barcode2DShape barcodeShape; // Specifies the shape of the barcodes that the function searches for. - public DataMatrixSubtype subtype; // Specifies the Data Matrix subtypes of the barcodes that the function searches for. - - private void init() { - - } - public DataMatrixOptions() { - super(20); - init(); - } - public DataMatrixOptions(Barcode2DSearchMode searchMode, Barcode2DContrast contrast, Barcode2DCellShape cellShape, Barcode2DShape barcodeShape, DataMatrixSubtype subtype) { - super(20); - this.searchMode = searchMode; - this.contrast = contrast; - this.cellShape = cellShape; - this.barcodeShape = barcodeShape; - this.subtype = subtype; - } - protected DataMatrixOptions(ByteBuffer backing, int offset) { - super(backing, offset, 20); - init(); - } - protected DataMatrixOptions(long nativeObj, boolean owned) { - super(nativeObj, owned, 20); - init(); - } - protected void setBuffer(ByteBuffer backing, int offset) { - super.setBuffer(backing, offset, 20); - } - public void read() { - searchMode = Barcode2DSearchMode.fromValue(backing.getInt(0)); - contrast = Barcode2DContrast.fromValue(backing.getInt(4)); - cellShape = Barcode2DCellShape.fromValue(backing.getInt(8)); - barcodeShape = Barcode2DShape.fromValue(backing.getInt(12)); - subtype = DataMatrixSubtype.fromValue(backing.getInt(16)); - } - public void write() { - if (searchMode != null) - backing.putInt(0, searchMode.getValue()); - if (contrast != null) - backing.putInt(4, contrast.getValue()); - if (cellShape != null) - backing.putInt(8, cellShape.getValue()); - if (barcodeShape != null) - backing.putInt(12, barcodeShape.getValue()); - if (subtype != null) - backing.putInt(16, subtype.getValue()); - } - public int size() { - return 20; - } - } - - public static class ClassifierAccuracyReport extends DisposedStruct { - public float accuracy; // The overall accuracy of the classifier, from 0 to 1000. - public String[] classNames; // The names of the classes of this classifier. - public double[] classAccuracy; // An array of size elements that contains accuracy information for each class. - public double[] classPredictiveValue; // An array containing size elements that contains the predictive values of each class. - private ByteBuffer classNames_buf; - private ByteBuffer[] classNames_bufs; - private ByteBuffer classAccuracy_buf; - private ByteBuffer classPredictiveValue_buf; - - private void init() { - classNames = new String[0]; - classAccuracy = new double[0]; - classPredictiveValue = new double[0]; - } - public ClassifierAccuracyReport() { - super(24); - init(); - } - public ClassifierAccuracyReport(double accuracy, String[] classNames, double[] classAccuracy, double[] classPredictiveValue) { - super(24); - this.accuracy = (float)accuracy; - this.classNames = classNames; - this.classAccuracy = classAccuracy; - this.classPredictiveValue = classPredictiveValue; - } - protected ClassifierAccuracyReport(ByteBuffer backing, int offset) { - super(backing, offset, 24); - init(); - } - protected ClassifierAccuracyReport(long nativeObj, boolean owned) { - super(nativeObj, owned, 24); - init(); - } - protected void setBuffer(ByteBuffer backing, int offset) { - super.setBuffer(backing, offset, 24); - } - public void read() { - accuracy = backing.getFloat(4); - int classNames_size = backing.getInt(0); - long classNames_addr = getPointer(backing, 8); - classNames = new String[classNames_size]; - if (classNames_size > 0 && classNames_addr != 0) { - ByteBuffer bb = newDirectByteBuffer(classNames_addr, classNames_size*4); - for (int i=0, off=0; i 0 && classAccuracy_addr != 0) { - newDirectByteBuffer(classAccuracy_addr, classAccuracy_size*8).asDoubleBuffer().get(classAccuracy); - } - int classPredictiveValue_size = backing.getInt(0); - long classPredictiveValue_addr = getPointer(backing, 16); - classPredictiveValue = new double[classPredictiveValue_size]; - if (classPredictiveValue_size > 0 && classPredictiveValue_addr != 0) { - newDirectByteBuffer(classPredictiveValue_addr, classPredictiveValue_size*8).asDoubleBuffer().get(classPredictiveValue); - } - } - public void write() { - backing.putFloat(4, accuracy); - classNames_buf = ByteBuffer.allocateDirect(classNames.length*4).order(ByteOrder.nativeOrder()); - for (int i=0, off=0; i 0 && allScores_addr != 0) { - ByteBuffer bb = newDirectByteBuffer(allScores_addr, allScores_allScoresSize*12); - for (int i=0, off=0; i 0 && featureVector_addr != 0) { - newDirectByteBuffer(featureVector_addr, featureVector_featureVectorSize*8).asDoubleBuffer().get(featureVector); - } - long thumbnail_addr = getPointer(backing, 12); - if (thumbnail_addr == 0) - thumbnail = null; - else - thumbnail = new Image(thumbnail_addr, false); - } - public void write() { - if (className != null) { - byte[] className_bytes; - try { - className_bytes = className.getBytes("UTF-8"); - } catch (UnsupportedEncodingException e) { - className_bytes = new byte[0]; - } - className_buf = ByteBuffer.allocateDirect(className_bytes.length+1); - putBytes(className_buf, className_bytes, 0, className_bytes.length).put(className_bytes.length, (byte)0); - } - putPointer(backing, 0, className == null ? 0 : getByteBufferAddress(className_buf)); - featureVector_buf = ByteBuffer.allocateDirect(featureVector.length*8).order(ByteOrder.nativeOrder()); - featureVector_buf.asDoubleBuffer().put(featureVector).rewind(); - backing.putInt(8, featureVector.length); - putPointer(backing, 4, featureVector_buf); - putPointer(backing, 12, thumbnail); - } - public int size() { - return 16; - } - } - - public static class ClassScore extends DisposedStruct { - public String className; // The name of the class. - public float distance; // The distance from the item to this class. - private ByteBuffer className_buf; - - private void init() { - - } - public ClassScore() { - super(8); - init(); - } - public ClassScore(String className, double distance) { - super(8); - this.className = className; - this.distance = (float)distance; - } - protected ClassScore(ByteBuffer backing, int offset) { - super(backing, offset, 8); - init(); - } - protected ClassScore(long nativeObj, boolean owned) { - super(nativeObj, owned, 8); - init(); - } - protected void setBuffer(ByteBuffer backing, int offset) { - super.setBuffer(backing, offset, 8); - } - public void read() { - long className_addr = getPointer(backing, 0); - if (className_addr == 0) - className = null; - else { - ByteBuffer bb = newDirectByteBuffer(className_addr, 1000); // FIXME - while (bb.get() != 0) {} - byte[] bytes = new byte[bb.position()-1]; - getBytes(bb, bytes, 0, bytes.length); - try { - className = new String(bytes, "UTF-8"); - } catch (UnsupportedEncodingException e) { - className = ""; - } - } - - distance = backing.getFloat(4); - } - public void write() { - if (className != null) { - byte[] className_bytes; - try { - className_bytes = className.getBytes("UTF-8"); - } catch (UnsupportedEncodingException e) { - className_bytes = new byte[0]; - } - className_buf = ByteBuffer.allocateDirect(className_bytes.length+1); - putBytes(className_buf, className_bytes, 0, className_bytes.length).put(className_bytes.length, (byte)0); - } - putPointer(backing, 0, className == null ? 0 : getByteBufferAddress(className_buf)); - backing.putFloat(4, distance); - } - public int size() { - return 8; - } - } - - public static class ClassifierReport extends DisposedStruct { - public String bestClassName; // The name of the best class for the sample. - public float classificationScore; // The similarity of the sample and the two closest classes in the classifier. - public float identificationScore; // The similarity of the sample and the assigned class. - public ClassScore[] allScores; // All classes and their scores. - private ByteBuffer bestClassName_buf; - private ByteBuffer allScores_buf; - - private void init() { - allScores = new ClassScore[0]; - } - public ClassifierReport() { - super(20); - init(); - } - public ClassifierReport(String bestClassName, double classificationScore, double identificationScore, ClassScore[] allScores) { - super(20); - this.bestClassName = bestClassName; - this.classificationScore = (float)classificationScore; - this.identificationScore = (float)identificationScore; - this.allScores = allScores; - } - protected ClassifierReport(ByteBuffer backing, int offset) { - super(backing, offset, 20); - init(); - } - protected ClassifierReport(long nativeObj, boolean owned) { - super(nativeObj, owned, 20); - init(); - } - protected void setBuffer(ByteBuffer backing, int offset) { - super.setBuffer(backing, offset, 20); - } - public void read() { - long bestClassName_addr = getPointer(backing, 0); - if (bestClassName_addr == 0) - bestClassName = null; - else { - ByteBuffer bb = newDirectByteBuffer(bestClassName_addr, 1000); // FIXME - while (bb.get() != 0) {} - byte[] bytes = new byte[bb.position()-1]; - getBytes(bb, bytes, 0, bytes.length); - try { - bestClassName = new String(bytes, "UTF-8"); - } catch (UnsupportedEncodingException e) { - bestClassName = ""; - } - } - - classificationScore = backing.getFloat(4); - identificationScore = backing.getFloat(8); - int allScores_allScoresSize = backing.getInt(16); - long allScores_addr = getPointer(backing, 12); - allScores = new ClassScore[allScores_allScoresSize]; - if (allScores_allScoresSize > 0 && allScores_addr != 0) { - ByteBuffer bb = newDirectByteBuffer(allScores_addr, allScores_allScoresSize*8); - for (int i=0, off=0; i 0 && angleRanges_addr != 0) { - ByteBuffer bb = newDirectByteBuffer(angleRanges_addr, angleRanges_numAngleRanges*8); - for (int i=0, off=0; i 0 && palette_addr != 0) { - ByteBuffer bb = newDirectByteBuffer(palette_addr, palette_numColors*4); - for (int i=0, off=0; i 0 && pointsUsed_addr != 0) { - newDirectByteBuffer(pointsUsed_addr, pointsUsed_numPointsUsed*4).asIntBuffer().get(pointsUsed); - } - } - public void write() { - center.write(); - majorAxisStart.write(); - majorAxisEnd.write(); - minorAxisStart.write(); - minorAxisEnd.write(); - backing.putDouble(40, area); - backing.putDouble(48, perimeter); - backing.putDouble(56, error); - backing.putInt(64, valid); - pointsUsed_buf = ByteBuffer.allocateDirect(pointsUsed.length*4).order(ByteOrder.nativeOrder()); - pointsUsed_buf.asIntBuffer().put(pointsUsed).rewind(); - backing.putInt(72, pointsUsed.length); - putPointer(backing, 68, pointsUsed_buf); - } - public int size() { - return 80; - } - } - - public static class LearnPatternAdvancedOptions extends DisposedStruct { - public LearnPatternAdvancedShiftOptions shiftOptions; // Use this element to control the behavior of imaqLearnPattern2() during the shift-invariant learning phase. - public LearnPatternAdvancedRotationOptions rotationOptions; // Use this element to control the behavior of imaqLearnPattern2()during the rotation-invariant learning phase. - - private void init() { - - } - public LearnPatternAdvancedOptions() { - super(8); - init(); - } - public LearnPatternAdvancedOptions(LearnPatternAdvancedShiftOptions shiftOptions, LearnPatternAdvancedRotationOptions rotationOptions) { - super(8); - this.shiftOptions = shiftOptions; - this.rotationOptions = rotationOptions; - } - protected LearnPatternAdvancedOptions(ByteBuffer backing, int offset) { - super(backing, offset, 8); - init(); - } - protected LearnPatternAdvancedOptions(long nativeObj, boolean owned) { - super(nativeObj, owned, 8); - init(); - } - protected void setBuffer(ByteBuffer backing, int offset) { - super.setBuffer(backing, offset, 8); - } - public void read() { - long shiftOptions_addr = getPointer(backing, 0); - if (shiftOptions_addr == 0) - shiftOptions = null; - else - shiftOptions = new LearnPatternAdvancedShiftOptions(shiftOptions_addr, false); - long rotationOptions_addr = getPointer(backing, 4); - if (rotationOptions_addr == 0) - rotationOptions = null; - else - rotationOptions = new LearnPatternAdvancedRotationOptions(rotationOptions_addr, false); - } - public void write() { - putPointer(backing, 0, shiftOptions); - putPointer(backing, 4, rotationOptions); - } - public int size() { - return 8; - } - } - - public static class AVIInfo extends DisposedStruct { - public int width; // The width of each frame. - public int height; // The height of each frame. - public ImageType imageType; // The type of images this AVI contains. - public int numFrames; // The number of frames in the AVI. - public int framesPerSecond; // The number of frames per second this AVI should be shown at. - public String filterName; // The name of the compression filter used to create this AVI. - public int hasData; // Specifies whether this AVI has data attached to each frame or not. - public int maxDataSize; // If this AVI has data, the maximum size of the data in each frame. - private ByteBuffer filterName_buf; - - private void init() { - - } - public AVIInfo() { - super(32); - init(); - } - public AVIInfo(int width, int height, ImageType imageType, int numFrames, int framesPerSecond, String filterName, int hasData, int maxDataSize) { - super(32); - this.width = width; - this.height = height; - this.imageType = imageType; - this.numFrames = numFrames; - this.framesPerSecond = framesPerSecond; - this.filterName = filterName; - this.hasData = hasData; - this.maxDataSize = maxDataSize; - } - protected AVIInfo(ByteBuffer backing, int offset) { - super(backing, offset, 32); - init(); - } - protected AVIInfo(long nativeObj, boolean owned) { - super(nativeObj, owned, 32); - init(); - } - protected void setBuffer(ByteBuffer backing, int offset) { - super.setBuffer(backing, offset, 32); - } - public void read() { - width = backing.getInt(0); - height = backing.getInt(4); - imageType = ImageType.fromValue(backing.getInt(8)); - numFrames = backing.getInt(12); - framesPerSecond = backing.getInt(16); - long filterName_addr = getPointer(backing, 20); - if (filterName_addr == 0) - filterName = null; - else { - ByteBuffer bb = newDirectByteBuffer(filterName_addr, 1000); // FIXME - while (bb.get() != 0) {} - byte[] bytes = new byte[bb.position()-1]; - getBytes(bb, bytes, 0, bytes.length); - try { - filterName = new String(bytes, "UTF-8"); - } catch (UnsupportedEncodingException e) { - filterName = ""; - } - } - - hasData = backing.getInt(24); - maxDataSize = backing.getInt(28); - } - public void write() { - backing.putInt(0, width); - backing.putInt(4, height); - if (imageType != null) - backing.putInt(8, imageType.getValue()); - backing.putInt(12, numFrames); - backing.putInt(16, framesPerSecond); - if (filterName != null) { - byte[] filterName_bytes; - try { - filterName_bytes = filterName.getBytes("UTF-8"); - } catch (UnsupportedEncodingException e) { - filterName_bytes = new byte[0]; - } - filterName_buf = ByteBuffer.allocateDirect(filterName_bytes.length+1); - putBytes(filterName_buf, filterName_bytes, 0, filterName_bytes.length).put(filterName_bytes.length, (byte)0); - } - putPointer(backing, 20, filterName == null ? 0 : getByteBufferAddress(filterName_buf)); - backing.putInt(24, hasData); - backing.putInt(28, maxDataSize); - } - public int size() { - return 32; - } - } - - public static class LearnPatternAdvancedShiftOptions extends DisposedStruct { - public int initialStepSize; // The largest number of image pixels to shift the sample across the inspection image during the initial phase of shift-invariant matching. - public int initialSampleSize; // Specifies the number of template pixels that you want to include in a sample for the initial phase of shift-invariant matching. - public double initialSampleSizeFactor; // Specifies the size of the sample for the initial phase of shift-invariant matching as a percent of the template size, in pixels. - public int finalSampleSize; // Specifies the number of template pixels you want to add to initialSampleSize for the final phase of shift-invariant matching. - public double finalSampleSizeFactor; // Specifies the size of the sample for the final phase of shift-invariant matching as a percent of the edge points in the template, in pixels. - public int subpixelSampleSize; // Specifies the number of template pixels that you want to include in a sample for the subpixel phase of shift-invariant matching. - public double subpixelSampleSizeFactor; // Specifies the size of the sample for the subpixel phase of shift-invariant matching as a percent of the template size, in pixels. - - private void init() { - - } - public LearnPatternAdvancedShiftOptions() { - super(48); - init(); - } - public LearnPatternAdvancedShiftOptions(int initialStepSize, int initialSampleSize, double initialSampleSizeFactor, int finalSampleSize, double finalSampleSizeFactor, int subpixelSampleSize, double subpixelSampleSizeFactor) { - super(48); - this.initialStepSize = initialStepSize; - this.initialSampleSize = initialSampleSize; - this.initialSampleSizeFactor = initialSampleSizeFactor; - this.finalSampleSize = finalSampleSize; - this.finalSampleSizeFactor = finalSampleSizeFactor; - this.subpixelSampleSize = subpixelSampleSize; - this.subpixelSampleSizeFactor = subpixelSampleSizeFactor; - } - protected LearnPatternAdvancedShiftOptions(ByteBuffer backing, int offset) { - super(backing, offset, 48); - init(); - } - protected LearnPatternAdvancedShiftOptions(long nativeObj, boolean owned) { - super(nativeObj, owned, 48); - init(); - } - protected void setBuffer(ByteBuffer backing, int offset) { - super.setBuffer(backing, offset, 48); - } - public void read() { - initialStepSize = backing.getInt(0); - initialSampleSize = backing.getInt(4); - initialSampleSizeFactor = backing.getDouble(8); - finalSampleSize = backing.getInt(16); - finalSampleSizeFactor = backing.getDouble(24); - subpixelSampleSize = backing.getInt(32); - subpixelSampleSizeFactor = backing.getDouble(40); - } - public void write() { - backing.putInt(0, initialStepSize); - backing.putInt(4, initialSampleSize); - backing.putDouble(8, initialSampleSizeFactor); - backing.putInt(16, finalSampleSize); - backing.putDouble(24, finalSampleSizeFactor); - backing.putInt(32, subpixelSampleSize); - backing.putDouble(40, subpixelSampleSizeFactor); - } - public int size() { - return 48; - } - } - - public static class LearnPatternAdvancedRotationOptions extends DisposedStruct { - public SearchStrategy searchStrategySupport; // Specifies the aggressiveness of the rotation search strategy available during the matching phase. - public int initialStepSize; // The largest number of image pixels to shift the sample across the inspection image during the initial phase of matching. - public int initialSampleSize; // Specifies the number of template pixels that you want to include in a sample for the initial phase of rotation-invariant matching. - public double initialSampleSizeFactor; // Specifies the size of the sample for the initial phase of rotation-invariant matching as a percent of the template size, in pixels. - public int initialAngularAccuracy; // Sets the angle accuracy, in degrees, to use during the initial phase of rotation-invariant matching. - public int finalSampleSize; // Specifies the number of template pixels you want to add to initialSampleSize for the final phase of rotation-invariant matching. - public double finalSampleSizeFactor; // Specifies the size of the sample for the final phase of rotation-invariant matching as a percent of the edge points in the template, in pixels. - public int finalAngularAccuracy; // Sets the angle accuracy, in degrees, to use during the final phase of the rotation-invariant matching. - public int subpixelSampleSize; // Specifies the number of template pixels that you want to include in a sample for the subpixel phase of rotation-invariant matching. - public double subpixelSampleSizeFactor; // Specifies the size of the sample for the subpixel phase of rotation-invariant matching as a percent of the template size, in pixels. - - private void init() { - - } - public LearnPatternAdvancedRotationOptions() { - super(56); - init(); - } - public LearnPatternAdvancedRotationOptions(SearchStrategy searchStrategySupport, int initialStepSize, int initialSampleSize, double initialSampleSizeFactor, int initialAngularAccuracy, int finalSampleSize, double finalSampleSizeFactor, int finalAngularAccuracy, int subpixelSampleSize, double subpixelSampleSizeFactor) { - super(56); - this.searchStrategySupport = searchStrategySupport; - this.initialStepSize = initialStepSize; - this.initialSampleSize = initialSampleSize; - this.initialSampleSizeFactor = initialSampleSizeFactor; - this.initialAngularAccuracy = initialAngularAccuracy; - this.finalSampleSize = finalSampleSize; - this.finalSampleSizeFactor = finalSampleSizeFactor; - this.finalAngularAccuracy = finalAngularAccuracy; - this.subpixelSampleSize = subpixelSampleSize; - this.subpixelSampleSizeFactor = subpixelSampleSizeFactor; - } - protected LearnPatternAdvancedRotationOptions(ByteBuffer backing, int offset) { - super(backing, offset, 56); - init(); - } - protected LearnPatternAdvancedRotationOptions(long nativeObj, boolean owned) { - super(nativeObj, owned, 56); - init(); - } - protected void setBuffer(ByteBuffer backing, int offset) { - super.setBuffer(backing, offset, 56); - } - public void read() { - searchStrategySupport = SearchStrategy.fromValue(backing.getInt(0)); - initialStepSize = backing.getInt(4); - initialSampleSize = backing.getInt(8); - initialSampleSizeFactor = backing.getDouble(16); - initialAngularAccuracy = backing.getInt(24); - finalSampleSize = backing.getInt(28); - finalSampleSizeFactor = backing.getDouble(32); - finalAngularAccuracy = backing.getInt(40); - subpixelSampleSize = backing.getInt(44); - subpixelSampleSizeFactor = backing.getDouble(48); - } - public void write() { - if (searchStrategySupport != null) - backing.putInt(0, searchStrategySupport.getValue()); - backing.putInt(4, initialStepSize); - backing.putInt(8, initialSampleSize); - backing.putDouble(16, initialSampleSizeFactor); - backing.putInt(24, initialAngularAccuracy); - backing.putInt(28, finalSampleSize); - backing.putDouble(32, finalSampleSizeFactor); - backing.putInt(40, finalAngularAccuracy); - backing.putInt(44, subpixelSampleSize); - backing.putDouble(48, subpixelSampleSizeFactor); - } - public int size() { - return 56; - } - } - - public static class MatchPatternAdvancedOptions extends DisposedStruct { - public int subpixelIterations; // Defines the maximum number of incremental improvements used to refine matching using subpixel information. - public double subpixelTolerance; // Defines the maximum amount of change, in pixels, between consecutive incremental improvements in the match position that you want to trigger the end of the refinement process. - public int initialMatchListLength; // Specifies the maximum size of the match list. - public int matchListReductionFactor; // Specifies the reduction of the match list as matches are refined. - public int initialStepSize; // Specifies the number of pixels to shift the sample across the inspection image during the initial phase of shift-invariant matching. - public SearchStrategy searchStrategy; // Specifies the aggressiveness of the rotation search strategy. - public int intermediateAngularAccuracy; // Specifies the accuracy to use during the intermediate phase of rotation-invariant matching. - - private void init() { - - } - public MatchPatternAdvancedOptions() { - super(40); - init(); - } - public MatchPatternAdvancedOptions(int subpixelIterations, double subpixelTolerance, int initialMatchListLength, int matchListReductionFactor, int initialStepSize, SearchStrategy searchStrategy, int intermediateAngularAccuracy) { - super(40); - this.subpixelIterations = subpixelIterations; - this.subpixelTolerance = subpixelTolerance; - this.initialMatchListLength = initialMatchListLength; - this.matchListReductionFactor = matchListReductionFactor; - this.initialStepSize = initialStepSize; - this.searchStrategy = searchStrategy; - this.intermediateAngularAccuracy = intermediateAngularAccuracy; - } - protected MatchPatternAdvancedOptions(ByteBuffer backing, int offset) { - super(backing, offset, 40); - init(); - } - protected MatchPatternAdvancedOptions(long nativeObj, boolean owned) { - super(nativeObj, owned, 40); - init(); - } - protected void setBuffer(ByteBuffer backing, int offset) { - super.setBuffer(backing, offset, 40); - } - public void read() { - subpixelIterations = backing.getInt(0); - subpixelTolerance = backing.getDouble(8); - initialMatchListLength = backing.getInt(16); - matchListReductionFactor = backing.getInt(20); - initialStepSize = backing.getInt(24); - searchStrategy = SearchStrategy.fromValue(backing.getInt(28)); - intermediateAngularAccuracy = backing.getInt(32); - } - public void write() { - backing.putInt(0, subpixelIterations); - backing.putDouble(8, subpixelTolerance); - backing.putInt(16, initialMatchListLength); - backing.putInt(20, matchListReductionFactor); - backing.putInt(24, initialStepSize); - if (searchStrategy != null) - backing.putInt(28, searchStrategy.getValue()); - backing.putInt(32, intermediateAngularAccuracy); - } - public int size() { - return 40; - } - } - - public static class ParticleFilterCriteria2 extends DisposedStruct { - public MeasurementType parameter; // The morphological measurement that the function uses for filtering. - public float lower; // The lower bound of the criteria range. - public float upper; // The upper bound of the criteria range. - public int calibrated; // Set this element to TRUE to take calibrated measurements. - public int exclude; // Set this element to TRUE to indicate that a match occurs when the measurement is outside the criteria range. - - private void init() { - - } - public ParticleFilterCriteria2() { - super(20); - init(); - } - public ParticleFilterCriteria2(MeasurementType parameter, double lower, double upper, int calibrated, int exclude) { - super(20); - this.parameter = parameter; - this.lower = (float)lower; - this.upper = (float)upper; - this.calibrated = calibrated; - this.exclude = exclude; - } - protected ParticleFilterCriteria2(ByteBuffer backing, int offset) { - super(backing, offset, 20); - init(); - } - protected ParticleFilterCriteria2(long nativeObj, boolean owned) { - super(nativeObj, owned, 20); - init(); - } - protected void setBuffer(ByteBuffer backing, int offset) { - super.setBuffer(backing, offset, 20); - } - public void read() { - parameter = MeasurementType.fromValue(backing.getInt(0)); - lower = backing.getFloat(4); - upper = backing.getFloat(8); - calibrated = backing.getInt(12); - exclude = backing.getInt(16); - } - public void write() { - if (parameter != null) - backing.putInt(0, parameter.getValue()); - backing.putFloat(4, lower); - backing.putFloat(8, upper); - backing.putInt(12, calibrated); - backing.putInt(16, exclude); - } - public int size() { - return 20; - } - } - - public static class BestCircle2 extends DisposedStruct { - public PointFloat center; // The coordinate location of the center of the circle. - public double radius; // The radius of the circle. - public double area; // The area of the circle. - public double perimeter; // The length of the perimeter of the circle. - public double error; // Represents the least square error of the fitted circle to the entire set of points. - public int valid; // This element is TRUE if the function achieved the minimum score within the number of allowed refinement iterations and FALSE if the function did not achieve the minimum score. - public int[] pointsUsed; // An array of the indexes for the points array indicating which points the function used to fit the circle. - private ByteBuffer pointsUsed_buf; - - private void init() { - center = new PointFloat(backing, 0); - pointsUsed = new int[0]; - } - public BestCircle2() { - super(56); - init(); - } - public BestCircle2(PointFloat center, double radius, double area, double perimeter, double error, int valid, int[] pointsUsed) { - super(56); - this.center = center; - this.radius = radius; - this.area = area; - this.perimeter = perimeter; - this.error = error; - this.valid = valid; - this.pointsUsed = pointsUsed; - } - protected BestCircle2(ByteBuffer backing, int offset) { - super(backing, offset, 56); - init(); - } - protected BestCircle2(long nativeObj, boolean owned) { - super(nativeObj, owned, 56); - init(); - } - protected void setBuffer(ByteBuffer backing, int offset) { - super.setBuffer(backing, offset, 56); - } - public void read() { - center.read(); - radius = backing.getDouble(8); - area = backing.getDouble(16); - perimeter = backing.getDouble(24); - error = backing.getDouble(32); - valid = backing.getInt(40); - int pointsUsed_numPointsUsed = backing.getInt(48); - long pointsUsed_addr = getPointer(backing, 44); - pointsUsed = new int[pointsUsed_numPointsUsed]; - if (pointsUsed_numPointsUsed > 0 && pointsUsed_addr != 0) { - newDirectByteBuffer(pointsUsed_addr, pointsUsed_numPointsUsed*4).asIntBuffer().get(pointsUsed); - } - } - public void write() { - center.write(); - backing.putDouble(8, radius); - backing.putDouble(16, area); - backing.putDouble(24, perimeter); - backing.putDouble(32, error); - backing.putInt(40, valid); - pointsUsed_buf = ByteBuffer.allocateDirect(pointsUsed.length*4).order(ByteOrder.nativeOrder()); - pointsUsed_buf.asIntBuffer().put(pointsUsed).rewind(); - backing.putInt(48, pointsUsed.length); - putPointer(backing, 44, pointsUsed_buf); - } - public int size() { - return 56; - } - } - - public static class OCRSpacingOptions extends DisposedStruct { - public int minCharSpacing; // The minimum number of pixels that must be between two characters for NI Vision to train or read the characters separately. - public int minCharSize; // The minimum number of pixels required for an object to be a potentially identifiable character. - public int maxCharSize; // The maximum number of pixels required for an object to be a potentially identifiable character. - public int maxHorizontalElementSpacing; // The maximum horizontal spacing, in pixels, allowed between character elements to train or read the character elements as a single character. - public int maxVerticalElementSpacing; // The maximum vertical element spacing in pixels. - public int minBoundingRectWidth; // The minimum possible width, in pixels, for a character bounding rectangle. - public int maxBoundingRectWidth; // The maximum possible width, in pixels, for a character bounding rectangle. - public int minBoundingRectHeight; // The minimum possible height, in pixels, for a character bounding rectangle. - public int maxBoundingRectHeight; // The maximum possible height, in pixels, for a character bounding rectangle. - public int autoSplit; // Set this element to TRUE to automatically adjust the location of the character bounding rectangle when characters overlap vertically. - - private void init() { - - } - public OCRSpacingOptions() { - super(40); - init(); - } - public OCRSpacingOptions(int minCharSpacing, int minCharSize, int maxCharSize, int maxHorizontalElementSpacing, int maxVerticalElementSpacing, int minBoundingRectWidth, int maxBoundingRectWidth, int minBoundingRectHeight, int maxBoundingRectHeight, int autoSplit) { - super(40); - this.minCharSpacing = minCharSpacing; - this.minCharSize = minCharSize; - this.maxCharSize = maxCharSize; - this.maxHorizontalElementSpacing = maxHorizontalElementSpacing; - this.maxVerticalElementSpacing = maxVerticalElementSpacing; - this.minBoundingRectWidth = minBoundingRectWidth; - this.maxBoundingRectWidth = maxBoundingRectWidth; - this.minBoundingRectHeight = minBoundingRectHeight; - this.maxBoundingRectHeight = maxBoundingRectHeight; - this.autoSplit = autoSplit; - } - protected OCRSpacingOptions(ByteBuffer backing, int offset) { - super(backing, offset, 40); - init(); - } - protected OCRSpacingOptions(long nativeObj, boolean owned) { - super(nativeObj, owned, 40); - init(); - } - protected void setBuffer(ByteBuffer backing, int offset) { - super.setBuffer(backing, offset, 40); - } - public void read() { - minCharSpacing = backing.getInt(0); - minCharSize = backing.getInt(4); - maxCharSize = backing.getInt(8); - maxHorizontalElementSpacing = backing.getInt(12); - maxVerticalElementSpacing = backing.getInt(16); - minBoundingRectWidth = backing.getInt(20); - maxBoundingRectWidth = backing.getInt(24); - minBoundingRectHeight = backing.getInt(28); - maxBoundingRectHeight = backing.getInt(32); - autoSplit = backing.getInt(36); - } - public void write() { - backing.putInt(0, minCharSpacing); - backing.putInt(4, minCharSize); - backing.putInt(8, maxCharSize); - backing.putInt(12, maxHorizontalElementSpacing); - backing.putInt(16, maxVerticalElementSpacing); - backing.putInt(20, minBoundingRectWidth); - backing.putInt(24, maxBoundingRectWidth); - backing.putInt(28, minBoundingRectHeight); - backing.putInt(32, maxBoundingRectHeight); - backing.putInt(36, autoSplit); - } - public int size() { - return 40; - } - } - - public static class OCRProcessingOptions extends DisposedStruct { - public ThresholdMode mode; // The thresholding mode. - public int lowThreshold; // The low threshold value when you set mode to IMAQ_FIXED_RANGE. - public int highThreshold; // The high threshold value when you set mode to IMAQ_FIXED_RANGE. - public int blockCount; // The number of blocks for threshold calculation algorithms that require blocks. - public int fastThreshold; // Set this element to TRUE to use a faster, less accurate threshold calculation algorithm. - public int biModalCalculation; // Set this element to TRUE to calculate both the low and high threshold values when using the fast thresholding method. - public int darkCharacters; // Set this element to TRUE to read or train dark characters on a light background. - public int removeParticlesTouchingROI; // Set this element to TRUE to remove the particles touching the ROI. - public int erosionCount; // The number of erosions to perform. - - private void init() { - - } - public OCRProcessingOptions() { - super(36); - init(); - } - public OCRProcessingOptions(ThresholdMode mode, int lowThreshold, int highThreshold, int blockCount, int fastThreshold, int biModalCalculation, int darkCharacters, int removeParticlesTouchingROI, int erosionCount) { - super(36); - this.mode = mode; - this.lowThreshold = lowThreshold; - this.highThreshold = highThreshold; - this.blockCount = blockCount; - this.fastThreshold = fastThreshold; - this.biModalCalculation = biModalCalculation; - this.darkCharacters = darkCharacters; - this.removeParticlesTouchingROI = removeParticlesTouchingROI; - this.erosionCount = erosionCount; - } - protected OCRProcessingOptions(ByteBuffer backing, int offset) { - super(backing, offset, 36); - init(); - } - protected OCRProcessingOptions(long nativeObj, boolean owned) { - super(nativeObj, owned, 36); - init(); - } - protected void setBuffer(ByteBuffer backing, int offset) { - super.setBuffer(backing, offset, 36); - } - public void read() { - mode = ThresholdMode.fromValue(backing.getInt(0)); - lowThreshold = backing.getInt(4); - highThreshold = backing.getInt(8); - blockCount = backing.getInt(12); - fastThreshold = backing.getInt(16); - biModalCalculation = backing.getInt(20); - darkCharacters = backing.getInt(24); - removeParticlesTouchingROI = backing.getInt(28); - erosionCount = backing.getInt(32); - } - public void write() { - if (mode != null) - backing.putInt(0, mode.getValue()); - backing.putInt(4, lowThreshold); - backing.putInt(8, highThreshold); - backing.putInt(12, blockCount); - backing.putInt(16, fastThreshold); - backing.putInt(20, biModalCalculation); - backing.putInt(24, darkCharacters); - backing.putInt(28, removeParticlesTouchingROI); - backing.putInt(32, erosionCount); - } - public int size() { - return 36; - } - } - - public static class ReadTextOptions extends DisposedStruct { - public String[] validChars; // An array of strings that specifies the valid characters. - public byte substitutionChar; // The character to substitute for objects that the function cannot match with any of the trained characters. - public ReadStrategy readStrategy; // The read strategy, which determines how closely the function analyzes images in the reading process to match objects with trained characters. - public int acceptanceLevel; // The minimum acceptance level at which an object is considered a trained character. - public int aspectRatio; // The maximum aspect ratio variance percentage for valid characters. - public ReadResolution readResolution; // The read resolution, which determines how much of the trained character data the function uses to match objects to trained characters. - private ByteBuffer validChars_buf; - private ByteBuffer[] validChars_bufs; - - private void init() { - validChars = new String[0]; - } - public ReadTextOptions() { - super(65304); - init(); - } - public ReadTextOptions(String[] validChars, byte substitutionChar, ReadStrategy readStrategy, int acceptanceLevel, int aspectRatio, ReadResolution readResolution) { - super(65304); - this.validChars = validChars; - this.substitutionChar = substitutionChar; - this.readStrategy = readStrategy; - this.acceptanceLevel = acceptanceLevel; - this.aspectRatio = aspectRatio; - this.readResolution = readResolution; - } - protected ReadTextOptions(ByteBuffer backing, int offset) { - super(backing, offset, 65304); - init(); - } - protected ReadTextOptions(long nativeObj, boolean owned) { - super(nativeObj, owned, 65304); - init(); - } - protected void setBuffer(ByteBuffer backing, int offset) { - super.setBuffer(backing, offset, 65304); - } - public void read() { - int validChars_numValidChars = backing.getInt(65280); - long validChars_addr = getPointer(backing, 0); - validChars = new String[validChars_numValidChars]; - if (validChars_numValidChars > 0 && validChars_addr != 0) { - ByteBuffer bb = newDirectByteBuffer(validChars_addr, validChars_numValidChars*4); - for (int i=0, off=0; i 0 && characterReport_addr != 0) { - ByteBuffer bb = newDirectByteBuffer(characterReport_addr, characterReport_numCharacterReports*48); - for (int i=0, off=0; i 0 && edges_addr != 0) { - ByteBuffer bb = newDirectByteBuffer(edges_addr, edges_numEdges*8); - for (int i=0, off=0; i 0 && segmentInfo_addr != 0) { - ByteBuffer bb = newDirectByteBuffer(segmentInfo_addr, segmentInfo_numCharacters*4); - for (int i=0, off=0; i 0 && colorsToIgnore_addr != 0) { - ByteBuffer bb = newDirectByteBuffer(colorsToIgnore_addr, colorsToIgnore_numColorsToIgnore*12); - for (int i=0, off=0; i 0 && columnAverages_addr != 0) { - newDirectByteBuffer(columnAverages_addr, columnAverages_columnCount*4).asFloatBuffer().get(columnAverages); - } - int rowAverages_rowCount = backing.getInt(12); - long rowAverages_addr = getPointer(backing, 8); - rowAverages = new float[rowAverages_rowCount]; - if (rowAverages_rowCount > 0 && rowAverages_addr != 0) { - newDirectByteBuffer(rowAverages_addr, rowAverages_rowCount*4).asFloatBuffer().get(rowAverages); - } - int risingDiagAverages_risingDiagCount = backing.getInt(20); - long risingDiagAverages_addr = getPointer(backing, 16); - risingDiagAverages = new float[risingDiagAverages_risingDiagCount]; - if (risingDiagAverages_risingDiagCount > 0 && risingDiagAverages_addr != 0) { - newDirectByteBuffer(risingDiagAverages_addr, risingDiagAverages_risingDiagCount*4).asFloatBuffer().get(risingDiagAverages); - } - int fallingDiagAverages_fallingDiagCount = backing.getInt(28); - long fallingDiagAverages_addr = getPointer(backing, 24); - fallingDiagAverages = new float[fallingDiagAverages_fallingDiagCount]; - if (fallingDiagAverages_fallingDiagCount > 0 && fallingDiagAverages_addr != 0) { - newDirectByteBuffer(fallingDiagAverages_addr, fallingDiagAverages_fallingDiagCount*4).asFloatBuffer().get(fallingDiagAverages); - } - } - public void write() { - columnAverages_buf = ByteBuffer.allocateDirect(columnAverages.length*4).order(ByteOrder.nativeOrder()); - columnAverages_buf.asFloatBuffer().put(columnAverages).rewind(); - backing.putInt(4, columnAverages.length); - putPointer(backing, 0, columnAverages_buf); - rowAverages_buf = ByteBuffer.allocateDirect(rowAverages.length*4).order(ByteOrder.nativeOrder()); - rowAverages_buf.asFloatBuffer().put(rowAverages).rewind(); - backing.putInt(12, rowAverages.length); - putPointer(backing, 8, rowAverages_buf); - risingDiagAverages_buf = ByteBuffer.allocateDirect(risingDiagAverages.length*4).order(ByteOrder.nativeOrder()); - risingDiagAverages_buf.asFloatBuffer().put(risingDiagAverages).rewind(); - backing.putInt(20, risingDiagAverages.length); - putPointer(backing, 16, risingDiagAverages_buf); - fallingDiagAverages_buf = ByteBuffer.allocateDirect(fallingDiagAverages.length*4).order(ByteOrder.nativeOrder()); - fallingDiagAverages_buf.asFloatBuffer().put(fallingDiagAverages).rewind(); - backing.putInt(28, fallingDiagAverages.length); - putPointer(backing, 24, fallingDiagAverages_buf); - } - public int size() { - return 32; - } - } - - public static class LineProfile extends DisposedStruct { - public float[] profileData; // An array containing the value of each pixel in the line. - public Rect boundingBox; // The bounding rectangle of the line. - public float min; // The smallest pixel value in the line profile. - public float max; // The largest pixel value in the line profile. - public float mean; // The mean value of the pixels in the line profile. - public float stdDev; // The standard deviation of the line profile. - private ByteBuffer profileData_buf; - - private void init() { - profileData = new float[0]; - boundingBox = new Rect(backing, 4); - } - public LineProfile() { - super(40); - init(); - } - public LineProfile(float[] profileData, Rect boundingBox, double min, double max, double mean, double stdDev) { - super(40); - this.profileData = profileData; - this.boundingBox = boundingBox; - this.min = (float)min; - this.max = (float)max; - this.mean = (float)mean; - this.stdDev = (float)stdDev; - } - protected LineProfile(ByteBuffer backing, int offset) { - super(backing, offset, 40); - init(); - } - protected LineProfile(long nativeObj, boolean owned) { - super(nativeObj, owned, 40); - init(); - } - protected void setBuffer(ByteBuffer backing, int offset) { - super.setBuffer(backing, offset, 40); - } - public void read() { - int profileData_dataCount = backing.getInt(36); - long profileData_addr = getPointer(backing, 0); - profileData = new float[profileData_dataCount]; - if (profileData_dataCount > 0 && profileData_addr != 0) { - newDirectByteBuffer(profileData_addr, profileData_dataCount*4).asFloatBuffer().get(profileData); - } - boundingBox.read(); - min = backing.getFloat(20); - max = backing.getFloat(24); - mean = backing.getFloat(28); - stdDev = backing.getFloat(32); - } - public void write() { - profileData_buf = ByteBuffer.allocateDirect(profileData.length*4).order(ByteOrder.nativeOrder()); - profileData_buf.asFloatBuffer().put(profileData).rewind(); - backing.putInt(36, profileData.length); - putPointer(backing, 0, profileData_buf); - boundingBox.write(); - backing.putFloat(20, min); - backing.putFloat(24, max); - backing.putFloat(28, mean); - backing.putFloat(32, stdDev); - } - public int size() { - return 40; - } - } - - public static class MatchColorPatternOptions extends DisposedStruct { - public MatchingMode matchMode; // Specifies the method to use when looking for the color pattern in the image. - public ImageFeatureMode featureMode; // Specifies the features to use when looking for the color pattern in the image. - public int minContrast; // Specifies the minimum contrast expected in the image. - public int subpixelAccuracy; // Set this parameter to TRUE to return areas in the image that match the pattern area with subpixel accuracy. - public RotationAngleRange[] angleRanges; // An array of angle ranges, in degrees, where each range specifies how much you expect the pattern to be rotated in the image. - public double colorWeight; // Determines the percent contribution of the color score to the final color pattern matching score. - public ColorSensitivity sensitivity; // Specifies the sensitivity of the color information in the image. - public SearchStrategy strategy; // Specifies how the color features of the image are used during the search phase. - public int numMatchesRequested; // Number of valid matches expected. - public float minMatchScore; // The minimum score a match can have for the function to consider the match valid. - private ByteBuffer angleRanges_buf; - - private void init() { - angleRanges = new RotationAngleRange[0]; - } - public MatchColorPatternOptions() { - super(48); - init(); - } - public MatchColorPatternOptions(MatchingMode matchMode, ImageFeatureMode featureMode, int minContrast, int subpixelAccuracy, RotationAngleRange[] angleRanges, double colorWeight, ColorSensitivity sensitivity, SearchStrategy strategy, int numMatchesRequested, double minMatchScore) { - super(48); - this.matchMode = matchMode; - this.featureMode = featureMode; - this.minContrast = minContrast; - this.subpixelAccuracy = subpixelAccuracy; - this.angleRanges = angleRanges; - this.colorWeight = colorWeight; - this.sensitivity = sensitivity; - this.strategy = strategy; - this.numMatchesRequested = numMatchesRequested; - this.minMatchScore = (float)minMatchScore; - } - protected MatchColorPatternOptions(ByteBuffer backing, int offset) { - super(backing, offset, 48); - init(); - } - protected MatchColorPatternOptions(long nativeObj, boolean owned) { - super(nativeObj, owned, 48); - init(); - } - protected void setBuffer(ByteBuffer backing, int offset) { - super.setBuffer(backing, offset, 48); - } - public void read() { - matchMode = MatchingMode.fromValue(backing.getInt(0)); - featureMode = ImageFeatureMode.fromValue(backing.getInt(4)); - minContrast = backing.getInt(8); - subpixelAccuracy = backing.getInt(12); - int angleRanges_numRanges = backing.getInt(20); - long angleRanges_addr = getPointer(backing, 16); - angleRanges = new RotationAngleRange[angleRanges_numRanges]; - if (angleRanges_numRanges > 0 && angleRanges_addr != 0) { - ByteBuffer bb = newDirectByteBuffer(angleRanges_addr, angleRanges_numRanges*8); - for (int i=0, off=0; i 0 && histogram_addr != 0) { - newDirectByteBuffer(histogram_addr, histogram_histogramCount*4).asIntBuffer().get(histogram); - } - min = backing.getFloat(8); - max = backing.getFloat(12); - start = backing.getFloat(16); - width = backing.getFloat(20); - mean = backing.getFloat(24); - stdDev = backing.getFloat(28); - numPixels = backing.getInt(32); - } - public void write() { - histogram_buf = ByteBuffer.allocateDirect(histogram.length*4).order(ByteOrder.nativeOrder()); - histogram_buf.asIntBuffer().put(histogram).rewind(); - backing.putInt(4, histogram.length); - putPointer(backing, 0, histogram_buf); - backing.putFloat(8, min); - backing.putFloat(12, max); - backing.putFloat(16, start); - backing.putFloat(20, width); - backing.putFloat(24, mean); - backing.putFloat(28, stdDev); - backing.putInt(32, numPixels); - } - public int size() { - return 36; - } - } - - public static class ArcInfo extends DisposedStruct { - public Rect boundingBox; // The coordinate location of the bounding box of the arc. - public double startAngle; // The counterclockwise angle from the x-axis in degrees to the start of the arc. - public double endAngle; // The counterclockwise angle from the x-axis in degrees to the end of the arc. - - private void init() { - boundingBox = new Rect(backing, 0); - } - public ArcInfo() { - super(32); - init(); - } - public ArcInfo(Rect boundingBox, double startAngle, double endAngle) { - super(32); - this.boundingBox = boundingBox; - this.startAngle = startAngle; - this.endAngle = endAngle; - } - protected ArcInfo(ByteBuffer backing, int offset) { - super(backing, offset, 32); - init(); - } - protected ArcInfo(long nativeObj, boolean owned) { - super(nativeObj, owned, 32); - init(); - } - protected void setBuffer(ByteBuffer backing, int offset) { - super.setBuffer(backing, offset, 32); - } - public void read() { - boundingBox.read(); - startAngle = backing.getDouble(16); - endAngle = backing.getDouble(24); - } - public void write() { - boundingBox.write(); - backing.putDouble(16, startAngle); - backing.putDouble(24, endAngle); - } - public int size() { - return 32; - } - } - - public static class AxisReport extends DisposedStruct { - public PointFloat origin; // The origin of the coordinate system, which is the intersection of the two axes of the coordinate system. - public PointFloat mainAxisEnd; // The end of the main axis, which is the result of the computation of the intersection of the main axis with the rectangular search area. - public PointFloat secondaryAxisEnd; // The end of the secondary axis, which is the result of the computation of the intersection of the secondary axis with the rectangular search area. - - private void init() { - origin = new PointFloat(backing, 0); - mainAxisEnd = new PointFloat(backing, 8); - secondaryAxisEnd = new PointFloat(backing, 16); - } - public AxisReport() { - super(24); - init(); - } - public AxisReport(PointFloat origin, PointFloat mainAxisEnd, PointFloat secondaryAxisEnd) { - super(24); - this.origin = origin; - this.mainAxisEnd = mainAxisEnd; - this.secondaryAxisEnd = secondaryAxisEnd; - } - protected AxisReport(ByteBuffer backing, int offset) { - super(backing, offset, 24); - init(); - } - protected AxisReport(long nativeObj, boolean owned) { - super(nativeObj, owned, 24); - init(); - } - protected void setBuffer(ByteBuffer backing, int offset) { - super.setBuffer(backing, offset, 24); - } - public void read() { - origin.read(); - mainAxisEnd.read(); - secondaryAxisEnd.read(); - } - public void write() { - origin.write(); - mainAxisEnd.write(); - secondaryAxisEnd.write(); - } - public int size() { - return 24; - } - } - - public static class BarcodeInfo extends DisposedStruct { - public String outputString; // A string containing the decoded barcode data. - public int size; // The size of the output string. - public byte outputChar1; // The contents of this character depend on the barcode type. - public byte outputChar2; // The contents of this character depend on the barcode type. - public double confidenceLevel; // A quality measure of the decoded barcode ranging from 0 to 100, with 100 being the best. - public BarcodeType type; // The type of barcode. - private ByteBuffer outputString_buf; - - private void init() { - - } - public BarcodeInfo() { - super(32); - init(); - } - public BarcodeInfo(String outputString, int size, byte outputChar1, byte outputChar2, double confidenceLevel, BarcodeType type) { - super(32); - this.outputString = outputString; - this.size = size; - this.outputChar1 = outputChar1; - this.outputChar2 = outputChar2; - this.confidenceLevel = confidenceLevel; - this.type = type; - } - protected BarcodeInfo(ByteBuffer backing, int offset) { - super(backing, offset, 32); - init(); - } - protected BarcodeInfo(long nativeObj, boolean owned) { - super(nativeObj, owned, 32); - init(); - } - protected void setBuffer(ByteBuffer backing, int offset) { - super.setBuffer(backing, offset, 32); - } - public void read() { - long outputString_addr = getPointer(backing, 0); - if (outputString_addr == 0) - outputString = null; - else { - ByteBuffer bb = newDirectByteBuffer(outputString_addr, 1000); // FIXME - while (bb.get() != 0) {} - byte[] bytes = new byte[bb.position()-1]; - getBytes(bb, bytes, 0, bytes.length); - try { - outputString = new String(bytes, "UTF-8"); - } catch (UnsupportedEncodingException e) { - outputString = ""; - } - } - - size = backing.getInt(4); - outputChar1 = backing.get(8); - outputChar2 = backing.get(9); - confidenceLevel = backing.getDouble(16); - type = BarcodeType.fromValue(backing.getInt(24)); - } - public void write() { - if (outputString != null) { - byte[] outputString_bytes; - try { - outputString_bytes = outputString.getBytes("UTF-8"); - } catch (UnsupportedEncodingException e) { - outputString_bytes = new byte[0]; - } - outputString_buf = ByteBuffer.allocateDirect(outputString_bytes.length+1); - putBytes(outputString_buf, outputString_bytes, 0, outputString_bytes.length).put(outputString_bytes.length, (byte)0); - } - putPointer(backing, 0, outputString == null ? 0 : getByteBufferAddress(outputString_buf)); - backing.putInt(4, size); - backing.put(8, outputChar1); - backing.put(9, outputChar2); - backing.putDouble(16, confidenceLevel); - if (type != null) - backing.putInt(24, type.getValue()); - } - public int size() { - return 32; - } - } - - public static class BCGOptions extends DisposedStruct { - public float brightness; // Adjusts the brightness of the image. - public float contrast; // Adjusts the contrast of the image. - public float gamma; // Performs gamma correction. - - private void init() { - - } - public BCGOptions() { - super(12); - init(); - } - public BCGOptions(double brightness, double contrast, double gamma) { - super(12); - this.brightness = (float)brightness; - this.contrast = (float)contrast; - this.gamma = (float)gamma; - } - protected BCGOptions(ByteBuffer backing, int offset) { - super(backing, offset, 12); - init(); - } - protected BCGOptions(long nativeObj, boolean owned) { - super(nativeObj, owned, 12); - init(); - } - protected void setBuffer(ByteBuffer backing, int offset) { - super.setBuffer(backing, offset, 12); - } - public void read() { - brightness = backing.getFloat(0); - contrast = backing.getFloat(4); - gamma = backing.getFloat(8); - } - public void write() { - backing.putFloat(0, brightness); - backing.putFloat(4, contrast); - backing.putFloat(8, gamma); - } - public int size() { - return 12; - } - } - - public static class BestCircle extends DisposedStruct { - public PointFloat center; // The coordinate location of the center of the circle. - public double radius; // The radius of the circle. - public double area; // The area of the circle. - public double perimeter; // The length of the perimeter of the circle. - public double error; // Represents the least square error of the fitted circle to the entire set of points. - - private void init() { - center = new PointFloat(backing, 0); - } - public BestCircle() { - super(40); - init(); - } - public BestCircle(PointFloat center, double radius, double area, double perimeter, double error) { - super(40); - this.center = center; - this.radius = radius; - this.area = area; - this.perimeter = perimeter; - this.error = error; - } - protected BestCircle(ByteBuffer backing, int offset) { - super(backing, offset, 40); - init(); - } - protected BestCircle(long nativeObj, boolean owned) { - super(nativeObj, owned, 40); - init(); - } - protected void setBuffer(ByteBuffer backing, int offset) { - super.setBuffer(backing, offset, 40); - } - public void read() { - center.read(); - radius = backing.getDouble(8); - area = backing.getDouble(16); - perimeter = backing.getDouble(24); - error = backing.getDouble(32); - } - public void write() { - center.write(); - backing.putDouble(8, radius); - backing.putDouble(16, area); - backing.putDouble(24, perimeter); - backing.putDouble(32, error); - } - public int size() { - return 40; - } - } - - public static class BestEllipse extends DisposedStruct { - public PointFloat center; // The coordinate location of the center of the ellipse. - public PointFloat majorAxisStart; // The coordinate location of the start of the major axis of the ellipse. - public PointFloat majorAxisEnd; // The coordinate location of the end of the major axis of the ellipse. - public PointFloat minorAxisStart; // The coordinate location of the start of the minor axis of the ellipse. - public PointFloat minorAxisEnd; // The coordinate location of the end of the minor axis of the ellipse. - public double area; // The area of the ellipse. - public double perimeter; // The length of the perimeter of the ellipse. - - private void init() { - center = new PointFloat(backing, 0); - majorAxisStart = new PointFloat(backing, 8); - majorAxisEnd = new PointFloat(backing, 16); - minorAxisStart = new PointFloat(backing, 24); - minorAxisEnd = new PointFloat(backing, 32); - } - public BestEllipse() { - super(56); - init(); - } - public BestEllipse(PointFloat center, PointFloat majorAxisStart, PointFloat majorAxisEnd, PointFloat minorAxisStart, PointFloat minorAxisEnd, double area, double perimeter) { - super(56); - this.center = center; - this.majorAxisStart = majorAxisStart; - this.majorAxisEnd = majorAxisEnd; - this.minorAxisStart = minorAxisStart; - this.minorAxisEnd = minorAxisEnd; - this.area = area; - this.perimeter = perimeter; - } - protected BestEllipse(ByteBuffer backing, int offset) { - super(backing, offset, 56); - init(); - } - protected BestEllipse(long nativeObj, boolean owned) { - super(nativeObj, owned, 56); - init(); - } - protected void setBuffer(ByteBuffer backing, int offset) { - super.setBuffer(backing, offset, 56); - } - public void read() { - center.read(); - majorAxisStart.read(); - majorAxisEnd.read(); - minorAxisStart.read(); - minorAxisEnd.read(); - area = backing.getDouble(40); - perimeter = backing.getDouble(48); - } - public void write() { - center.write(); - majorAxisStart.write(); - majorAxisEnd.write(); - minorAxisStart.write(); - minorAxisEnd.write(); - backing.putDouble(40, area); - backing.putDouble(48, perimeter); - } - public int size() { - return 56; - } - } - - public static class BestLine extends DisposedStruct { - public PointFloat start; // The coordinate location of the start of the line. - public PointFloat end; // The coordinate location of the end of the line. - public LineEquation equation; // Defines the three coefficients of the equation of the best fit line. - public int valid; // This element is TRUE if the function achieved the minimum score within the number of allowed refinement iterations and FALSE if the function did not achieve the minimum score. - public double error; // Represents the least square error of the fitted line to the entire set of points. - public int[] pointsUsed; // An array of the indexes for the points array indicating which points the function used to fit the line. - private ByteBuffer pointsUsed_buf; - - private void init() { - start = new PointFloat(backing, 0); - end = new PointFloat(backing, 8); - equation = new LineEquation(backing, 16); - pointsUsed = new int[0]; - } - public BestLine() { - super(64); - init(); - } - public BestLine(PointFloat start, PointFloat end, LineEquation equation, int valid, double error, int[] pointsUsed) { - super(64); - this.start = start; - this.end = end; - this.equation = equation; - this.valid = valid; - this.error = error; - this.pointsUsed = pointsUsed; - } - protected BestLine(ByteBuffer backing, int offset) { - super(backing, offset, 64); - init(); - } - protected BestLine(long nativeObj, boolean owned) { - super(nativeObj, owned, 64); - init(); - } - protected void setBuffer(ByteBuffer backing, int offset) { - super.setBuffer(backing, offset, 64); - } - public void read() { - start.read(); - end.read(); - equation.read(); - valid = backing.getInt(40); - error = backing.getDouble(48); - int pointsUsed_numPointsUsed = backing.getInt(60); - long pointsUsed_addr = getPointer(backing, 56); - pointsUsed = new int[pointsUsed_numPointsUsed]; - if (pointsUsed_numPointsUsed > 0 && pointsUsed_addr != 0) { - newDirectByteBuffer(pointsUsed_addr, pointsUsed_numPointsUsed*4).asIntBuffer().get(pointsUsed); - } - } - public void write() { - start.write(); - end.write(); - equation.write(); - backing.putInt(40, valid); - backing.putDouble(48, error); - pointsUsed_buf = ByteBuffer.allocateDirect(pointsUsed.length*4).order(ByteOrder.nativeOrder()); - pointsUsed_buf.asIntBuffer().put(pointsUsed).rewind(); - backing.putInt(60, pointsUsed.length); - putPointer(backing, 56, pointsUsed_buf); - } - public int size() { - return 64; - } - } - - public static class BrowserOptions extends DisposedStruct { - public int width; // The width to make the browser. - public int height; // The height to make the browser image. - public int imagesPerLine; // The number of images to place on a single line. - public RGBValue backgroundColor; // The background color of the browser. - public int frameSize; // Specifies the number of pixels with which to border each thumbnail. - public BrowserFrameStyle style; // The style for the frame around each thumbnail. - public float ratio; // Specifies the width to height ratio of each thumbnail. - public RGBValue focusColor; // The color to use to display focused cells. - - private void init() { - backgroundColor = new RGBValue(backing, 12); - focusColor = new RGBValue(backing, 28); - } - public BrowserOptions() { - super(32); - init(); - } - public BrowserOptions(int width, int height, int imagesPerLine, RGBValue backgroundColor, int frameSize, BrowserFrameStyle style, double ratio, RGBValue focusColor) { - super(32); - this.width = width; - this.height = height; - this.imagesPerLine = imagesPerLine; - this.backgroundColor = backgroundColor; - this.frameSize = frameSize; - this.style = style; - this.ratio = (float)ratio; - this.focusColor = focusColor; - } - protected BrowserOptions(ByteBuffer backing, int offset) { - super(backing, offset, 32); - init(); - } - protected BrowserOptions(long nativeObj, boolean owned) { - super(nativeObj, owned, 32); - init(); - } - protected void setBuffer(ByteBuffer backing, int offset) { - super.setBuffer(backing, offset, 32); - } - public void read() { - width = backing.getInt(0); - height = backing.getInt(4); - imagesPerLine = backing.getInt(8); - backgroundColor.read(); - frameSize = backing.getInt(16); - style = BrowserFrameStyle.fromValue(backing.getInt(20)); - ratio = backing.getFloat(24); - focusColor.read(); - } - public void write() { - backing.putInt(0, width); - backing.putInt(4, height); - backing.putInt(8, imagesPerLine); - backgroundColor.write(); - backing.putInt(16, frameSize); - if (style != null) - backing.putInt(20, style.getValue()); - backing.putFloat(24, ratio); - focusColor.write(); - } - public int size() { - return 32; - } - } - - public static class CoordinateSystem extends DisposedStruct { - public PointFloat origin; // The origin of the coordinate system. - public float angle; // The angle, in degrees, of the x-axis of the coordinate system relative to the image x-axis. - public AxisOrientation axisOrientation; // The direction of the y-axis of the coordinate reference system. - - private void init() { - origin = new PointFloat(backing, 0); - } - public CoordinateSystem() { - super(16); - init(); - } - public CoordinateSystem(PointFloat origin, double angle, AxisOrientation axisOrientation) { - super(16); - this.origin = origin; - this.angle = (float)angle; - this.axisOrientation = axisOrientation; - } - protected CoordinateSystem(ByteBuffer backing, int offset) { - super(backing, offset, 16); - init(); - } - protected CoordinateSystem(long nativeObj, boolean owned) { - super(nativeObj, owned, 16); - init(); - } - protected void setBuffer(ByteBuffer backing, int offset) { - super.setBuffer(backing, offset, 16); - } - public void read() { - origin.read(); - angle = backing.getFloat(8); - axisOrientation = AxisOrientation.fromValue(backing.getInt(12)); - } - public void write() { - origin.write(); - backing.putFloat(8, angle); - if (axisOrientation != null) - backing.putInt(12, axisOrientation.getValue()); - } - public int size() { - return 16; - } - } - - public static class CalibrationInfo extends DisposedStruct { - public int mapColumns; // The number of columns in the error map. - public int mapRows; // The number of rows in the error map. - public ROI userRoi; // Specifies the ROI the user provided when learning the calibration. - public ROI calibrationRoi; // Specifies the ROI that corresponds to the region of the image where the calibration information is accurate. - public LearnCalibrationOptions options; // Specifies the calibration options the user provided when learning the calibration. - public GridDescriptor grid; // Specifies the scaling constants for the image. - public CoordinateSystem system; // Specifies the coordinate system for the real world coordinates. - public RangeFloat range; // The range of the grayscale the function used to represent the circles in the grid image. - public float quality; // The quality score of the learning process, which is a value between 0-1000. - - private void init() { - options = new LearnCalibrationOptions(backing, 20); - grid = new GridDescriptor(backing, 40); - system = new CoordinateSystem(backing, 52); - range = new RangeFloat(backing, 68); - } - public CalibrationInfo() { - super(80); - init(); - } - public CalibrationInfo(int mapColumns, int mapRows, ROI userRoi, ROI calibrationRoi, LearnCalibrationOptions options, GridDescriptor grid, CoordinateSystem system, RangeFloat range, double quality) { - super(80); - this.mapColumns = mapColumns; - this.mapRows = mapRows; - this.userRoi = userRoi; - this.calibrationRoi = calibrationRoi; - this.options = options; - this.grid = grid; - this.system = system; - this.range = range; - this.quality = (float)quality; - } - protected CalibrationInfo(ByteBuffer backing, int offset) { - super(backing, offset, 80); - init(); - } - protected CalibrationInfo(long nativeObj, boolean owned) { - super(nativeObj, owned, 80); - init(); - } - protected void setBuffer(ByteBuffer backing, int offset) { - super.setBuffer(backing, offset, 80); - } - public void read() { - mapColumns = backing.getInt(4); - mapRows = backing.getInt(8); - long userRoi_addr = getPointer(backing, 12); - if (userRoi_addr == 0) - userRoi = null; - else - userRoi = new ROI(userRoi_addr, false); - long calibrationRoi_addr = getPointer(backing, 16); - if (calibrationRoi_addr == 0) - calibrationRoi = null; - else - calibrationRoi = new ROI(calibrationRoi_addr, false); - options.read(); - grid.read(); - system.read(); - range.read(); - quality = backing.getFloat(76); - } - public void write() { - backing.putInt(4, mapColumns); - backing.putInt(8, mapRows); - putPointer(backing, 12, userRoi); - putPointer(backing, 16, calibrationRoi); - options.write(); - grid.write(); - system.write(); - range.write(); - backing.putFloat(76, quality); - } - public int size() { - return 80; - } - } - - public static class CalibrationPoints extends DisposedStruct { - public PointFloat[] pixelCoordinates; // The array of pixel coordinates. - public PointFloat[] realWorldCoordinates; // The array of corresponding real-world coordinates. - private ByteBuffer pixelCoordinates_buf; - private ByteBuffer realWorldCoordinates_buf; - - private void init() { - pixelCoordinates = new PointFloat[0]; - realWorldCoordinates = new PointFloat[0]; - } - public CalibrationPoints() { - super(12); - init(); - } - public CalibrationPoints(PointFloat[] pixelCoordinates, PointFloat[] realWorldCoordinates) { - super(12); - this.pixelCoordinates = pixelCoordinates; - this.realWorldCoordinates = realWorldCoordinates; - } - protected CalibrationPoints(ByteBuffer backing, int offset) { - super(backing, offset, 12); - init(); - } - protected CalibrationPoints(long nativeObj, boolean owned) { - super(nativeObj, owned, 12); - init(); - } - protected void setBuffer(ByteBuffer backing, int offset) { - super.setBuffer(backing, offset, 12); - } - public void read() { - int pixelCoordinates_numCoordinates = backing.getInt(8); - long pixelCoordinates_addr = getPointer(backing, 0); - pixelCoordinates = new PointFloat[pixelCoordinates_numCoordinates]; - if (pixelCoordinates_numCoordinates > 0 && pixelCoordinates_addr != 0) { - ByteBuffer bb = newDirectByteBuffer(pixelCoordinates_addr, pixelCoordinates_numCoordinates*8); - for (int i=0, off=0; i 0 && realWorldCoordinates_addr != 0) { - ByteBuffer bb = newDirectByteBuffer(realWorldCoordinates_addr, realWorldCoordinates_numCoordinates*8); - for (int i=0, off=0; i 0 && points_addr != 0) { - ByteBuffer bb = newDirectByteBuffer(points_addr, points_numPoints*8); - for (int i=0, off=0; i 0 && info_addr != 0) { - newDirectByteBuffer(info_addr, info_infoCount*8).asDoubleBuffer().get(info); - } - } - public void write() { - backing.putInt(4, saturation); - info_buf = ByteBuffer.allocateDirect(info.length*8).order(ByteOrder.nativeOrder()); - info_buf.asDoubleBuffer().put(info).rewind(); - backing.putInt(0, info.length); - putPointer(backing, 8, info_buf); - } - public int size() { - return 12; - } - } - - public static class Complex extends DisposedStruct { - public float r; // The real part of the value. - public float i; // The imaginary part of the value. - - private void init() { - - } - public Complex() { - super(8); - init(); - } - public Complex(double r, double i) { - super(8); - this.r = (float)r; - this.i = (float)i; - } - protected Complex(ByteBuffer backing, int offset) { - super(backing, offset, 8); - init(); - } - protected Complex(long nativeObj, boolean owned) { - super(nativeObj, owned, 8); - init(); - } - protected void setBuffer(ByteBuffer backing, int offset) { - super.setBuffer(backing, offset, 8); - } - public void read() { - r = backing.getFloat(0); - i = backing.getFloat(4); - } - public void write() { - backing.putFloat(0, r); - backing.putFloat(4, i); - } - public int size() { - return 8; - } - } - - public static class ConcentricRakeReport extends DisposedStruct { - public ArcInfo[] rakeArcs; // An array containing the location of each concentric arc line used for edge detection. - public PointFloat[] firstEdges; // The coordinate location of all edges detected as first edges. - public PointFloat[] lastEdges; // The coordinate location of all edges detected as last edges. - public EdgeLocationReport[] allEdges; // An array of reports describing the location of the edges located by each concentric rake arc line. - public int[] linesWithEdges; // An array of indices into the rakeArcs array indicating the concentric rake arc lines on which the function detected at least one edge. - private ByteBuffer rakeArcs_buf; - private ByteBuffer firstEdges_buf; - private ByteBuffer lastEdges_buf; - private ByteBuffer allEdges_buf; - private ByteBuffer linesWithEdges_buf; - - private void init() { - rakeArcs = new ArcInfo[0]; - firstEdges = new PointFloat[0]; - lastEdges = new PointFloat[0]; - allEdges = new EdgeLocationReport[0]; - linesWithEdges = new int[0]; - } - public ConcentricRakeReport() { - super(36); - init(); - } - public ConcentricRakeReport(ArcInfo[] rakeArcs, PointFloat[] firstEdges, PointFloat[] lastEdges, EdgeLocationReport[] allEdges, int[] linesWithEdges) { - super(36); - this.rakeArcs = rakeArcs; - this.firstEdges = firstEdges; - this.lastEdges = lastEdges; - this.allEdges = allEdges; - this.linesWithEdges = linesWithEdges; - } - protected ConcentricRakeReport(ByteBuffer backing, int offset) { - super(backing, offset, 36); - init(); - } - protected ConcentricRakeReport(long nativeObj, boolean owned) { - super(nativeObj, owned, 36); - init(); - } - protected void setBuffer(ByteBuffer backing, int offset) { - super.setBuffer(backing, offset, 36); - } - public void read() { - int rakeArcs_numArcs = backing.getInt(4); - long rakeArcs_addr = getPointer(backing, 0); - rakeArcs = new ArcInfo[rakeArcs_numArcs]; - if (rakeArcs_numArcs > 0 && rakeArcs_addr != 0) { - ByteBuffer bb = newDirectByteBuffer(rakeArcs_addr, rakeArcs_numArcs*32); - for (int i=0, off=0; i 0 && firstEdges_addr != 0) { - ByteBuffer bb = newDirectByteBuffer(firstEdges_addr, firstEdges_numFirstEdges*8); - for (int i=0, off=0; i 0 && lastEdges_addr != 0) { - ByteBuffer bb = newDirectByteBuffer(lastEdges_addr, lastEdges_numLastEdges*8); - for (int i=0, off=0; i 0 && allEdges_addr != 0) { - ByteBuffer bb = newDirectByteBuffer(allEdges_addr, allEdges_numLinesWithEdges*8); - for (int i=0, off=0; i 0 && linesWithEdges_addr != 0) { - newDirectByteBuffer(linesWithEdges_addr, linesWithEdges_numLinesWithEdges*4).asIntBuffer().get(linesWithEdges); - } - } - public void write() { - rakeArcs_buf = ByteBuffer.allocateDirect(rakeArcs.length*32).order(ByteOrder.nativeOrder()); - for (int i=0, off=0; i 0 && palette_addr != 0) { - ByteBuffer bb = newDirectByteBuffer(palette_addr, palette_numColors*4); - for (int i=0, off=0; i 0 && points_addr != 0) { - ByteBuffer bb = newDirectByteBuffer(points_addr, points_numPoints*8); - for (int i=0, off=0; i 0 && angleRanges_addr != 0) { - ByteBuffer bb = newDirectByteBuffer(angleRanges_addr, angleRanges_numRanges*8); - for (int i=0, off=0; i 0 && points_addr != 0) { - ByteBuffer bb = newDirectByteBuffer(points_addr, points_numPoints*8); - for (int i=0, off=0; i 0 && regions_addr != 0) { - ByteBuffer bb = newDirectByteBuffer(regions_addr, regions_regionCount*28); - for (int i=0, off=0; i 0 && rakeLines_addr != 0) { - ByteBuffer bb = newDirectByteBuffer(rakeLines_addr, rakeLines_numRakeLines*16); - for (int i=0, off=0; i 0 && firstEdges_addr != 0) { - ByteBuffer bb = newDirectByteBuffer(firstEdges_addr, firstEdges_numFirstEdges*8); - for (int i=0, off=0; i 0 && lastEdges_addr != 0) { - ByteBuffer bb = newDirectByteBuffer(lastEdges_addr, lastEdges_numLastEdges*8); - for (int i=0, off=0; i 0 && allEdges_addr != 0) { - ByteBuffer bb = newDirectByteBuffer(allEdges_addr, allEdges_numLinesWithEdges*8); - for (int i=0, off=0; i 0 && linesWithEdges_addr != 0) { - newDirectByteBuffer(linesWithEdges_addr, linesWithEdges_numLinesWithEdges*4).asIntBuffer().get(linesWithEdges); - } - } - public void write() { - rakeLines_buf = ByteBuffer.allocateDirect(rakeLines.length*16).order(ByteOrder.nativeOrder()); - for (int i=0, off=0; i 0 && points_addr != 0) { - ByteBuffer bb = newDirectByteBuffer(points_addr, points_numPoints*8); - for (int i=0, off=0; i 0 && validPoints_addr != 0) { - newDirectByteBuffer(validPoints_addr, validPoints_numPoints*4).asIntBuffer().get(validPoints); - } - } - public void write() { - points_buf = ByteBuffer.allocateDirect(points.length*8).order(ByteOrder.nativeOrder()); - for (int i=0, off=0; i 0 && arcCoordPoints_addr != 0) { - ByteBuffer bb = newDirectByteBuffer(arcCoordPoints_addr, arcCoordPoints_numOfArcCoordPoints*8); - for (int i=0, off=0; i 0 && spokeLines_addr != 0) { - ByteBuffer bb = newDirectByteBuffer(spokeLines_addr, spokeLines_numSpokeLines*16); - for (int i=0, off=0; i 0 && firstEdges_addr != 0) { - ByteBuffer bb = newDirectByteBuffer(firstEdges_addr, firstEdges_numFirstEdges*8); - for (int i=0, off=0; i 0 && lastEdges_addr != 0) { - ByteBuffer bb = newDirectByteBuffer(lastEdges_addr, lastEdges_numLastEdges*8); - for (int i=0, off=0; i 0 && allEdges_addr != 0) { - ByteBuffer bb = newDirectByteBuffer(allEdges_addr, allEdges_numLinesWithEdges*8); - for (int i=0, off=0; i 0 && linesWithEdges_addr != 0) { - newDirectByteBuffer(linesWithEdges_addr, linesWithEdges_numLinesWithEdges*4).asIntBuffer().get(linesWithEdges); - } - } - public void write() { - spokeLines_buf = ByteBuffer.allocateDirect(spokeLines.length*16).order(ByteOrder.nativeOrder()); - for (int i=0, off=0; i 0 && array_addr != 0) { - ByteBuffer bb = newDirectByteBuffer(array_addr, array_numCircles*16); - for (int i=0, off=0; i 0 && array_addr != 0) { - ByteBuffer bb = newDirectByteBuffer(array_addr, array_numEdgePairs*32); - for (int i=0, off=0; i 0 && array_addr != 0) { - ByteBuffer bb = newDirectByteBuffer(array_addr, array_numExtremes*24); - for (int i=0, off=0; i 0 && array_addr != 0) { - ByteBuffer bb = newDirectByteBuffer(array_addr, array_numEdges*8); - for (int i=0, off=0; i 0 && array_addr != 0) { - ByteBuffer bb = newDirectByteBuffer(array_addr, array_size*4); - for (int i=0, off=0; i 0 && array_addr != 0) { - ByteBuffer bb = newDirectByteBuffer(array_addr, array_numSegments*24); - for (int i=0, off=0; i 0 && array_addr != 0) { - ByteBuffer bb = newDirectByteBuffer(array_addr, array_numPoints*8); - for (int i=0, off=0; i 0 && array_addr != 0) { - newDirectByteBuffer(array_addr, array_interpCount*4).asFloatBuffer().get(array); - } - } + public ContourFitSplineReport(PointDouble[] points) { + super(8); + this.points = points; + } - @Override - protected void finalize() throws Throwable { - imaqDispose(array_addr); - super.finalize(); - } + protected ContourFitSplineReport(ByteBuffer backing, int offset) { + super(backing, offset, 8); + init(); + } + + protected ContourFitSplineReport(long nativeObj, boolean owned) { + super(nativeObj, owned, 8); + init(); } - public static InterpolatePointsResult imaqInterpolatePoints(Image image, Point[] points, InterpolationMethod method, int subpixel) { - int numPoints = points.length; - ByteBuffer points_buf = null; - points_buf = ByteBuffer.allocateDirect(points.length*8).order(ByteOrder.nativeOrder()); - for (int i=0, off=0; i 0 && points_addr != 0) { + ByteBuffer bb = newDirectByteBuffer(points_addr, points_numberOfPoints * 16); + for (int i = 0, off = 0; i < points_numberOfPoints; i++, off += 16) { + points[i] = new PointDouble(bb, off); + points[i].read(); } - ByteBuffer rv_buf = ByteBuffer.allocateDirect(8).order(ByteOrder.nativeOrder()); - long rv_addr = getByteBufferAddress(rv_buf); - long jn_rv = _imaqInterpolatePoints(image.getAddress(), getByteBufferAddress(points_buf), numPoints, method.getValue(), subpixel, rv_addr+0); - InterpolatePointsResult rv = new InterpolatePointsResult(rv_buf, jn_rv); - return rv; + } + } + + public void write() { + points_buf = ByteBuffer.allocateDirect(points.length * 16).order(ByteOrder.nativeOrder()); + for (int i = 0, off = 0; i < points.length; i++, off += 16) { + points[i].setBuffer(points_buf, off); + points[i].write(); + } + backing.putInt(4, points.length); + putPointer(backing, 0, points_buf); } - private static native long _imaqInterpolatePoints(long image, long points, int numPoints, int method, int subpixel, long interpCount); - /** - * Clipboard functions - */ + public int size() { + return 8; + } + } + + public static class LineFloat extends DisposedStruct { + public PointFloat start; // The coordinate location of the start of the + // line. + public PointFloat end; // The coordinate location of the end of the line. - /** - * Border functions - */ + private void init() { + start = new PointFloat(backing, 0); + end = new PointFloat(backing, 8); + } - public static void imaqFillBorder(Image image, BorderMethod method) { - - _imaqFillBorder(image.getAddress(), method.getValue()); - + public LineFloat() { + super(16); + init(); } - private static native void _imaqFillBorder(long image, int method); - public static int imaqGetBorderSize(Image image) { - ByteBuffer rv_buf = ByteBuffer.allocateDirect(8).order(ByteOrder.nativeOrder()); - long rv_addr = getByteBufferAddress(rv_buf); - _imaqGetBorderSize(image.getAddress(), rv_addr+0); - int borderSize; - borderSize = rv_buf.getInt(0); - return borderSize; + public LineFloat(PointFloat start, PointFloat end) { + super(16); + this.start = start; + this.end = end; } - private static native void _imaqGetBorderSize(long image, long borderSize); - public static void imaqSetBorderSize(Image image, int size) { - - _imaqSetBorderSize(image.getAddress(), size); - + protected LineFloat(ByteBuffer backing, int offset) { + super(backing, offset, 16); + init(); } - private static native void _imaqSetBorderSize(long image, int size); - /** - * Image Management functions - */ + protected LineFloat(long nativeObj, boolean owned) { + super(nativeObj, owned, 16); + init(); + } - public static void imaqArrayToImage(Image image, RawData array, int numCols, int numRows) { - - _imaqArrayToImage(image.getAddress(), array.getAddress(), numCols, numRows); - + protected void setBuffer(ByteBuffer backing, int offset) { + super.setBuffer(backing, offset, 16); } - private static native void _imaqArrayToImage(long image, long array, int numCols, int numRows); - public static Image imaqCreateImage(ImageType type, int borderSize) { - - long jn_rv = _imaqCreateImage(type.getValue(), borderSize); - - return new Image(jn_rv, true); + public void read() { + start.read(); + end.read(); } - private static native long _imaqCreateImage(int type, int borderSize); - /** - * Color Processing functions - */ + public void write() { + start.write(); + end.write(); + } - public static void imaqColorBCGTransform(Image dest, Image source, BCGOptions redOptions, BCGOptions greenOptions, BCGOptions blueOptions, Image mask) { - - _imaqColorBCGTransform(dest.getAddress(), source.getAddress(), redOptions == null ? 0 : redOptions.getAddress(), greenOptions == null ? 0 : greenOptions.getAddress(), blueOptions == null ? 0 : blueOptions.getAddress(), mask == null ? 0 : mask.getAddress()); - + public int size() { + return 16; } - private static native void _imaqColorBCGTransform(long dest, long source, long redOptions, long greenOptions, long blueOptions, long mask); + } + + public static class LineEquation extends DisposedStruct { + public double a; // The a coefficient of the line equation. + public double b; // The b coefficient of the line equation. + public double c; // The c coefficient of the line equation. + + private void init() { - public static void imaqColorEqualize(Image dest, Image source, int colorEqualization) { - - _imaqColorEqualize(dest.getAddress(), source.getAddress(), colorEqualization); - } - private static native void _imaqColorEqualize(long dest, long source, int colorEqualization); - public static ColorHistogramReport imaqColorHistogram2(Image image, int numClasses, ColorMode mode, CIEXYZValue whiteReference, Image mask) { - - long jn_rv = _imaqColorHistogram2(image.getAddress(), numClasses, mode.getValue(), whiteReference.getAddress(), mask == null ? 0 : mask.getAddress()); - - return new ColorHistogramReport(jn_rv, true); + public LineEquation() { + super(24); + init(); } - private static native long _imaqColorHistogram2(long image, int numClasses, int mode, long whiteReference, long mask); - public static void imaqColorThreshold(Image dest, Image source, int replaceValue, ColorMode mode, Range plane1Range, Range plane2Range, Range plane3Range) { - - _imaqColorThreshold(dest.getAddress(), source.getAddress(), replaceValue, mode.getValue(), plane1Range == null ? 0 : plane1Range.getAddress(), plane2Range == null ? 0 : plane2Range.getAddress(), plane3Range == null ? 0 : plane3Range.getAddress()); - + public LineEquation(double a, double b, double c) { + super(24); + this.a = a; + this.b = b; + this.c = c; } - private static native void _imaqColorThreshold(long dest, long source, int replaceValue, int mode, long plane1Range, long plane2Range, long plane3Range); - - public static SupervisedColorSegmentationReport imaqSupervisedColorSegmentation(ClassifierSession session, Image labelImage, Image srcImage, ROI roi, ROILabel labelIn, int numLabelIn, int maxDistance, int minIdentificationScore, ColorSegmenationOptions segmentOptions) { - - long jn_rv = _imaqSupervisedColorSegmentation(session.getAddress(), labelImage.getAddress(), srcImage.getAddress(), roi.getAddress(), labelIn.getAddress(), numLabelIn, maxDistance, minIdentificationScore, segmentOptions.getAddress()); - - return new SupervisedColorSegmentationReport(jn_rv, true); + + protected LineEquation(ByteBuffer backing, int offset) { + super(backing, offset, 24); + init(); } - private static native long _imaqSupervisedColorSegmentation(long session, long labelImage, long srcImage, long roi, long labelIn, int numLabelIn, int maxDistance, int minIdentificationScore, long segmentOptions); - public static int imaqGetColorSegmentationMaxDistance(ClassifierSession session, ColorSegmenationOptions segmentOptions, SegmentationDistanceLevel distLevel) { - ByteBuffer rv_buf = ByteBuffer.allocateDirect(8).order(ByteOrder.nativeOrder()); - long rv_addr = getByteBufferAddress(rv_buf); - _imaqGetColorSegmentationMaxDistance(session.getAddress(), segmentOptions.getAddress(), distLevel.getValue(), rv_addr+0); - int maxDistance; - maxDistance = rv_buf.getInt(0); - return maxDistance; + protected LineEquation(long nativeObj, boolean owned) { + super(nativeObj, owned, 24); + init(); } - private static native void _imaqGetColorSegmentationMaxDistance(long session, long segmentOptions, int distLevel, long maxDistance); - /** - * Transform functions - */ + protected void setBuffer(ByteBuffer backing, int offset) { + super.setBuffer(backing, offset, 24); + } - public static void imaqBCGTransform(Image dest, Image source, BCGOptions options, Image mask) { - - _imaqBCGTransform(dest.getAddress(), source.getAddress(), options.getAddress(), mask == null ? 0 : mask.getAddress()); - + public void read() { + a = backing.getDouble(0); + b = backing.getDouble(8); + c = backing.getDouble(16); } - private static native void _imaqBCGTransform(long dest, long source, long options, long mask); - public static void imaqEqualize(Image dest, Image source, float min, float max, Image mask) { - - _imaqEqualize(dest.getAddress(), source.getAddress(), min, max, mask == null ? 0 : mask.getAddress()); - + public void write() { + backing.putDouble(0, a); + backing.putDouble(8, b); + backing.putDouble(16, c); } - private static native void _imaqEqualize(long dest, long source, float min, float max, long mask); - public static void imaqInverse(Image dest, Image source, Image mask) { - - _imaqInverse(dest.getAddress(), source.getAddress(), mask == null ? 0 : mask.getAddress()); - + public int size() { + return 24; } - private static native void _imaqInverse(long dest, long source, long mask); + } + + public static class ContourFitLineReport extends DisposedStruct { + public LineFloat lineSegment; // Line Segment represents the intersection of + // the line equation and the contour. + public LineEquation lineEquation; // Line Equation is a structure of three + // coefficients A, B, and C of the + // equation in the normal form (Ax + By + + // C=0) of the best fit line. - public static void imaqMathTransform(Image dest, Image source, MathTransformMethod method, float rangeMin, float rangeMax, float power, Image mask) { - - _imaqMathTransform(dest.getAddress(), source.getAddress(), method.getValue(), rangeMin, rangeMax, power, mask == null ? 0 : mask.getAddress()); - + private void init() { + lineSegment = new LineFloat(backing, 0); + lineEquation = new LineEquation(backing, 16); } - private static native void _imaqMathTransform(long dest, long source, int method, float rangeMin, float rangeMax, float power, long mask); - public static int imaqWatershedTransform(Image dest, Image source, int connectivity8) { - ByteBuffer rv_buf = ByteBuffer.allocateDirect(8).order(ByteOrder.nativeOrder()); - long rv_addr = getByteBufferAddress(rv_buf); - _imaqWatershedTransform(dest.getAddress(), source.getAddress(), connectivity8, rv_addr+0); - int zoneCount; - zoneCount = rv_buf.getInt(0); - return zoneCount; + public ContourFitLineReport() { + super(40); + init(); } - private static native void _imaqWatershedTransform(long dest, long source, int connectivity8, long zoneCount); - /** - * Window Management functions - */ + public ContourFitLineReport(LineFloat lineSegment, LineEquation lineEquation) { + super(40); + this.lineSegment = lineSegment; + this.lineEquation = lineEquation; + } - /** - * Utilities functions - */ + protected ContourFitLineReport(ByteBuffer backing, int offset) { + super(backing, offset, 40); + init(); + } - public static int imaqMulticoreOptions(MulticoreOperation operation) { - ByteBuffer rv_buf = ByteBuffer.allocateDirect(8).order(ByteOrder.nativeOrder()); - long rv_addr = getByteBufferAddress(rv_buf); - _imaqMulticoreOptions(operation.getValue(), rv_addr+0); - int customNumCores; - customNumCores = rv_buf.getInt(0); - return customNumCores; + protected ContourFitLineReport(long nativeObj, boolean owned) { + super(nativeObj, owned, 40); + init(); } - private static native void _imaqMulticoreOptions(int operation, long customNumCores); - /** - * Tool Window functions - */ + protected void setBuffer(ByteBuffer backing, int offset) { + super.setBuffer(backing, offset, 40); + } - /** - * Meter functions - */ - - public static MeterArc imaqGetMeterArc(int lightNeedle, MeterArcMode mode, ROI roi, PointFloat base, PointFloat start, PointFloat end) { - - long jn_rv = _imaqGetMeterArc(lightNeedle, mode.getValue(), roi.getAddress(), base.getAddress(), start.getAddress(), end.getAddress()); - - return new MeterArc(jn_rv, true); - } - private static native long _imaqGetMeterArc(int lightNeedle, int mode, long roi, long base, long start, long end); - - public static class ReadMeterResult { - public double percentage; - public PointFloat endOfNeedle; - private ReadMeterResult(ByteBuffer rv_buf) { - percentage = rv_buf.getDouble(0); - endOfNeedle = new PointFloat(rv_buf, 8); - endOfNeedle.read(); - } - } - - public static ReadMeterResult imaqReadMeter(Image image, MeterArc arcInfo) { - ByteBuffer rv_buf = ByteBuffer.allocateDirect(8+8).order(ByteOrder.nativeOrder()); - long rv_addr = getByteBufferAddress(rv_buf); - _imaqReadMeter(image.getAddress(), arcInfo.getAddress(), rv_addr+0, rv_addr+8); - ReadMeterResult rv = new ReadMeterResult(rv_buf); - return rv; - } - private static native void _imaqReadMeter(long image, long arcInfo, long percentage, long endOfNeedle); - - /** - * Calibration functions - */ - - public static void imaqCopyCalibrationInfo2(Image dest, Image source, Point offset) { - - _imaqCopyCalibrationInfo2(dest.getAddress(), source.getAddress(), offset.getAddress()); - - } - private static native void _imaqCopyCalibrationInfo2(long dest, long source, long offset); - - public static CalibrationInfo imaqGetCalibrationInfo2(Image image) { - - long jn_rv = _imaqGetCalibrationInfo2(image.getAddress()); - - return new CalibrationInfo(jn_rv, true); - } - private static native long _imaqGetCalibrationInfo2(long image); - - public static CalibrationInfo imaqGetCalibrationInfo3(Image image, int isGetErrorMap) { - - long jn_rv = _imaqGetCalibrationInfo3(image.getAddress(), isGetErrorMap); - - return new CalibrationInfo(jn_rv, true); - } - private static native long _imaqGetCalibrationInfo3(long image, int isGetErrorMap); - - public static float imaqLearnCalibrationGrid(Image image, ROI roi, LearnCalibrationOptions options, GridDescriptor grid, CoordinateSystem system, RangeFloat range) { - ByteBuffer rv_buf = ByteBuffer.allocateDirect(8).order(ByteOrder.nativeOrder()); - long rv_addr = getByteBufferAddress(rv_buf); - _imaqLearnCalibrationGrid(image.getAddress(), roi.getAddress(), options.getAddress(), grid.getAddress(), system.getAddress(), range.getAddress(), rv_addr+0); - float quality; - quality = rv_buf.getFloat(0); - return quality; - } - private static native void _imaqLearnCalibrationGrid(long image, long roi, long options, long grid, long system, long range, long quality); - - public static float imaqLearnCalibrationPoints(Image image, CalibrationPoints points, ROI roi, LearnCalibrationOptions options, GridDescriptor grid, CoordinateSystem system) { - ByteBuffer rv_buf = ByteBuffer.allocateDirect(8).order(ByteOrder.nativeOrder()); - long rv_addr = getByteBufferAddress(rv_buf); - _imaqLearnCalibrationPoints(image.getAddress(), points.getAddress(), roi.getAddress(), options.getAddress(), grid.getAddress(), system.getAddress(), rv_addr+0); - float quality; - quality = rv_buf.getFloat(0); - return quality; - } - private static native void _imaqLearnCalibrationPoints(long image, long points, long roi, long options, long grid, long system, long quality); - - public static void imaqSetCoordinateSystem(Image image, CoordinateSystem system) { - - _imaqSetCoordinateSystem(image.getAddress(), system.getAddress()); - - } - private static native void _imaqSetCoordinateSystem(long image, long system); - - public static void imaqSetSimpleCalibration(Image image, ScalingMethod method, int learnTable, GridDescriptor grid, CoordinateSystem system) { - - _imaqSetSimpleCalibration(image.getAddress(), method.getValue(), learnTable, grid.getAddress(), system.getAddress()); - - } - private static native void _imaqSetSimpleCalibration(long image, int method, int learnTable, long grid, long system); + public void read() { + lineSegment.read(); + lineEquation.read(); + } - public static TransformReport imaqTransformPixelToRealWorld(Image image, PointFloat[] pixelCoordinates) { - int numCoordinates = pixelCoordinates.length; - ByteBuffer pixelCoordinates_buf = null; - pixelCoordinates_buf = ByteBuffer.allocateDirect(pixelCoordinates.length*8).order(ByteOrder.nativeOrder()); - for (int i=0, off=0; i 0 && array_addr != 0) { - newDirectByteBuffer(array_addr, array_numScores*4).asIntBuffer().get(array); - } - } + public ContourFitPolynomialReport(PointDouble[] bestFit, double[] polynomialCoefficients) { + super(16); + this.bestFit = bestFit; + this.polynomialCoefficients = polynomialCoefficients; + } - @Override - protected void finalize() throws Throwable { - imaqDispose(array_addr); - super.finalize(); - } + protected ContourFitPolynomialReport(ByteBuffer backing, int offset) { + super(backing, offset, 16); + init(); } - public static MatchColorResult imaqMatchColor(Image image, ColorInformation info, ROI roi) { - ByteBuffer rv_buf = ByteBuffer.allocateDirect(8).order(ByteOrder.nativeOrder()); - long rv_addr = getByteBufferAddress(rv_buf); - long jn_rv = _imaqMatchColor(image.getAddress(), info.getAddress(), roi == null ? 0 : roi.getAddress(), rv_addr+0); - MatchColorResult rv = new MatchColorResult(rv_buf, jn_rv); - return rv; + protected ContourFitPolynomialReport(long nativeObj, boolean owned) { + super(nativeObj, owned, 16); + init(); } - private static native long _imaqMatchColor(long image, long info, long roi, long numScores); - /** - * Frequency Domain Analysis functions - */ + protected void setBuffer(ByteBuffer backing, int offset) { + super.setBuffer(backing, offset, 16); + } - public static void imaqAttenuate(Image dest, Image source, AttenuateMode highlow) { - - _imaqAttenuate(dest.getAddress(), source.getAddress(), highlow.getValue()); - + public void read() { + int bestFit_numberOfPoints = backing.getInt(4); + long bestFit_addr = getPointer(backing, 0); + bestFit = new PointDouble[bestFit_numberOfPoints]; + if (bestFit_numberOfPoints > 0 && bestFit_addr != 0) { + ByteBuffer bb = newDirectByteBuffer(bestFit_addr, bestFit_numberOfPoints * 16); + for (int i = 0, off = 0; i < bestFit_numberOfPoints; i++, off += 16) { + bestFit[i] = new PointDouble(bb, off); + bestFit[i].read(); + } + } + int polynomialCoefficients_numberOfCoefficients = backing.getInt(12); + long polynomialCoefficients_addr = getPointer(backing, 8); + polynomialCoefficients = new double[polynomialCoefficients_numberOfCoefficients]; + if (polynomialCoefficients_numberOfCoefficients > 0 && polynomialCoefficients_addr != 0) { + newDirectByteBuffer(polynomialCoefficients_addr, + polynomialCoefficients_numberOfCoefficients * 8).asDoubleBuffer().get( + polynomialCoefficients); + } } - private static native void _imaqAttenuate(long dest, long source, int highlow); - public static void imaqConjugate(Image dest, Image source) { - - _imaqConjugate(dest.getAddress(), source.getAddress()); - + public void write() { + bestFit_buf = ByteBuffer.allocateDirect(bestFit.length * 16).order(ByteOrder.nativeOrder()); + for (int i = 0, off = 0; i < bestFit.length; i++, off += 16) { + bestFit[i].setBuffer(bestFit_buf, off); + bestFit[i].write(); + } + backing.putInt(4, bestFit.length); + putPointer(backing, 0, bestFit_buf); + polynomialCoefficients_buf = + ByteBuffer.allocateDirect(polynomialCoefficients.length * 8).order( + ByteOrder.nativeOrder()); + polynomialCoefficients_buf.asDoubleBuffer().put(polynomialCoefficients).rewind(); + backing.putInt(12, polynomialCoefficients.length); + putPointer(backing, 8, polynomialCoefficients_buf); } - private static native void _imaqConjugate(long dest, long source); - public static void imaqFFT(Image dest, Image source) { - - _imaqFFT(dest.getAddress(), source.getAddress()); - + public int size() { + return 16; } - private static native void _imaqFFT(long dest, long source); + } - public static void imaqFlipFrequencies(Image dest, Image source) { - - _imaqFlipFrequencies(dest.getAddress(), source.getAddress()); - + public static class PartialCircle extends DisposedStruct { + public PointFloat center; // Center of the circle. + public double radius; // Radius of the circle. + public double startAngle; // Start angle of the fitted structure. + public double endAngle; // End angle of the fitted structure. + + private void init() { + center = new PointFloat(backing, 0); } - private static native void _imaqFlipFrequencies(long dest, long source); - public static void imaqInverseFFT(Image dest, Image source) { - - _imaqInverseFFT(dest.getAddress(), source.getAddress()); - + public PartialCircle() { + super(32); + init(); } - private static native void _imaqInverseFFT(long dest, long source); - public static void imaqTruncate(Image dest, Image source, TruncateMode highlow, float ratioToKeep) { - - _imaqTruncate(dest.getAddress(), source.getAddress(), highlow.getValue(), ratioToKeep); - + public PartialCircle(PointFloat center, double radius, double startAngle, double endAngle) { + super(32); + this.center = center; + this.radius = radius; + this.startAngle = startAngle; + this.endAngle = endAngle; } - private static native void _imaqTruncate(long dest, long source, int highlow, float ratioToKeep); - /** - * Barcode I/O functions - */ + protected PartialCircle(ByteBuffer backing, int offset) { + super(backing, offset, 32); + init(); + } - public static AIMGradeReport imaqGradeDataMatrixBarcodeAIM(Image image) { - ByteBuffer rv_buf = ByteBuffer.allocateDirect(8).order(ByteOrder.nativeOrder()); - long rv_addr = getByteBufferAddress(rv_buf); - _imaqGradeDataMatrixBarcodeAIM(image.getAddress(), rv_addr+0); - AIMGradeReport report; - report = new AIMGradeReport(rv_buf, 0); - report.read(); - return report; + protected PartialCircle(long nativeObj, boolean owned) { + super(nativeObj, owned, 32); + init(); } - private static native void _imaqGradeDataMatrixBarcodeAIM(long image, long report); - public static BarcodeInfo imaqReadBarcode(Image image, BarcodeType type, ROI roi, int validate) { - - long jn_rv = _imaqReadBarcode(image.getAddress(), type.getValue(), roi == null ? 0 : roi.getAddress(), validate); - - return new BarcodeInfo(jn_rv, true); + protected void setBuffer(ByteBuffer backing, int offset) { + super.setBuffer(backing, offset, 32); } - private static native long _imaqReadBarcode(long image, int type, long roi, int validate); - public static DataMatrixReport imaqReadDataMatrixBarcode2(Image image, ROI roi, DataMatrixGradingMode prepareForGrading, DataMatrixDescriptionOptions descriptionOptions, DataMatrixSizeOptions sizeOptions, DataMatrixSearchOptions searchOptions) { - - long jn_rv = _imaqReadDataMatrixBarcode2(image.getAddress(), roi.getAddress(), prepareForGrading.getValue(), descriptionOptions.getAddress(), sizeOptions.getAddress(), searchOptions.getAddress()); - - return new DataMatrixReport(jn_rv, true); + public void read() { + center.read(); + radius = backing.getDouble(8); + startAngle = backing.getDouble(16); + endAngle = backing.getDouble(24); } - private static native long _imaqReadDataMatrixBarcode2(long image, long roi, int prepareForGrading, long descriptionOptions, long sizeOptions, long searchOptions); - public static class ReadPDF417BarcodeResult { - public Barcode2DInfo[] array; - private long array_addr; - private ReadPDF417BarcodeResult(ByteBuffer rv_buf, long jn_rv) { - array_addr = jn_rv; - int array_numBarcodes; - array_numBarcodes = rv_buf.getInt(0); - array = new Barcode2DInfo[array_numBarcodes]; - if (array_numBarcodes > 0 && array_addr != 0) { - ByteBuffer bb = newDirectByteBuffer(array_addr, array_numBarcodes*64); - for (int i=0, off=0; i 0 && array_addr != 0) { - ByteBuffer bb = newDirectByteBuffer(array_addr, array_numMatches*40); - for (int i=0, off=0; i 0 && matchSetupData_addr != 0) { + getBytes(newDirectByteBuffer(matchSetupData_addr, matchSetupData_numMatchSetupData), + matchSetupData, 0, matchSetupData_numMatchSetupData); + } } - private static native int _imaqAddPointContour(long roi, long point); - public static int imaqAddRectContour(ROI roi, Rect rect) { - - int jn_rv = _imaqAddRectContour(roi.getAddress(), rect.getAddress()); - - return jn_rv; + public void write() { + matchSetupData_buf = ByteBuffer.allocateDirect(matchSetupData.length); + putBytes(matchSetupData_buf, matchSetupData, 0, matchSetupData.length); + backing.putInt(4, matchSetupData.length); + putPointer(backing, 0, matchSetupData_buf); } - private static native int _imaqAddRectContour(long roi, long rect); - public static int imaqAddRotatedRectContour2(ROI roi, RotatedRect rect) { - - int jn_rv = _imaqAddRotatedRectContour2(roi.getAddress(), rect.getAddress()); - - return jn_rv; + public int size() { + return 8; } - private static native int _imaqAddRotatedRectContour2(long roi, long rect); + } - public static int imaqCopyContour(ROI destRoi, ROI sourceRoi, int id) { - - int jn_rv = _imaqCopyContour(destRoi.getAddress(), sourceRoi.getAddress(), id); - - return jn_rv; - } - private static native int _imaqCopyContour(long destRoi, long sourceRoi, int id); + public static class RangeSettingDouble extends DisposedStruct { + public SettingType settingType; // Match Constraints specifies the match + // option whose values you want to constrain + // by the given range. + public double min; // Min is the minimum value of the range for a given + // Match Constraint. + public double max; // Max is the maximum value of the range for a given + // Match Constraint. - public static int imaqGetContour(ROI roi, int index) { - - int jn_rv = _imaqGetContour(roi.getAddress(), index); - - return jn_rv; - } - private static native int _imaqGetContour(long roi, int index); - - public static RGBValue imaqGetContourColor(ROI roi, int id) { - ByteBuffer rv_buf = ByteBuffer.allocateDirect(8).order(ByteOrder.nativeOrder()); - long rv_addr = getByteBufferAddress(rv_buf); - _imaqGetContourColor(roi.getAddress(), id, rv_addr+0); - RGBValue contourColor; - contourColor = new RGBValue(rv_buf, 0); - contourColor.read(); - return contourColor; - } - private static native void _imaqGetContourColor(long roi, int id, long contourColor); - - public static void imaqGetContourCount(ROI roi) { - - _imaqGetContourCount(roi.getAddress()); - - } - private static native void _imaqGetContourCount(long roi); - - public static ContourInfo2 imaqGetContourInfo2(ROI roi, int id) { - - long jn_rv = _imaqGetContourInfo2(roi.getAddress(), id); - - return new ContourInfo2(jn_rv, true); - } - private static native long _imaqGetContourInfo2(long roi, int id); - - public static void imaqMoveContour(ROI roi, int id, int deltaX, int deltaY) { - - _imaqMoveContour(roi.getAddress(), id, deltaX, deltaY); - - } - private static native void _imaqMoveContour(long roi, int id, int deltaX, int deltaY); - - public static void imaqRemoveContour(ROI roi, int id) { - - _imaqRemoveContour(roi.getAddress(), id); - - } - private static native void _imaqRemoveContour(long roi, int id); - - public static void imaqSetContourColor(ROI roi, int id, RGBValue color) { - - _imaqSetContourColor(roi.getAddress(), id, color.getAddress()); - - } - private static native void _imaqSetContourColor(long roi, int id, long color); - - /** - * Regions of Interest functions - */ - - public static ROI imaqCreateROI() { - - long jn_rv = _imaqCreateROI(); - - return new ROI(jn_rv, true); - } - private static native long _imaqCreateROI(); - - public static Rect imaqGetROIBoundingBox(ROI roi) { - ByteBuffer rv_buf = ByteBuffer.allocateDirect(8).order(ByteOrder.nativeOrder()); - long rv_addr = getByteBufferAddress(rv_buf); - _imaqGetROIBoundingBox(roi.getAddress(), rv_addr+0); - Rect boundingBox; - boundingBox = new Rect(rv_buf, 0); - boundingBox.read(); - return boundingBox; - } - private static native void _imaqGetROIBoundingBox(long roi, long boundingBox); - - public static RGBValue imaqGetROIColor(ROI roi) { - ByteBuffer rv_buf = ByteBuffer.allocateDirect(8).order(ByteOrder.nativeOrder()); - long rv_addr = getByteBufferAddress(rv_buf); - _imaqGetROIColor(roi.getAddress(), rv_addr+0); - RGBValue roiColor; - roiColor = new RGBValue(rv_buf, 0); - roiColor.read(); - return roiColor; - } - private static native void _imaqGetROIColor(long roi, long roiColor); - - public static void imaqSetROIColor(ROI roi, RGBValue color) { - - _imaqSetROIColor(roi.getAddress(), color.getAddress()); - - } - private static native void _imaqSetROIColor(long roi, long color); - - /** - * Image Analysis functions - */ - - public static PointFloat imaqCentroid(Image image, Image mask) { - ByteBuffer rv_buf = ByteBuffer.allocateDirect(8).order(ByteOrder.nativeOrder()); - long rv_addr = getByteBufferAddress(rv_buf); - _imaqCentroid(image.getAddress(), rv_addr+0, mask.getAddress()); - PointFloat centroid; - centroid = new PointFloat(rv_buf, 0); - centroid.read(); - return centroid; - } - private static native void _imaqCentroid(long image, long centroid, long mask); - - public static class ExtractCurvesResult { - public Curve[] array; - private long array_addr; - private ExtractCurvesResult(ByteBuffer rv_buf, long jn_rv) { - array_addr = jn_rv; - int array_numCurves; - array_numCurves = rv_buf.getInt(0); - array = new Curve[array_numCurves]; - if (array_numCurves > 0 && array_addr != 0) { - ByteBuffer bb = newDirectByteBuffer(array_addr, array_numCurves*48); - for (int i=0, off=0; i 0 && array_addr != 0) { - ByteBuffer bb = newDirectByteBuffer(array_addr, array_numMatchesReturned*24); - for (int i=0, off=0; i 0 && array_addr != 0) { - ByteBuffer bb = newDirectByteBuffer(array_addr, array_numMatchesReturned*40); - for (int i=0, off=0; i 0 && array_addr != 0) { - ByteBuffer bb = newDirectByteBuffer(array_addr, array_numMatchesReturned*40); - for (int i=0, off=0; i 0 && array_addr != 0) { - ByteBuffer bb = newDirectByteBuffer(array_addr, array_numMatchesReturned*64); - for (int i=0, off=0; i 0 && array_addr != 0) { - ByteBuffer bb = newDirectByteBuffer(array_addr, array_numFeatures*16); - for (int i=0, off=0; i 0 && array_addr != 0) { - ByteBuffer bb = newDirectByteBuffer(array_addr, array_numFeatures*16); - for (int i=0, off=0; i 0 && array_addr != 0) { - ByteBuffer bb = newDirectByteBuffer(array_addr, array_numMatches*52); - for (int i=0, off=0; i 0 && array_addr != 0) { - ByteBuffer bb = newDirectByteBuffer(array_addr, array_numMatches*380); - for (int i=0, off=0; i 0 && array_addr != 0) { - ByteBuffer bb = newDirectByteBuffer(array_addr, array_numMatches*380); - for (int i=0, off=0; i 0 && pointsPixel_addr != 0) { + ByteBuffer bb = newDirectByteBuffer(pointsPixel_addr, pointsPixel_numPointsPixel * 16); + for (int i = 0, off = 0; i < pointsPixel_numPointsPixel; i++, off += 16) { + pointsPixel[i] = new PointDouble(bb, off); + pointsPixel[i].read(); } - ByteBuffer description_buf = ByteBuffer.allocateDirect(256).order(ByteOrder.nativeOrder()); - if (description != null) { - byte[] bytes; - try { - bytes = description.getBytes("UTF-8"); - } catch (UnsupportedEncodingException e) { - bytes = new byte[0]; - } - putBytes(description_buf, bytes, 0, bytes.length); - for (int i=bytes.length; i<256; i++) - description_buf.put(i, (byte)0); // fill with zero - } - long jn_rv = _imaqReadMultipleGeometricPatternFile(fileName == null ? 0 : getByteBufferAddress(fileName_buf), description == null ? 0 : getByteBufferAddress(description_buf)); - - return new MultipleGeometricPattern(jn_rv, true); - } - private static native long _imaqReadMultipleGeometricPatternFile(long fileName, long description); - - public static class RefineMatchesResult { - public MatchPatternOptions options; - public MatchPatternAdvancedOptions advancedOptions; - public PatternMatch[] array; - private long array_addr; - private RefineMatchesResult(ByteBuffer rv_buf, long jn_rv) { - array_addr = jn_rv; - options = new MatchPatternOptions(rv_buf, 0); - options.read(); - advancedOptions = new MatchPatternAdvancedOptions(rv_buf, 8); - advancedOptions.read(); - int array_numCandidatesOut; - array_numCandidatesOut = rv_buf.getInt(16); - array = new PatternMatch[array_numCandidatesOut]; - if (array_numCandidatesOut > 0 && array_addr != 0) { - ByteBuffer bb = newDirectByteBuffer(array_addr, array_numCandidatesOut*52); - for (int i=0, off=0; i 0 && pointsReal_addr != 0) { + ByteBuffer bb = newDirectByteBuffer(pointsReal_addr, pointsReal_numPointsReal * 16); + for (int i = 0, off = 0; i < pointsReal_numPointsReal; i++, off += 16) { + pointsReal[i] = new PointDouble(bb, off); + pointsReal[i].read(); } - - @Override - protected void finalize() throws Throwable { - imaqDispose(array_addr); - super.finalize(); + } + int curvaturePixel_numCurvaturePixel = backing.getInt(20); + long curvaturePixel_addr = getPointer(backing, 16); + curvaturePixel = new double[curvaturePixel_numCurvaturePixel]; + if (curvaturePixel_numCurvaturePixel > 0 && curvaturePixel_addr != 0) { + newDirectByteBuffer(curvaturePixel_addr, curvaturePixel_numCurvaturePixel * 8) + .asDoubleBuffer().get(curvaturePixel); + } + int curvatureReal_numCurvatureReal = backing.getInt(28); + long curvatureReal_addr = getPointer(backing, 24); + curvatureReal = new double[curvatureReal_numCurvatureReal]; + if (curvatureReal_numCurvatureReal > 0 && curvatureReal_addr != 0) { + newDirectByteBuffer(curvatureReal_addr, curvatureReal_numCurvatureReal * 8) + .asDoubleBuffer().get(curvatureReal); + } + length = backing.getDouble(32); + lengthReal = backing.getDouble(40); + hasEquation = backing.getInt(48); + } + + public void write() { + pointsPixel_buf = + ByteBuffer.allocateDirect(pointsPixel.length * 16).order(ByteOrder.nativeOrder()); + for (int i = 0, off = 0; i < pointsPixel.length; i++, off += 16) { + pointsPixel[i].setBuffer(pointsPixel_buf, off); + pointsPixel[i].write(); + } + backing.putInt(4, pointsPixel.length); + putPointer(backing, 0, pointsPixel_buf); + pointsReal_buf = + ByteBuffer.allocateDirect(pointsReal.length * 16).order(ByteOrder.nativeOrder()); + for (int i = 0, off = 0; i < pointsReal.length; i++, off += 16) { + pointsReal[i].setBuffer(pointsReal_buf, off); + pointsReal[i].write(); + } + backing.putInt(12, pointsReal.length); + putPointer(backing, 8, pointsReal_buf); + curvaturePixel_buf = + ByteBuffer.allocateDirect(curvaturePixel.length * 8).order(ByteOrder.nativeOrder()); + curvaturePixel_buf.asDoubleBuffer().put(curvaturePixel).rewind(); + backing.putInt(20, curvaturePixel.length); + putPointer(backing, 16, curvaturePixel_buf); + curvatureReal_buf = + ByteBuffer.allocateDirect(curvatureReal.length * 8).order(ByteOrder.nativeOrder()); + curvatureReal_buf.asDoubleBuffer().put(curvatureReal).rewind(); + backing.putInt(28, curvatureReal.length); + putPointer(backing, 24, curvatureReal_buf); + backing.putDouble(32, length); + backing.putDouble(40, lengthReal); + backing.putInt(48, hasEquation); + } + + public int size() { + return 56; + } + } + + public static class ROILabel extends DisposedStruct { + public String className; // Specifies the classname you want to segment. + public int label; // Label is the label number associated with the Class + // Name. + private ByteBuffer className_buf; + + private void init() { + + } + + public ROILabel() { + super(8); + init(); + } + + public ROILabel(String className, int label) { + super(8); + this.className = className; + this.label = label; + } + + protected ROILabel(ByteBuffer backing, int offset) { + super(backing, offset, 8); + init(); + } + + protected ROILabel(long nativeObj, boolean owned) { + super(nativeObj, owned, 8); + init(); + } + + protected void setBuffer(ByteBuffer backing, int offset) { + super.setBuffer(backing, offset, 8); + } + + public void read() { + long className_addr = getPointer(backing, 0); + if (className_addr == 0) + className = null; + else { + ByteBuffer bb = newDirectByteBuffer(className_addr, 1000); // FIXME + while (bb.get() != 0) { } + byte[] bytes = new byte[bb.position() - 1]; + getBytes(bb, bytes, 0, bytes.length); + try { + className = new String(bytes, "UTF-8"); + } catch (UnsupportedEncodingException e) { + className = ""; + } + } + + label = backing.getInt(4); } - public static RefineMatchesResult imaqRefineMatches(Image image, Image pattern, PatternMatch[] candidatesIn) { - int numCandidatesIn = candidatesIn.length; - ByteBuffer candidatesIn_buf = null; - candidatesIn_buf = ByteBuffer.allocateDirect(candidatesIn.length*52).order(ByteOrder.nativeOrder()); - for (int i=0, off=0; i 0 && array_addr != 0) { - ByteBuffer bb = newDirectByteBuffer(array_addr, array_numMatches*116); - for (int i=0, off=0; i 0 && array_addr != 0) { - ByteBuffer bb = newDirectByteBuffer(array_addr, array_numMatches*52); - for (int i=0, off=0; i 0 && labelOut_addr != 0) { + ByteBuffer bb = newDirectByteBuffer(labelOut_addr, labelOut_numLabelOut * 8); + for (int i = 0, off = 0; i < labelOut_numLabelOut; i++, off += 8) { + labelOut[i] = new ROILabel(bb, off); + labelOut[i].read(); } - _imaqClearOverlay(image.getAddress(), group == null ? 0 : getByteBufferAddress(group_buf)); - + } } - private static native void _imaqClearOverlay(long image, long group); - public static void imaqCopyOverlay(Image dest, Image source, String group) { - ByteBuffer group_buf = null; - if (group != null) { - byte[] group_bytes; - try { - group_bytes = group.getBytes("UTF-8"); - } catch (UnsupportedEncodingException e) { - group_bytes = new byte[0]; - } - group_buf = ByteBuffer.allocateDirect(group_bytes.length+1); - putBytes(group_buf, group_bytes, 0, group_bytes.length).put(group_bytes.length, (byte)0); - } - _imaqCopyOverlay(dest.getAddress(), source.getAddress(), group == null ? 0 : getByteBufferAddress(group_buf)); - + public void write() { + labelOut_buf = ByteBuffer.allocateDirect(labelOut.length * 8).order(ByteOrder.nativeOrder()); + for (int i = 0, off = 0; i < labelOut.length; i++, off += 8) { + labelOut[i].setBuffer(labelOut_buf, off); + labelOut[i].write(); + } + backing.putInt(4, labelOut.length); + putPointer(backing, 0, labelOut_buf); } - private static native void _imaqCopyOverlay(long dest, long source, long group); - public static TransformBehaviors imaqGetOverlayProperties(Image image, String group) { - ByteBuffer group_buf = null; - if (group != null) { - byte[] group_bytes; - try { - group_bytes = group.getBytes("UTF-8"); - } catch (UnsupportedEncodingException e) { - group_bytes = new byte[0]; - } - group_buf = ByteBuffer.allocateDirect(group_bytes.length+1); - putBytes(group_buf, group_bytes, 0, group_bytes.length).put(group_bytes.length, (byte)0); - } - ByteBuffer rv_buf = ByteBuffer.allocateDirect(8).order(ByteOrder.nativeOrder()); - long rv_addr = getByteBufferAddress(rv_buf); - _imaqGetOverlayProperties(image.getAddress(), group == null ? 0 : getByteBufferAddress(group_buf), rv_addr+0); - TransformBehaviors transformBehaviors; - transformBehaviors = new TransformBehaviors(rv_buf, 0); - transformBehaviors.read(); - return transformBehaviors; - } - private static native void _imaqGetOverlayProperties(long image, long group, long transformBehaviors); - - public static void imaqMergeOverlay(Image dest, Image source, RGBValue[] palette, String group) { - int numColors = palette.length; - ByteBuffer palette_buf = null; - palette_buf = ByteBuffer.allocateDirect(palette.length*4).order(ByteOrder.nativeOrder()); - for (int i=0, off=0; i 0 && roiArray_addr != 0) { + ByteBuffer bb = newDirectByteBuffer(roiArray_addr, roiArray_numOfROIs * 4); + for (int i = 0, off = 0; i < roiArray_numOfROIs; i++, off += 4) { + roiArray[i] = new ROI(getPointer(bb, off), false); } - _imaqOverlayROI(image.getAddress(), roi.getAddress(), symbol.getValue(), userSymbol.getAddress(), group == null ? 0 : getByteBufferAddress(group_buf)); - + } + int labelsOutArray_numOfLabels = backing.getInt(12); + long labelsOutArray_addr = getPointer(backing, 8); + labelsOutArray = new int[labelsOutArray_numOfLabels]; + if (labelsOutArray_numOfLabels > 0 && labelsOutArray_addr != 0) { + newDirectByteBuffer(labelsOutArray_addr, labelsOutArray_numOfLabels * 4).asIntBuffer().get( + labelsOutArray); + } + int isTooManyVectorsArray_isTooManyVectorsArraySize = backing.getInt(20); + long isTooManyVectorsArray_addr = getPointer(backing, 16); + isTooManyVectorsArray = new int[isTooManyVectorsArray_isTooManyVectorsArraySize]; + if (isTooManyVectorsArray_isTooManyVectorsArraySize > 0 && isTooManyVectorsArray_addr != 0) { + newDirectByteBuffer(isTooManyVectorsArray_addr, + isTooManyVectorsArray_isTooManyVectorsArraySize * 4).asIntBuffer().get( + isTooManyVectorsArray); + } + } + + public void write() { + roiArray_buf = ByteBuffer.allocateDirect(roiArray.length * 4).order(ByteOrder.nativeOrder()); + for (int i = 0, off = 0; i < roiArray.length; i++, off += 4) { + putPointer(roiArray_buf, off, roiArray[i]); + } + backing.putInt(4, roiArray.length); + putPointer(backing, 0, roiArray_buf); + labelsOutArray_buf = + ByteBuffer.allocateDirect(labelsOutArray.length * 4).order(ByteOrder.nativeOrder()); + labelsOutArray_buf.asIntBuffer().put(labelsOutArray).rewind(); + backing.putInt(12, labelsOutArray.length); + putPointer(backing, 8, labelsOutArray_buf); + isTooManyVectorsArray_buf = + ByteBuffer.allocateDirect(isTooManyVectorsArray.length * 4) + .order(ByteOrder.nativeOrder()); + isTooManyVectorsArray_buf.asIntBuffer().put(isTooManyVectorsArray).rewind(); + backing.putInt(20, isTooManyVectorsArray.length); + putPointer(backing, 16, isTooManyVectorsArray_buf); + } + + public int size() { + return 24; + } + } + + public static class ColorSegmenationOptions extends DisposedStruct { + public int windowX; // X is the window size in x direction. + public int windowY; // Y is the window size in y direction. + public int stepSize; // Step Size is the distance between two windows. + public int minParticleArea; // Min Particle Area is the minimum number of + // allowed pixels. + public int maxParticleArea; // Max Particle Area is the maximum number of + // allowed pixels. + public short isFineSegment; // When enabled, the step processes the boundary + // pixels of each segmentation cluster using a + // step size of 1. + + private void init() { + + } + + public ColorSegmenationOptions() { + super(24); + init(); + } + + public ColorSegmenationOptions(int windowX, int windowY, int stepSize, int minParticleArea, + int maxParticleArea, int isFineSegment) { + super(24); + this.windowX = windowX; + this.windowY = windowY; + this.stepSize = stepSize; + this.minParticleArea = minParticleArea; + this.maxParticleArea = maxParticleArea; + this.isFineSegment = (short) isFineSegment; + } + + protected ColorSegmenationOptions(ByteBuffer backing, int offset) { + super(backing, offset, 24); + init(); + } + + protected ColorSegmenationOptions(long nativeObj, boolean owned) { + super(nativeObj, owned, 24); + init(); + } + + protected void setBuffer(ByteBuffer backing, int offset) { + super.setBuffer(backing, offset, 24); + } + + public void read() { + windowX = backing.getInt(0); + windowY = backing.getInt(4); + stepSize = backing.getInt(8); + minParticleArea = backing.getInt(12); + maxParticleArea = backing.getInt(16); + isFineSegment = backing.getShort(20); + } + + public void write() { + backing.putInt(0, windowX); + backing.putInt(4, windowY); + backing.putInt(8, stepSize); + backing.putInt(12, minParticleArea); + backing.putInt(16, maxParticleArea); + backing.putShort(20, isFineSegment); + } + + public int size() { + return 24; + } + } + + public static class ClassifiedCurve extends DisposedStruct { + public double length; // Specifies the length, in pixels, of the curves + // within the curvature range. + public double lengthReal; // specifies the length, in calibrated units, of + // the curves within the curvature range. + public double maxCurvature; // specifies the maximum curvature, in pixels, + // for the selected curvature range. + public double maxCurvatureReal; // specifies the maximum curvature, in + // calibrated units, for the selected + // curvature range. + public int label; // specifies the class to which the the sample belongs. + public PointDouble[] curvePoints; // Curve Points is a point-coordinate + // cluster that defines the points of the + // curve. + private ByteBuffer curvePoints_buf; + + private void init() { + curvePoints = new PointDouble[0]; } - private static native void _imaqOverlayROI(long image, long roi, int symbol, long userSymbol, long group); - public static void imaqOverlayText(Image image, Point origin, String text, RGBValue color, OverlayTextOptions options, String group) { - ByteBuffer text_buf = null; - if (text != null) { - byte[] text_bytes; - try { - text_bytes = text.getBytes("UTF-8"); - } catch (UnsupportedEncodingException e) { - text_bytes = new byte[0]; - } - text_buf = ByteBuffer.allocateDirect(text_bytes.length+1); - putBytes(text_buf, text_bytes, 0, text_bytes.length).put(text_bytes.length, (byte)0); - } - ByteBuffer group_buf = null; - if (group != null) { - byte[] group_bytes; - try { - group_bytes = group.getBytes("UTF-8"); - } catch (UnsupportedEncodingException e) { - group_bytes = new byte[0]; - } - group_buf = ByteBuffer.allocateDirect(group_bytes.length+1); - putBytes(group_buf, group_bytes, 0, group_bytes.length).put(group_bytes.length, (byte)0); - } - _imaqOverlayText(image.getAddress(), origin.getAddress(), text == null ? 0 : getByteBufferAddress(text_buf), color.getAddress(), options.getAddress(), group == null ? 0 : getByteBufferAddress(group_buf)); - + public ClassifiedCurve() { + super(48); + init(); } - private static native void _imaqOverlayText(long image, long origin, long text, long color, long options, long group); - public static TransformBehaviors imaqSetOverlayProperties(Image image, String group) { - ByteBuffer group_buf = null; - if (group != null) { - byte[] group_bytes; - try { - group_bytes = group.getBytes("UTF-8"); - } catch (UnsupportedEncodingException e) { - group_bytes = new byte[0]; - } - group_buf = ByteBuffer.allocateDirect(group_bytes.length+1); - putBytes(group_buf, group_bytes, 0, group_bytes.length).put(group_bytes.length, (byte)0); - } - ByteBuffer rv_buf = ByteBuffer.allocateDirect(8).order(ByteOrder.nativeOrder()); - long rv_addr = getByteBufferAddress(rv_buf); - _imaqSetOverlayProperties(image.getAddress(), group == null ? 0 : getByteBufferAddress(group_buf), rv_addr+0); - TransformBehaviors transformBehaviors; - transformBehaviors = new TransformBehaviors(rv_buf, 0); - transformBehaviors.read(); - return transformBehaviors; - } - private static native void _imaqSetOverlayProperties(long image, long group, long transformBehaviors); - - /** - * OCR functions - */ - - public static CharSet imaqCreateCharSet() { - - long jn_rv = _imaqCreateCharSet(); - - return new CharSet(jn_rv, true); - } - private static native long _imaqCreateCharSet(); - - public static void imaqDeleteChar(CharSet set, int index) { - - _imaqDeleteChar(set.getAddress(), index); - - } - private static native void _imaqDeleteChar(long set, int index); - - public static void imaqGetCharCount(CharSet set) { - - _imaqGetCharCount(set.getAddress()); - - } - private static native void _imaqGetCharCount(long set); - - public static CharInfo2 imaqGetCharInfo2(CharSet set, int index) { - - long jn_rv = _imaqGetCharInfo2(set.getAddress(), index); - - return new CharInfo2(jn_rv, true); - } - private static native long _imaqGetCharInfo2(long set, int index); - - public static class ReadOCRFileResult { - public ReadTextOptions readOptions; - public OCRProcessingOptions processingOptions; - public OCRSpacingOptions spacingOptions; - private ReadOCRFileResult(ByteBuffer rv_buf) { - readOptions = new ReadTextOptions(rv_buf, 0); - readOptions.read(); - processingOptions = new OCRProcessingOptions(rv_buf, 8); - processingOptions.read(); - spacingOptions = new OCRSpacingOptions(rv_buf, 16); - spacingOptions.read(); - } - } - - public static ReadOCRFileResult imaqReadOCRFile(String fileName, CharSet set, String setDescription) { - ByteBuffer fileName_buf = null; - if (fileName != null) { - byte[] fileName_bytes; - try { - fileName_bytes = fileName.getBytes("UTF-8"); - } catch (UnsupportedEncodingException e) { - fileName_bytes = new byte[0]; - } - fileName_buf = ByteBuffer.allocateDirect(fileName_bytes.length+1); - putBytes(fileName_buf, fileName_bytes, 0, fileName_bytes.length).put(fileName_bytes.length, (byte)0); - } - ByteBuffer setDescription_buf = ByteBuffer.allocateDirect(256).order(ByteOrder.nativeOrder()); - if (setDescription != null) { - byte[] bytes; - try { - bytes = setDescription.getBytes("UTF-8"); - } catch (UnsupportedEncodingException e) { - bytes = new byte[0]; - } - putBytes(setDescription_buf, bytes, 0, bytes.length); - for (int i=bytes.length; i<256; i++) - setDescription_buf.put(i, (byte)0); // fill with zero - } - ByteBuffer rv_buf = ByteBuffer.allocateDirect(8+8+8).order(ByteOrder.nativeOrder()); - long rv_addr = getByteBufferAddress(rv_buf); - _imaqReadOCRFile(fileName == null ? 0 : getByteBufferAddress(fileName_buf), set.getAddress(), setDescription == null ? 0 : getByteBufferAddress(setDescription_buf), rv_addr+0, rv_addr+8, rv_addr+16); - ReadOCRFileResult rv = new ReadOCRFileResult(rv_buf); - return rv; - } - private static native void _imaqReadOCRFile(long fileName, long set, long setDescription, long readOptions, long processingOptions, long spacingOptions); - - public static ReadTextReport3 imaqReadText3(Image image, CharSet set, ROI roi, ReadTextOptions readOptions, OCRProcessingOptions processingOptions, OCRSpacingOptions spacingOptions) { - - long jn_rv = _imaqReadText3(image.getAddress(), set.getAddress(), roi.getAddress(), readOptions.getAddress(), processingOptions.getAddress(), spacingOptions.getAddress()); - - return new ReadTextReport3(jn_rv, true); - } - private static native long _imaqReadText3(long image, long set, long roi, long readOptions, long processingOptions, long spacingOptions); - - public static void imaqRenameChar(CharSet set, int index, String newCharValue) { - ByteBuffer newCharValue_buf = null; - if (newCharValue != null) { - byte[] newCharValue_bytes; - try { - newCharValue_bytes = newCharValue.getBytes("UTF-8"); - } catch (UnsupportedEncodingException e) { - newCharValue_bytes = new byte[0]; - } - newCharValue_buf = ByteBuffer.allocateDirect(newCharValue_bytes.length+1); - putBytes(newCharValue_buf, newCharValue_bytes, 0, newCharValue_bytes.length).put(newCharValue_bytes.length, (byte)0); - } - _imaqRenameChar(set.getAddress(), index, newCharValue == null ? 0 : getByteBufferAddress(newCharValue_buf)); - + public ClassifiedCurve(double length, double lengthReal, double maxCurvature, + double maxCurvatureReal, int label, PointDouble[] curvePoints) { + super(48); + this.length = length; + this.lengthReal = lengthReal; + this.maxCurvature = maxCurvature; + this.maxCurvatureReal = maxCurvatureReal; + this.label = label; + this.curvePoints = curvePoints; } - private static native void _imaqRenameChar(long set, int index, long newCharValue); - public static void imaqSetReferenceChar(CharSet set, int index, int isReferenceChar) { - - _imaqSetReferenceChar(set.getAddress(), index, isReferenceChar); - + protected ClassifiedCurve(ByteBuffer backing, int offset) { + super(backing, offset, 48); + init(); } - private static native void _imaqSetReferenceChar(long set, int index, int isReferenceChar); - public static void imaqTrainChars(Image image, CharSet set, int index, String charValue, ROI roi, OCRProcessingOptions processingOptions, OCRSpacingOptions spacingOptions) { - ByteBuffer charValue_buf = null; - if (charValue != null) { - byte[] charValue_bytes; - try { - charValue_bytes = charValue.getBytes("UTF-8"); - } catch (UnsupportedEncodingException e) { - charValue_bytes = new byte[0]; - } - charValue_buf = ByteBuffer.allocateDirect(charValue_bytes.length+1); - putBytes(charValue_buf, charValue_bytes, 0, charValue_bytes.length).put(charValue_bytes.length, (byte)0); - } - _imaqTrainChars(image.getAddress(), set.getAddress(), index, charValue == null ? 0 : getByteBufferAddress(charValue_buf), roi.getAddress(), processingOptions.getAddress(), spacingOptions.getAddress()); - - } - private static native void _imaqTrainChars(long image, long set, int index, long charValue, long roi, long processingOptions, long spacingOptions); - - public static class VerifyTextResult { - public int[] array; - private long array_addr; - private VerifyTextResult(ByteBuffer rv_buf, long jn_rv) { - array_addr = jn_rv; - int array_numScores; - array_numScores = rv_buf.getInt(0); - array = new int[array_numScores]; - if (array_numScores > 0 && array_addr != 0) { - newDirectByteBuffer(array_addr, array_numScores*4).asIntBuffer().get(array); - } - } + protected ClassifiedCurve(long nativeObj, boolean owned) { + super(nativeObj, owned, 48); + init(); + } - @Override - protected void finalize() throws Throwable { - imaqDispose(array_addr); - super.finalize(); - } + protected void setBuffer(ByteBuffer backing, int offset) { + super.setBuffer(backing, offset, 48); } - public static VerifyTextResult imaqVerifyText(Image image, CharSet set, String expectedString, ROI roi) { - ByteBuffer expectedString_buf = null; - if (expectedString != null) { - byte[] expectedString_bytes; - try { - expectedString_bytes = expectedString.getBytes("UTF-8"); - } catch (UnsupportedEncodingException e) { - expectedString_bytes = new byte[0]; - } - expectedString_buf = ByteBuffer.allocateDirect(expectedString_bytes.length+1); - putBytes(expectedString_buf, expectedString_bytes, 0, expectedString_bytes.length).put(expectedString_bytes.length, (byte)0); + public void read() { + length = backing.getDouble(0); + lengthReal = backing.getDouble(8); + maxCurvature = backing.getDouble(16); + maxCurvatureReal = backing.getDouble(24); + label = backing.getInt(32); + int curvePoints_numCurvePoints = backing.getInt(40); + long curvePoints_addr = getPointer(backing, 36); + curvePoints = new PointDouble[curvePoints_numCurvePoints]; + if (curvePoints_numCurvePoints > 0 && curvePoints_addr != 0) { + ByteBuffer bb = newDirectByteBuffer(curvePoints_addr, curvePoints_numCurvePoints * 16); + for (int i = 0, off = 0; i < curvePoints_numCurvePoints; i++, off += 16) { + curvePoints[i] = new PointDouble(bb, off); + curvePoints[i].read(); } - ByteBuffer rv_buf = ByteBuffer.allocateDirect(8).order(ByteOrder.nativeOrder()); - long rv_addr = getByteBufferAddress(rv_buf); - long jn_rv = _imaqVerifyText(image.getAddress(), set.getAddress(), expectedString == null ? 0 : getByteBufferAddress(expectedString_buf), roi.getAddress(), rv_addr+0); - VerifyTextResult rv = new VerifyTextResult(rv_buf, jn_rv); - return rv; + } } - private static native long _imaqVerifyText(long image, long set, long expectedString, long roi, long numScores); - public static void imaqWriteOCRFile(String fileName, CharSet set, String setDescription, ReadTextOptions readOptions, OCRProcessingOptions processingOptions, OCRSpacingOptions spacingOptions) { - ByteBuffer fileName_buf = null; - if (fileName != null) { - byte[] fileName_bytes; - try { - fileName_bytes = fileName.getBytes("UTF-8"); - } catch (UnsupportedEncodingException e) { - fileName_bytes = new byte[0]; - } - fileName_buf = ByteBuffer.allocateDirect(fileName_bytes.length+1); - putBytes(fileName_buf, fileName_bytes, 0, fileName_bytes.length).put(fileName_bytes.length, (byte)0); - } - ByteBuffer setDescription_buf = null; - if (setDescription != null) { - byte[] setDescription_bytes; - try { - setDescription_bytes = setDescription.getBytes("UTF-8"); - } catch (UnsupportedEncodingException e) { - setDescription_bytes = new byte[0]; - } - setDescription_buf = ByteBuffer.allocateDirect(setDescription_bytes.length+1); - putBytes(setDescription_buf, setDescription_bytes, 0, setDescription_bytes.length).put(setDescription_bytes.length, (byte)0); - } - _imaqWriteOCRFile(fileName == null ? 0 : getByteBufferAddress(fileName_buf), set.getAddress(), setDescription == null ? 0 : getByteBufferAddress(setDescription_buf), readOptions.getAddress(), processingOptions.getAddress(), spacingOptions.getAddress()); - + public void write() { + backing.putDouble(0, length); + backing.putDouble(8, lengthReal); + backing.putDouble(16, maxCurvature); + backing.putDouble(24, maxCurvatureReal); + backing.putInt(32, label); + curvePoints_buf = + ByteBuffer.allocateDirect(curvePoints.length * 16).order(ByteOrder.nativeOrder()); + for (int i = 0, off = 0; i < curvePoints.length; i++, off += 16) { + curvePoints[i].setBuffer(curvePoints_buf, off); + curvePoints[i].write(); + } + backing.putInt(40, curvePoints.length); + putPointer(backing, 36, curvePoints_buf); + } + + public int size() { + return 48; } - private static native void _imaqWriteOCRFile(long fileName, long set, long setDescription, long readOptions, long processingOptions, long spacingOptions); + } - /** - * Geometric Matching functions - */ + public static class RangeDouble extends DisposedStruct { + public double minValue; // The minimum value of the range. + public double maxValue; // The maximum value of the range. + + private void init() { - public static class ExtractContourResult { - public CurveParameters curveParams; - public ExtractContourReport val; - private ExtractContourResult(ByteBuffer rv_buf) { - curveParams = new CurveParameters(rv_buf, 0); - curveParams.read(); - } } - public static ExtractContourResult imaqExtractContour(Image image, ROI roi, ExtractContourDirection direction, ConnectionConstraint connectionConstraintParams, int numOfConstraints, ExtractContourSelection selection, Image contourImage) { - ByteBuffer rv_buf = ByteBuffer.allocateDirect(8).order(ByteOrder.nativeOrder()); - long rv_addr = getByteBufferAddress(rv_buf); - long jn_rv = _imaqExtractContour(image.getAddress(), roi.getAddress(), direction.getValue(), rv_addr+0, connectionConstraintParams.getAddress(), numOfConstraints, selection.getValue(), contourImage.getAddress()); - ExtractContourResult rv = new ExtractContourResult(rv_buf); - rv.val = new ExtractContourReport(jn_rv, true); - return rv; + public RangeDouble() { + super(16); + init(); } - private static native long _imaqExtractContour(long image, long roi, int direction, long curveParams, long connectionConstraintParams, int numOfConstraints, int selection, long contourImage); - public static void imaqContourOverlay(Image image, Image contourImage, ContourOverlaySettings pointsSettings, ContourOverlaySettings eqnSettings, String groupName) { - ByteBuffer groupName_buf = null; - if (groupName != null) { - byte[] groupName_bytes; - try { - groupName_bytes = groupName.getBytes("UTF-8"); - } catch (UnsupportedEncodingException e) { - groupName_bytes = new byte[0]; - } - groupName_buf = ByteBuffer.allocateDirect(groupName_bytes.length+1); - putBytes(groupName_buf, groupName_bytes, 0, groupName_bytes.length).put(groupName_bytes.length, (byte)0); - } - _imaqContourOverlay(image.getAddress(), contourImage.getAddress(), pointsSettings.getAddress(), eqnSettings.getAddress(), groupName == null ? 0 : getByteBufferAddress(groupName_buf)); - - } - private static native void _imaqContourOverlay(long image, long contourImage, long pointsSettings, long eqnSettings, long groupName); - - public static ContourComputeCurvatureReport imaqContourComputeCurvature(Image contourImage, int kernel) { - - long jn_rv = _imaqContourComputeCurvature(contourImage.getAddress(), kernel); - - return new ContourComputeCurvatureReport(jn_rv, true); - } - private static native long _imaqContourComputeCurvature(long contourImage, int kernel); - - public static CurvatureAnalysisReport imaqContourClassifyCurvature(Image contourImage, int kernel, RangeLabel[] curvatureClasses) { - int numCurvatureClasses = curvatureClasses.length; - ByteBuffer curvatureClasses_buf = null; - curvatureClasses_buf = ByteBuffer.allocateDirect(curvatureClasses.length*24).order(ByteOrder.nativeOrder()); - for (int i=0, off=0; i 0 && array_addr != 0) { - ByteBuffer bb = newDirectByteBuffer(array_addr, array_numMatches*52); - for (int i=0, off=0; i 0 && curves_addr != 0) { + ByteBuffer bb = newDirectByteBuffer(curves_addr, curves_numCurves * 48); + for (int i = 0, off = 0; i < curves_numCurves; i++, off += 48) { + curves[i] = new ClassifiedCurve(bb, off); + curves[i].read(); } + } } - /** - * Controller Destination Mode Enumeration - */ + public void write() { + curves_buf = ByteBuffer.allocateDirect(curves.length * 48).order(ByteOrder.nativeOrder()); + for (int i = 0, off = 0; i < curves.length; i++, off += 48) { + curves[i].setBuffer(curves_buf, off); + curves[i].write(); + } + backing.putInt(4, curves.length); + putPointer(backing, 0, curves_buf); + } - public static enum IMAQdxDestinationMode { - DestinationModeUnicast(0), - DestinationModeBroadcast(1), - DestinationModeMulticast(2), - DestinationModeGuard(0xFFFFFFFF), - ; - private final int value; - private IMAQdxDestinationMode(int value) { - this.value = value; - } - public static IMAQdxDestinationMode fromValue(int val) { - for (IMAQdxDestinationMode v : values()) { - if (v.value == val) - return v; - } - return null; - } - public int getValue() { - return value; - } - } - - /** - * Attribute Type Enumeration - */ - - public static enum IMAQdxAttributeType { - AttributeTypeU32(0), - AttributeTypeI64(1), - AttributeTypeF64(2), - AttributeTypeString(3), - AttributeTypeEnum(4), - AttributeTypeBool(5), - AttributeTypeCommand(6), - AttributeTypeBlob(7), - AttributeTypeGuard(0xFFFFFFFF), - ; - private final int value; - private IMAQdxAttributeType(int value) { - this.value = value; - } - public static IMAQdxAttributeType fromValue(int val) { - for (IMAQdxAttributeType v : values()) { - if (v.value == val) - return v; - } - return null; - } - public int getValue() { - return value; - } - } - - /** - * Value Type Enumeration - */ - - public static enum IMAQdxValueType { - ValueTypeU32(0), - ValueTypeI64(1), - ValueTypeF64(2), - ValueTypeString(3), - ValueTypeEnumItem(4), - ValueTypeBool(5), - ValueTypeDisposableString(6), - ValueTypeGuard(0xFFFFFFFF), - ; - private final int value; - private IMAQdxValueType(int value) { - this.value = value; - } - public static IMAQdxValueType fromValue(int val) { - for (IMAQdxValueType v : values()) { - if (v.value == val) - return v; - } - return null; - } - public int getValue() { - return value; - } + public int size() { + return 8; } + } - /** - * Interface File Flags Enumeration - */ + public static class Disparity extends DisposedStruct { + public PointDouble current; // Current is a array of points that defines the + // target contour. + public PointDouble reference; // reference is a array of points that defines + // the template contour. + public double distance; // Specifies the distance, in pixels, between the + // template contour point and the target contour + // point. - public static enum IMAQdxInterfaceFileFlags { - InterfaceFileFlagsConnected(0x1), - InterfaceFileFlagsDirty(0x2), - InterfaceFileFlagsGuard(0xFFFFFFFF), - ; - private final int value; - private IMAQdxInterfaceFileFlags(int value) { - this.value = value; - } - public static IMAQdxInterfaceFileFlags fromValue(int val) { - for (IMAQdxInterfaceFileFlags v : values()) { - if (v.value == val) - return v; - } - return null; - } - public int getValue() { - return value; - } + private void init() { + current = new PointDouble(backing, 0); + reference = new PointDouble(backing, 16); } - /** - * Overwrite Mode Enumeration - */ + public Disparity() { + super(40); + init(); + } - public static enum IMAQdxOverwriteMode { - OverwriteModeGetOldest(0x0), - OverwriteModeFail(0x2), - OverwriteModeGetNewest(0x3), - OverwriteModeGuard(0xFFFFFFFF), - ; - private final int value; - private IMAQdxOverwriteMode(int value) { - this.value = value; - } - public static IMAQdxOverwriteMode fromValue(int val) { - for (IMAQdxOverwriteMode v : values()) { - if (v.value == val) - return v; - } - return null; - } - public int getValue() { - return value; - } + public Disparity(PointDouble current, PointDouble reference, double distance) { + super(40); + this.current = current; + this.reference = reference; + this.distance = distance; } - /** - * Incomplete Buffer Mode Enumeration - */ + protected Disparity(ByteBuffer backing, int offset) { + super(backing, offset, 40); + init(); + } - public static enum IMAQdxIncompleteBufferMode { - IncompleteBufferModeIgnore(0), - IncompleteBufferModeFail(1), - IncompleteBufferModeGuard(0xFFFFFFFF), - ; - private final int value; - private IMAQdxIncompleteBufferMode(int value) { - this.value = value; - } - public static IMAQdxIncompleteBufferMode fromValue(int val) { - for (IMAQdxIncompleteBufferMode v : values()) { - if (v.value == val) - return v; - } - return null; - } - public int getValue() { - return value; - } + protected Disparity(long nativeObj, boolean owned) { + super(nativeObj, owned, 40); + init(); } - /** - * Lost Packet Mode Enumeration - */ + protected void setBuffer(ByteBuffer backing, int offset) { + super.setBuffer(backing, offset, 40); + } - public static enum IMAQdxLostPacketMode { - LostPacketModeIgnore(0), - LostPacketModeFail(1), - LostPacketModeGuard(0xFFFFFFFF), - ; - private final int value; - private IMAQdxLostPacketMode(int value) { - this.value = value; - } - public static IMAQdxLostPacketMode fromValue(int val) { - for (IMAQdxLostPacketMode v : values()) { - if (v.value == val) - return v; - } - return null; - } - public int getValue() { - return value; - } + public void read() { + current.read(); + reference.read(); + distance = backing.getDouble(32); } - /** - * Attribute Visibility Enumeration - */ + public void write() { + current.write(); + reference.write(); + backing.putDouble(32, distance); + } - public static enum IMAQdxAttributeVisibility { - AttributeVisibilitySimple(0x00001000), - AttributeVisibilityIntermediate(0x00002000), - AttributeVisibilityAdvanced(0x00004000), - AttributeVisibilityGuard(0xFFFFFFFF), - ; - private final int value; - private IMAQdxAttributeVisibility(int value) { - this.value = value; - } - public static IMAQdxAttributeVisibility fromValue(int val) { - for (IMAQdxAttributeVisibility v : values()) { - if (v.value == val) - return v; - } - return null; - } - public int getValue() { - return value; - } + public int size() { + return 40; } + } - /** - * Stream Channel Mode Enumeration - */ + public static class ComputeDistancesReport extends DisposedStruct { + public Disparity[] distances; // Distances is an array containing the + // computed distances. + public Disparity[] distancesReal; // Distances Real is an array containing + // the computed distances in calibrated + // units. + private ByteBuffer distances_buf; + private ByteBuffer distancesReal_buf; - public static enum IMAQdxStreamChannelMode { - StreamChannelModeAutomatic(0), - StreamChannelModeManual(1), - StreamChannelModeGuard(0xFFFFFFFF), - ; - private final int value; - private IMAQdxStreamChannelMode(int value) { - this.value = value; - } - public static IMAQdxStreamChannelMode fromValue(int val) { - for (IMAQdxStreamChannelMode v : values()) { - if (v.value == val) - return v; - } - return null; - } - public int getValue() { - return value; - } + private void init() { + distances = new Disparity[0]; + distancesReal = new Disparity[0]; } - /** - * Pixel Signedness Enumeration - */ + public ComputeDistancesReport() { + super(16); + init(); + } - public static enum IMAQdxPixelSignedness { - PixelSignednessUnsigned(0), - PixelSignednessSigned(1), - PixelSignednessHardware(2), - PixelSignednessGuard(0xFFFFFFFF), - ; - private final int value; - private IMAQdxPixelSignedness(int value) { - this.value = value; - } - public static IMAQdxPixelSignedness fromValue(int val) { - for (IMAQdxPixelSignedness v : values()) { - if (v.value == val) - return v; - } - return null; - } - public int getValue() { - return value; - } + public ComputeDistancesReport(Disparity[] distances, Disparity[] distancesReal) { + super(16); + this.distances = distances; + this.distancesReal = distancesReal; } - /** - * USB Connection Speed Enumeration - */ + protected ComputeDistancesReport(ByteBuffer backing, int offset) { + super(backing, offset, 16); + init(); + } - public static enum IMAQdxUSBConnectionSpeed { - USBConnectionSpeedLow(1), - USBConnectionSpeedFull(2), - USBConnectionSpeedHigh(4), - USBConnectionSpeedSuper(8), - USBConnectionSpeedGuard(0xFFFFFFFF), - ; - private final int value; - private IMAQdxUSBConnectionSpeed(int value) { - this.value = value; - } - public static IMAQdxUSBConnectionSpeed fromValue(int val) { - for (IMAQdxUSBConnectionSpeed v : values()) { - if (v.value == val) - return v; - } - return null; - } - public int getValue() { - return value; - } - } - - /** - * CVI Structures - */ - - /** - * Camera Information Structure - */ - - public static class IMAQdxCameraInformation extends DisposedStruct { - public int Type; - public int Version; - public int Flags; - public int SerialNumberHi; - public int SerialNumberLo; - public IMAQdxBusType BusType; - public String InterfaceName; - public String VendorName; - public String ModelName; - public String CameraFileName; - public String CameraAttributeURL; - - private void init() { - - } - public IMAQdxCameraInformation() { - super(2584); - init(); - } - public IMAQdxCameraInformation(int Type, int Version, int Flags, int SerialNumberHi, int SerialNumberLo, IMAQdxBusType BusType, String InterfaceName, String VendorName, String ModelName, String CameraFileName, String CameraAttributeURL) { - super(2584); - this.Type = Type; - this.Version = Version; - this.Flags = Flags; - this.SerialNumberHi = SerialNumberHi; - this.SerialNumberLo = SerialNumberLo; - this.BusType = BusType; - this.InterfaceName = InterfaceName; - this.VendorName = VendorName; - this.ModelName = ModelName; - this.CameraFileName = CameraFileName; - this.CameraAttributeURL = CameraAttributeURL; - } - protected IMAQdxCameraInformation(ByteBuffer backing, int offset) { - super(backing, offset, 2584); - init(); - } - protected IMAQdxCameraInformation(long nativeObj, boolean owned) { - super(nativeObj, owned, 2584); - init(); - } - protected void setBuffer(ByteBuffer backing, int offset) { - super.setBuffer(backing, offset, 2584); - } - public void read() { - Type = backing.getInt(0); - Version = backing.getInt(4); - Flags = backing.getInt(8); - SerialNumberHi = backing.getInt(12); - SerialNumberLo = backing.getInt(16); - BusType = IMAQdxBusType.fromValue(backing.getInt(20)); - { - byte[] bytes = new byte[IMAQDX_MAX_API_STRING_LENGTH]; - getBytes(backing, bytes, 24, IMAQDX_MAX_API_STRING_LENGTH); - int len; - for (len=0; len 0 && distances_addr != 0) { + ByteBuffer bb = newDirectByteBuffer(distances_addr, distances_numDistances * 40); + for (int i = 0, off = 0; i < distances_numDistances; i++, off += 40) { + distances[i] = new Disparity(bb, off); + distances[i].read(); } - public int size() { - return 520; + } + int distancesReal_numDistancesReal = backing.getInt(12); + long distancesReal_addr = getPointer(backing, 8); + distancesReal = new Disparity[distancesReal_numDistancesReal]; + if (distancesReal_numDistancesReal > 0 && distancesReal_addr != 0) { + ByteBuffer bb = + newDirectByteBuffer(distancesReal_addr, distancesReal_numDistancesReal * 40); + for (int i = 0, off = 0; i < distancesReal_numDistancesReal; i++, off += 40) { + distancesReal[i] = new Disparity(bb, off); + distancesReal[i].read(); } + } } - /** - * Camera Information Structure - */ + public void write() { + distances_buf = + ByteBuffer.allocateDirect(distances.length * 40).order(ByteOrder.nativeOrder()); + for (int i = 0, off = 0; i < distances.length; i++, off += 40) { + distances[i].setBuffer(distances_buf, off); + distances[i].write(); + } + backing.putInt(4, distances.length); + putPointer(backing, 0, distances_buf); + distancesReal_buf = + ByteBuffer.allocateDirect(distancesReal.length * 40).order(ByteOrder.nativeOrder()); + for (int i = 0, off = 0; i < distancesReal.length; i++, off += 40) { + distancesReal[i].setBuffer(distancesReal_buf, off); + distancesReal[i].write(); + } + backing.putInt(12, distancesReal.length); + putPointer(backing, 8, distancesReal_buf); + } - /** - * Attributes - */ + public int size() { + return 16; + } + } - /** - * Functions - */ + public static class MatchMode extends DisposedStruct { + public int rotation; // Rotation When enabled, the Function searches for + // occurrences of the template in the inspection image, + // allowing for template matches to be rotated. + public int scale; // Rotation When enabled, the Function searches for + // occurrences of the template in the inspection image, + // allowing for template matches to be rotated. + public int occlusion; // Occlusion specifies whether or not to search for + // occluded versions of the shape. - public static void IMAQdxSnap(int id, Image image) { - - _IMAQdxSnap(id, image.getAddress()); - - } - private static native void _IMAQdxSnap(int id, long image); + private void init() { - public static void IMAQdxConfigureGrab(int id) { - - _IMAQdxConfigureGrab(id); - } - private static native void _IMAQdxConfigureGrab(int id); - public static int IMAQdxGrab(int id, Image image, int waitForNextBuffer) { - ByteBuffer rv_buf = ByteBuffer.allocateDirect(8).order(ByteOrder.nativeOrder()); - long rv_addr = getByteBufferAddress(rv_buf); - _IMAQdxGrab(id, image.getAddress(), waitForNextBuffer, rv_addr+0); - int actualBufferNumber; - actualBufferNumber = rv_buf.getInt(0); - return actualBufferNumber; + public MatchMode() { + super(12); + init(); } - private static native void _IMAQdxGrab(int id, long image, int waitForNextBuffer, long actualBufferNumber); - public static void IMAQdxDiscoverEthernetCameras(String address, int timeout) { - ByteBuffer address_buf = null; - if (address != null) { - byte[] address_bytes; - try { - address_bytes = address.getBytes("UTF-8"); - } catch (UnsupportedEncodingException e) { - address_bytes = new byte[0]; - } - address_buf = ByteBuffer.allocateDirect(address_bytes.length+1); - putBytes(address_buf, address_bytes, 0, address_bytes.length).put(address_bytes.length, (byte)0); - } - _IMAQdxDiscoverEthernetCameras(address == null ? 0 : getByteBufferAddress(address_buf), timeout); - + public MatchMode(int rotation, int scale, int occlusion) { + super(12); + this.rotation = rotation; + this.scale = scale; + this.occlusion = occlusion; } - private static native void _IMAQdxDiscoverEthernetCameras(long address, int timeout); - public static void IMAQdxResetCamera(String name, int resetAll) { - ByteBuffer name_buf = null; - if (name != null) { - byte[] name_bytes; - try { - name_bytes = name.getBytes("UTF-8"); - } catch (UnsupportedEncodingException e) { - name_bytes = new byte[0]; - } - name_buf = ByteBuffer.allocateDirect(name_bytes.length+1); - putBytes(name_buf, name_bytes, 0, name_bytes.length).put(name_bytes.length, (byte)0); - } - _IMAQdxResetCamera(name == null ? 0 : getByteBufferAddress(name_buf), resetAll); - + protected MatchMode(ByteBuffer backing, int offset) { + super(backing, offset, 12); + init(); } - private static native void _IMAQdxResetCamera(long name, int resetAll); - public static int IMAQdxOpenCamera(String name, IMAQdxCameraControlMode mode) { - ByteBuffer name_buf = null; - if (name != null) { - byte[] name_bytes; - try { - name_bytes = name.getBytes("UTF-8"); - } catch (UnsupportedEncodingException e) { - name_bytes = new byte[0]; - } - name_buf = ByteBuffer.allocateDirect(name_bytes.length+1); - putBytes(name_buf, name_bytes, 0, name_bytes.length).put(name_bytes.length, (byte)0); - } - ByteBuffer rv_buf = ByteBuffer.allocateDirect(8).order(ByteOrder.nativeOrder()); - long rv_addr = getByteBufferAddress(rv_buf); - _IMAQdxOpenCamera(name == null ? 0 : getByteBufferAddress(name_buf), mode.getValue(), rv_addr+0); - int id; - id = rv_buf.getInt(0); - return id; - } - private static native void _IMAQdxOpenCamera(long name, int mode, long id); - - public static void IMAQdxCloseCamera(int id) { - - _IMAQdxCloseCamera(id); - - } - private static native void _IMAQdxCloseCamera(int id); - - public static void IMAQdxConfigureAcquisition(int id, int continuous, int bufferCount) { - - _IMAQdxConfigureAcquisition(id, continuous, bufferCount); - - } - private static native void _IMAQdxConfigureAcquisition(int id, int continuous, int bufferCount); - - public static void IMAQdxStartAcquisition(int id) { - - _IMAQdxStartAcquisition(id); - - } - private static native void _IMAQdxStartAcquisition(int id); - - public static int IMAQdxGetImage(int id, Image image, IMAQdxBufferNumberMode mode, int desiredBufferNumber) { - ByteBuffer rv_buf = ByteBuffer.allocateDirect(8).order(ByteOrder.nativeOrder()); - long rv_addr = getByteBufferAddress(rv_buf); - _IMAQdxGetImage(id, image.getAddress(), mode.getValue(), desiredBufferNumber, rv_addr+0); - int actualBufferNumber; - actualBufferNumber = rv_buf.getInt(0); - return actualBufferNumber; - } - private static native void _IMAQdxGetImage(int id, long image, int mode, int desiredBufferNumber, long actualBufferNumber); - - public static int IMAQdxGetImageData(int id, ByteBuffer buffer, IMAQdxBufferNumberMode mode, int desiredBufferNumber) { - long buffer_addr = getByteBufferAddress(buffer); - int buffer_size = buffer.capacity(); - return _IMAQdxGetImageData(id, buffer_addr, buffer_size, mode.getValue(), desiredBufferNumber); - } - private static native int _IMAQdxGetImageData(int id, long buffer, int bufferSize, int mode, int desiredBufferNumber); - - public static void IMAQdxStopAcquisition(int id) { - - _IMAQdxStopAcquisition(id); - - } - private static native void _IMAQdxStopAcquisition(int id); - - public static void IMAQdxUnconfigureAcquisition(int id) { - - _IMAQdxUnconfigureAcquisition(id); - - } - private static native void _IMAQdxUnconfigureAcquisition(int id); - - public static class dxEnumerateVideoModesResult { - public IMAQdxEnumItem[] videoModeArray; - public int currentMode; - private ByteBuffer videoModeArray_buf; - private dxEnumerateVideoModesResult(ByteBuffer rv_buf, ByteBuffer videoModeArray_buf) { - this.videoModeArray_buf = videoModeArray_buf; - int count = rv_buf.getInt(0); - videoModeArray = new IMAQdxEnumItem[count]; - for (int i=0, off=0; i 0 && templateSubsection_addr != 0) { + ByteBuffer bb = + newDirectByteBuffer(templateSubsection_addr, + templateSubsection_numTemplateSubsection * 16); + for (int i = 0, off = 0; i < templateSubsection_numTemplateSubsection; i++, off += 16) { + templateSubsection[i] = new PointDouble(bb, off); + templateSubsection[i].read(); } - ByteBuffer gateway_buf = null; - if (gateway != null) { - byte[] gateway_bytes; - try { - gateway_bytes = gateway.getBytes("UTF-8"); - } catch (UnsupportedEncodingException e) { - gateway_bytes = new byte[0]; - } - gateway_buf = ByteBuffer.allocateDirect(gateway_bytes.length+1); - putBytes(gateway_buf, gateway_bytes, 0, gateway_bytes.length).put(gateway_bytes.length, (byte)0); + } + int targetSubsection_numTargetSubsection = backing.getInt(48); + long targetSubsection_addr = getPointer(backing, 44); + targetSubsection = new PointDouble[targetSubsection_numTargetSubsection]; + if (targetSubsection_numTargetSubsection > 0 && targetSubsection_addr != 0) { + ByteBuffer bb = + newDirectByteBuffer(targetSubsection_addr, targetSubsection_numTargetSubsection * 16); + for (int i = 0, off = 0; i < targetSubsection_numTargetSubsection; i++, off += 16) { + targetSubsection[i] = new PointDouble(bb, off); + targetSubsection[i].read(); } - _IMAQdxResetEthernetCameraAddress(name == null ? 0 : getByteBufferAddress(name_buf), address == null ? 0 : getByteBufferAddress(address_buf), subnet == null ? 0 : getByteBufferAddress(subnet_buf), gateway == null ? 0 : getByteBufferAddress(gateway_buf), timeout); - + } } - private static native void _IMAQdxResetEthernetCameraAddress(long name, long address, long subnet, long gateway, int timeout); - public static IMAQdxAttributeVisibility IMAQdxGetAttributeVisibility(int id, String name) { - ByteBuffer name_buf = null; - if (name != null) { - byte[] name_bytes; - try { - name_bytes = name.getBytes("UTF-8"); - } catch (UnsupportedEncodingException e) { - name_bytes = new byte[0]; - } - name_buf = ByteBuffer.allocateDirect(name_bytes.length+1); - putBytes(name_buf, name_bytes, 0, name_bytes.length).put(name_bytes.length, (byte)0); - } - ByteBuffer rv_buf = ByteBuffer.allocateDirect(8).order(ByteOrder.nativeOrder()); - long rv_addr = getByteBufferAddress(rv_buf); - _IMAQdxGetAttributeVisibility(id, name == null ? 0 : getByteBufferAddress(name_buf), rv_addr+0); - IMAQdxAttributeVisibility visibility; - visibility = IMAQdxAttributeVisibility.fromValue(rv_buf.getInt(0)); - return visibility; - } - private static native void _IMAQdxGetAttributeVisibility(int id, long name, long visibility); - - public static int IMAQdxGetAttributeU32(int id, String name) { - ByteBuffer name_buf = null; - if (name != null) { - byte[] name_bytes; - try { - name_bytes = name.getBytes("UTF-8"); - } catch (UnsupportedEncodingException e) { - name_bytes = new byte[0]; - } - name_buf = ByteBuffer.allocateDirect(name_bytes.length+1); - putBytes(name_buf, name_bytes, 0, name_bytes.length).put(name_bytes.length, (byte)0); - } - ByteBuffer rv_buf = ByteBuffer.allocateDirect(8).order(ByteOrder.nativeOrder()); - long rv_addr = getByteBufferAddress(rv_buf); - _IMAQdxGetAttributeU32(id, name == null ? 0 : getByteBufferAddress(name_buf), rv_addr+0); - int value; - value = rv_buf.getInt(0); - return value; - } - private static native void _IMAQdxGetAttributeU32(int id, long name, long value); - - public static long IMAQdxGetAttributeI64(int id, String name) { - ByteBuffer name_buf = null; - if (name != null) { - byte[] name_bytes; - try { - name_bytes = name.getBytes("UTF-8"); - } catch (UnsupportedEncodingException e) { - name_bytes = new byte[0]; - } - name_buf = ByteBuffer.allocateDirect(name_bytes.length+1); - putBytes(name_buf, name_bytes, 0, name_bytes.length).put(name_bytes.length, (byte)0); - } - ByteBuffer rv_buf = ByteBuffer.allocateDirect(8).order(ByteOrder.nativeOrder()); - long rv_addr = getByteBufferAddress(rv_buf); - _IMAQdxGetAttributeI64(id, name == null ? 0 : getByteBufferAddress(name_buf), rv_addr+0); - long value; - value = rv_buf.getLong(0); - return value; - } - private static native void _IMAQdxGetAttributeI64(int id, long name, long value); - - public static double IMAQdxGetAttributeF64(int id, String name) { - ByteBuffer name_buf = null; - if (name != null) { - byte[] name_bytes; - try { - name_bytes = name.getBytes("UTF-8"); - } catch (UnsupportedEncodingException e) { - name_bytes = new byte[0]; - } - name_buf = ByteBuffer.allocateDirect(name_bytes.length+1); - putBytes(name_buf, name_bytes, 0, name_bytes.length).put(name_bytes.length, (byte)0); - } - ByteBuffer rv_buf = ByteBuffer.allocateDirect(8).order(ByteOrder.nativeOrder()); - long rv_addr = getByteBufferAddress(rv_buf); - _IMAQdxGetAttributeF64(id, name == null ? 0 : getByteBufferAddress(name_buf), rv_addr+0); - double value; - value = rv_buf.getDouble(0); - return value; - } - private static native void _IMAQdxGetAttributeF64(int id, long name, long value); - - public static String IMAQdxGetAttributeString(int id, String name) { - ByteBuffer name_buf = null; - if (name != null) { - byte[] name_bytes; - try { - name_bytes = name.getBytes("UTF-8"); - } catch (UnsupportedEncodingException e) { - name_bytes = new byte[0]; - } - name_buf = ByteBuffer.allocateDirect(name_bytes.length+1); - putBytes(name_buf, name_bytes, 0, name_bytes.length).put(name_bytes.length, (byte)0); - } - ByteBuffer rv_buf = ByteBuffer.allocateDirect(IMAQDX_MAX_API_STRING_LENGTH).order(ByteOrder.nativeOrder()); - long rv_addr = getByteBufferAddress(rv_buf); - _IMAQdxGetAttributeString(id, name == null ? 0 : getByteBufferAddress(name_buf), rv_addr+0); - String value; - { - byte[] bytes = new byte[IMAQDX_MAX_API_STRING_LENGTH]; - getBytes(rv_buf, bytes, 0, IMAQDX_MAX_API_STRING_LENGTH); - int len; - for (len=0; len 0 && classifiedDistances_addr != 0) { + ByteBuffer bb = + newDirectByteBuffer(classifiedDistances_addr, + classifiedDistances_numClassifiedDistances * 56); + for (int i = 0, off = 0; i < classifiedDistances_numClassifiedDistances; i++, off += 56) { + classifiedDistances[i] = new ClassifiedDisparity(bb, off); + classifiedDistances[i].read(); } - _IMAQdxSetAttributeBool(id, name == null ? 0 : getByteBufferAddress(name_buf), value); - + } + } + + public void write() { + classifiedDistances_buf = + ByteBuffer.allocateDirect(classifiedDistances.length * 56).order(ByteOrder.nativeOrder()); + for (int i = 0, off = 0; i < classifiedDistances.length; i++, off += 56) { + classifiedDistances[i].setBuffer(classifiedDistances_buf, off); + classifiedDistances[i].write(); + } + backing.putInt(4, classifiedDistances.length); + putPointer(backing, 0, classifiedDistances_buf); + } + + public int size() { + return 8; } - private static native void _IMAQdxSetAttributeBool(int id, long name, int value); + } + + public static class ContourComputeCurvatureReport extends DisposedStruct { + public double[] curvaturePixel; // Curvature Pixel displays the curvature + // profile for the selected contour, in + // pixels. + public double[] curvatureReal; // Curvature Real displays the curvature + // profile for the selected contour, in + // calibrated units. + private ByteBuffer curvaturePixel_buf; + private ByteBuffer curvatureReal_buf; + + private void init() { + curvaturePixel = new double[0]; + curvatureReal = new double[0]; + } + + public ContourComputeCurvatureReport() { + super(16); + init(); + } + + public ContourComputeCurvatureReport(double[] curvaturePixel, double[] curvatureReal) { + super(16); + this.curvaturePixel = curvaturePixel; + this.curvatureReal = curvatureReal; + } + + protected ContourComputeCurvatureReport(ByteBuffer backing, int offset) { + super(backing, offset, 16); + init(); + } + + protected ContourComputeCurvatureReport(long nativeObj, boolean owned) { + super(nativeObj, owned, 16); + init(); + } + + protected void setBuffer(ByteBuffer backing, int offset) { + super.setBuffer(backing, offset, 16); + } + + public void read() { + int curvaturePixel_numCurvaturePixel = backing.getInt(4); + long curvaturePixel_addr = getPointer(backing, 0); + curvaturePixel = new double[curvaturePixel_numCurvaturePixel]; + if (curvaturePixel_numCurvaturePixel > 0 && curvaturePixel_addr != 0) { + newDirectByteBuffer(curvaturePixel_addr, curvaturePixel_numCurvaturePixel * 8) + .asDoubleBuffer().get(curvaturePixel); + } + int curvatureReal_numCurvatureReal = backing.getInt(12); + long curvatureReal_addr = getPointer(backing, 8); + curvatureReal = new double[curvatureReal_numCurvatureReal]; + if (curvatureReal_numCurvatureReal > 0 && curvatureReal_addr != 0) { + newDirectByteBuffer(curvatureReal_addr, curvatureReal_numCurvatureReal * 8) + .asDoubleBuffer().get(curvatureReal); + } + } + + public void write() { + curvaturePixel_buf = + ByteBuffer.allocateDirect(curvaturePixel.length * 8).order(ByteOrder.nativeOrder()); + curvaturePixel_buf.asDoubleBuffer().put(curvaturePixel).rewind(); + backing.putInt(4, curvaturePixel.length); + putPointer(backing, 0, curvaturePixel_buf); + curvatureReal_buf = + ByteBuffer.allocateDirect(curvatureReal.length * 8).order(ByteOrder.nativeOrder()); + curvatureReal_buf.asDoubleBuffer().put(curvatureReal).rewind(); + backing.putInt(12, curvatureReal.length); + putPointer(backing, 8, curvatureReal_buf); + } + + public int size() { + return 16; + } + } + + public static class ContourOverlaySettings extends DisposedStruct { + public int overlay; // Overlay specifies whether to display the overlay on + // the image. + public RGBValue color; // Color is the color of the overlay. + public int width; // Width specifies the width of the overlay in pixels. + public int maintainWidth; // Maintain Width? specifies whether you want the + // overlay measured in screen pixels or image + // pixels. + + private void init() { + color = new RGBValue(backing, 4); + } + + public ContourOverlaySettings() { + super(16); + init(); + } + + public ContourOverlaySettings(int overlay, RGBValue color, int width, int maintainWidth) { + super(16); + this.overlay = overlay; + this.color = color; + this.width = width; + this.maintainWidth = maintainWidth; + } + + protected ContourOverlaySettings(ByteBuffer backing, int offset) { + super(backing, offset, 16); + init(); + } + + protected ContourOverlaySettings(long nativeObj, boolean owned) { + super(nativeObj, owned, 16); + init(); + } + + protected void setBuffer(ByteBuffer backing, int offset) { + super.setBuffer(backing, offset, 16); + } + + public void read() { + overlay = backing.getInt(0); + color.read(); + width = backing.getInt(8); + maintainWidth = backing.getInt(12); + } + + public void write() { + backing.putInt(0, overlay); + color.write(); + backing.putInt(8, width); + backing.putInt(12, maintainWidth); + } + + public int size() { + return 16; + } + } + + public static class CurveParameters extends DisposedStruct { + public ExtractionMode extractionMode; // Specifies the method the function + // uses to identify curves in the + // image. + public int threshold; // Specifies the minimum contrast a seed point must + // have in order to begin a curve. + public EdgeFilterSize filterSize; // Specifies the width of the edge filter + // the function uses to identify curves in + // the image. + public int minLength; // Specifies the length, in pixels, of the smallest + // curve the function will extract. + public int searchStep; // Search Step Size specifies the distance, in the y + // direction, between the image rows that the + // algorithm inspects for curve seed points. + public int maxEndPointGap; // Specifies the maximum gap, in pixels, between + // the endpoints of a curve that the function + // identifies as a closed curve. + public int subpixel; // Subpixel specifies whether to detect curve points + // with subpixel accuracy. + + private void init() { + + } + + public CurveParameters() { + super(28); + init(); + } + + public CurveParameters(ExtractionMode extractionMode, int threshold, EdgeFilterSize filterSize, + int minLength, int searchStep, int maxEndPointGap, int subpixel) { + super(28); + this.extractionMode = extractionMode; + this.threshold = threshold; + this.filterSize = filterSize; + this.minLength = minLength; + this.searchStep = searchStep; + this.maxEndPointGap = maxEndPointGap; + this.subpixel = subpixel; + } + + protected CurveParameters(ByteBuffer backing, int offset) { + super(backing, offset, 28); + init(); + } + + protected CurveParameters(long nativeObj, boolean owned) { + super(nativeObj, owned, 28); + init(); + } + + protected void setBuffer(ByteBuffer backing, int offset) { + super.setBuffer(backing, offset, 28); + } + + public void read() { + extractionMode = ExtractionMode.fromValue(backing.getInt(0)); + threshold = backing.getInt(4); + filterSize = EdgeFilterSize.fromValue(backing.getInt(8)); + minLength = backing.getInt(12); + searchStep = backing.getInt(16); + maxEndPointGap = backing.getInt(20); + subpixel = backing.getInt(24); + } + + public void write() { + if (extractionMode != null) + backing.putInt(0, extractionMode.getValue()); + backing.putInt(4, threshold); + if (filterSize != null) + backing.putInt(8, filterSize.getValue()); + backing.putInt(12, minLength); + backing.putInt(16, searchStep); + backing.putInt(20, maxEndPointGap); + backing.putInt(24, subpixel); + } + + public int size() { + return 28; + } + } + + public static class ExtractContourReport extends DisposedStruct { + public PointDouble[] contourPoints; // Contour Points specifies every point + // found on the contour. + public PointDouble[] sourcePoints; // Source Image Points specifies every + // point found on the contour in the + // source image. + private ByteBuffer contourPoints_buf; + private ByteBuffer sourcePoints_buf; + + private void init() { + contourPoints = new PointDouble[0]; + sourcePoints = new PointDouble[0]; + } + + public ExtractContourReport() { + super(16); + init(); + } + + public ExtractContourReport(PointDouble[] contourPoints, PointDouble[] sourcePoints) { + super(16); + this.contourPoints = contourPoints; + this.sourcePoints = sourcePoints; + } + + protected ExtractContourReport(ByteBuffer backing, int offset) { + super(backing, offset, 16); + init(); + } + + protected ExtractContourReport(long nativeObj, boolean owned) { + super(nativeObj, owned, 16); + init(); + } + + protected void setBuffer(ByteBuffer backing, int offset) { + super.setBuffer(backing, offset, 16); + } + + public void read() { + int contourPoints_numContourPoints = backing.getInt(4); + long contourPoints_addr = getPointer(backing, 0); + contourPoints = new PointDouble[contourPoints_numContourPoints]; + if (contourPoints_numContourPoints > 0 && contourPoints_addr != 0) { + ByteBuffer bb = + newDirectByteBuffer(contourPoints_addr, contourPoints_numContourPoints * 16); + for (int i = 0, off = 0; i < contourPoints_numContourPoints; i++, off += 16) { + contourPoints[i] = new PointDouble(bb, off); + contourPoints[i].read(); + } + } + int sourcePoints_numSourcePoints = backing.getInt(12); + long sourcePoints_addr = getPointer(backing, 8); + sourcePoints = new PointDouble[sourcePoints_numSourcePoints]; + if (sourcePoints_numSourcePoints > 0 && sourcePoints_addr != 0) { + ByteBuffer bb = newDirectByteBuffer(sourcePoints_addr, sourcePoints_numSourcePoints * 16); + for (int i = 0, off = 0; i < sourcePoints_numSourcePoints; i++, off += 16) { + sourcePoints[i] = new PointDouble(bb, off); + sourcePoints[i].read(); + } + } + } + + public void write() { + contourPoints_buf = + ByteBuffer.allocateDirect(contourPoints.length * 16).order(ByteOrder.nativeOrder()); + for (int i = 0, off = 0; i < contourPoints.length; i++, off += 16) { + contourPoints[i].setBuffer(contourPoints_buf, off); + contourPoints[i].write(); + } + backing.putInt(4, contourPoints.length); + putPointer(backing, 0, contourPoints_buf); + sourcePoints_buf = + ByteBuffer.allocateDirect(sourcePoints.length * 16).order(ByteOrder.nativeOrder()); + for (int i = 0, off = 0; i < sourcePoints.length; i++, off += 16) { + sourcePoints[i].setBuffer(sourcePoints_buf, off); + sourcePoints[i].write(); + } + backing.putInt(12, sourcePoints.length); + putPointer(backing, 8, sourcePoints_buf); + } + + public int size() { + return 16; + } + } + + public static class ConnectionConstraint extends DisposedStruct { + public ConnectionConstraintType constraintType; // Constraint Type specifies + // what criteria to use to + // consider two curves part + // of a contour. + public RangeDouble range; // Specifies range for a given Match Constraint. + + private void init() { + range = new RangeDouble(backing, 8); + } + + public ConnectionConstraint() { + super(24); + init(); + } + + public ConnectionConstraint(ConnectionConstraintType constraintType, RangeDouble range) { + super(24); + this.constraintType = constraintType; + this.range = range; + } + + protected ConnectionConstraint(ByteBuffer backing, int offset) { + super(backing, offset, 24); + init(); + } + + protected ConnectionConstraint(long nativeObj, boolean owned) { + super(nativeObj, owned, 24); + init(); + } + + protected void setBuffer(ByteBuffer backing, int offset) { + super.setBuffer(backing, offset, 24); + } + + public void read() { + constraintType = ConnectionConstraintType.fromValue(backing.getInt(0)); + range.read(); + } + + public void write() { + if (constraintType != null) + backing.putInt(0, constraintType.getValue()); + range.write(); + } + + public int size() { + return 24; + } + } + + public static class ExtractTextureFeaturesReport extends DisposedStruct { + public int[] waveletBands; // The array having all the Wavelet Banks used + // for extraction. + public int textureFeaturesRows; // Number of Rows in the Texture Features + // array. + public int textureFeaturesCols; // Number of Cols in Texture Features array. + private ByteBuffer waveletBands_buf; + + private void init() { + waveletBands = new int[0]; + } + + public ExtractTextureFeaturesReport() { + super(20); + init(); + } + + public ExtractTextureFeaturesReport(int[] waveletBands, int textureFeaturesRows, + int textureFeaturesCols) { + super(20); + this.waveletBands = waveletBands; + this.textureFeaturesRows = textureFeaturesRows; + this.textureFeaturesCols = textureFeaturesCols; + } + + protected ExtractTextureFeaturesReport(ByteBuffer backing, int offset) { + super(backing, offset, 20); + init(); + } + + protected ExtractTextureFeaturesReport(long nativeObj, boolean owned) { + super(nativeObj, owned, 20); + init(); + } + + protected void setBuffer(ByteBuffer backing, int offset) { + super.setBuffer(backing, offset, 20); + } + + public void read() { + int waveletBands_numWaveletBands = backing.getInt(4); + long waveletBands_addr = getPointer(backing, 0); + waveletBands = new int[waveletBands_numWaveletBands]; + if (waveletBands_numWaveletBands > 0 && waveletBands_addr != 0) { + newDirectByteBuffer(waveletBands_addr, waveletBands_numWaveletBands * 4).asIntBuffer().get( + waveletBands); + } + textureFeaturesRows = backing.getInt(12); + textureFeaturesCols = backing.getInt(16); + } + + public void write() { + waveletBands_buf = + ByteBuffer.allocateDirect(waveletBands.length * 4).order(ByteOrder.nativeOrder()); + waveletBands_buf.asIntBuffer().put(waveletBands).rewind(); + backing.putInt(4, waveletBands.length); + putPointer(backing, 0, waveletBands_buf); + backing.putInt(12, textureFeaturesRows); + backing.putInt(16, textureFeaturesCols); + } + + public int size() { + return 20; + } + } + + public static class WaveletBandsReport extends DisposedStruct { + public float LHLBand; // 2-D array for LHL Band. + public int rows; // Number of Rows for each of the 2-D arrays. + public int cols; // Number of Columns for each of the 2-D arrays. + + private void init() { + + } + + public WaveletBandsReport() { + super(40); + init(); + } + + public WaveletBandsReport(double LHLBand, int rows, int cols) { + super(40); + this.LHLBand = (float) LHLBand; + this.rows = rows; + this.cols = cols; + } + + protected WaveletBandsReport(ByteBuffer backing, int offset) { + super(backing, offset, 40); + init(); + } + + protected WaveletBandsReport(long nativeObj, boolean owned) { + super(nativeObj, owned, 40); + init(); + } + + protected void setBuffer(ByteBuffer backing, int offset) { + super.setBuffer(backing, offset, 40); + } + + public void read() { + LHLBand = backing.getFloat(24); + rows = backing.getInt(32); + cols = backing.getInt(36); + } + + public void write() { + backing.putFloat(24, LHLBand); + backing.putInt(32, rows); + backing.putInt(36, cols); + } + + public int size() { + return 40; + } + } + + public static class CircleFitOptions extends DisposedStruct { + public int maxRadius; // Specifies the acceptable distance, in pixels, that + // a point determined to belong to the circle can be + // from the perimeter of the circle. + public double stepSize; // Step Size is the angle, in degrees, between each + // radial line in the annular region. + public RakeProcessType processType; // Method used to process the data + // extracted for edge detection. + + private void init() { + + } + + public CircleFitOptions() { + super(24); + init(); + } + + public CircleFitOptions(int maxRadius, double stepSize, RakeProcessType processType) { + super(24); + this.maxRadius = maxRadius; + this.stepSize = stepSize; + this.processType = processType; + } + + protected CircleFitOptions(ByteBuffer backing, int offset) { + super(backing, offset, 24); + init(); + } + + protected CircleFitOptions(long nativeObj, boolean owned) { + super(nativeObj, owned, 24); + init(); + } + + protected void setBuffer(ByteBuffer backing, int offset) { + super.setBuffer(backing, offset, 24); + } + + public void read() { + maxRadius = backing.getInt(0); + stepSize = backing.getDouble(8); + processType = RakeProcessType.fromValue(backing.getInt(16)); + } + + public void write() { + backing.putInt(0, maxRadius); + backing.putDouble(8, stepSize); + if (processType != null) + backing.putInt(16, processType.getValue()); + } + + public int size() { + return 24; + } + } + + public static class EdgeOptions2 extends DisposedStruct { + public EdgePolaritySearchMode polarity; // Specifies the polarity of the + // edges to be found. + public int kernelSize; // Specifies the size of the edge detection kernel. + public int width; // Specifies the number of pixels averaged perpendicular + // to the search direction to compute the edge profile + // strength at each point along the search ROI. + public float minThreshold; // Specifies the minimum edge strength (gradient + // magnitude) required for a detected edge. + public InterpolationMethod interpolationType; // Specifies the interpolation + // method used to locate the + // edge position. + public ColumnProcessingMode columnProcessingMode; // Specifies the method + // used to find the + // straight edge. + + private void init() { + + } + + public EdgeOptions2() { + super(24); + init(); + } + + public EdgeOptions2(EdgePolaritySearchMode polarity, int kernelSize, int width, + double minThreshold, InterpolationMethod interpolationType, + ColumnProcessingMode columnProcessingMode) { + super(24); + this.polarity = polarity; + this.kernelSize = kernelSize; + this.width = width; + this.minThreshold = (float) minThreshold; + this.interpolationType = interpolationType; + this.columnProcessingMode = columnProcessingMode; + } + + protected EdgeOptions2(ByteBuffer backing, int offset) { + super(backing, offset, 24); + init(); + } + + protected EdgeOptions2(long nativeObj, boolean owned) { + super(nativeObj, owned, 24); + init(); + } + + protected void setBuffer(ByteBuffer backing, int offset) { + super.setBuffer(backing, offset, 24); + } + + public void read() { + polarity = EdgePolaritySearchMode.fromValue(backing.getInt(0)); + kernelSize = backing.getInt(4); + width = backing.getInt(8); + minThreshold = backing.getFloat(12); + interpolationType = InterpolationMethod.fromValue(backing.getInt(16)); + columnProcessingMode = ColumnProcessingMode.fromValue(backing.getInt(20)); + } + + public void write() { + if (polarity != null) + backing.putInt(0, polarity.getValue()); + backing.putInt(4, kernelSize); + backing.putInt(8, width); + backing.putFloat(12, minThreshold); + if (interpolationType != null) + backing.putInt(16, interpolationType.getValue()); + if (columnProcessingMode != null) + backing.putInt(20, columnProcessingMode.getValue()); + } + + public int size() { + return 24; + } + } + + public static class FindCircularEdgeOptions extends DisposedStruct { + public SpokeDirection direction; // Specifies the Spoke direction to search + // in the ROI. + public int showSearchArea; // If TRUE, the function overlays the search area + // on the image. + public int showSearchLines; // If TRUE, the function overlays the search + // lines used to locate the edges on the image. + public int showEdgesFound; // If TRUE, the function overlays the locations + // of the edges found on the image. + public int showResult; // If TRUE, the function overlays the hit lines to + // the object and the edge used to generate the hit + // line on the result image. + public RGBValue searchAreaColor; // Specifies the RGB color value to use to + // overlay the search area. + public RGBValue searchLinesColor; // Specifies the RGB color value to use to + // overlay the search lines. + public RGBValue searchEdgesColor; // Specifies the RGB color value to use to + // overlay the search edges. + public RGBValue resultColor; // Specifies the RGB color value to use to + // overlay the results. + public String overlayGroupName; // Specifies the overlay group name to + // assign to the overlays. + public EdgeOptions2 edgeOptions; // Specifies the edge detection options + // along a single search line. + private ByteBuffer overlayGroupName_buf; + + private void init() { + searchAreaColor = new RGBValue(backing, 20); + searchLinesColor = new RGBValue(backing, 24); + searchEdgesColor = new RGBValue(backing, 28); + resultColor = new RGBValue(backing, 32); + edgeOptions = new EdgeOptions2(backing, 40); + } + + public FindCircularEdgeOptions() { + super(64); + init(); + } + + public FindCircularEdgeOptions(SpokeDirection direction, int showSearchArea, + int showSearchLines, int showEdgesFound, int showResult, RGBValue searchAreaColor, + RGBValue searchLinesColor, RGBValue searchEdgesColor, RGBValue resultColor, + String overlayGroupName, EdgeOptions2 edgeOptions) { + super(64); + this.direction = direction; + this.showSearchArea = showSearchArea; + this.showSearchLines = showSearchLines; + this.showEdgesFound = showEdgesFound; + this.showResult = showResult; + this.searchAreaColor = searchAreaColor; + this.searchLinesColor = searchLinesColor; + this.searchEdgesColor = searchEdgesColor; + this.resultColor = resultColor; + this.overlayGroupName = overlayGroupName; + this.edgeOptions = edgeOptions; + } + + protected FindCircularEdgeOptions(ByteBuffer backing, int offset) { + super(backing, offset, 64); + init(); + } + + protected FindCircularEdgeOptions(long nativeObj, boolean owned) { + super(nativeObj, owned, 64); + init(); + } + + protected void setBuffer(ByteBuffer backing, int offset) { + super.setBuffer(backing, offset, 64); + } + + public void read() { + direction = SpokeDirection.fromValue(backing.getInt(0)); + showSearchArea = backing.getInt(4); + showSearchLines = backing.getInt(8); + showEdgesFound = backing.getInt(12); + showResult = backing.getInt(16); + searchAreaColor.read(); + searchLinesColor.read(); + searchEdgesColor.read(); + resultColor.read(); + long overlayGroupName_addr = getPointer(backing, 36); + if (overlayGroupName_addr == 0) + overlayGroupName = null; + else { + ByteBuffer bb = newDirectByteBuffer(overlayGroupName_addr, 1000); // FIXME + while (bb.get() != 0) { + } + byte[] bytes = new byte[bb.position() - 1]; + getBytes(bb, bytes, 0, bytes.length); + try { + overlayGroupName = new String(bytes, "UTF-8"); + } catch (UnsupportedEncodingException e) { + overlayGroupName = ""; + } + } + + edgeOptions.read(); + } + + public void write() { + if (direction != null) + backing.putInt(0, direction.getValue()); + backing.putInt(4, showSearchArea); + backing.putInt(8, showSearchLines); + backing.putInt(12, showEdgesFound); + backing.putInt(16, showResult); + searchAreaColor.write(); + searchLinesColor.write(); + searchEdgesColor.write(); + resultColor.write(); + if (overlayGroupName != null) { + byte[] overlayGroupName_bytes; + try { + overlayGroupName_bytes = overlayGroupName.getBytes("UTF-8"); + } catch (UnsupportedEncodingException e) { + overlayGroupName_bytes = new byte[0]; + } + overlayGroupName_buf = ByteBuffer.allocateDirect(overlayGroupName_bytes.length + 1); + putBytes(overlayGroupName_buf, overlayGroupName_bytes, 0, overlayGroupName_bytes.length) + .put(overlayGroupName_bytes.length, (byte) 0); + } + putPointer(backing, 36, overlayGroupName == null ? 0 + : getByteBufferAddress(overlayGroupName_buf)); + edgeOptions.write(); + } + + public int size() { + return 64; + } + } + + public static class FindConcentricEdgeOptions extends DisposedStruct { + public ConcentricRakeDirection direction; // Specifies the Concentric Rake + // direction. + public int showSearchArea; // If TRUE, the function overlays the search area + // on the image. + public int showSearchLines; // If TRUE, the function overlays the search + // lines used to locate the edges on the image. + public int showEdgesFound; // If TRUE, the function overlays the locations + // of the edges found on the image. + public int showResult; // If TRUE, the function overlays the hit lines to + // the object and the edge used to generate the hit + // line on the result image. + public RGBValue searchAreaColor; // Specifies the RGB color value to use to + // overlay the search area. + public RGBValue searchLinesColor; // Specifies the RGB color value to use to + // overlay the search lines. + public RGBValue searchEdgesColor; // Specifies the RGB color value to use to + // overlay the search edges. + public RGBValue resultColor; // Specifies the RGB color value to use to + // overlay the results. + public String overlayGroupName; // Specifies the overlay group name to + // assign to the overlays. + public EdgeOptions2 edgeOptions; // Specifies the edge detection options + // along a single search line. + private ByteBuffer overlayGroupName_buf; + + private void init() { + searchAreaColor = new RGBValue(backing, 20); + searchLinesColor = new RGBValue(backing, 24); + searchEdgesColor = new RGBValue(backing, 28); + resultColor = new RGBValue(backing, 32); + edgeOptions = new EdgeOptions2(backing, 40); + } + + public FindConcentricEdgeOptions() { + super(64); + init(); + } + + public FindConcentricEdgeOptions(ConcentricRakeDirection direction, int showSearchArea, + int showSearchLines, int showEdgesFound, int showResult, RGBValue searchAreaColor, + RGBValue searchLinesColor, RGBValue searchEdgesColor, RGBValue resultColor, + String overlayGroupName, EdgeOptions2 edgeOptions) { + super(64); + this.direction = direction; + this.showSearchArea = showSearchArea; + this.showSearchLines = showSearchLines; + this.showEdgesFound = showEdgesFound; + this.showResult = showResult; + this.searchAreaColor = searchAreaColor; + this.searchLinesColor = searchLinesColor; + this.searchEdgesColor = searchEdgesColor; + this.resultColor = resultColor; + this.overlayGroupName = overlayGroupName; + this.edgeOptions = edgeOptions; + } + + protected FindConcentricEdgeOptions(ByteBuffer backing, int offset) { + super(backing, offset, 64); + init(); + } + + protected FindConcentricEdgeOptions(long nativeObj, boolean owned) { + super(nativeObj, owned, 64); + init(); + } + + protected void setBuffer(ByteBuffer backing, int offset) { + super.setBuffer(backing, offset, 64); + } + + public void read() { + direction = ConcentricRakeDirection.fromValue(backing.getInt(0)); + showSearchArea = backing.getInt(4); + showSearchLines = backing.getInt(8); + showEdgesFound = backing.getInt(12); + showResult = backing.getInt(16); + searchAreaColor.read(); + searchLinesColor.read(); + searchEdgesColor.read(); + resultColor.read(); + long overlayGroupName_addr = getPointer(backing, 36); + if (overlayGroupName_addr == 0) + overlayGroupName = null; + else { + ByteBuffer bb = newDirectByteBuffer(overlayGroupName_addr, 1000); // FIXME + while (bb.get() != 0) { + } + byte[] bytes = new byte[bb.position() - 1]; + getBytes(bb, bytes, 0, bytes.length); + try { + overlayGroupName = new String(bytes, "UTF-8"); + } catch (UnsupportedEncodingException e) { + overlayGroupName = ""; + } + } + + edgeOptions.read(); + } + + public void write() { + if (direction != null) + backing.putInt(0, direction.getValue()); + backing.putInt(4, showSearchArea); + backing.putInt(8, showSearchLines); + backing.putInt(12, showEdgesFound); + backing.putInt(16, showResult); + searchAreaColor.write(); + searchLinesColor.write(); + searchEdgesColor.write(); + resultColor.write(); + if (overlayGroupName != null) { + byte[] overlayGroupName_bytes; + try { + overlayGroupName_bytes = overlayGroupName.getBytes("UTF-8"); + } catch (UnsupportedEncodingException e) { + overlayGroupName_bytes = new byte[0]; + } + overlayGroupName_buf = ByteBuffer.allocateDirect(overlayGroupName_bytes.length + 1); + putBytes(overlayGroupName_buf, overlayGroupName_bytes, 0, overlayGroupName_bytes.length) + .put(overlayGroupName_bytes.length, (byte) 0); + } + putPointer(backing, 36, overlayGroupName == null ? 0 + : getByteBufferAddress(overlayGroupName_buf)); + edgeOptions.write(); + } + + public int size() { + return 64; + } + } + + public static class ConcentricEdgeFitOptions extends DisposedStruct { + public int maxRadius; // Specifies the acceptable distance, in pixels, that + // a point determined to belong to the circle can be + // from the perimeter of the circle. + public double stepSize; // The sampling factor that determines the gap + // between the rake lines. + public RakeProcessType processType; // Method used to process the data + // extracted for edge detection. + + private void init() { + + } + + public ConcentricEdgeFitOptions() { + super(24); + init(); + } + + public ConcentricEdgeFitOptions(int maxRadius, double stepSize, RakeProcessType processType) { + super(24); + this.maxRadius = maxRadius; + this.stepSize = stepSize; + this.processType = processType; + } + + protected ConcentricEdgeFitOptions(ByteBuffer backing, int offset) { + super(backing, offset, 24); + init(); + } + + protected ConcentricEdgeFitOptions(long nativeObj, boolean owned) { + super(nativeObj, owned, 24); + init(); + } + + protected void setBuffer(ByteBuffer backing, int offset) { + super.setBuffer(backing, offset, 24); + } + + public void read() { + maxRadius = backing.getInt(0); + stepSize = backing.getDouble(8); + processType = RakeProcessType.fromValue(backing.getInt(16)); + } + + public void write() { + backing.putInt(0, maxRadius); + backing.putDouble(8, stepSize); + if (processType != null) + backing.putInt(16, processType.getValue()); + } + + public int size() { + return 24; + } + } + + public static class FindConcentricEdgeReport extends DisposedStruct { + public PointFloat startPt; // Pixel Coordinates for starting point of the + // edge. + public PointFloat endPt; // Pixel Coordinates for end point of the edge. + public PointFloat startPtCalibrated; // Real world Coordinates for starting + // point of the edge. + public PointFloat endPtCalibrated; // Real world Coordinates for end point + // of the edge. + public double angle; // Angle of the edge found. + public double angleCalibrated; // Calibrated angle of the edge found. + public double straightness; // The straightness value of the detected + // straight edge. + public double avgStrength; // Average strength of the egde found. + public double avgSNR; // Average SNR(Signal to Noise Ratio) for the edge + // found. + public int lineFound; // If the edge is found or not. + + private void init() { + startPt = new PointFloat(backing, 0); + endPt = new PointFloat(backing, 8); + startPtCalibrated = new PointFloat(backing, 16); + endPtCalibrated = new PointFloat(backing, 24); + } + + public FindConcentricEdgeReport() { + super(80); + init(); + } + + public FindConcentricEdgeReport(PointFloat startPt, PointFloat endPt, + PointFloat startPtCalibrated, PointFloat endPtCalibrated, double angle, + double angleCalibrated, double straightness, double avgStrength, double avgSNR, + int lineFound) { + super(80); + this.startPt = startPt; + this.endPt = endPt; + this.startPtCalibrated = startPtCalibrated; + this.endPtCalibrated = endPtCalibrated; + this.angle = angle; + this.angleCalibrated = angleCalibrated; + this.straightness = straightness; + this.avgStrength = avgStrength; + this.avgSNR = avgSNR; + this.lineFound = lineFound; + } + + protected FindConcentricEdgeReport(ByteBuffer backing, int offset) { + super(backing, offset, 80); + init(); + } + + protected FindConcentricEdgeReport(long nativeObj, boolean owned) { + super(nativeObj, owned, 80); + init(); + } + + protected void setBuffer(ByteBuffer backing, int offset) { + super.setBuffer(backing, offset, 80); + } + + public void read() { + startPt.read(); + endPt.read(); + startPtCalibrated.read(); + endPtCalibrated.read(); + angle = backing.getDouble(32); + angleCalibrated = backing.getDouble(40); + straightness = backing.getDouble(48); + avgStrength = backing.getDouble(56); + avgSNR = backing.getDouble(64); + lineFound = backing.getInt(72); + } + + public void write() { + startPt.write(); + endPt.write(); + startPtCalibrated.write(); + endPtCalibrated.write(); + backing.putDouble(32, angle); + backing.putDouble(40, angleCalibrated); + backing.putDouble(48, straightness); + backing.putDouble(56, avgStrength); + backing.putDouble(64, avgSNR); + backing.putInt(72, lineFound); + } + + public int size() { + return 80; + } + } + + public static class FindCircularEdgeReport extends DisposedStruct { + public PointFloat centerCalibrated; // Real world Coordinates of the Center. + public double radiusCalibrated; // Real world radius of the Circular Edge + // found. + public PointFloat center; // Pixel Coordinates of the Center. + public double radius; // Radius in pixels of the Circular Edge found. + public double roundness; // The roundness of the calculated circular edge. + public double avgStrength; // Average strength of the egde found. + public double avgSNR; // Average SNR(Signal to Noise Ratio) for the edge + // found. + public int circleFound; // If the circlular edge is found or not. + + private void init() { + centerCalibrated = new PointFloat(backing, 0); + center = new PointFloat(backing, 16); + } + + public FindCircularEdgeReport() { + super(64); + init(); + } + + public FindCircularEdgeReport(PointFloat centerCalibrated, double radiusCalibrated, + PointFloat center, double radius, double roundness, double avgStrength, double avgSNR, + int circleFound) { + super(64); + this.centerCalibrated = centerCalibrated; + this.radiusCalibrated = radiusCalibrated; + this.center = center; + this.radius = radius; + this.roundness = roundness; + this.avgStrength = avgStrength; + this.avgSNR = avgSNR; + this.circleFound = circleFound; + } + + protected FindCircularEdgeReport(ByteBuffer backing, int offset) { + super(backing, offset, 64); + init(); + } + + protected FindCircularEdgeReport(long nativeObj, boolean owned) { + super(nativeObj, owned, 64); + init(); + } + + protected void setBuffer(ByteBuffer backing, int offset) { + super.setBuffer(backing, offset, 64); + } + + public void read() { + centerCalibrated.read(); + radiusCalibrated = backing.getDouble(8); + center.read(); + radius = backing.getDouble(24); + roundness = backing.getDouble(32); + avgStrength = backing.getDouble(40); + avgSNR = backing.getDouble(48); + circleFound = backing.getInt(56); + } + + public void write() { + centerCalibrated.write(); + backing.putDouble(8, radiusCalibrated); + center.write(); + backing.putDouble(24, radius); + backing.putDouble(32, roundness); + backing.putDouble(40, avgStrength); + backing.putDouble(48, avgSNR); + backing.putInt(56, circleFound); + } + + public int size() { + return 64; + } + } + + public static class WindowSize extends DisposedStruct { + public int x; // Window lenght on X direction. + public int y; // Window lenght on Y direction. + public int stepSize; // Distance between windows. + + private void init() { + + } + + public WindowSize() { + super(12); + init(); + } + + public WindowSize(int x, int y, int stepSize) { + super(12); + this.x = x; + this.y = y; + this.stepSize = stepSize; + } + + protected WindowSize(ByteBuffer backing, int offset) { + super(backing, offset, 12); + init(); + } + + protected WindowSize(long nativeObj, boolean owned) { + super(nativeObj, owned, 12); + init(); + } + + protected void setBuffer(ByteBuffer backing, int offset) { + super.setBuffer(backing, offset, 12); + } + + public void read() { + x = backing.getInt(0); + y = backing.getInt(4); + stepSize = backing.getInt(8); + } + + public void write() { + backing.putInt(0, x); + backing.putInt(4, y); + backing.putInt(8, stepSize); + } + + public int size() { + return 12; + } + } + + public static class DisplacementVector extends DisposedStruct { + public int x; // length on X direction. + public int y; // length on Y direction. + + private void init() { + + } + + public DisplacementVector() { + super(8); + init(); + } + + public DisplacementVector(int x, int y) { + super(8); + this.x = x; + this.y = y; + } + + protected DisplacementVector(ByteBuffer backing, int offset) { + super(backing, offset, 8); + init(); + } + + protected DisplacementVector(long nativeObj, boolean owned) { + super(nativeObj, owned, 8); + init(); + } + + protected void setBuffer(ByteBuffer backing, int offset) { + super.setBuffer(backing, offset, 8); + } + + public void read() { + x = backing.getInt(0); + y = backing.getInt(4); + } + + public void write() { + backing.putInt(0, x); + backing.putInt(4, y); + } + + public int size() { + return 8; + } + } + + public static class WaveletOptions extends DisposedStruct { + public WaveletType typeOfWavelet; // Type of wavelet(db, bior. + public float minEnergy; // Minimum Energy in the bands to consider for + // texture defect detection. + + private void init() { + + } + + public WaveletOptions() { + super(8); + init(); + } + + public WaveletOptions(WaveletType typeOfWavelet, double minEnergy) { + super(8); + this.typeOfWavelet = typeOfWavelet; + this.minEnergy = (float) minEnergy; + } + + protected WaveletOptions(ByteBuffer backing, int offset) { + super(backing, offset, 8); + init(); + } + + protected WaveletOptions(long nativeObj, boolean owned) { + super(nativeObj, owned, 8); + init(); + } + + protected void setBuffer(ByteBuffer backing, int offset) { + super.setBuffer(backing, offset, 8); + } + + public void read() { + typeOfWavelet = WaveletType.fromValue(backing.getInt(0)); + minEnergy = backing.getFloat(4); + } + + public void write() { + if (typeOfWavelet != null) + backing.putInt(0, typeOfWavelet.getValue()); + backing.putFloat(4, minEnergy); + } + + public int size() { + return 8; + } + } + + public static class CooccurrenceOptions extends DisposedStruct { + public int level; // Level/size of matrix. + public DisplacementVector displacement; // Displacemnet between pixels to + // accumulate the matrix. + + private void init() { + displacement = new DisplacementVector(backing, 4); + } + + public CooccurrenceOptions() { + super(12); + init(); + } + + public CooccurrenceOptions(int level, DisplacementVector displacement) { + super(12); + this.level = level; + this.displacement = displacement; + } + + protected CooccurrenceOptions(ByteBuffer backing, int offset) { + super(backing, offset, 12); + init(); + } + + protected CooccurrenceOptions(long nativeObj, boolean owned) { + super(nativeObj, owned, 12); + init(); + } + + protected void setBuffer(ByteBuffer backing, int offset) { + super.setBuffer(backing, offset, 12); + } + + public void read() { + level = backing.getInt(0); + displacement.read(); + } + + public void write() { + backing.putInt(0, level); + displacement.write(); + } + + public int size() { + return 12; + } + } + + public static class ParticleClassifierLocalThresholdOptions extends DisposedStruct { + public LocalThresholdMethod method; // Specifies the local thresholding + // method the function uses. + public ParticleType particleType; // Specifies what kind of particles to + // look for. + public int windowWidth; // The width of the rectangular window around the + // pixel on which the function performs the local + // threshold. + public int windowHeight; // The height of the rectangular window around the + // pixel on which the function performs the local + // threshold. + public double deviationWeight; // Specifies the k constant used in the + // Niblack local thresholding algorithm, + // which determines the weight applied to the + // variance calculation. + + private void init() { + + } + + public ParticleClassifierLocalThresholdOptions() { + super(24); + init(); + } + + public ParticleClassifierLocalThresholdOptions(LocalThresholdMethod method, + ParticleType particleType, int windowWidth, int windowHeight, double deviationWeight) { + super(24); + this.method = method; + this.particleType = particleType; + this.windowWidth = windowWidth; + this.windowHeight = windowHeight; + this.deviationWeight = deviationWeight; + } + + protected ParticleClassifierLocalThresholdOptions(ByteBuffer backing, int offset) { + super(backing, offset, 24); + init(); + } + + protected ParticleClassifierLocalThresholdOptions(long nativeObj, boolean owned) { + super(nativeObj, owned, 24); + init(); + } + + protected void setBuffer(ByteBuffer backing, int offset) { + super.setBuffer(backing, offset, 24); + } + + public void read() { + method = LocalThresholdMethod.fromValue(backing.getInt(0)); + particleType = ParticleType.fromValue(backing.getInt(4)); + windowWidth = backing.getInt(8); + windowHeight = backing.getInt(12); + deviationWeight = backing.getDouble(16); + } + + public void write() { + if (method != null) + backing.putInt(0, method.getValue()); + if (particleType != null) + backing.putInt(4, particleType.getValue()); + backing.putInt(8, windowWidth); + backing.putInt(12, windowHeight); + backing.putDouble(16, deviationWeight); + } + + public int size() { + return 24; + } + } + + public static class RangeFloat extends DisposedStruct { + public float minValue; // The minimum value of the range. + public float maxValue; // The maximum value of the range. + + private void init() { + + } + + public RangeFloat() { + super(8); + init(); + } + + public RangeFloat(double minValue, double maxValue) { + super(8); + this.minValue = (float) minValue; + this.maxValue = (float) maxValue; + } + + protected RangeFloat(ByteBuffer backing, int offset) { + super(backing, offset, 8); + init(); + } + + protected RangeFloat(long nativeObj, boolean owned) { + super(nativeObj, owned, 8); + init(); + } + + protected void setBuffer(ByteBuffer backing, int offset) { + super.setBuffer(backing, offset, 8); + } + + public void read() { + minValue = backing.getFloat(0); + maxValue = backing.getFloat(4); + } + + public void write() { + backing.putFloat(0, minValue); + backing.putFloat(4, maxValue); + } + + public int size() { + return 8; + } + } + + public static class ParticleClassifierAutoThresholdOptions extends DisposedStruct { + public ThresholdMethod method; // The method for binary thresholding, which + // specifies how to calculate the classes. + public ParticleType particleType; // Specifies what kind of particles to + // look for. + public RangeFloat limits; // The limits on the automatic threshold range. + + private void init() { + limits = new RangeFloat(backing, 8); + } + + public ParticleClassifierAutoThresholdOptions() { + super(16); + init(); + } + + public ParticleClassifierAutoThresholdOptions(ThresholdMethod method, + ParticleType particleType, RangeFloat limits) { + super(16); + this.method = method; + this.particleType = particleType; + this.limits = limits; + } + + protected ParticleClassifierAutoThresholdOptions(ByteBuffer backing, int offset) { + super(backing, offset, 16); + init(); + } + + protected ParticleClassifierAutoThresholdOptions(long nativeObj, boolean owned) { + super(nativeObj, owned, 16); + init(); + } + + protected void setBuffer(ByteBuffer backing, int offset) { + super.setBuffer(backing, offset, 16); + } + + public void read() { + method = ThresholdMethod.fromValue(backing.getInt(0)); + particleType = ParticleType.fromValue(backing.getInt(4)); + limits.read(); + } + + public void write() { + if (method != null) + backing.putInt(0, method.getValue()); + if (particleType != null) + backing.putInt(4, particleType.getValue()); + limits.write(); + } + + public int size() { + return 16; + } + } + + public static class ParticleClassifierPreprocessingOptions2 extends DisposedStruct { + public ParticleClassifierThresholdType thresholdType; // The type of + // threshold to + // perform on the + // image. + public RangeFloat manualThresholdRange; // The range of pixels to keep if + // manually thresholding the image. + public ParticleClassifierAutoThresholdOptions autoThresholdOptions; // The + // options + // used + // to + // auto + // threshold + // the + // image. + public ParticleClassifierLocalThresholdOptions localThresholdOptions; // The + // options + // used + // to + // local + // threshold + // the + // image. + public int rejectBorder; // Set this element to TRUE to reject border + // particles. + public int numErosions; // The number of erosions to perform. + + private void init() { + manualThresholdRange = new RangeFloat(backing, 4); + autoThresholdOptions = new ParticleClassifierAutoThresholdOptions(backing, 12); + localThresholdOptions = new ParticleClassifierLocalThresholdOptions(backing, 32); + } + + public ParticleClassifierPreprocessingOptions2() { + super(64); + init(); + } + + public ParticleClassifierPreprocessingOptions2(ParticleClassifierThresholdType thresholdType, + RangeFloat manualThresholdRange, + ParticleClassifierAutoThresholdOptions autoThresholdOptions, + ParticleClassifierLocalThresholdOptions localThresholdOptions, int rejectBorder, + int numErosions) { + super(64); + this.thresholdType = thresholdType; + this.manualThresholdRange = manualThresholdRange; + this.autoThresholdOptions = autoThresholdOptions; + this.localThresholdOptions = localThresholdOptions; + this.rejectBorder = rejectBorder; + this.numErosions = numErosions; + } + + protected ParticleClassifierPreprocessingOptions2(ByteBuffer backing, int offset) { + super(backing, offset, 64); + init(); + } + + protected ParticleClassifierPreprocessingOptions2(long nativeObj, boolean owned) { + super(nativeObj, owned, 64); + init(); + } + + protected void setBuffer(ByteBuffer backing, int offset) { + super.setBuffer(backing, offset, 64); + } + + public void read() { + thresholdType = ParticleClassifierThresholdType.fromValue(backing.getInt(0)); + manualThresholdRange.read(); + autoThresholdOptions.read(); + localThresholdOptions.read(); + rejectBorder = backing.getInt(56); + numErosions = backing.getInt(60); + } + + public void write() { + if (thresholdType != null) + backing.putInt(0, thresholdType.getValue()); + manualThresholdRange.write(); + autoThresholdOptions.write(); + localThresholdOptions.write(); + backing.putInt(56, rejectBorder); + backing.putInt(60, numErosions); + } + + public int size() { + return 64; + } + } + + public static class MeasureParticlesReport extends DisposedStruct { + public int numParticles; // The number of particles on which measurements + // were taken. + public int numMeasurements; // The number of measurements taken. + + private void init() { + + } + + public MeasureParticlesReport() { + super(16); + init(); + } + + public MeasureParticlesReport(int numParticles, int numMeasurements) { + super(16); + this.numParticles = numParticles; + this.numMeasurements = numMeasurements; + } + + protected MeasureParticlesReport(ByteBuffer backing, int offset) { + super(backing, offset, 16); + init(); + } + + protected MeasureParticlesReport(long nativeObj, boolean owned) { + super(nativeObj, owned, 16); + init(); + } + + protected void setBuffer(ByteBuffer backing, int offset) { + super.setBuffer(backing, offset, 16); + } + + public void read() { + numParticles = backing.getInt(8); + numMeasurements = backing.getInt(12); + } + + public void write() { + backing.putInt(8, numParticles); + backing.putInt(12, numMeasurements); + } + + public int size() { + return 16; + } + } + + public static class GeometricPatternMatch3 extends DisposedStruct { + public PointFloat position; // The location of the origin of the template in + // the match. + public float rotation; // The rotation of the match relative to the template + // image, in degrees. + public float scale; // The size of the match relative to the size of the + // template image, expressed as a percentage. + public float score; // The accuracy of the match. + public PointFloat[] corner; // An array of four points describing the + // rectangle surrounding the template image. + public int inverse; // This element is TRUE if the match is an inverse of + // the template image. + public float occlusion; // The percentage of the match that is occluded. + public float templateMatchCurveScore; // The accuracy of the match obtained + // by comparing the template curves to + // the curves in the match region. + public float matchTemplateCurveScore; // The accuracy of the match obtained + // by comparing the curves in the + // match region to the template + // curves. + public float correlationScore; // The accuracy of the match obtained by + // comparing the template image to the match + // region using a correlation metric that + // compares the two regions as a function of + // their pixel values. + public PointFloat calibratedPosition; // The location of the origin of the + // template in the match. + public float calibratedRotation; // The rotation of the match relative to + // the template image, in degrees. + public PointFloat[] calibratedCorner; // An array of four points describing + // the rectangle surrounding the + // template image. + + private void init() { + position = new PointFloat(backing, 0); + corner = new PointFloat[4]; + + for (int i = 0, off = 20; i < 4; i++, off += 8) + corner[i] = new PointFloat(backing, off); + calibratedPosition = new PointFloat(backing, 72); + calibratedCorner = new PointFloat[4]; + + for (int i = 0, off = 84; i < 4; i++, off += 8) + calibratedCorner[i] = new PointFloat(backing, off); + } + + public GeometricPatternMatch3() { + super(116); + init(); + } + + public GeometricPatternMatch3(PointFloat position, double rotation, double scale, double score, + PointFloat[] corner, int inverse, double occlusion, double templateMatchCurveScore, + double matchTemplateCurveScore, double correlationScore, PointFloat calibratedPosition, + double calibratedRotation, PointFloat[] calibratedCorner) { + super(116); + this.position = position; + this.rotation = (float) rotation; + this.scale = (float) scale; + this.score = (float) score; + this.corner = corner; + this.inverse = inverse; + this.occlusion = (float) occlusion; + this.templateMatchCurveScore = (float) templateMatchCurveScore; + this.matchTemplateCurveScore = (float) matchTemplateCurveScore; + this.correlationScore = (float) correlationScore; + this.calibratedPosition = calibratedPosition; + this.calibratedRotation = (float) calibratedRotation; + this.calibratedCorner = calibratedCorner; + } + + protected GeometricPatternMatch3(ByteBuffer backing, int offset) { + super(backing, offset, 116); + init(); + } + + protected GeometricPatternMatch3(long nativeObj, boolean owned) { + super(nativeObj, owned, 116); + init(); + } + + protected void setBuffer(ByteBuffer backing, int offset) { + super.setBuffer(backing, offset, 116); + } + + public void read() { + position.read(); + rotation = backing.getFloat(8); + scale = backing.getFloat(12); + score = backing.getFloat(16); + for (PointFloat it : corner) { + it.read(); + } + inverse = backing.getInt(52); + occlusion = backing.getFloat(56); + templateMatchCurveScore = backing.getFloat(60); + matchTemplateCurveScore = backing.getFloat(64); + correlationScore = backing.getFloat(68); + calibratedPosition.read(); + calibratedRotation = backing.getFloat(80); + for (PointFloat it : calibratedCorner) { + it.read(); + } + } + + public void write() { + position.write(); + backing.putFloat(8, rotation); + backing.putFloat(12, scale); + backing.putFloat(16, score); + for (PointFloat it : corner) { + it.write(); + } + backing.putInt(52, inverse); + backing.putFloat(56, occlusion); + backing.putFloat(60, templateMatchCurveScore); + backing.putFloat(64, matchTemplateCurveScore); + backing.putFloat(68, correlationScore); + calibratedPosition.write(); + backing.putFloat(80, calibratedRotation); + for (PointFloat it : calibratedCorner) { + it.write(); + } + } + + public int size() { + return 116; + } + } + + public static class MatchGeometricPatternAdvancedOptions3 extends DisposedStruct { + public int subpixelIterations; // Specifies the maximum number of + // incremental improvements used to refine + // matches with subpixel information. + public double subpixelTolerance; // Specifies the maximum amount of change, + // in pixels, between consecutive + // incremental improvements in the match + // position before the function stops + // refining the match position. + public int initialMatchListLength; // Specifies the maximum size of the + // match list. + public int targetTemplateCurveScore; // Set this element to TRUE to specify + // that the function should calculate + // the match curve to template curve + // score and return it for each match + // result. + public int correlationScore; // Set this element to TRUE to specify that the + // function should calculate the correlation + // score and return it for each match result. + public double minMatchSeparationDistance; // Specifies the minimum + // separation distance, in pixels, + // between the origins of two + // matches that have unique + // positions. + public double minMatchSeparationAngle; // Specifies the minimum angular + // difference, in degrees, between + // two matches that have unique + // angles. + public double minMatchSeparationScale; // Specifies the minimum difference + // in scale, expressed as a + // percentage, between two matches + // that have unique scales. + public double maxMatchOverlap; // Specifies the maximum amount of overlap, + // expressed as a percentage, allowed between + // the bounding rectangles of two unique + // matches. + public int coarseResult; // Specifies whether you want the function to spend + // less time accurately estimating the location of + // a match. + public int enableCalibrationSupport; // Set this element to TRUE to specify + // the algorithm treat the inspection + // image as a calibrated image. + public ContrastMode enableContrastReversal; // Use this element to specify + // the contrast of the matches + // to search for in the image. + public GeometricMatchingSearchStrategy matchStrategy; // Specifies the + // aggressiveness of + // the search + // strategy. + public int refineMatchFactor; // Specifies the factor that is applied to the + // number of matches requested by the user to + // determine the number of matches that are + // refined at the initial matching stage. + public int subpixelMatchFactor; // Specifies the factor that is applied to + // the number of matches requested by the + // user to determine the number of matches + // that are evaluated at the final subpixel + // matching stage. + + private void init() { + + } + + public MatchGeometricPatternAdvancedOptions3() { + super(88); + init(); + } + + public MatchGeometricPatternAdvancedOptions3(int subpixelIterations, double subpixelTolerance, + int initialMatchListLength, int targetTemplateCurveScore, int correlationScore, + double minMatchSeparationDistance, double minMatchSeparationAngle, + double minMatchSeparationScale, double maxMatchOverlap, int coarseResult, + int enableCalibrationSupport, ContrastMode enableContrastReversal, + GeometricMatchingSearchStrategy matchStrategy, int refineMatchFactor, + int subpixelMatchFactor) { + super(88); + this.subpixelIterations = subpixelIterations; + this.subpixelTolerance = subpixelTolerance; + this.initialMatchListLength = initialMatchListLength; + this.targetTemplateCurveScore = targetTemplateCurveScore; + this.correlationScore = correlationScore; + this.minMatchSeparationDistance = minMatchSeparationDistance; + this.minMatchSeparationAngle = minMatchSeparationAngle; + this.minMatchSeparationScale = minMatchSeparationScale; + this.maxMatchOverlap = maxMatchOverlap; + this.coarseResult = coarseResult; + this.enableCalibrationSupport = enableCalibrationSupport; + this.enableContrastReversal = enableContrastReversal; + this.matchStrategy = matchStrategy; + this.refineMatchFactor = refineMatchFactor; + this.subpixelMatchFactor = subpixelMatchFactor; + } + + protected MatchGeometricPatternAdvancedOptions3(ByteBuffer backing, int offset) { + super(backing, offset, 88); + init(); + } + + protected MatchGeometricPatternAdvancedOptions3(long nativeObj, boolean owned) { + super(nativeObj, owned, 88); + init(); + } + + protected void setBuffer(ByteBuffer backing, int offset) { + super.setBuffer(backing, offset, 88); + } + + public void read() { + subpixelIterations = backing.getInt(0); + subpixelTolerance = backing.getDouble(8); + initialMatchListLength = backing.getInt(16); + targetTemplateCurveScore = backing.getInt(20); + correlationScore = backing.getInt(24); + minMatchSeparationDistance = backing.getDouble(32); + minMatchSeparationAngle = backing.getDouble(40); + minMatchSeparationScale = backing.getDouble(48); + maxMatchOverlap = backing.getDouble(56); + coarseResult = backing.getInt(64); + enableCalibrationSupport = backing.getInt(68); + enableContrastReversal = ContrastMode.fromValue(backing.getInt(72)); + matchStrategy = GeometricMatchingSearchStrategy.fromValue(backing.getInt(76)); + refineMatchFactor = backing.getInt(80); + subpixelMatchFactor = backing.getInt(84); + } + + public void write() { + backing.putInt(0, subpixelIterations); + backing.putDouble(8, subpixelTolerance); + backing.putInt(16, initialMatchListLength); + backing.putInt(20, targetTemplateCurveScore); + backing.putInt(24, correlationScore); + backing.putDouble(32, minMatchSeparationDistance); + backing.putDouble(40, minMatchSeparationAngle); + backing.putDouble(48, minMatchSeparationScale); + backing.putDouble(56, maxMatchOverlap); + backing.putInt(64, coarseResult); + backing.putInt(68, enableCalibrationSupport); + if (enableContrastReversal != null) + backing.putInt(72, enableContrastReversal.getValue()); + if (matchStrategy != null) + backing.putInt(76, matchStrategy.getValue()); + backing.putInt(80, refineMatchFactor); + backing.putInt(84, subpixelMatchFactor); + } + + public int size() { + return 88; + } + } + + public static class ColorOptions extends DisposedStruct { + public ColorClassificationResolution colorClassificationResolution; // Specifies + // the + // color + // resolution + // of + // the + // classifier. + public int useLuminance; // Specifies if the luminance band is going to be + // used in the feature vector. + public ColorMode colorMode; // Specifies the color mode of the classifier. + + private void init() { + + } + + public ColorOptions() { + super(12); + init(); + } + + public ColorOptions(ColorClassificationResolution colorClassificationResolution, + int useLuminance, ColorMode colorMode) { + super(12); + this.colorClassificationResolution = colorClassificationResolution; + this.useLuminance = useLuminance; + this.colorMode = colorMode; + } + + protected ColorOptions(ByteBuffer backing, int offset) { + super(backing, offset, 12); + init(); + } + + protected ColorOptions(long nativeObj, boolean owned) { + super(nativeObj, owned, 12); + init(); + } + + protected void setBuffer(ByteBuffer backing, int offset) { + super.setBuffer(backing, offset, 12); + } + + public void read() { + colorClassificationResolution = ColorClassificationResolution.fromValue(backing.getInt(0)); + useLuminance = backing.getInt(4); + colorMode = ColorMode.fromValue(backing.getInt(8)); + } + + public void write() { + if (colorClassificationResolution != null) + backing.putInt(0, colorClassificationResolution.getValue()); + backing.putInt(4, useLuminance); + if (colorMode != null) + backing.putInt(8, colorMode.getValue()); + } + + public int size() { + return 12; + } + } + + public static class SampleScore extends DisposedStruct { + public String className; // The name of the class. + public float distance; // The distance from the item to this class. + public int index; // index of this sample. + private ByteBuffer className_buf; + + private void init() { + + } + + public SampleScore() { + super(12); + init(); + } + + public SampleScore(String className, double distance, int index) { + super(12); + this.className = className; + this.distance = (float) distance; + this.index = index; + } + + protected SampleScore(ByteBuffer backing, int offset) { + super(backing, offset, 12); + init(); + } + + protected SampleScore(long nativeObj, boolean owned) { + super(nativeObj, owned, 12); + init(); + } + + protected void setBuffer(ByteBuffer backing, int offset) { + super.setBuffer(backing, offset, 12); + } + + public void read() { + long className_addr = getPointer(backing, 0); + if (className_addr == 0) + className = null; + else { + ByteBuffer bb = newDirectByteBuffer(className_addr, 1000); // FIXME + while (bb.get() != 0) { + } + byte[] bytes = new byte[bb.position() - 1]; + getBytes(bb, bytes, 0, bytes.length); + try { + className = new String(bytes, "UTF-8"); + } catch (UnsupportedEncodingException e) { + className = ""; + } + } + + distance = backing.getFloat(4); + index = backing.getInt(8); + } + + public void write() { + if (className != null) { + byte[] className_bytes; + try { + className_bytes = className.getBytes("UTF-8"); + } catch (UnsupportedEncodingException e) { + className_bytes = new byte[0]; + } + className_buf = ByteBuffer.allocateDirect(className_bytes.length + 1); + putBytes(className_buf, className_bytes, 0, className_bytes.length).put( + className_bytes.length, (byte) 0); + } + putPointer(backing, 0, className == null ? 0 : getByteBufferAddress(className_buf)); + backing.putFloat(4, distance); + backing.putInt(8, index); + } + + public int size() { + return 12; + } + } + + public static class ClassifierReportAdvanced extends DisposedStruct { + public String bestClassName; // The name of the best class for the sample. + public float classificationScore; // The similarity of the sample and the + // two closest classes in the classifier. + public float identificationScore; // The similarity of the sample and the + // assigned class. + public ClassScore[] allScores; // All classes and their scores. + public SampleScore[] sampleScores; // All samples and their scores. + private ByteBuffer bestClassName_buf; + private ByteBuffer allScores_buf; + private ByteBuffer sampleScores_buf; + + private void init() { + allScores = new ClassScore[0]; + sampleScores = new SampleScore[0]; + } + + public ClassifierReportAdvanced() { + super(28); + init(); + } + + public ClassifierReportAdvanced(String bestClassName, double classificationScore, + double identificationScore, ClassScore[] allScores, SampleScore[] sampleScores) { + super(28); + this.bestClassName = bestClassName; + this.classificationScore = (float) classificationScore; + this.identificationScore = (float) identificationScore; + this.allScores = allScores; + this.sampleScores = sampleScores; + } + + protected ClassifierReportAdvanced(ByteBuffer backing, int offset) { + super(backing, offset, 28); + init(); + } + + protected ClassifierReportAdvanced(long nativeObj, boolean owned) { + super(nativeObj, owned, 28); + init(); + } + + protected void setBuffer(ByteBuffer backing, int offset) { + super.setBuffer(backing, offset, 28); + } + + public void read() { + long bestClassName_addr = getPointer(backing, 0); + if (bestClassName_addr == 0) + bestClassName = null; + else { + ByteBuffer bb = newDirectByteBuffer(bestClassName_addr, 1000); // FIXME + while (bb.get() != 0) { + } + byte[] bytes = new byte[bb.position() - 1]; + getBytes(bb, bytes, 0, bytes.length); + try { + bestClassName = new String(bytes, "UTF-8"); + } catch (UnsupportedEncodingException e) { + bestClassName = ""; + } + } + + classificationScore = backing.getFloat(4); + identificationScore = backing.getFloat(8); + int allScores_allScoresSize = backing.getInt(16); + long allScores_addr = getPointer(backing, 12); + allScores = new ClassScore[allScores_allScoresSize]; + if (allScores_allScoresSize > 0 && allScores_addr != 0) { + ByteBuffer bb = newDirectByteBuffer(allScores_addr, allScores_allScoresSize * 8); + for (int i = 0, off = 0; i < allScores_allScoresSize; i++, off += 8) { + allScores[i] = new ClassScore(bb, off); + allScores[i].read(); + } + } + int sampleScores_sampleScoresSize = backing.getInt(24); + long sampleScores_addr = getPointer(backing, 20); + sampleScores = new SampleScore[sampleScores_sampleScoresSize]; + if (sampleScores_sampleScoresSize > 0 && sampleScores_addr != 0) { + ByteBuffer bb = newDirectByteBuffer(sampleScores_addr, sampleScores_sampleScoresSize * 12); + for (int i = 0, off = 0; i < sampleScores_sampleScoresSize; i++, off += 12) { + sampleScores[i] = new SampleScore(bb, off); + sampleScores[i].read(); + } + } + } + + public void write() { + if (bestClassName != null) { + byte[] bestClassName_bytes; + try { + bestClassName_bytes = bestClassName.getBytes("UTF-8"); + } catch (UnsupportedEncodingException e) { + bestClassName_bytes = new byte[0]; + } + bestClassName_buf = ByteBuffer.allocateDirect(bestClassName_bytes.length + 1); + putBytes(bestClassName_buf, bestClassName_bytes, 0, bestClassName_bytes.length).put( + bestClassName_bytes.length, (byte) 0); + } + putPointer(backing, 0, bestClassName == null ? 0 : getByteBufferAddress(bestClassName_buf)); + backing.putFloat(4, classificationScore); + backing.putFloat(8, identificationScore); + allScores_buf = + ByteBuffer.allocateDirect(allScores.length * 8).order(ByteOrder.nativeOrder()); + for (int i = 0, off = 0; i < allScores.length; i++, off += 8) { + allScores[i].setBuffer(allScores_buf, off); + allScores[i].write(); + } + backing.putInt(16, allScores.length); + putPointer(backing, 12, allScores_buf); + sampleScores_buf = + ByteBuffer.allocateDirect(sampleScores.length * 12).order(ByteOrder.nativeOrder()); + for (int i = 0, off = 0; i < sampleScores.length; i++, off += 12) { + sampleScores[i].setBuffer(sampleScores_buf, off); + sampleScores[i].write(); + } + backing.putInt(24, sampleScores.length); + putPointer(backing, 20, sampleScores_buf); + } + + public int size() { + return 28; + } + } + + public static class LearnGeometricPatternAdvancedOptions2 extends DisposedStruct { + public double minScaleFactor; // Specifies the minimum scale factor that the + // template is learned for. + public double maxScaleFactor; // Specifies the maximum scale factor the + // template is learned for. + public double minRotationAngleValue; // Specifies the minimum rotation angle + // the template is learned for. + public double maxRotationAngleValue; // Specifies the maximum rotation angle + // the template is learned for. + public int imageSamplingFactor; // Specifies the factor that is used to + // subsample the template and the image for + // the initial matching phase. + + private void init() { + + } + + public LearnGeometricPatternAdvancedOptions2() { + super(40); + init(); + } + + public LearnGeometricPatternAdvancedOptions2(double minScaleFactor, double maxScaleFactor, + double minRotationAngleValue, double maxRotationAngleValue, int imageSamplingFactor) { + super(40); + this.minScaleFactor = minScaleFactor; + this.maxScaleFactor = maxScaleFactor; + this.minRotationAngleValue = minRotationAngleValue; + this.maxRotationAngleValue = maxRotationAngleValue; + this.imageSamplingFactor = imageSamplingFactor; + } + + protected LearnGeometricPatternAdvancedOptions2(ByteBuffer backing, int offset) { + super(backing, offset, 40); + init(); + } + + protected LearnGeometricPatternAdvancedOptions2(long nativeObj, boolean owned) { + super(nativeObj, owned, 40); + init(); + } + + protected void setBuffer(ByteBuffer backing, int offset) { + super.setBuffer(backing, offset, 40); + } + + public void read() { + minScaleFactor = backing.getDouble(0); + maxScaleFactor = backing.getDouble(8); + minRotationAngleValue = backing.getDouble(16); + maxRotationAngleValue = backing.getDouble(24); + imageSamplingFactor = backing.getInt(32); + } + + public void write() { + backing.putDouble(0, minScaleFactor); + backing.putDouble(8, maxScaleFactor); + backing.putDouble(16, minRotationAngleValue); + backing.putDouble(24, maxRotationAngleValue); + backing.putInt(32, imageSamplingFactor); + } + + public int size() { + return 40; + } + } + + public static class ParticleFilterOptions2 extends DisposedStruct { + public int rejectMatches; // Set this parameter to TRUE to transfer only + // those particles that do not meet all the + // criteria. + public int rejectBorder; // Set this element to TRUE to reject border + // particles. + public int fillHoles; // Set this element to TRUE to fill holes in + // particles. + public int connectivity8; // Set this parameter to TRUE to use + // connectivity-8 to determine whether particles + // are touching. + + private void init() { + + } + + public ParticleFilterOptions2() { + super(16); + init(); + } + + public ParticleFilterOptions2(int rejectMatches, int rejectBorder, int fillHoles, + int connectivity8) { + super(16); + this.rejectMatches = rejectMatches; + this.rejectBorder = rejectBorder; + this.fillHoles = fillHoles; + this.connectivity8 = connectivity8; + } + + protected ParticleFilterOptions2(ByteBuffer backing, int offset) { + super(backing, offset, 16); + init(); + } + + protected ParticleFilterOptions2(long nativeObj, boolean owned) { + super(nativeObj, owned, 16); + init(); + } + + protected void setBuffer(ByteBuffer backing, int offset) { + super.setBuffer(backing, offset, 16); + } + + public void read() { + rejectMatches = backing.getInt(0); + rejectBorder = backing.getInt(4); + fillHoles = backing.getInt(8); + connectivity8 = backing.getInt(12); + } + + public void write() { + backing.putInt(0, rejectMatches); + backing.putInt(4, rejectBorder); + backing.putInt(8, fillHoles); + backing.putInt(12, connectivity8); + } + + public int size() { + return 16; + } + } + + public static class FindEdgeOptions2 extends DisposedStruct { + public RakeDirection direction; // The direction to search in the ROI. + public int showSearchArea; // If TRUE, the function overlays the search area + // on the image. + public int showSearchLines; // If TRUE, the function overlays the search + // lines used to locate the edges on the image. + public int showEdgesFound; // If TRUE, the function overlays the locations + // of the edges found on the image. + public int showResult; // If TRUE, the function overlays the hit lines to + // the object and the edge used to generate the hit + // line on the result image. + public RGBValue searchAreaColor; // Specifies the RGB color value to use to + // overlay the search area. + public RGBValue searchLinesColor; // Specifies the RGB color value to use to + // overlay the search lines. + public RGBValue searchEdgesColor; // Specifies the RGB color value to use to + // overlay the search edges. + public RGBValue resultColor; // Specifies the RGB color value to use to + // overlay the results. + public String overlayGroupName; // Specifies the overlay group name to + // assign to the overlays. + public EdgeOptions2 edgeOptions; // Specifies the edge detection options + // along a single search line. + private ByteBuffer overlayGroupName_buf; + + private void init() { + searchAreaColor = new RGBValue(backing, 20); + searchLinesColor = new RGBValue(backing, 24); + searchEdgesColor = new RGBValue(backing, 28); + resultColor = new RGBValue(backing, 32); + edgeOptions = new EdgeOptions2(backing, 40); + } + + public FindEdgeOptions2() { + super(64); + init(); + } + + public FindEdgeOptions2(RakeDirection direction, int showSearchArea, int showSearchLines, + int showEdgesFound, int showResult, RGBValue searchAreaColor, RGBValue searchLinesColor, + RGBValue searchEdgesColor, RGBValue resultColor, String overlayGroupName, + EdgeOptions2 edgeOptions) { + super(64); + this.direction = direction; + this.showSearchArea = showSearchArea; + this.showSearchLines = showSearchLines; + this.showEdgesFound = showEdgesFound; + this.showResult = showResult; + this.searchAreaColor = searchAreaColor; + this.searchLinesColor = searchLinesColor; + this.searchEdgesColor = searchEdgesColor; + this.resultColor = resultColor; + this.overlayGroupName = overlayGroupName; + this.edgeOptions = edgeOptions; + } + + protected FindEdgeOptions2(ByteBuffer backing, int offset) { + super(backing, offset, 64); + init(); + } + + protected FindEdgeOptions2(long nativeObj, boolean owned) { + super(nativeObj, owned, 64); + init(); + } + + protected void setBuffer(ByteBuffer backing, int offset) { + super.setBuffer(backing, offset, 64); + } + + public void read() { + direction = RakeDirection.fromValue(backing.getInt(0)); + showSearchArea = backing.getInt(4); + showSearchLines = backing.getInt(8); + showEdgesFound = backing.getInt(12); + showResult = backing.getInt(16); + searchAreaColor.read(); + searchLinesColor.read(); + searchEdgesColor.read(); + resultColor.read(); + long overlayGroupName_addr = getPointer(backing, 36); + if (overlayGroupName_addr == 0) + overlayGroupName = null; + else { + ByteBuffer bb = newDirectByteBuffer(overlayGroupName_addr, 1000); // FIXME + while (bb.get() != 0) { + } + byte[] bytes = new byte[bb.position() - 1]; + getBytes(bb, bytes, 0, bytes.length); + try { + overlayGroupName = new String(bytes, "UTF-8"); + } catch (UnsupportedEncodingException e) { + overlayGroupName = ""; + } + } + + edgeOptions.read(); + } + + public void write() { + if (direction != null) + backing.putInt(0, direction.getValue()); + backing.putInt(4, showSearchArea); + backing.putInt(8, showSearchLines); + backing.putInt(12, showEdgesFound); + backing.putInt(16, showResult); + searchAreaColor.write(); + searchLinesColor.write(); + searchEdgesColor.write(); + resultColor.write(); + if (overlayGroupName != null) { + byte[] overlayGroupName_bytes; + try { + overlayGroupName_bytes = overlayGroupName.getBytes("UTF-8"); + } catch (UnsupportedEncodingException e) { + overlayGroupName_bytes = new byte[0]; + } + overlayGroupName_buf = ByteBuffer.allocateDirect(overlayGroupName_bytes.length + 1); + putBytes(overlayGroupName_buf, overlayGroupName_bytes, 0, overlayGroupName_bytes.length) + .put(overlayGroupName_bytes.length, (byte) 0); + } + putPointer(backing, 36, overlayGroupName == null ? 0 + : getByteBufferAddress(overlayGroupName_buf)); + edgeOptions.write(); + } + + public int size() { + return 64; + } + } + + public static class FindEdgeReport extends DisposedStruct { + public StraightEdge[] straightEdges; // An array of straight edges detected. + private ByteBuffer straightEdges_buf; + + private void init() { + straightEdges = new StraightEdge[0]; + } + + public FindEdgeReport() { + super(8); + init(); + } + + public FindEdgeReport(StraightEdge[] straightEdges) { + super(8); + this.straightEdges = straightEdges; + } + + protected FindEdgeReport(ByteBuffer backing, int offset) { + super(backing, offset, 8); + init(); + } + + protected FindEdgeReport(long nativeObj, boolean owned) { + super(nativeObj, owned, 8); + init(); + } + + protected void setBuffer(ByteBuffer backing, int offset) { + super.setBuffer(backing, offset, 8); + } + + public void read() { + int straightEdges_numStraightEdges = backing.getInt(4); + long straightEdges_addr = getPointer(backing, 0); + straightEdges = new StraightEdge[straightEdges_numStraightEdges]; + if (straightEdges_numStraightEdges > 0 && straightEdges_addr != 0) { + ByteBuffer bb = + newDirectByteBuffer(straightEdges_addr, straightEdges_numStraightEdges * 88); + for (int i = 0, off = 0; i < straightEdges_numStraightEdges; i++, off += 88) { + straightEdges[i] = new StraightEdge(bb, off); + straightEdges[i].read(); + } + } + } + + public void write() { + straightEdges_buf = + ByteBuffer.allocateDirect(straightEdges.length * 88).order(ByteOrder.nativeOrder()); + for (int i = 0, off = 0; i < straightEdges.length; i++, off += 88) { + straightEdges[i].setBuffer(straightEdges_buf, off); + straightEdges[i].write(); + } + backing.putInt(4, straightEdges.length); + putPointer(backing, 0, straightEdges_buf); + } + + public int size() { + return 8; + } + } + + public static class FindTransformRectOptions2 extends DisposedStruct { + public FindReferenceDirection direction; // Specifies the direction and + // orientation in which the + // function searches for the + // primary axis. + public int showSearchArea; // If TRUE, the function overlays the search area + // on the image. + public int showSearchLines; // If TRUE, the function overlays the search + // lines used to locate the edges on the image. + public int showEdgesFound; // If TRUE, the function overlays the locations + // of the edges found on the image. + public int showResult; // If TRUE, the function overlays the hit lines to + // the object and the edge used to generate the hit + // line on the result image. + public RGBValue searchAreaColor; // Specifies the RGB color value to use to + // overlay the search area. + public RGBValue searchLinesColor; // Specifies the RGB color value to use to + // overlay the search lines. + public RGBValue searchEdgesColor; // Specifies the RGB color value to use to + // overlay the search edges. + public RGBValue resultColor; // Specifies the RGB color value to use to + // overlay the results. + public String overlayGroupName; // Specifies the overlay group name to + // assign to the overlays. + public EdgeOptions2 edgeOptions; // Specifies the edge detection options + // along a single search line. + private ByteBuffer overlayGroupName_buf; + + private void init() { + searchAreaColor = new RGBValue(backing, 20); + searchLinesColor = new RGBValue(backing, 24); + searchEdgesColor = new RGBValue(backing, 28); + resultColor = new RGBValue(backing, 32); + edgeOptions = new EdgeOptions2(backing, 40); + } + + public FindTransformRectOptions2() { + super(64); + init(); + } + + public FindTransformRectOptions2(FindReferenceDirection direction, int showSearchArea, + int showSearchLines, int showEdgesFound, int showResult, RGBValue searchAreaColor, + RGBValue searchLinesColor, RGBValue searchEdgesColor, RGBValue resultColor, + String overlayGroupName, EdgeOptions2 edgeOptions) { + super(64); + this.direction = direction; + this.showSearchArea = showSearchArea; + this.showSearchLines = showSearchLines; + this.showEdgesFound = showEdgesFound; + this.showResult = showResult; + this.searchAreaColor = searchAreaColor; + this.searchLinesColor = searchLinesColor; + this.searchEdgesColor = searchEdgesColor; + this.resultColor = resultColor; + this.overlayGroupName = overlayGroupName; + this.edgeOptions = edgeOptions; + } + + protected FindTransformRectOptions2(ByteBuffer backing, int offset) { + super(backing, offset, 64); + init(); + } + + protected FindTransformRectOptions2(long nativeObj, boolean owned) { + super(nativeObj, owned, 64); + init(); + } + + protected void setBuffer(ByteBuffer backing, int offset) { + super.setBuffer(backing, offset, 64); + } + + public void read() { + direction = FindReferenceDirection.fromValue(backing.getInt(0)); + showSearchArea = backing.getInt(4); + showSearchLines = backing.getInt(8); + showEdgesFound = backing.getInt(12); + showResult = backing.getInt(16); + searchAreaColor.read(); + searchLinesColor.read(); + searchEdgesColor.read(); + resultColor.read(); + long overlayGroupName_addr = getPointer(backing, 36); + if (overlayGroupName_addr == 0) + overlayGroupName = null; + else { + ByteBuffer bb = newDirectByteBuffer(overlayGroupName_addr, 1000); // FIXME + while (bb.get() != 0) { + } + byte[] bytes = new byte[bb.position() - 1]; + getBytes(bb, bytes, 0, bytes.length); + try { + overlayGroupName = new String(bytes, "UTF-8"); + } catch (UnsupportedEncodingException e) { + overlayGroupName = ""; + } + } + + edgeOptions.read(); + } + + public void write() { + if (direction != null) + backing.putInt(0, direction.getValue()); + backing.putInt(4, showSearchArea); + backing.putInt(8, showSearchLines); + backing.putInt(12, showEdgesFound); + backing.putInt(16, showResult); + searchAreaColor.write(); + searchLinesColor.write(); + searchEdgesColor.write(); + resultColor.write(); + if (overlayGroupName != null) { + byte[] overlayGroupName_bytes; + try { + overlayGroupName_bytes = overlayGroupName.getBytes("UTF-8"); + } catch (UnsupportedEncodingException e) { + overlayGroupName_bytes = new byte[0]; + } + overlayGroupName_buf = ByteBuffer.allocateDirect(overlayGroupName_bytes.length + 1); + putBytes(overlayGroupName_buf, overlayGroupName_bytes, 0, overlayGroupName_bytes.length) + .put(overlayGroupName_bytes.length, (byte) 0); + } + putPointer(backing, 36, overlayGroupName == null ? 0 + : getByteBufferAddress(overlayGroupName_buf)); + edgeOptions.write(); + } + + public int size() { + return 64; + } + } + + public static class FindTransformRectsOptions2 extends DisposedStruct { + public FindReferenceDirection direction; // Specifies the direction and + // orientation in which the + // function searches for the + // primary axis. + public int showSearchArea; // If TRUE, the function overlays the search area + // on the image. + public int showSearchLines; // If TRUE, the function overlays the search + // lines used to locate the edges on the image. + public int showEdgesFound; // If TRUE, the function overlays the locations + // of the edges found on the image. + public int showResult; // If TRUE, the function overlays the hit lines to + // the object and the edge used to generate the hit + // line on the result image. + public RGBValue searchAreaColor; // Specifies the RGB color value to use to + // overlay the search area. + public RGBValue searchLinesColor; // Specifies the RGB color value to use to + // overlay the search lines. + public RGBValue searchEdgesColor; // Specifies the RGB color value to use to + // overlay the search edges. + public RGBValue resultColor; // Specifies the RGB color value to use to + // overlay the results. + public String overlayGroupName; // Specifies the overlay group name to + // assign to the overlays. + public EdgeOptions2 primaryEdgeOptions; // Specifies the parameters used to + // compute the edge gradient + // information and detect the edges + // for the primary ROI. + public EdgeOptions2 secondaryEdgeOptions; // Specifies the parameters used + // to compute the edge gradient + // information and detect the + // edges for the secondary ROI. + private ByteBuffer overlayGroupName_buf; + + private void init() { + searchAreaColor = new RGBValue(backing, 20); + searchLinesColor = new RGBValue(backing, 24); + searchEdgesColor = new RGBValue(backing, 28); + resultColor = new RGBValue(backing, 32); + primaryEdgeOptions = new EdgeOptions2(backing, 40); + secondaryEdgeOptions = new EdgeOptions2(backing, 64); + } + + public FindTransformRectsOptions2() { + super(88); + init(); + } + + public FindTransformRectsOptions2(FindReferenceDirection direction, int showSearchArea, + int showSearchLines, int showEdgesFound, int showResult, RGBValue searchAreaColor, + RGBValue searchLinesColor, RGBValue searchEdgesColor, RGBValue resultColor, + String overlayGroupName, EdgeOptions2 primaryEdgeOptions, EdgeOptions2 secondaryEdgeOptions) { + super(88); + this.direction = direction; + this.showSearchArea = showSearchArea; + this.showSearchLines = showSearchLines; + this.showEdgesFound = showEdgesFound; + this.showResult = showResult; + this.searchAreaColor = searchAreaColor; + this.searchLinesColor = searchLinesColor; + this.searchEdgesColor = searchEdgesColor; + this.resultColor = resultColor; + this.overlayGroupName = overlayGroupName; + this.primaryEdgeOptions = primaryEdgeOptions; + this.secondaryEdgeOptions = secondaryEdgeOptions; + } + + protected FindTransformRectsOptions2(ByteBuffer backing, int offset) { + super(backing, offset, 88); + init(); + } + + protected FindTransformRectsOptions2(long nativeObj, boolean owned) { + super(nativeObj, owned, 88); + init(); + } + + protected void setBuffer(ByteBuffer backing, int offset) { + super.setBuffer(backing, offset, 88); + } + + public void read() { + direction = FindReferenceDirection.fromValue(backing.getInt(0)); + showSearchArea = backing.getInt(4); + showSearchLines = backing.getInt(8); + showEdgesFound = backing.getInt(12); + showResult = backing.getInt(16); + searchAreaColor.read(); + searchLinesColor.read(); + searchEdgesColor.read(); + resultColor.read(); + long overlayGroupName_addr = getPointer(backing, 36); + if (overlayGroupName_addr == 0) + overlayGroupName = null; + else { + ByteBuffer bb = newDirectByteBuffer(overlayGroupName_addr, 1000); // FIXME + while (bb.get() != 0) { + } + byte[] bytes = new byte[bb.position() - 1]; + getBytes(bb, bytes, 0, bytes.length); + try { + overlayGroupName = new String(bytes, "UTF-8"); + } catch (UnsupportedEncodingException e) { + overlayGroupName = ""; + } + } + + primaryEdgeOptions.read(); + secondaryEdgeOptions.read(); + } + + public void write() { + if (direction != null) + backing.putInt(0, direction.getValue()); + backing.putInt(4, showSearchArea); + backing.putInt(8, showSearchLines); + backing.putInt(12, showEdgesFound); + backing.putInt(16, showResult); + searchAreaColor.write(); + searchLinesColor.write(); + searchEdgesColor.write(); + resultColor.write(); + if (overlayGroupName != null) { + byte[] overlayGroupName_bytes; + try { + overlayGroupName_bytes = overlayGroupName.getBytes("UTF-8"); + } catch (UnsupportedEncodingException e) { + overlayGroupName_bytes = new byte[0]; + } + overlayGroupName_buf = ByteBuffer.allocateDirect(overlayGroupName_bytes.length + 1); + putBytes(overlayGroupName_buf, overlayGroupName_bytes, 0, overlayGroupName_bytes.length) + .put(overlayGroupName_bytes.length, (byte) 0); + } + putPointer(backing, 36, overlayGroupName == null ? 0 + : getByteBufferAddress(overlayGroupName_buf)); + primaryEdgeOptions.write(); + secondaryEdgeOptions.write(); + } + + public int size() { + return 88; + } + } + + public static class ReadTextReport3 extends DisposedStruct { + public String readString; // The read string. + public CharReport3[] characterReport; // An array of reports describing the + // properties of each identified + // character. + public ROI roiBoundingCharacters; // An array specifying the coordinates of + // the character bounding ROI. + private ByteBuffer readString_buf; + private ByteBuffer characterReport_buf; + + private void init() { + characterReport = new CharReport3[0]; + } + + public ReadTextReport3() { + super(16); + init(); + } + + public ReadTextReport3(String readString, CharReport3[] characterReport, + ROI roiBoundingCharacters) { + super(16); + this.readString = readString; + this.characterReport = characterReport; + this.roiBoundingCharacters = roiBoundingCharacters; + } + + protected ReadTextReport3(ByteBuffer backing, int offset) { + super(backing, offset, 16); + init(); + } + + protected ReadTextReport3(long nativeObj, boolean owned) { + super(nativeObj, owned, 16); + init(); + } + + protected void setBuffer(ByteBuffer backing, int offset) { + super.setBuffer(backing, offset, 16); + } + + public void read() { + long readString_addr = getPointer(backing, 0); + if (readString_addr == 0) + readString = null; + else { + ByteBuffer bb = newDirectByteBuffer(readString_addr, 1000); // FIXME + while (bb.get() != 0) { + } + byte[] bytes = new byte[bb.position() - 1]; + getBytes(bb, bytes, 0, bytes.length); + try { + readString = new String(bytes, "UTF-8"); + } catch (UnsupportedEncodingException e) { + readString = ""; + } + } + + int characterReport_numCharacterReports = backing.getInt(8); + long characterReport_addr = getPointer(backing, 4); + characterReport = new CharReport3[characterReport_numCharacterReports]; + if (characterReport_numCharacterReports > 0 && characterReport_addr != 0) { + ByteBuffer bb = + newDirectByteBuffer(characterReport_addr, characterReport_numCharacterReports * 44); + for (int i = 0, off = 0; i < characterReport_numCharacterReports; i++, off += 44) { + characterReport[i] = new CharReport3(bb, off); + characterReport[i].read(); + } + } + long roiBoundingCharacters_addr = getPointer(backing, 12); + if (roiBoundingCharacters_addr == 0) + roiBoundingCharacters = null; + else + roiBoundingCharacters = new ROI(roiBoundingCharacters_addr, false); + } + + public void write() { + if (readString != null) { + byte[] readString_bytes; + try { + readString_bytes = readString.getBytes("UTF-8"); + } catch (UnsupportedEncodingException e) { + readString_bytes = new byte[0]; + } + readString_buf = ByteBuffer.allocateDirect(readString_bytes.length + 1); + putBytes(readString_buf, readString_bytes, 0, readString_bytes.length).put( + readString_bytes.length, (byte) 0); + } + putPointer(backing, 0, readString == null ? 0 : getByteBufferAddress(readString_buf)); + characterReport_buf = + ByteBuffer.allocateDirect(characterReport.length * 44).order(ByteOrder.nativeOrder()); + for (int i = 0, off = 0; i < characterReport.length; i++, off += 44) { + characterReport[i].setBuffer(characterReport_buf, off); + characterReport[i].write(); + } + backing.putInt(8, characterReport.length); + putPointer(backing, 4, characterReport_buf); + putPointer(backing, 12, roiBoundingCharacters); + } + + public int size() { + return 16; + } + } + + public static class CharacterStatistics extends DisposedStruct { + public int left; // The left offset of the character bounding rectangles in + // the current ROI. + public int top; // The top offset of the character bounding rectangles in + // the current ROI. + public int width; // The width of each of the characters you trained in the + // current ROI. + public int height; // The height of each trained character in the current + // ROI. + public int characterSize; // The size of the character in pixels. + + private void init() { + + } + + public CharacterStatistics() { + super(20); + init(); + } + + public CharacterStatistics(int left, int top, int width, int height, int characterSize) { + super(20); + this.left = left; + this.top = top; + this.width = width; + this.height = height; + this.characterSize = characterSize; + } + + protected CharacterStatistics(ByteBuffer backing, int offset) { + super(backing, offset, 20); + init(); + } + + protected CharacterStatistics(long nativeObj, boolean owned) { + super(nativeObj, owned, 20); + init(); + } + + protected void setBuffer(ByteBuffer backing, int offset) { + super.setBuffer(backing, offset, 20); + } + + public void read() { + left = backing.getInt(0); + top = backing.getInt(4); + width = backing.getInt(8); + height = backing.getInt(12); + characterSize = backing.getInt(16); + } + + public void write() { + backing.putInt(0, left); + backing.putInt(4, top); + backing.putInt(8, width); + backing.putInt(12, height); + backing.putInt(16, characterSize); + } + + public int size() { + return 20; + } + } + + public static class CharReport3 extends DisposedStruct { + public String character; // The character value. + public int classificationScore; // The degree to which the assigned + // character class represents the object + // better than the other character classes + // in the character set. + public int verificationScore; // The similarity of the character and the + // reference character for the character + // class. + public int verified; // This element is TRUE if a reference character was + // found for the character class and FALSE if a + // reference character was not found. + public int lowThreshold; // The minimum value of the threshold range used + // for this character. + public int highThreshold; // The maximum value of the threshold range used + // for this character. + public CharacterStatistics characterStats; // Describes the characters + // segmented in the ROI. + private ByteBuffer character_buf; + + private void init() { + characterStats = new CharacterStatistics(backing, 24); + } + + public CharReport3() { + super(44); + init(); + } + + public CharReport3(String character, int classificationScore, int verificationScore, + int verified, int lowThreshold, int highThreshold, CharacterStatistics characterStats) { + super(44); + this.character = character; + this.classificationScore = classificationScore; + this.verificationScore = verificationScore; + this.verified = verified; + this.lowThreshold = lowThreshold; + this.highThreshold = highThreshold; + this.characterStats = characterStats; + } + + protected CharReport3(ByteBuffer backing, int offset) { + super(backing, offset, 44); + init(); + } + + protected CharReport3(long nativeObj, boolean owned) { + super(nativeObj, owned, 44); + init(); + } + + protected void setBuffer(ByteBuffer backing, int offset) { + super.setBuffer(backing, offset, 44); + } + + public void read() { + long character_addr = getPointer(backing, 0); + if (character_addr == 0) + character = null; + else { + ByteBuffer bb = newDirectByteBuffer(character_addr, 1000); // FIXME + while (bb.get() != 0) { + } + byte[] bytes = new byte[bb.position() - 1]; + getBytes(bb, bytes, 0, bytes.length); + try { + character = new String(bytes, "UTF-8"); + } catch (UnsupportedEncodingException e) { + character = ""; + } + } + + classificationScore = backing.getInt(4); + verificationScore = backing.getInt(8); + verified = backing.getInt(12); + lowThreshold = backing.getInt(16); + highThreshold = backing.getInt(20); + characterStats.read(); + } + + public void write() { + if (character != null) { + byte[] character_bytes; + try { + character_bytes = character.getBytes("UTF-8"); + } catch (UnsupportedEncodingException e) { + character_bytes = new byte[0]; + } + character_buf = ByteBuffer.allocateDirect(character_bytes.length + 1); + putBytes(character_buf, character_bytes, 0, character_bytes.length).put( + character_bytes.length, (byte) 0); + } + putPointer(backing, 0, character == null ? 0 : getByteBufferAddress(character_buf)); + backing.putInt(4, classificationScore); + backing.putInt(8, verificationScore); + backing.putInt(12, verified); + backing.putInt(16, lowThreshold); + backing.putInt(20, highThreshold); + characterStats.write(); + } + + public int size() { + return 44; + } + } + + public static class ArcInfo2 extends DisposedStruct { + public PointFloat center; // The center point of the arc. + public double radius; // The radius of the arc. + public double startAngle; // The starting angle of the arc, specified + // counter-clockwise from the x-axis. + public double endAngle; // The ending angle of the arc, specified + // counter-clockwise from the x-axis. + + private void init() { + center = new PointFloat(backing, 0); + } + + public ArcInfo2() { + super(32); + init(); + } + + public ArcInfo2(PointFloat center, double radius, double startAngle, double endAngle) { + super(32); + this.center = center; + this.radius = radius; + this.startAngle = startAngle; + this.endAngle = endAngle; + } + + protected ArcInfo2(ByteBuffer backing, int offset) { + super(backing, offset, 32); + init(); + } + + protected ArcInfo2(long nativeObj, boolean owned) { + super(nativeObj, owned, 32); + init(); + } + + protected void setBuffer(ByteBuffer backing, int offset) { + super.setBuffer(backing, offset, 32); + } + + public void read() { + center.read(); + radius = backing.getDouble(8); + startAngle = backing.getDouble(16); + endAngle = backing.getDouble(24); + } + + public void write() { + center.write(); + backing.putDouble(8, radius); + backing.putDouble(16, startAngle); + backing.putDouble(24, endAngle); + } + + public int size() { + return 32; + } + } + + public static class EdgeReport2 extends DisposedStruct { + public EdgeInfo[] edges; // An array of edges detected. + public double[] gradientInfo; // An array that contains the calculated edge + // strengths along the user-defined search + // area. + public int calibrationValid; // Indicates if the calibration data + // corresponding to the location of the edges + // is correct. + private ByteBuffer edges_buf; + private ByteBuffer gradientInfo_buf; + + private void init() { + edges = new EdgeInfo[0]; + gradientInfo = new double[0]; + } + + public EdgeReport2() { + super(20); + init(); + } + + public EdgeReport2(EdgeInfo[] edges, double[] gradientInfo, int calibrationValid) { + super(20); + this.edges = edges; + this.gradientInfo = gradientInfo; + this.calibrationValid = calibrationValid; + } + + protected EdgeReport2(ByteBuffer backing, int offset) { + super(backing, offset, 20); + init(); + } + + protected EdgeReport2(long nativeObj, boolean owned) { + super(nativeObj, owned, 20); + init(); + } + + protected void setBuffer(ByteBuffer backing, int offset) { + super.setBuffer(backing, offset, 20); + } + + public void read() { + int edges_numEdges = backing.getInt(4); + long edges_addr = getPointer(backing, 0); + edges = new EdgeInfo[edges_numEdges]; + if (edges_numEdges > 0 && edges_addr != 0) { + ByteBuffer bb = newDirectByteBuffer(edges_addr, edges_numEdges * 56); + for (int i = 0, off = 0; i < edges_numEdges; i++, off += 56) { + edges[i] = new EdgeInfo(bb, off); + edges[i].read(); + } + } + int gradientInfo_numGradientInfo = backing.getInt(12); + long gradientInfo_addr = getPointer(backing, 8); + gradientInfo = new double[gradientInfo_numGradientInfo]; + if (gradientInfo_numGradientInfo > 0 && gradientInfo_addr != 0) { + newDirectByteBuffer(gradientInfo_addr, gradientInfo_numGradientInfo * 8).asDoubleBuffer() + .get(gradientInfo); + } + calibrationValid = backing.getInt(16); + } + + public void write() { + edges_buf = ByteBuffer.allocateDirect(edges.length * 56).order(ByteOrder.nativeOrder()); + for (int i = 0, off = 0; i < edges.length; i++, off += 56) { + edges[i].setBuffer(edges_buf, off); + edges[i].write(); + } + backing.putInt(4, edges.length); + putPointer(backing, 0, edges_buf); + gradientInfo_buf = + ByteBuffer.allocateDirect(gradientInfo.length * 8).order(ByteOrder.nativeOrder()); + gradientInfo_buf.asDoubleBuffer().put(gradientInfo).rewind(); + backing.putInt(12, gradientInfo.length); + putPointer(backing, 8, gradientInfo_buf); + backing.putInt(16, calibrationValid); + } + + public int size() { + return 20; + } + } + + public static class SearchArcInfo extends DisposedStruct { + public ArcInfo2 arcCoordinates; // Describes the arc used for edge + // detection. + public EdgeReport2 edgeReport; // Describes the edges found in this search + // line. + + private void init() { + arcCoordinates = new ArcInfo2(backing, 0); + edgeReport = new EdgeReport2(backing, 32); + } + + public SearchArcInfo() { + super(56); + init(); + } + + public SearchArcInfo(ArcInfo2 arcCoordinates, EdgeReport2 edgeReport) { + super(56); + this.arcCoordinates = arcCoordinates; + this.edgeReport = edgeReport; + } + + protected SearchArcInfo(ByteBuffer backing, int offset) { + super(backing, offset, 56); + init(); + } + + protected SearchArcInfo(long nativeObj, boolean owned) { + super(nativeObj, owned, 56); + init(); + } + + protected void setBuffer(ByteBuffer backing, int offset) { + super.setBuffer(backing, offset, 56); + } + + public void read() { + arcCoordinates.read(); + edgeReport.read(); + } + + public void write() { + arcCoordinates.write(); + edgeReport.write(); + } + + public int size() { + return 56; + } + } + + public static class ConcentricRakeReport2 extends DisposedStruct { + public EdgeInfo[] firstEdges; // The first edge point detected along each + // search line in the ROI. + public EdgeInfo[] lastEdges; // The last edge point detected along each + // search line in the ROI. + public SearchArcInfo[] searchArcs; // Contains the arcs used for edge + // detection and the edge information for + // each arc. + private ByteBuffer firstEdges_buf; + private ByteBuffer lastEdges_buf; + private ByteBuffer searchArcs_buf; + + private void init() { + firstEdges = new EdgeInfo[0]; + lastEdges = new EdgeInfo[0]; + searchArcs = new SearchArcInfo[0]; + } + + public ConcentricRakeReport2() { + super(24); + init(); + } + + public ConcentricRakeReport2(EdgeInfo[] firstEdges, EdgeInfo[] lastEdges, + SearchArcInfo[] searchArcs) { + super(24); + this.firstEdges = firstEdges; + this.lastEdges = lastEdges; + this.searchArcs = searchArcs; + } + + protected ConcentricRakeReport2(ByteBuffer backing, int offset) { + super(backing, offset, 24); + init(); + } + + protected ConcentricRakeReport2(long nativeObj, boolean owned) { + super(nativeObj, owned, 24); + init(); + } + + protected void setBuffer(ByteBuffer backing, int offset) { + super.setBuffer(backing, offset, 24); + } + + public void read() { + int firstEdges_numFirstEdges = backing.getInt(4); + long firstEdges_addr = getPointer(backing, 0); + firstEdges = new EdgeInfo[firstEdges_numFirstEdges]; + if (firstEdges_numFirstEdges > 0 && firstEdges_addr != 0) { + ByteBuffer bb = newDirectByteBuffer(firstEdges_addr, firstEdges_numFirstEdges * 56); + for (int i = 0, off = 0; i < firstEdges_numFirstEdges; i++, off += 56) { + firstEdges[i] = new EdgeInfo(bb, off); + firstEdges[i].read(); + } + } + int lastEdges_numLastEdges = backing.getInt(12); + long lastEdges_addr = getPointer(backing, 8); + lastEdges = new EdgeInfo[lastEdges_numLastEdges]; + if (lastEdges_numLastEdges > 0 && lastEdges_addr != 0) { + ByteBuffer bb = newDirectByteBuffer(lastEdges_addr, lastEdges_numLastEdges * 56); + for (int i = 0, off = 0; i < lastEdges_numLastEdges; i++, off += 56) { + lastEdges[i] = new EdgeInfo(bb, off); + lastEdges[i].read(); + } + } + int searchArcs_numSearchArcs = backing.getInt(20); + long searchArcs_addr = getPointer(backing, 16); + searchArcs = new SearchArcInfo[searchArcs_numSearchArcs]; + if (searchArcs_numSearchArcs > 0 && searchArcs_addr != 0) { + ByteBuffer bb = newDirectByteBuffer(searchArcs_addr, searchArcs_numSearchArcs * 56); + for (int i = 0, off = 0; i < searchArcs_numSearchArcs; i++, off += 56) { + searchArcs[i] = new SearchArcInfo(bb, off); + searchArcs[i].read(); + } + } + } + + public void write() { + firstEdges_buf = + ByteBuffer.allocateDirect(firstEdges.length * 56).order(ByteOrder.nativeOrder()); + for (int i = 0, off = 0; i < firstEdges.length; i++, off += 56) { + firstEdges[i].setBuffer(firstEdges_buf, off); + firstEdges[i].write(); + } + backing.putInt(4, firstEdges.length); + putPointer(backing, 0, firstEdges_buf); + lastEdges_buf = + ByteBuffer.allocateDirect(lastEdges.length * 56).order(ByteOrder.nativeOrder()); + for (int i = 0, off = 0; i < lastEdges.length; i++, off += 56) { + lastEdges[i].setBuffer(lastEdges_buf, off); + lastEdges[i].write(); + } + backing.putInt(12, lastEdges.length); + putPointer(backing, 8, lastEdges_buf); + searchArcs_buf = + ByteBuffer.allocateDirect(searchArcs.length * 56).order(ByteOrder.nativeOrder()); + for (int i = 0, off = 0; i < searchArcs.length; i++, off += 56) { + searchArcs[i].setBuffer(searchArcs_buf, off); + searchArcs[i].write(); + } + backing.putInt(20, searchArcs.length); + putPointer(backing, 16, searchArcs_buf); + } + + public int size() { + return 24; + } + } + + public static class SpokeReport2 extends DisposedStruct { + public EdgeInfo[] firstEdges; // The first edge point detected along each + // search line in the ROI. + public EdgeInfo[] lastEdges; // The last edge point detected along each + // search line in the ROI. + public SearchLineInfo[] searchLines; // The search lines used for edge + // detection. + private ByteBuffer firstEdges_buf; + private ByteBuffer lastEdges_buf; + private ByteBuffer searchLines_buf; + + private void init() { + firstEdges = new EdgeInfo[0]; + lastEdges = new EdgeInfo[0]; + searchLines = new SearchLineInfo[0]; + } + + public SpokeReport2() { + super(24); + init(); + } + + public SpokeReport2(EdgeInfo[] firstEdges, EdgeInfo[] lastEdges, SearchLineInfo[] searchLines) { + super(24); + this.firstEdges = firstEdges; + this.lastEdges = lastEdges; + this.searchLines = searchLines; + } + + protected SpokeReport2(ByteBuffer backing, int offset) { + super(backing, offset, 24); + init(); + } + + protected SpokeReport2(long nativeObj, boolean owned) { + super(nativeObj, owned, 24); + init(); + } + + protected void setBuffer(ByteBuffer backing, int offset) { + super.setBuffer(backing, offset, 24); + } + + public void read() { + int firstEdges_numFirstEdges = backing.getInt(4); + long firstEdges_addr = getPointer(backing, 0); + firstEdges = new EdgeInfo[firstEdges_numFirstEdges]; + if (firstEdges_numFirstEdges > 0 && firstEdges_addr != 0) { + ByteBuffer bb = newDirectByteBuffer(firstEdges_addr, firstEdges_numFirstEdges * 56); + for (int i = 0, off = 0; i < firstEdges_numFirstEdges; i++, off += 56) { + firstEdges[i] = new EdgeInfo(bb, off); + firstEdges[i].read(); + } + } + int lastEdges_numLastEdges = backing.getInt(12); + long lastEdges_addr = getPointer(backing, 8); + lastEdges = new EdgeInfo[lastEdges_numLastEdges]; + if (lastEdges_numLastEdges > 0 && lastEdges_addr != 0) { + ByteBuffer bb = newDirectByteBuffer(lastEdges_addr, lastEdges_numLastEdges * 56); + for (int i = 0, off = 0; i < lastEdges_numLastEdges; i++, off += 56) { + lastEdges[i] = new EdgeInfo(bb, off); + lastEdges[i].read(); + } + } + int searchLines_numSearchLines = backing.getInt(20); + long searchLines_addr = getPointer(backing, 16); + searchLines = new SearchLineInfo[searchLines_numSearchLines]; + if (searchLines_numSearchLines > 0 && searchLines_addr != 0) { + ByteBuffer bb = newDirectByteBuffer(searchLines_addr, searchLines_numSearchLines * 36); + for (int i = 0, off = 0; i < searchLines_numSearchLines; i++, off += 36) { + searchLines[i] = new SearchLineInfo(bb, off); + searchLines[i].read(); + } + } + } + + public void write() { + firstEdges_buf = + ByteBuffer.allocateDirect(firstEdges.length * 56).order(ByteOrder.nativeOrder()); + for (int i = 0, off = 0; i < firstEdges.length; i++, off += 56) { + firstEdges[i].setBuffer(firstEdges_buf, off); + firstEdges[i].write(); + } + backing.putInt(4, firstEdges.length); + putPointer(backing, 0, firstEdges_buf); + lastEdges_buf = + ByteBuffer.allocateDirect(lastEdges.length * 56).order(ByteOrder.nativeOrder()); + for (int i = 0, off = 0; i < lastEdges.length; i++, off += 56) { + lastEdges[i].setBuffer(lastEdges_buf, off); + lastEdges[i].write(); + } + backing.putInt(12, lastEdges.length); + putPointer(backing, 8, lastEdges_buf); + searchLines_buf = + ByteBuffer.allocateDirect(searchLines.length * 36).order(ByteOrder.nativeOrder()); + for (int i = 0, off = 0; i < searchLines.length; i++, off += 36) { + searchLines[i].setBuffer(searchLines_buf, off); + searchLines[i].write(); + } + backing.putInt(20, searchLines.length); + putPointer(backing, 16, searchLines_buf); + } + + public int size() { + return 24; + } + } + + public static class EdgeInfo extends DisposedStruct { + public PointFloat position; // The location of the edge in the image. + public PointFloat calibratedPosition; // The position of the edge in the + // image in real-world coordinates. + public double distance; // The location of the edge from the first point + // along the boundary of the input ROI. + public double calibratedDistance; // The location of the edge from the first + // point along the boundary of the input + // ROI in real-world coordinates. + public double magnitude; // The intensity contrast at the edge. + public double noisePeak; // The strength of the noise associated with the + // current edge. + public int rising; // Indicates the polarity of the edge. + + private void init() { + position = new PointFloat(backing, 0); + calibratedPosition = new PointFloat(backing, 8); + } + + public EdgeInfo() { + super(56); + init(); + } + + public EdgeInfo(PointFloat position, PointFloat calibratedPosition, double distance, + double calibratedDistance, double magnitude, double noisePeak, int rising) { + super(56); + this.position = position; + this.calibratedPosition = calibratedPosition; + this.distance = distance; + this.calibratedDistance = calibratedDistance; + this.magnitude = magnitude; + this.noisePeak = noisePeak; + this.rising = rising; + } + + protected EdgeInfo(ByteBuffer backing, int offset) { + super(backing, offset, 56); + init(); + } + + protected EdgeInfo(long nativeObj, boolean owned) { + super(nativeObj, owned, 56); + init(); + } + + protected void setBuffer(ByteBuffer backing, int offset) { + super.setBuffer(backing, offset, 56); + } + + public void read() { + position.read(); + calibratedPosition.read(); + distance = backing.getDouble(16); + calibratedDistance = backing.getDouble(24); + magnitude = backing.getDouble(32); + noisePeak = backing.getDouble(40); + rising = backing.getInt(48); + } + + public void write() { + position.write(); + calibratedPosition.write(); + backing.putDouble(16, distance); + backing.putDouble(24, calibratedDistance); + backing.putDouble(32, magnitude); + backing.putDouble(40, noisePeak); + backing.putInt(48, rising); + } + + public int size() { + return 56; + } + } + + public static class SearchLineInfo extends DisposedStruct { + public LineFloat lineCoordinates; // The endpoints of the search line. + public EdgeReport2 edgeReport; // Describes the edges found in this search + // line. + + private void init() { + lineCoordinates = new LineFloat(backing, 0); + edgeReport = new EdgeReport2(backing, 16); + } + + public SearchLineInfo() { + super(36); + init(); + } + + public SearchLineInfo(LineFloat lineCoordinates, EdgeReport2 edgeReport) { + super(36); + this.lineCoordinates = lineCoordinates; + this.edgeReport = edgeReport; + } + + protected SearchLineInfo(ByteBuffer backing, int offset) { + super(backing, offset, 36); + init(); + } + + protected SearchLineInfo(long nativeObj, boolean owned) { + super(nativeObj, owned, 36); + init(); + } + + protected void setBuffer(ByteBuffer backing, int offset) { + super.setBuffer(backing, offset, 36); + } + + public void read() { + lineCoordinates.read(); + edgeReport.read(); + } + + public void write() { + lineCoordinates.write(); + edgeReport.write(); + } + + public int size() { + return 36; + } + } + + public static class RakeReport2 extends DisposedStruct { + public EdgeInfo[] firstEdges; // The first edge point detected along each + // search line in the ROI. + public EdgeInfo[] lastEdges; // The last edge point detected along each + // search line in the ROI. + public SearchLineInfo[] searchLines; // The search lines used for edge + // detection. + private ByteBuffer firstEdges_buf; + private ByteBuffer lastEdges_buf; + private ByteBuffer searchLines_buf; + + private void init() { + firstEdges = new EdgeInfo[0]; + lastEdges = new EdgeInfo[0]; + searchLines = new SearchLineInfo[0]; + } + + public RakeReport2() { + super(24); + init(); + } + + public RakeReport2(EdgeInfo[] firstEdges, EdgeInfo[] lastEdges, SearchLineInfo[] searchLines) { + super(24); + this.firstEdges = firstEdges; + this.lastEdges = lastEdges; + this.searchLines = searchLines; + } + + protected RakeReport2(ByteBuffer backing, int offset) { + super(backing, offset, 24); + init(); + } + + protected RakeReport2(long nativeObj, boolean owned) { + super(nativeObj, owned, 24); + init(); + } + + protected void setBuffer(ByteBuffer backing, int offset) { + super.setBuffer(backing, offset, 24); + } + + public void read() { + int firstEdges_numFirstEdges = backing.getInt(4); + long firstEdges_addr = getPointer(backing, 0); + firstEdges = new EdgeInfo[firstEdges_numFirstEdges]; + if (firstEdges_numFirstEdges > 0 && firstEdges_addr != 0) { + ByteBuffer bb = newDirectByteBuffer(firstEdges_addr, firstEdges_numFirstEdges * 56); + for (int i = 0, off = 0; i < firstEdges_numFirstEdges; i++, off += 56) { + firstEdges[i] = new EdgeInfo(bb, off); + firstEdges[i].read(); + } + } + int lastEdges_numLastEdges = backing.getInt(12); + long lastEdges_addr = getPointer(backing, 8); + lastEdges = new EdgeInfo[lastEdges_numLastEdges]; + if (lastEdges_numLastEdges > 0 && lastEdges_addr != 0) { + ByteBuffer bb = newDirectByteBuffer(lastEdges_addr, lastEdges_numLastEdges * 56); + for (int i = 0, off = 0; i < lastEdges_numLastEdges; i++, off += 56) { + lastEdges[i] = new EdgeInfo(bb, off); + lastEdges[i].read(); + } + } + int searchLines_numSearchLines = backing.getInt(20); + long searchLines_addr = getPointer(backing, 16); + searchLines = new SearchLineInfo[searchLines_numSearchLines]; + if (searchLines_numSearchLines > 0 && searchLines_addr != 0) { + ByteBuffer bb = newDirectByteBuffer(searchLines_addr, searchLines_numSearchLines * 36); + for (int i = 0, off = 0; i < searchLines_numSearchLines; i++, off += 36) { + searchLines[i] = new SearchLineInfo(bb, off); + searchLines[i].read(); + } + } + } + + public void write() { + firstEdges_buf = + ByteBuffer.allocateDirect(firstEdges.length * 56).order(ByteOrder.nativeOrder()); + for (int i = 0, off = 0; i < firstEdges.length; i++, off += 56) { + firstEdges[i].setBuffer(firstEdges_buf, off); + firstEdges[i].write(); + } + backing.putInt(4, firstEdges.length); + putPointer(backing, 0, firstEdges_buf); + lastEdges_buf = + ByteBuffer.allocateDirect(lastEdges.length * 56).order(ByteOrder.nativeOrder()); + for (int i = 0, off = 0; i < lastEdges.length; i++, off += 56) { + lastEdges[i].setBuffer(lastEdges_buf, off); + lastEdges[i].write(); + } + backing.putInt(12, lastEdges.length); + putPointer(backing, 8, lastEdges_buf); + searchLines_buf = + ByteBuffer.allocateDirect(searchLines.length * 36).order(ByteOrder.nativeOrder()); + for (int i = 0, off = 0; i < searchLines.length; i++, off += 36) { + searchLines[i].setBuffer(searchLines_buf, off); + searchLines[i].write(); + } + backing.putInt(20, searchLines.length); + putPointer(backing, 16, searchLines_buf); + } + + public int size() { + return 24; + } + } + + public static class TransformBehaviors extends DisposedStruct { + public GroupBehavior ShiftBehavior; // Specifies the behavior of an overlay + // group when a shift operation is + // applied to an image. + public GroupBehavior ScaleBehavior; // Specifies the behavior of an overlay + // group when a scale operation is + // applied to an image. + public GroupBehavior RotateBehavior; // Specifies the behavior of an overlay + // group when a rotate operation is + // applied to an image. + public GroupBehavior SymmetryBehavior; // Specifies the behavior of an + // overlay group when a symmetry + // operation is applied to an image. + + private void init() { + + } + + public TransformBehaviors() { + super(16); + init(); + } + + public TransformBehaviors(GroupBehavior ShiftBehavior, GroupBehavior ScaleBehavior, + GroupBehavior RotateBehavior, GroupBehavior SymmetryBehavior) { + super(16); + this.ShiftBehavior = ShiftBehavior; + this.ScaleBehavior = ScaleBehavior; + this.RotateBehavior = RotateBehavior; + this.SymmetryBehavior = SymmetryBehavior; + } + + protected TransformBehaviors(ByteBuffer backing, int offset) { + super(backing, offset, 16); + init(); + } + + protected TransformBehaviors(long nativeObj, boolean owned) { + super(nativeObj, owned, 16); + init(); + } + + protected void setBuffer(ByteBuffer backing, int offset) { + super.setBuffer(backing, offset, 16); + } + + public void read() { + ShiftBehavior = GroupBehavior.fromValue(backing.getInt(0)); + ScaleBehavior = GroupBehavior.fromValue(backing.getInt(4)); + RotateBehavior = GroupBehavior.fromValue(backing.getInt(8)); + SymmetryBehavior = GroupBehavior.fromValue(backing.getInt(12)); + } + + public void write() { + if (ShiftBehavior != null) + backing.putInt(0, ShiftBehavior.getValue()); + if (ScaleBehavior != null) + backing.putInt(4, ScaleBehavior.getValue()); + if (RotateBehavior != null) + backing.putInt(8, RotateBehavior.getValue()); + if (SymmetryBehavior != null) + backing.putInt(12, SymmetryBehavior.getValue()); + } + + public int size() { + return 16; + } + } + + public static class QRCodeDataToken extends DisposedStruct { + public QRStreamMode mode; // Specifies the stream mode or the format of the + // data that is encoded in the QR code. + public int modeData; // Indicates specifiers used by the user to postprocess + // the data if it requires it. + public byte[] data; // Shows the encoded data in the QR code. + private ByteBuffer data_buf; + + private void init() { + data = new byte[0]; + } + + public QRCodeDataToken() { + super(16); + init(); + } + + public QRCodeDataToken(QRStreamMode mode, int modeData, byte[] data) { + super(16); + this.mode = mode; + this.modeData = modeData; + this.data = data; + } + + protected QRCodeDataToken(ByteBuffer backing, int offset) { + super(backing, offset, 16); + init(); + } + + protected QRCodeDataToken(long nativeObj, boolean owned) { + super(nativeObj, owned, 16); + init(); + } + + protected void setBuffer(ByteBuffer backing, int offset) { + super.setBuffer(backing, offset, 16); + } + + public void read() { + mode = QRStreamMode.fromValue(backing.getInt(0)); + modeData = backing.getInt(4); + int data_dataLength = backing.getInt(12); + long data_addr = getPointer(backing, 8); + data = new byte[data_dataLength]; + if (data_dataLength > 0 && data_addr != 0) { + getBytes(newDirectByteBuffer(data_addr, data_dataLength), data, 0, data_dataLength); + } + } + + public void write() { + if (mode != null) + backing.putInt(0, mode.getValue()); + backing.putInt(4, modeData); + data_buf = ByteBuffer.allocateDirect(data.length); + putBytes(data_buf, data, 0, data.length); + backing.putInt(12, data.length); + putPointer(backing, 8, data_buf); + } + + public int size() { + return 16; + } + } + + public static class ParticleFilterOptions extends DisposedStruct { + public int rejectMatches; // Set this parameter to TRUE to transfer only + // those particles that do not meet all the + // criteria. + public int rejectBorder; // Set this element to TRUE to reject border + // particles. + public int connectivity8; // Set this parameter to TRUE to use + // connectivity-8 to determine whether particles + // are touching. + + private void init() { + + } + + public ParticleFilterOptions() { + super(12); + init(); + } + + public ParticleFilterOptions(int rejectMatches, int rejectBorder, int connectivity8) { + super(12); + this.rejectMatches = rejectMatches; + this.rejectBorder = rejectBorder; + this.connectivity8 = connectivity8; + } + + protected ParticleFilterOptions(ByteBuffer backing, int offset) { + super(backing, offset, 12); + init(); + } + + protected ParticleFilterOptions(long nativeObj, boolean owned) { + super(nativeObj, owned, 12); + init(); + } + + protected void setBuffer(ByteBuffer backing, int offset) { + super.setBuffer(backing, offset, 12); + } + + public void read() { + rejectMatches = backing.getInt(0); + rejectBorder = backing.getInt(4); + connectivity8 = backing.getInt(8); + } + + public void write() { + backing.putInt(0, rejectMatches); + backing.putInt(4, rejectBorder); + backing.putInt(8, connectivity8); + } + + public int size() { + return 12; + } + } + + public static class StraightEdgeReport2 extends DisposedStruct { + public StraightEdge[] straightEdges; // Contains an array of found straight + // edges. + public SearchLineInfo[] searchLines; // Contains an array of all search + // lines used in the detection. + private ByteBuffer straightEdges_buf; + private ByteBuffer searchLines_buf; + + private void init() { + straightEdges = new StraightEdge[0]; + searchLines = new SearchLineInfo[0]; + } + + public StraightEdgeReport2() { + super(16); + init(); + } + + public StraightEdgeReport2(StraightEdge[] straightEdges, SearchLineInfo[] searchLines) { + super(16); + this.straightEdges = straightEdges; + this.searchLines = searchLines; + } + + protected StraightEdgeReport2(ByteBuffer backing, int offset) { + super(backing, offset, 16); + init(); + } + + protected StraightEdgeReport2(long nativeObj, boolean owned) { + super(nativeObj, owned, 16); + init(); + } + + protected void setBuffer(ByteBuffer backing, int offset) { + super.setBuffer(backing, offset, 16); + } + + public void read() { + int straightEdges_numStraightEdges = backing.getInt(4); + long straightEdges_addr = getPointer(backing, 0); + straightEdges = new StraightEdge[straightEdges_numStraightEdges]; + if (straightEdges_numStraightEdges > 0 && straightEdges_addr != 0) { + ByteBuffer bb = + newDirectByteBuffer(straightEdges_addr, straightEdges_numStraightEdges * 88); + for (int i = 0, off = 0; i < straightEdges_numStraightEdges; i++, off += 88) { + straightEdges[i] = new StraightEdge(bb, off); + straightEdges[i].read(); + } + } + int searchLines_numSearchLines = backing.getInt(12); + long searchLines_addr = getPointer(backing, 8); + searchLines = new SearchLineInfo[searchLines_numSearchLines]; + if (searchLines_numSearchLines > 0 && searchLines_addr != 0) { + ByteBuffer bb = newDirectByteBuffer(searchLines_addr, searchLines_numSearchLines * 36); + for (int i = 0, off = 0; i < searchLines_numSearchLines; i++, off += 36) { + searchLines[i] = new SearchLineInfo(bb, off); + searchLines[i].read(); + } + } + } + + public void write() { + straightEdges_buf = + ByteBuffer.allocateDirect(straightEdges.length * 88).order(ByteOrder.nativeOrder()); + for (int i = 0, off = 0; i < straightEdges.length; i++, off += 88) { + straightEdges[i].setBuffer(straightEdges_buf, off); + straightEdges[i].write(); + } + backing.putInt(4, straightEdges.length); + putPointer(backing, 0, straightEdges_buf); + searchLines_buf = + ByteBuffer.allocateDirect(searchLines.length * 36).order(ByteOrder.nativeOrder()); + for (int i = 0, off = 0; i < searchLines.length; i++, off += 36) { + searchLines[i].setBuffer(searchLines_buf, off); + searchLines[i].write(); + } + backing.putInt(12, searchLines.length); + putPointer(backing, 8, searchLines_buf); + } + + public int size() { + return 16; + } + } + + public static class StraightEdgeOptions extends DisposedStruct { + public int numLines; // Specifies the number of straight edges to find. + public StraightEdgeSearchMode searchMode; // Specifies the method used to + // find the straight edge. + public double minScore; // Specifies the minimum score of a detected + // straight edge. + public double maxScore; // Specifies the maximum score of a detected edge. + public double orientation; // Specifies the angle at which the straight edge + // is expected to be found. + public double angleRange; // Specifies the +/- range around the orientation + // within which the straight edge is expected to + // be found. + public double angleTolerance; // Specifies the expected angular accuracy of + // the straight edge. + public int stepSize; // Specifies the gap in pixels between the search lines + // used with the rake-based methods. + public double minSignalToNoiseRatio; // Specifies the minimum signal to + // noise ratio (SNR) of the edge points + // used to fit the straight edge. + public double minCoverage; // Specifies the minimum number of points as a + // percentage of the number of search lines that + // need to be included in the detected straight + // edge. + public int houghIterations; // Specifies the number of iterations used in + // the Hough-based method. + + private void init() { + + } + + public StraightEdgeOptions() { + super(80); + init(); + } + + public StraightEdgeOptions(int numLines, StraightEdgeSearchMode searchMode, double minScore, + double maxScore, double orientation, double angleRange, double angleTolerance, + int stepSize, double minSignalToNoiseRatio, double minCoverage, int houghIterations) { + super(80); + this.numLines = numLines; + this.searchMode = searchMode; + this.minScore = minScore; + this.maxScore = maxScore; + this.orientation = orientation; + this.angleRange = angleRange; + this.angleTolerance = angleTolerance; + this.stepSize = stepSize; + this.minSignalToNoiseRatio = minSignalToNoiseRatio; + this.minCoverage = minCoverage; + this.houghIterations = houghIterations; + } + + protected StraightEdgeOptions(ByteBuffer backing, int offset) { + super(backing, offset, 80); + init(); + } + + protected StraightEdgeOptions(long nativeObj, boolean owned) { + super(nativeObj, owned, 80); + init(); + } + + protected void setBuffer(ByteBuffer backing, int offset) { + super.setBuffer(backing, offset, 80); + } + + public void read() { + numLines = backing.getInt(0); + searchMode = StraightEdgeSearchMode.fromValue(backing.getInt(4)); + minScore = backing.getDouble(8); + maxScore = backing.getDouble(16); + orientation = backing.getDouble(24); + angleRange = backing.getDouble(32); + angleTolerance = backing.getDouble(40); + stepSize = backing.getInt(48); + minSignalToNoiseRatio = backing.getDouble(56); + minCoverage = backing.getDouble(64); + houghIterations = backing.getInt(72); + } + + public void write() { + backing.putInt(0, numLines); + if (searchMode != null) + backing.putInt(4, searchMode.getValue()); + backing.putDouble(8, minScore); + backing.putDouble(16, maxScore); + backing.putDouble(24, orientation); + backing.putDouble(32, angleRange); + backing.putDouble(40, angleTolerance); + backing.putInt(48, stepSize); + backing.putDouble(56, minSignalToNoiseRatio); + backing.putDouble(64, minCoverage); + backing.putInt(72, houghIterations); + } + + public int size() { + return 80; + } + } + + public static class StraightEdge extends DisposedStruct { + public LineFloat straightEdgeCoordinates; // End points of the detected + // straight edge in pixel + // coordinates. + public LineFloat calibratedStraightEdgeCoordinates; // End points of the + // detected straight + // edge in real-world + // coordinates. + public double angle; // Angle of the found edge using the pixel coordinates. + public double calibratedAngle; // Angle of the found edge using the + // real-world coordinates. + public double score; // Describes the score of the detected edge. + public double straightness; // The straightness value of the detected + // straight edge. + public double averageSignalToNoiseRatio; // Describes the average signal to + // noise ratio (SNR) of the + // detected edge. + public int calibrationValid; // Indicates if the calibration data for the + // straight edge is valid. + public EdgeInfo[] usedEdges; // An array of edges that were used to + // determine this straight line. + private ByteBuffer usedEdges_buf; + + private void init() { + straightEdgeCoordinates = new LineFloat(backing, 0); + calibratedStraightEdgeCoordinates = new LineFloat(backing, 16); + usedEdges = new EdgeInfo[0]; + } + + public StraightEdge() { + super(88); + init(); + } + + public StraightEdge(LineFloat straightEdgeCoordinates, + LineFloat calibratedStraightEdgeCoordinates, double angle, double calibratedAngle, + double score, double straightness, double averageSignalToNoiseRatio, int calibrationValid, + EdgeInfo[] usedEdges) { + super(88); + this.straightEdgeCoordinates = straightEdgeCoordinates; + this.calibratedStraightEdgeCoordinates = calibratedStraightEdgeCoordinates; + this.angle = angle; + this.calibratedAngle = calibratedAngle; + this.score = score; + this.straightness = straightness; + this.averageSignalToNoiseRatio = averageSignalToNoiseRatio; + this.calibrationValid = calibrationValid; + this.usedEdges = usedEdges; + } + + protected StraightEdge(ByteBuffer backing, int offset) { + super(backing, offset, 88); + init(); + } + + protected StraightEdge(long nativeObj, boolean owned) { + super(nativeObj, owned, 88); + init(); + } + + protected void setBuffer(ByteBuffer backing, int offset) { + super.setBuffer(backing, offset, 88); + } + + public void read() { + straightEdgeCoordinates.read(); + calibratedStraightEdgeCoordinates.read(); + angle = backing.getDouble(32); + calibratedAngle = backing.getDouble(40); + score = backing.getDouble(48); + straightness = backing.getDouble(56); + averageSignalToNoiseRatio = backing.getDouble(64); + calibrationValid = backing.getInt(72); + int usedEdges_numUsedEdges = backing.getInt(80); + long usedEdges_addr = getPointer(backing, 76); + usedEdges = new EdgeInfo[usedEdges_numUsedEdges]; + if (usedEdges_numUsedEdges > 0 && usedEdges_addr != 0) { + ByteBuffer bb = newDirectByteBuffer(usedEdges_addr, usedEdges_numUsedEdges * 56); + for (int i = 0, off = 0; i < usedEdges_numUsedEdges; i++, off += 56) { + usedEdges[i] = new EdgeInfo(bb, off); + usedEdges[i].read(); + } + } + } + + public void write() { + straightEdgeCoordinates.write(); + calibratedStraightEdgeCoordinates.write(); + backing.putDouble(32, angle); + backing.putDouble(40, calibratedAngle); + backing.putDouble(48, score); + backing.putDouble(56, straightness); + backing.putDouble(64, averageSignalToNoiseRatio); + backing.putInt(72, calibrationValid); + usedEdges_buf = + ByteBuffer.allocateDirect(usedEdges.length * 56).order(ByteOrder.nativeOrder()); + for (int i = 0, off = 0; i < usedEdges.length; i++, off += 56) { + usedEdges[i].setBuffer(usedEdges_buf, off); + usedEdges[i].write(); + } + backing.putInt(80, usedEdges.length); + putPointer(backing, 76, usedEdges_buf); + } + + public int size() { + return 88; + } + } + + public static class QRCodeSearchOptions extends DisposedStruct { + public QRRotationMode rotationMode; // Specifies the amount of QR code + // rotation the function should allow + // for. + public int skipLocation; // If set to TRUE, specifies that the function + // should assume that the QR code occupies the + // entire image (or the entire search region). + public int edgeThreshold; // The strength of the weakest edge the function + // uses to find the coarse location of the QR code + // in the image. + public QRDemodulationMode demodulationMode; // The demodulation mode the + // function uses to locate the + // QR code. + public QRCellSampleSize cellSampleSize; // The cell sample size the function + // uses to locate the QR code. + public QRCellFilterMode cellFilterMode; // The cell filter mode the function + // uses to locate the QR code. + public int skewDegreesAllowed; // Specifies the amount of skew in the QR + // code the function should allow for. + + private void init() { + + } + + public QRCodeSearchOptions() { + super(48); + init(); + } + + public QRCodeSearchOptions(QRRotationMode rotationMode, int skipLocation, int edgeThreshold, + QRDemodulationMode demodulationMode, QRCellSampleSize cellSampleSize, + QRCellFilterMode cellFilterMode, int skewDegreesAllowed) { + super(48); + this.rotationMode = rotationMode; + this.skipLocation = skipLocation; + this.edgeThreshold = edgeThreshold; + this.demodulationMode = demodulationMode; + this.cellSampleSize = cellSampleSize; + this.cellFilterMode = cellFilterMode; + this.skewDegreesAllowed = skewDegreesAllowed; + } + + protected QRCodeSearchOptions(ByteBuffer backing, int offset) { + super(backing, offset, 48); + init(); + } + + protected QRCodeSearchOptions(long nativeObj, boolean owned) { + super(nativeObj, owned, 48); + init(); + } + + protected void setBuffer(ByteBuffer backing, int offset) { + super.setBuffer(backing, offset, 48); + } + + public void read() { + rotationMode = QRRotationMode.fromValue(backing.getInt(0)); + skipLocation = backing.getInt(4); + edgeThreshold = backing.getInt(8); + demodulationMode = QRDemodulationMode.fromValue(backing.getInt(16)); + cellSampleSize = QRCellSampleSize.fromValue(backing.getInt(24)); + cellFilterMode = QRCellFilterMode.fromValue(backing.getInt(32)); + skewDegreesAllowed = backing.getInt(40); + } + + public void write() { + if (rotationMode != null) + backing.putInt(0, rotationMode.getValue()); + backing.putInt(4, skipLocation); + backing.putInt(8, edgeThreshold); + if (demodulationMode != null) + backing.putInt(16, demodulationMode.getValue()); + if (cellSampleSize != null) + backing.putInt(24, cellSampleSize.getValue()); + if (cellFilterMode != null) + backing.putInt(32, cellFilterMode.getValue()); + backing.putInt(40, skewDegreesAllowed); + } + + public int size() { + return 48; + } + } + + public static class QRCodeSizeOptions extends DisposedStruct { + public int minSize; // Specifies the minimum size (in pixels) of the QR code + // in the image. + public int maxSize; // Specifies the maximum size (in pixels) of the QR code + // in the image. + + private void init() { + + } + + public QRCodeSizeOptions() { + super(8); + init(); + } + + public QRCodeSizeOptions(int minSize, int maxSize) { + super(8); + this.minSize = minSize; + this.maxSize = maxSize; + } + + protected QRCodeSizeOptions(ByteBuffer backing, int offset) { + super(backing, offset, 8); + init(); + } + + protected QRCodeSizeOptions(long nativeObj, boolean owned) { + super(nativeObj, owned, 8); + init(); + } + + protected void setBuffer(ByteBuffer backing, int offset) { + super.setBuffer(backing, offset, 8); + } + + public void read() { + minSize = backing.getInt(0); + maxSize = backing.getInt(4); + } + + public void write() { + backing.putInt(0, minSize); + backing.putInt(4, maxSize); + } + + public int size() { + return 8; + } + } + + public static class QRCodeDescriptionOptions extends DisposedStruct { + public QRDimensions dimensions; // The number of rows and columns that are + // populated for the QR code, measured in + // cells. + public QRPolarities polarity; // The polarity of the QR code. + public QRMirrorMode mirror; // This element is TRUE if the QR code appears + // mirrored in the image and FALSE if the QR + // code appears normally in the image. + public QRModelType modelType; // This option allows you to specify the type + // of QR code. + + private void init() { + + } + + public QRCodeDescriptionOptions() { + super(32); + init(); + } + + public QRCodeDescriptionOptions(QRDimensions dimensions, QRPolarities polarity, + QRMirrorMode mirror, QRModelType modelType) { + super(32); + this.dimensions = dimensions; + this.polarity = polarity; + this.mirror = mirror; + this.modelType = modelType; + } + + protected QRCodeDescriptionOptions(ByteBuffer backing, int offset) { + super(backing, offset, 32); + init(); + } + + protected QRCodeDescriptionOptions(long nativeObj, boolean owned) { + super(nativeObj, owned, 32); + init(); + } + + protected void setBuffer(ByteBuffer backing, int offset) { + super.setBuffer(backing, offset, 32); + } + + public void read() { + dimensions = QRDimensions.fromValue(backing.getInt(0)); + polarity = QRPolarities.fromValue(backing.getInt(8)); + mirror = QRMirrorMode.fromValue(backing.getInt(16)); + modelType = QRModelType.fromValue(backing.getInt(24)); + } + + public void write() { + if (dimensions != null) + backing.putInt(0, dimensions.getValue()); + if (polarity != null) + backing.putInt(8, polarity.getValue()); + if (mirror != null) + backing.putInt(16, mirror.getValue()); + if (modelType != null) + backing.putInt(24, modelType.getValue()); + } + + public int size() { + return 32; + } + } + + public static class QRCodeReport extends DisposedStruct { + public int found; // This element is TRUE if the function located and + // decoded a QR code and FALSE if the function failed to + // locate and decode a QR code. + public byte[] data; // The data encoded in the QR code. + public PointFloat[] boundingBox; // An array of four points describing the + // rectangle surrounding the QR code. + public QRCodeDataToken[] tokenizedData; // Contains the data tokenized in + // exactly the way it was encoded in + // the code. + public int numErrorsCorrected; // The number of errors the function + // corrected when decoding the QR code. + public int dimensions; // The number of rows and columns that are populated + // for the QR code, measured in cells. + public int version; // The version of the QR code. + public QRModelType modelType; // This option allows you to specify what type + // of QR code this is. + public QRStreamMode streamMode; // The format of the data encoded in the + // stream. + public QRPolarities matrixPolarity; // The polarity of the QR code. + public int mirrored; // This element is TRUE if the QR code appears mirrored + // in the image and FALSE if the QR code appears + // normally in the image. + public int positionInAppendStream; // Indicates what position the QR code is + // in with respect to the stream of data + // in all codes. + public int sizeOfAppendStream; // Specifies how many QR codes are part of a + // larger array of codes. + public int firstEAN128ApplicationID; // The first EAN-128 Application ID + // encountered in the stream. + public int firstECIDesignator; // The first Regional Language Designator + // encountered in the stream. + public int appendStreamIdentifier; // Specifies what stream the QR code is + // in relation to when the code is part + // of a larger array of codes. + public int minimumEdgeStrength; // The strength of the weakest edge the + // function used to find the coarse location + // of the QR code in the image. + public QRDemodulationMode demodulationMode; // The demodulation mode the + // function used to locate the + // QR code. + public QRCellSampleSize cellSampleSize; // The cell sample size the function + // used to locate the QR code. + public QRCellFilterMode cellFilterMode; // The cell filter mode the function + // used to locate the QR code. + private ByteBuffer data_buf; + private ByteBuffer tokenizedData_buf; + + private void init() { + data = new byte[0]; + boundingBox = new PointFloat[4]; + + for (int i = 0, off = 12; i < 4; i++, off += 8) + boundingBox[i] = new PointFloat(backing, off); + tokenizedData = new QRCodeDataToken[0]; + } + + public QRCodeReport() { + super(136); + init(); + } + + public QRCodeReport(int found, byte[] data, PointFloat[] boundingBox, + QRCodeDataToken[] tokenizedData, int numErrorsCorrected, int dimensions, int version, + QRModelType modelType, QRStreamMode streamMode, QRPolarities matrixPolarity, int mirrored, + int positionInAppendStream, int sizeOfAppendStream, int firstEAN128ApplicationID, + int firstECIDesignator, int appendStreamIdentifier, int minimumEdgeStrength, + QRDemodulationMode demodulationMode, QRCellSampleSize cellSampleSize, + QRCellFilterMode cellFilterMode) { + super(136); + this.found = found; + this.data = data; + this.boundingBox = boundingBox; + this.tokenizedData = tokenizedData; + this.numErrorsCorrected = numErrorsCorrected; + this.dimensions = dimensions; + this.version = version; + this.modelType = modelType; + this.streamMode = streamMode; + this.matrixPolarity = matrixPolarity; + this.mirrored = mirrored; + this.positionInAppendStream = positionInAppendStream; + this.sizeOfAppendStream = sizeOfAppendStream; + this.firstEAN128ApplicationID = firstEAN128ApplicationID; + this.firstECIDesignator = firstECIDesignator; + this.appendStreamIdentifier = appendStreamIdentifier; + this.minimumEdgeStrength = minimumEdgeStrength; + this.demodulationMode = demodulationMode; + this.cellSampleSize = cellSampleSize; + this.cellFilterMode = cellFilterMode; + } + + protected QRCodeReport(ByteBuffer backing, int offset) { + super(backing, offset, 136); + init(); + } + + protected QRCodeReport(long nativeObj, boolean owned) { + super(nativeObj, owned, 136); + init(); + } + + protected void setBuffer(ByteBuffer backing, int offset) { + super.setBuffer(backing, offset, 136); + } + + public void read() { + found = backing.getInt(0); + int data_dataLength = backing.getInt(8); + long data_addr = getPointer(backing, 4); + data = new byte[data_dataLength]; + if (data_dataLength > 0 && data_addr != 0) { + getBytes(newDirectByteBuffer(data_addr, data_dataLength), data, 0, data_dataLength); + } + for (PointFloat it : boundingBox) { + it.read(); + } + int tokenizedData_sizeOfTokenizedData = backing.getInt(48); + long tokenizedData_addr = getPointer(backing, 44); + tokenizedData = new QRCodeDataToken[tokenizedData_sizeOfTokenizedData]; + if (tokenizedData_sizeOfTokenizedData > 0 && tokenizedData_addr != 0) { + ByteBuffer bb = + newDirectByteBuffer(tokenizedData_addr, tokenizedData_sizeOfTokenizedData * 16); + for (int i = 0, off = 0; i < tokenizedData_sizeOfTokenizedData; i++, off += 16) { + tokenizedData[i] = new QRCodeDataToken(bb, off); + tokenizedData[i].read(); + } + } + numErrorsCorrected = backing.getInt(52); + dimensions = backing.getInt(56); + version = backing.getInt(60); + modelType = QRModelType.fromValue(backing.getInt(64)); + streamMode = QRStreamMode.fromValue(backing.getInt(68)); + matrixPolarity = QRPolarities.fromValue(backing.getInt(72)); + mirrored = backing.getInt(80); + positionInAppendStream = backing.getInt(84); + sizeOfAppendStream = backing.getInt(88); + firstEAN128ApplicationID = backing.getInt(92); + firstECIDesignator = backing.getInt(96); + appendStreamIdentifier = backing.getInt(100); + minimumEdgeStrength = backing.getInt(104); + demodulationMode = QRDemodulationMode.fromValue(backing.getInt(112)); + cellSampleSize = QRCellSampleSize.fromValue(backing.getInt(120)); + cellFilterMode = QRCellFilterMode.fromValue(backing.getInt(128)); + } + + public void write() { + backing.putInt(0, found); + data_buf = ByteBuffer.allocateDirect(data.length); + putBytes(data_buf, data, 0, data.length); + backing.putInt(8, data.length); + putPointer(backing, 4, data_buf); + for (PointFloat it : boundingBox) { + it.write(); + } + tokenizedData_buf = + ByteBuffer.allocateDirect(tokenizedData.length * 16).order(ByteOrder.nativeOrder()); + for (int i = 0, off = 0; i < tokenizedData.length; i++, off += 16) { + tokenizedData[i].setBuffer(tokenizedData_buf, off); + tokenizedData[i].write(); + } + backing.putInt(48, tokenizedData.length); + putPointer(backing, 44, tokenizedData_buf); + backing.putInt(52, numErrorsCorrected); + backing.putInt(56, dimensions); + backing.putInt(60, version); + if (modelType != null) + backing.putInt(64, modelType.getValue()); + if (streamMode != null) + backing.putInt(68, streamMode.getValue()); + if (matrixPolarity != null) + backing.putInt(72, matrixPolarity.getValue()); + backing.putInt(80, mirrored); + backing.putInt(84, positionInAppendStream); + backing.putInt(88, sizeOfAppendStream); + backing.putInt(92, firstEAN128ApplicationID); + backing.putInt(96, firstECIDesignator); + backing.putInt(100, appendStreamIdentifier); + backing.putInt(104, minimumEdgeStrength); + if (demodulationMode != null) + backing.putInt(112, demodulationMode.getValue()); + if (cellSampleSize != null) + backing.putInt(120, cellSampleSize.getValue()); + if (cellFilterMode != null) + backing.putInt(128, cellFilterMode.getValue()); + } + + public int size() { + return 136; + } + } + + public static class AIMGradeReport extends DisposedStruct { + public AIMGrade overallGrade; // The overall letter grade, which is equal to + // the lowest of the other five letter grades. + public AIMGrade decodingGrade; // The letter grade assigned to a Data Matrix + // barcode based on the success of the + // function in decoding the Data Matrix + // barcode. + public AIMGrade symbolContrastGrade; // The letter grade assigned to a Data + // Matrix barcode based on the symbol + // contrast raw score. + public float symbolContrast; // The symbol contrast raw score representing + // the percentage difference between the mean + // of the reflectance of the darkest 10 percent + // and lightest 10 percent of the Data Matrix + // barcode. + public AIMGrade printGrowthGrade; // The print growth letter grade for the + // Data Matrix barcode. + public float printGrowth; // The print growth raw score for the barcode, + // which is based on the extent to which dark or + // light markings appropriately fill their module + // boundaries. + public AIMGrade axialNonuniformityGrade; // The axial nonuniformity grade + // for the Data Matrix barcode. + public float axialNonuniformity; // The axial nonuniformity raw score for + // the barcode, which is based on how much + // the sampling point spacing differs from + // one axis to another. + public AIMGrade unusedErrorCorrectionGrade; // The unused error correction + // letter grade for the Data + // Matrix barcode. + public float unusedErrorCorrection; // The unused error correction raw score + // for the Data Matrix barcode, which is + // based on the extent to which regional + // or spot damage in the Data Matrix + // barcode has eroded the reading safety + // margin provided by the error + // correction. + + private void init() { + + } + + public AIMGradeReport() { + super(40); + init(); + } + + public AIMGradeReport(AIMGrade overallGrade, AIMGrade decodingGrade, + AIMGrade symbolContrastGrade, double symbolContrast, AIMGrade printGrowthGrade, + double printGrowth, AIMGrade axialNonuniformityGrade, double axialNonuniformity, + AIMGrade unusedErrorCorrectionGrade, double unusedErrorCorrection) { + super(40); + this.overallGrade = overallGrade; + this.decodingGrade = decodingGrade; + this.symbolContrastGrade = symbolContrastGrade; + this.symbolContrast = (float) symbolContrast; + this.printGrowthGrade = printGrowthGrade; + this.printGrowth = (float) printGrowth; + this.axialNonuniformityGrade = axialNonuniformityGrade; + this.axialNonuniformity = (float) axialNonuniformity; + this.unusedErrorCorrectionGrade = unusedErrorCorrectionGrade; + this.unusedErrorCorrection = (float) unusedErrorCorrection; + } + + protected AIMGradeReport(ByteBuffer backing, int offset) { + super(backing, offset, 40); + init(); + } + + protected AIMGradeReport(long nativeObj, boolean owned) { + super(nativeObj, owned, 40); + init(); + } + + protected void setBuffer(ByteBuffer backing, int offset) { + super.setBuffer(backing, offset, 40); + } + + public void read() { + overallGrade = AIMGrade.fromValue(backing.getInt(0)); + decodingGrade = AIMGrade.fromValue(backing.getInt(4)); + symbolContrastGrade = AIMGrade.fromValue(backing.getInt(8)); + symbolContrast = backing.getFloat(12); + printGrowthGrade = AIMGrade.fromValue(backing.getInt(16)); + printGrowth = backing.getFloat(20); + axialNonuniformityGrade = AIMGrade.fromValue(backing.getInt(24)); + axialNonuniformity = backing.getFloat(28); + unusedErrorCorrectionGrade = AIMGrade.fromValue(backing.getInt(32)); + unusedErrorCorrection = backing.getFloat(36); + } + + public void write() { + if (overallGrade != null) + backing.putInt(0, overallGrade.getValue()); + if (decodingGrade != null) + backing.putInt(4, decodingGrade.getValue()); + if (symbolContrastGrade != null) + backing.putInt(8, symbolContrastGrade.getValue()); + backing.putFloat(12, symbolContrast); + if (printGrowthGrade != null) + backing.putInt(16, printGrowthGrade.getValue()); + backing.putFloat(20, printGrowth); + if (axialNonuniformityGrade != null) + backing.putInt(24, axialNonuniformityGrade.getValue()); + backing.putFloat(28, axialNonuniformity); + if (unusedErrorCorrectionGrade != null) + backing.putInt(32, unusedErrorCorrectionGrade.getValue()); + backing.putFloat(36, unusedErrorCorrection); + } + + public int size() { + return 40; + } + } + + public static class DataMatrixSizeOptions extends DisposedStruct { + public int minSize; // Specifies the minimum size (in pixels) of the Data + // Matrix barcode in the image. + public int maxSize; // Specifies the maximum size (in pixels) of the Data + // Matrix barcode in the image. + public int quietZoneWidth; // Specifies the expected minimum size of the + // quiet zone, in pixels. + + private void init() { + + } + + public DataMatrixSizeOptions() { + super(12); + init(); + } + + public DataMatrixSizeOptions(int minSize, int maxSize, int quietZoneWidth) { + super(12); + this.minSize = minSize; + this.maxSize = maxSize; + this.quietZoneWidth = quietZoneWidth; + } + + protected DataMatrixSizeOptions(ByteBuffer backing, int offset) { + super(backing, offset, 12); + init(); + } + + protected DataMatrixSizeOptions(long nativeObj, boolean owned) { + super(nativeObj, owned, 12); + init(); + } + + protected void setBuffer(ByteBuffer backing, int offset) { + super.setBuffer(backing, offset, 12); + } + + public void read() { + minSize = backing.getInt(0); + maxSize = backing.getInt(4); + quietZoneWidth = backing.getInt(8); + } + + public void write() { + backing.putInt(0, minSize); + backing.putInt(4, maxSize); + backing.putInt(8, quietZoneWidth); + } + + public int size() { + return 12; + } + } + + public static class DataMatrixDescriptionOptions extends DisposedStruct { + public float aspectRatio; // Specifies the ratio of the width of each Data + // Matrix barcode cell (in pixels) to the height + // of the Data Matrix barcode (in pixels). + public int rows; // Specifies the number of rows in the Data Matrix barcode. + public int columns; // Specifies the number of columns in the Data Matrix + // barcode. + public int rectangle; // Set this element to TRUE to specify that the Data + // Matrix barcode is rectangular. + public DataMatrixECC ecc; // Specifies the ECC used for this Data Matrix + // barcode. + public DataMatrixPolarity polarity; // Specifies the data-to-background + // contrast for the Data Matrix barcode. + public DataMatrixCellFillMode cellFill; // Specifies the fill percentage for + // a cell of the Data Matrix barcode + // that is in the "ON" state. + public float minBorderIntegrity; // Specifies the minimum percentage of the + // border (locator pattern and timing + // pattern) the function should expect in + // the Data Matrix barcode. + public DataMatrixMirrorMode mirrorMode; // Specifies if the Data Matrix + // barcode appears normally in the + // image or if the barcode appears + // mirrored in the image. + + private void init() { + + } + + public DataMatrixDescriptionOptions() { + super(56); + init(); + } + + public DataMatrixDescriptionOptions(double aspectRatio, int rows, int columns, int rectangle, + DataMatrixECC ecc, DataMatrixPolarity polarity, DataMatrixCellFillMode cellFill, + double minBorderIntegrity, DataMatrixMirrorMode mirrorMode) { + super(56); + this.aspectRatio = (float) aspectRatio; + this.rows = rows; + this.columns = columns; + this.rectangle = rectangle; + this.ecc = ecc; + this.polarity = polarity; + this.cellFill = cellFill; + this.minBorderIntegrity = (float) minBorderIntegrity; + this.mirrorMode = mirrorMode; + } + + protected DataMatrixDescriptionOptions(ByteBuffer backing, int offset) { + super(backing, offset, 56); + init(); + } + + protected DataMatrixDescriptionOptions(long nativeObj, boolean owned) { + super(nativeObj, owned, 56); + init(); + } + + protected void setBuffer(ByteBuffer backing, int offset) { + super.setBuffer(backing, offset, 56); + } + + public void read() { + aspectRatio = backing.getFloat(0); + rows = backing.getInt(4); + columns = backing.getInt(8); + rectangle = backing.getInt(12); + ecc = DataMatrixECC.fromValue(backing.getInt(16)); + polarity = DataMatrixPolarity.fromValue(backing.getInt(24)); + cellFill = DataMatrixCellFillMode.fromValue(backing.getInt(32)); + minBorderIntegrity = backing.getFloat(40); + mirrorMode = DataMatrixMirrorMode.fromValue(backing.getInt(48)); + } + + public void write() { + backing.putFloat(0, aspectRatio); + backing.putInt(4, rows); + backing.putInt(8, columns); + backing.putInt(12, rectangle); + if (ecc != null) + backing.putInt(16, ecc.getValue()); + if (polarity != null) + backing.putInt(24, polarity.getValue()); + if (cellFill != null) + backing.putInt(32, cellFill.getValue()); + backing.putFloat(40, minBorderIntegrity); + if (mirrorMode != null) + backing.putInt(48, mirrorMode.getValue()); + } + + public int size() { + return 56; + } + } + + public static class DataMatrixSearchOptions extends DisposedStruct { + public DataMatrixRotationMode rotationMode; // Specifies the amount of Data + // Matrix barcode rotation the + // function should allow for. + public int skipLocation; // If set to TRUE, specifies that the function + // should assume that the Data Matrix barcode + // occupies the entire image (or the entire search + // region). + public int edgeThreshold; // Specifies the minimum contrast a pixel must + // have in order to be considered part of a matrix + // cell edge. + public DataMatrixDemodulationMode demodulationMode; // Specifies the mode + // the function should + // use to demodulate + // (determine which + // cells are on and + // which cells are off) + // the Data Matrix + // barcode. + public DataMatrixCellSampleSize cellSampleSize; // Specifies the sample + // size, in pixels, the + // function should take to + // determine if each cell is + // on or off. + public DataMatrixCellFilterMode cellFilterMode; // Specifies the mode the + // function uses to + // determine the pixel value + // for each cell. + public int skewDegreesAllowed; // Specifies the amount of skew in the Data + // Matrix barcode the function should allow + // for. + public int maxIterations; // Specifies the maximum number of iterations + // before the function stops looking for the Data + // Matrix barcode. + public int initialSearchVectorWidth; // Specifies the number of pixels the + // function should average together to + // determine the location of an edge. + + private void init() { + + } + + public DataMatrixSearchOptions() { + super(56); + init(); + } + + public DataMatrixSearchOptions(DataMatrixRotationMode rotationMode, int skipLocation, + int edgeThreshold, DataMatrixDemodulationMode demodulationMode, + DataMatrixCellSampleSize cellSampleSize, DataMatrixCellFilterMode cellFilterMode, + int skewDegreesAllowed, int maxIterations, int initialSearchVectorWidth) { + super(56); + this.rotationMode = rotationMode; + this.skipLocation = skipLocation; + this.edgeThreshold = edgeThreshold; + this.demodulationMode = demodulationMode; + this.cellSampleSize = cellSampleSize; + this.cellFilterMode = cellFilterMode; + this.skewDegreesAllowed = skewDegreesAllowed; + this.maxIterations = maxIterations; + this.initialSearchVectorWidth = initialSearchVectorWidth; + } + + protected DataMatrixSearchOptions(ByteBuffer backing, int offset) { + super(backing, offset, 56); + init(); + } + + protected DataMatrixSearchOptions(long nativeObj, boolean owned) { + super(nativeObj, owned, 56); + init(); + } + + protected void setBuffer(ByteBuffer backing, int offset) { + super.setBuffer(backing, offset, 56); + } + + public void read() { + rotationMode = DataMatrixRotationMode.fromValue(backing.getInt(0)); + skipLocation = backing.getInt(4); + edgeThreshold = backing.getInt(8); + demodulationMode = DataMatrixDemodulationMode.fromValue(backing.getInt(16)); + cellSampleSize = DataMatrixCellSampleSize.fromValue(backing.getInt(24)); + cellFilterMode = DataMatrixCellFilterMode.fromValue(backing.getInt(32)); + skewDegreesAllowed = backing.getInt(40); + maxIterations = backing.getInt(44); + initialSearchVectorWidth = backing.getInt(48); + } + + public void write() { + if (rotationMode != null) + backing.putInt(0, rotationMode.getValue()); + backing.putInt(4, skipLocation); + backing.putInt(8, edgeThreshold); + if (demodulationMode != null) + backing.putInt(16, demodulationMode.getValue()); + if (cellSampleSize != null) + backing.putInt(24, cellSampleSize.getValue()); + if (cellFilterMode != null) + backing.putInt(32, cellFilterMode.getValue()); + backing.putInt(40, skewDegreesAllowed); + backing.putInt(44, maxIterations); + backing.putInt(48, initialSearchVectorWidth); + } + + public int size() { + return 56; + } + } + + public static class DataMatrixReport extends DisposedStruct { + public int found; // This element is TRUE if the function located and + // decoded a Data Matrix barcode and FALSE if the function + // failed to locate and decode a Data Matrix barcode. + public int binary; // This element is TRUE if the Data Matrix barcode + // contains binary data and FALSE if the Data Matrix + // barcode contains text data. + public byte[] data; // The data encoded in the Data Matrix barcode. + public PointFloat[] boundingBox; // An array of four points describing the + // rectangle surrounding the Data Matrix + // barcode. + public int numErrorsCorrected; // The number of errors the function + // corrected when decoding the Data Matrix + // barcode. + public int numErasuresCorrected; // The number of erasures the function + // corrected when decoding the Data Matrix + // barcode. + public float aspectRatio; // Specifies the aspect ratio of the Data Matrix + // barcode in the image, which equals the ratio of + // the width of a Data Matrix barcode cell (in + // pixels) to the height of a Data Matrix barcode + // cell (in pixels). + public int rows; // The number of rows in the Data Matrix barcode. + public int columns; // The number of columns in the Data Matrix barcode. + public DataMatrixECC ecc; // The Error Correction Code (ECC) used by the + // Data Matrix barcode. + public DataMatrixPolarity polarity; // The polarity of the Data Matrix + // barcode. + public DataMatrixCellFillMode cellFill; // The cell fill percentage of the + // Data Matrix barcode. + public float borderIntegrity; // The percentage of the Data Matrix barcode + // border that appears correctly in the image. + public int mirrored; // This element is TRUE if the Data Matrix barcode + // appears mirrored in the image and FALSE if the Data + // Matrix barcode appears normally in the image. + public int minimumEdgeStrength; // The strength of the weakest edge the + // function used to find the coarse location + // of the Data Matrix barcode in the image. + public DataMatrixDemodulationMode demodulationMode; // The demodulation mode + // the function used to + // locate the Data + // Matrix barcode. + public DataMatrixCellSampleSize cellSampleSize; // The cell sample size the + // function used to locate + // the Data Matrix barcode. + public DataMatrixCellFilterMode cellFilterMode; // The cell filter mode the + // function used to locate + // the Data Matrix barcode. + public int iterations; // The number of iterations the function took in + // attempting to locate the Data Matrix barcode. + private ByteBuffer data_buf; + + private void init() { + data = new byte[0]; + boundingBox = new PointFloat[4]; + + for (int i = 0, off = 16; i < 4; i++, off += 8) + boundingBox[i] = new PointFloat(backing, off); + } + + public DataMatrixReport() { + super(144); + init(); + } + + public DataMatrixReport(int found, int binary, byte[] data, PointFloat[] boundingBox, + int numErrorsCorrected, int numErasuresCorrected, double aspectRatio, int rows, + int columns, DataMatrixECC ecc, DataMatrixPolarity polarity, + DataMatrixCellFillMode cellFill, double borderIntegrity, int mirrored, + int minimumEdgeStrength, DataMatrixDemodulationMode demodulationMode, + DataMatrixCellSampleSize cellSampleSize, DataMatrixCellFilterMode cellFilterMode, + int iterations) { + super(144); + this.found = found; + this.binary = binary; + this.data = data; + this.boundingBox = boundingBox; + this.numErrorsCorrected = numErrorsCorrected; + this.numErasuresCorrected = numErasuresCorrected; + this.aspectRatio = (float) aspectRatio; + this.rows = rows; + this.columns = columns; + this.ecc = ecc; + this.polarity = polarity; + this.cellFill = cellFill; + this.borderIntegrity = (float) borderIntegrity; + this.mirrored = mirrored; + this.minimumEdgeStrength = minimumEdgeStrength; + this.demodulationMode = demodulationMode; + this.cellSampleSize = cellSampleSize; + this.cellFilterMode = cellFilterMode; + this.iterations = iterations; + } + + protected DataMatrixReport(ByteBuffer backing, int offset) { + super(backing, offset, 144); + init(); + } + + protected DataMatrixReport(long nativeObj, boolean owned) { + super(nativeObj, owned, 144); + init(); + } + + protected void setBuffer(ByteBuffer backing, int offset) { + super.setBuffer(backing, offset, 144); + } + + public void read() { + found = backing.getInt(0); + binary = backing.getInt(4); + int data_dataLength = backing.getInt(12); + long data_addr = getPointer(backing, 8); + data = new byte[data_dataLength]; + if (data_dataLength > 0 && data_addr != 0) { + getBytes(newDirectByteBuffer(data_addr, data_dataLength), data, 0, data_dataLength); + } + for (PointFloat it : boundingBox) { + it.read(); + } + numErrorsCorrected = backing.getInt(48); + numErasuresCorrected = backing.getInt(52); + aspectRatio = backing.getFloat(56); + rows = backing.getInt(60); + columns = backing.getInt(64); + ecc = DataMatrixECC.fromValue(backing.getInt(72)); + polarity = DataMatrixPolarity.fromValue(backing.getInt(80)); + cellFill = DataMatrixCellFillMode.fromValue(backing.getInt(88)); + borderIntegrity = backing.getFloat(96); + mirrored = backing.getInt(100); + minimumEdgeStrength = backing.getInt(104); + demodulationMode = DataMatrixDemodulationMode.fromValue(backing.getInt(112)); + cellSampleSize = DataMatrixCellSampleSize.fromValue(backing.getInt(120)); + cellFilterMode = DataMatrixCellFilterMode.fromValue(backing.getInt(128)); + iterations = backing.getInt(136); + } + + public void write() { + backing.putInt(0, found); + backing.putInt(4, binary); + data_buf = ByteBuffer.allocateDirect(data.length); + putBytes(data_buf, data, 0, data.length); + backing.putInt(12, data.length); + putPointer(backing, 8, data_buf); + for (PointFloat it : boundingBox) { + it.write(); + } + backing.putInt(48, numErrorsCorrected); + backing.putInt(52, numErasuresCorrected); + backing.putFloat(56, aspectRatio); + backing.putInt(60, rows); + backing.putInt(64, columns); + if (ecc != null) + backing.putInt(72, ecc.getValue()); + if (polarity != null) + backing.putInt(80, polarity.getValue()); + if (cellFill != null) + backing.putInt(88, cellFill.getValue()); + backing.putFloat(96, borderIntegrity); + backing.putInt(100, mirrored); + backing.putInt(104, minimumEdgeStrength); + if (demodulationMode != null) + backing.putInt(112, demodulationMode.getValue()); + if (cellSampleSize != null) + backing.putInt(120, cellSampleSize.getValue()); + if (cellFilterMode != null) + backing.putInt(128, cellFilterMode.getValue()); + backing.putInt(136, iterations); + } + + public int size() { + return 144; + } + } + + public static class JPEG2000FileAdvancedOptions extends DisposedStruct { + public WaveletTransformMode waveletMode; // Determines which wavelet + // transform to use when writing + // the file. + public int useMultiComponentTransform; // Set this parameter to TRUE to use + // an additional transform on RGB + // images. + public int maxWaveletTransformLevel; // Specifies the maximum allowed level + // of wavelet transform. + public float quantizationStepSize; // Specifies the absolute base + // quantization step size for derived + // quantization mode. + + private void init() { + + } + + public JPEG2000FileAdvancedOptions() { + super(16); + init(); + } + + public JPEG2000FileAdvancedOptions(WaveletTransformMode waveletMode, + int useMultiComponentTransform, int maxWaveletTransformLevel, double quantizationStepSize) { + super(16); + this.waveletMode = waveletMode; + this.useMultiComponentTransform = useMultiComponentTransform; + this.maxWaveletTransformLevel = maxWaveletTransformLevel; + this.quantizationStepSize = (float) quantizationStepSize; + } + + protected JPEG2000FileAdvancedOptions(ByteBuffer backing, int offset) { + super(backing, offset, 16); + init(); + } + + protected JPEG2000FileAdvancedOptions(long nativeObj, boolean owned) { + super(nativeObj, owned, 16); + init(); + } + + protected void setBuffer(ByteBuffer backing, int offset) { + super.setBuffer(backing, offset, 16); + } + + public void read() { + waveletMode = WaveletTransformMode.fromValue(backing.getInt(0)); + useMultiComponentTransform = backing.getInt(4); + maxWaveletTransformLevel = backing.getInt(8); + quantizationStepSize = backing.getFloat(12); + } + + public void write() { + if (waveletMode != null) + backing.putInt(0, waveletMode.getValue()); + backing.putInt(4, useMultiComponentTransform); + backing.putInt(8, maxWaveletTransformLevel); + backing.putFloat(12, quantizationStepSize); + } + + public int size() { + return 16; + } + } + + public static class MatchGeometricPatternAdvancedOptions2 extends DisposedStruct { + public int minFeaturesUsed; // Specifies the minimum number of features the + // function uses when matching. + public int maxFeaturesUsed; // Specifies the maximum number of features the + // function uses when matching. + public int subpixelIterations; // Specifies the maximum number of + // incremental improvements used to refine + // matches with subpixel information. + public double subpixelTolerance; // Specifies the maximum amount of change, + // in pixels, between consecutive + // incremental improvements in the match + // position before the function stops + // refining the match position. + public int initialMatchListLength; // Specifies the maximum size of the + // match list. + public float matchTemplateCurveScore; // Set this element to TRUE to specify + // that the function should calculate + // the match curve to template curve + // score and return it for each match + // result. + public int correlationScore; // Set this element to TRUE to specify that the + // function should calculate the correlation + // score and return it for each match result. + public double minMatchSeparationDistance; // Specifies the minimum + // separation distance, in pixels, + // between the origins of two + // matches that have unique + // positions. + public double minMatchSeparationAngle; // Specifies the minimum angular + // difference, in degrees, between + // two matches that have unique + // angles. + public double minMatchSeparationScale; // Specifies the minimum difference + // in scale, expressed as a + // percentage, between two matches + // that have unique scales. + public double maxMatchOverlap; // Specifies the maximum amount of overlap, + // expressed as a percentage, allowed between + // the bounding rectangles of two unique + // matches. + public int coarseResult; // Specifies whether you want the function to spend + // less time accurately estimating the location of + // a match. + public int smoothContours; // Set this element to TRUE to specify smoothing + // be done on the contours of the inspection + // image before feature extraction. + public int enableCalibrationSupport; // Set this element to TRUE to specify + // the algorithm treat the inspection + // image as a calibrated image. + + private void init() { + + } + + public MatchGeometricPatternAdvancedOptions2() { + super(88); + init(); + } + + public MatchGeometricPatternAdvancedOptions2(int minFeaturesUsed, int maxFeaturesUsed, + int subpixelIterations, double subpixelTolerance, int initialMatchListLength, + double matchTemplateCurveScore, int correlationScore, double minMatchSeparationDistance, + double minMatchSeparationAngle, double minMatchSeparationScale, double maxMatchOverlap, + int coarseResult, int smoothContours, int enableCalibrationSupport) { + super(88); + this.minFeaturesUsed = minFeaturesUsed; + this.maxFeaturesUsed = maxFeaturesUsed; + this.subpixelIterations = subpixelIterations; + this.subpixelTolerance = subpixelTolerance; + this.initialMatchListLength = initialMatchListLength; + this.matchTemplateCurveScore = (float) matchTemplateCurveScore; + this.correlationScore = correlationScore; + this.minMatchSeparationDistance = minMatchSeparationDistance; + this.minMatchSeparationAngle = minMatchSeparationAngle; + this.minMatchSeparationScale = minMatchSeparationScale; + this.maxMatchOverlap = maxMatchOverlap; + this.coarseResult = coarseResult; + this.smoothContours = smoothContours; + this.enableCalibrationSupport = enableCalibrationSupport; + } + + protected MatchGeometricPatternAdvancedOptions2(ByteBuffer backing, int offset) { + super(backing, offset, 88); + init(); + } + + protected MatchGeometricPatternAdvancedOptions2(long nativeObj, boolean owned) { + super(nativeObj, owned, 88); + init(); + } + + protected void setBuffer(ByteBuffer backing, int offset) { + super.setBuffer(backing, offset, 88); + } + + public void read() { + minFeaturesUsed = backing.getInt(0); + maxFeaturesUsed = backing.getInt(4); + subpixelIterations = backing.getInt(8); + subpixelTolerance = backing.getDouble(16); + initialMatchListLength = backing.getInt(24); + matchTemplateCurveScore = backing.getFloat(28); + correlationScore = backing.getInt(32); + minMatchSeparationDistance = backing.getDouble(40); + minMatchSeparationAngle = backing.getDouble(48); + minMatchSeparationScale = backing.getDouble(56); + maxMatchOverlap = backing.getDouble(64); + coarseResult = backing.getInt(72); + smoothContours = backing.getInt(76); + enableCalibrationSupport = backing.getInt(80); + } + + public void write() { + backing.putInt(0, minFeaturesUsed); + backing.putInt(4, maxFeaturesUsed); + backing.putInt(8, subpixelIterations); + backing.putDouble(16, subpixelTolerance); + backing.putInt(24, initialMatchListLength); + backing.putFloat(28, matchTemplateCurveScore); + backing.putInt(32, correlationScore); + backing.putDouble(40, minMatchSeparationDistance); + backing.putDouble(48, minMatchSeparationAngle); + backing.putDouble(56, minMatchSeparationScale); + backing.putDouble(64, maxMatchOverlap); + backing.putInt(72, coarseResult); + backing.putInt(76, smoothContours); + backing.putInt(80, enableCalibrationSupport); + } + + public int size() { + return 88; + } + } + + public static class InspectionAlignment extends DisposedStruct { + public PointFloat position; // The location of the center of the golden + // template in the image under inspection. + public float rotation; // The rotation of the golden template in the image + // under inspection, in degrees. + public float scale; // The percentage of the size of the area under + // inspection compared to the size of the golden + // template. + + private void init() { + position = new PointFloat(backing, 0); + } + + public InspectionAlignment() { + super(16); + init(); + } + + public InspectionAlignment(PointFloat position, double rotation, double scale) { + super(16); + this.position = position; + this.rotation = (float) rotation; + this.scale = (float) scale; + } + + protected InspectionAlignment(ByteBuffer backing, int offset) { + super(backing, offset, 16); + init(); + } + + protected InspectionAlignment(long nativeObj, boolean owned) { + super(nativeObj, owned, 16); + init(); + } + + protected void setBuffer(ByteBuffer backing, int offset) { + super.setBuffer(backing, offset, 16); + } + + public void read() { + position.read(); + rotation = backing.getFloat(8); + scale = backing.getFloat(12); + } + + public void write() { + position.write(); + backing.putFloat(8, rotation); + backing.putFloat(12, scale); + } + + public int size() { + return 16; + } + } + + public static class InspectionOptions extends DisposedStruct { + public RegistrationMethod registrationMethod; // Specifies how the function + // registers the golden + // template and the target + // image. + public NormalizationMethod normalizationMethod; // Specifies how the + // function normalizes the + // golden template to the + // target image. + public int edgeThicknessToIgnore; // Specifies desired thickness of edges to + // be ignored. + public float brightThreshold; // Specifies the threshold for areas where the + // target image is brighter than the golden + // template. + public float darkThreshold; // Specifies the threshold for areas where the + // target image is darker than the golden + // template. + public int binary; // Specifies whether the function should return a binary + // image giving the location of defects, or a grayscale + // image giving the intensity of defects. + + private void init() { + + } + + public InspectionOptions() { + super(24); + init(); + } + + public InspectionOptions(RegistrationMethod registrationMethod, + NormalizationMethod normalizationMethod, int edgeThicknessToIgnore, double brightThreshold, + double darkThreshold, int binary) { + super(24); + this.registrationMethod = registrationMethod; + this.normalizationMethod = normalizationMethod; + this.edgeThicknessToIgnore = edgeThicknessToIgnore; + this.brightThreshold = (float) brightThreshold; + this.darkThreshold = (float) darkThreshold; + this.binary = binary; + } + + protected InspectionOptions(ByteBuffer backing, int offset) { + super(backing, offset, 24); + init(); + } + + protected InspectionOptions(long nativeObj, boolean owned) { + super(nativeObj, owned, 24); + init(); + } + + protected void setBuffer(ByteBuffer backing, int offset) { + super.setBuffer(backing, offset, 24); + } + + public void read() { + registrationMethod = RegistrationMethod.fromValue(backing.getInt(0)); + normalizationMethod = NormalizationMethod.fromValue(backing.getInt(4)); + edgeThicknessToIgnore = backing.getInt(8); + brightThreshold = backing.getFloat(12); + darkThreshold = backing.getFloat(16); + binary = backing.getInt(20); + } + + public void write() { + if (registrationMethod != null) + backing.putInt(0, registrationMethod.getValue()); + if (normalizationMethod != null) + backing.putInt(4, normalizationMethod.getValue()); + backing.putInt(8, edgeThicknessToIgnore); + backing.putFloat(12, brightThreshold); + backing.putFloat(16, darkThreshold); + backing.putInt(20, binary); + } + + public int size() { + return 24; + } + } + + public static class CharReport2 extends DisposedStruct { + public String character; // The character value. + public PointFloat[] corner; // An array of four points that describes the + // rectangle that surrounds the character. + public int lowThreshold; // The minimum value of the threshold range used + // for this character. + public int highThreshold; // The maximum value of the threshold range used + // for this character. + public int classificationScore; // The degree to which the assigned + // character class represents the object + // better than the other character classes + // in the character set. + public int verificationScore; // The similarity of the character and the + // reference character for the character + // class. + public int verified; // This element is TRUE if a reference character was + // found for the character class and FALSE if a + // reference character was not found. + private ByteBuffer character_buf; + + private void init() { + corner = new PointFloat[4]; + + for (int i = 0, off = 4; i < 4; i++, off += 8) + corner[i] = new PointFloat(backing, off); + } + + public CharReport2() { + super(56); + init(); + } + + public CharReport2(String character, PointFloat[] corner, int lowThreshold, int highThreshold, + int classificationScore, int verificationScore, int verified) { + super(56); + this.character = character; + this.corner = corner; + this.lowThreshold = lowThreshold; + this.highThreshold = highThreshold; + this.classificationScore = classificationScore; + this.verificationScore = verificationScore; + this.verified = verified; + } + + protected CharReport2(ByteBuffer backing, int offset) { + super(backing, offset, 56); + init(); + } + + protected CharReport2(long nativeObj, boolean owned) { + super(nativeObj, owned, 56); + init(); + } + + protected void setBuffer(ByteBuffer backing, int offset) { + super.setBuffer(backing, offset, 56); + } + + public void read() { + long character_addr = getPointer(backing, 0); + if (character_addr == 0) + character = null; + else { + ByteBuffer bb = newDirectByteBuffer(character_addr, 1000); // FIXME + while (bb.get() != 0) { + } + byte[] bytes = new byte[bb.position() - 1]; + getBytes(bb, bytes, 0, bytes.length); + try { + character = new String(bytes, "UTF-8"); + } catch (UnsupportedEncodingException e) { + character = ""; + } + } + + for (PointFloat it : corner) { + it.read(); + } + lowThreshold = backing.getInt(36); + highThreshold = backing.getInt(40); + classificationScore = backing.getInt(44); + verificationScore = backing.getInt(48); + verified = backing.getInt(52); + } + + public void write() { + if (character != null) { + byte[] character_bytes; + try { + character_bytes = character.getBytes("UTF-8"); + } catch (UnsupportedEncodingException e) { + character_bytes = new byte[0]; + } + character_buf = ByteBuffer.allocateDirect(character_bytes.length + 1); + putBytes(character_buf, character_bytes, 0, character_bytes.length).put( + character_bytes.length, (byte) 0); + } + putPointer(backing, 0, character == null ? 0 : getByteBufferAddress(character_buf)); + for (PointFloat it : corner) { + it.write(); + } + backing.putInt(36, lowThreshold); + backing.putInt(40, highThreshold); + backing.putInt(44, classificationScore); + backing.putInt(48, verificationScore); + backing.putInt(52, verified); + } + + public int size() { + return 56; + } + } + + public static class CharInfo2 extends DisposedStruct { + public String charValue; // Retrieves the character value of the + // corresponding character in the character set. + public Image charImage; // The image you used to train this character. + public Image internalImage; // The internal representation that NI Vision + // uses to match objects to this character. + public int isReferenceChar; // This element is TRUE if the character is the + // reference character for the character class. + private ByteBuffer charValue_buf; + + private void init() { + + } + + public CharInfo2() { + super(16); + init(); + } + + public CharInfo2(String charValue, Image charImage, Image internalImage, int isReferenceChar) { + super(16); + this.charValue = charValue; + this.charImage = charImage; + this.internalImage = internalImage; + this.isReferenceChar = isReferenceChar; + } + + protected CharInfo2(ByteBuffer backing, int offset) { + super(backing, offset, 16); + init(); + } + + protected CharInfo2(long nativeObj, boolean owned) { + super(nativeObj, owned, 16); + init(); + } + + protected void setBuffer(ByteBuffer backing, int offset) { + super.setBuffer(backing, offset, 16); + } + + public void read() { + long charValue_addr = getPointer(backing, 0); + if (charValue_addr == 0) + charValue = null; + else { + ByteBuffer bb = newDirectByteBuffer(charValue_addr, 1000); // FIXME + while (bb.get() != 0) { + } + byte[] bytes = new byte[bb.position() - 1]; + getBytes(bb, bytes, 0, bytes.length); + try { + charValue = new String(bytes, "UTF-8"); + } catch (UnsupportedEncodingException e) { + charValue = ""; + } + } + + long charImage_addr = getPointer(backing, 4); + if (charImage_addr == 0) + charImage = null; + else + charImage = new Image(charImage_addr, false); + long internalImage_addr = getPointer(backing, 8); + if (internalImage_addr == 0) + internalImage = null; + else + internalImage = new Image(internalImage_addr, false); + isReferenceChar = backing.getInt(12); + } + + public void write() { + if (charValue != null) { + byte[] charValue_bytes; + try { + charValue_bytes = charValue.getBytes("UTF-8"); + } catch (UnsupportedEncodingException e) { + charValue_bytes = new byte[0]; + } + charValue_buf = ByteBuffer.allocateDirect(charValue_bytes.length + 1); + putBytes(charValue_buf, charValue_bytes, 0, charValue_bytes.length).put( + charValue_bytes.length, (byte) 0); + } + putPointer(backing, 0, charValue == null ? 0 : getByteBufferAddress(charValue_buf)); + putPointer(backing, 4, charImage); + putPointer(backing, 8, internalImage); + backing.putInt(12, isReferenceChar); + } + + public int size() { + return 16; + } + } + + public static class ReadTextReport2 extends DisposedStruct { + public String readString; // The read string. + public CharReport2[] characterReport; // An array of reports describing the + // properties of each identified + // character. + private ByteBuffer readString_buf; + private ByteBuffer characterReport_buf; + + private void init() { + characterReport = new CharReport2[0]; + } + + public ReadTextReport2() { + super(12); + init(); + } + + public ReadTextReport2(String readString, CharReport2[] characterReport) { + super(12); + this.readString = readString; + this.characterReport = characterReport; + } + + protected ReadTextReport2(ByteBuffer backing, int offset) { + super(backing, offset, 12); + init(); + } + + protected ReadTextReport2(long nativeObj, boolean owned) { + super(nativeObj, owned, 12); + init(); + } + + protected void setBuffer(ByteBuffer backing, int offset) { + super.setBuffer(backing, offset, 12); + } + + public void read() { + long readString_addr = getPointer(backing, 0); + if (readString_addr == 0) + readString = null; + else { + ByteBuffer bb = newDirectByteBuffer(readString_addr, 1000); // FIXME + while (bb.get() != 0) { + } + byte[] bytes = new byte[bb.position() - 1]; + getBytes(bb, bytes, 0, bytes.length); + try { + readString = new String(bytes, "UTF-8"); + } catch (UnsupportedEncodingException e) { + readString = ""; + } + } + + int characterReport_numCharacterReports = backing.getInt(8); + long characterReport_addr = getPointer(backing, 4); + characterReport = new CharReport2[characterReport_numCharacterReports]; + if (characterReport_numCharacterReports > 0 && characterReport_addr != 0) { + ByteBuffer bb = + newDirectByteBuffer(characterReport_addr, characterReport_numCharacterReports * 56); + for (int i = 0, off = 0; i < characterReport_numCharacterReports; i++, off += 56) { + characterReport[i] = new CharReport2(bb, off); + characterReport[i].read(); + } + } + } + + public void write() { + if (readString != null) { + byte[] readString_bytes; + try { + readString_bytes = readString.getBytes("UTF-8"); + } catch (UnsupportedEncodingException e) { + readString_bytes = new byte[0]; + } + readString_buf = ByteBuffer.allocateDirect(readString_bytes.length + 1); + putBytes(readString_buf, readString_bytes, 0, readString_bytes.length).put( + readString_bytes.length, (byte) 0); + } + putPointer(backing, 0, readString == null ? 0 : getByteBufferAddress(readString_buf)); + characterReport_buf = + ByteBuffer.allocateDirect(characterReport.length * 56).order(ByteOrder.nativeOrder()); + for (int i = 0, off = 0; i < characterReport.length; i++, off += 56) { + characterReport[i].setBuffer(characterReport_buf, off); + characterReport[i].write(); + } + backing.putInt(8, characterReport.length); + putPointer(backing, 4, characterReport_buf); + } + + public int size() { + return 12; + } + } + + public static class EllipseFeature extends DisposedStruct { + public PointFloat position; // The location of the center of the ellipse. + public double rotation; // The orientation of the semi-major axis of the + // ellipse with respect to the horizontal. + public double minorRadius; // The length of the semi-minor axis of the + // ellipse. + public double majorRadius; // The length of the semi-major axis of the + // ellipse. + + private void init() { + position = new PointFloat(backing, 0); + } + + public EllipseFeature() { + super(32); + init(); + } + + public EllipseFeature(PointFloat position, double rotation, double minorRadius, + double majorRadius) { + super(32); + this.position = position; + this.rotation = rotation; + this.minorRadius = minorRadius; + this.majorRadius = majorRadius; + } + + protected EllipseFeature(ByteBuffer backing, int offset) { + super(backing, offset, 32); + init(); + } + + protected EllipseFeature(long nativeObj, boolean owned) { + super(nativeObj, owned, 32); + init(); + } + + protected void setBuffer(ByteBuffer backing, int offset) { + super.setBuffer(backing, offset, 32); + } + + public void read() { + position.read(); + rotation = backing.getDouble(8); + minorRadius = backing.getDouble(16); + majorRadius = backing.getDouble(24); + } + + public void write() { + position.write(); + backing.putDouble(8, rotation); + backing.putDouble(16, minorRadius); + backing.putDouble(24, majorRadius); + } + + public int size() { + return 32; + } + } + + public static class CircleFeature extends DisposedStruct { + public PointFloat position; // The location of the center of the circle. + public double radius; // The radius of the circle. + + private void init() { + position = new PointFloat(backing, 0); + } + + public CircleFeature() { + super(16); + init(); + } + + public CircleFeature(PointFloat position, double radius) { + super(16); + this.position = position; + this.radius = radius; + } + + protected CircleFeature(ByteBuffer backing, int offset) { + super(backing, offset, 16); + init(); + } + + protected CircleFeature(long nativeObj, boolean owned) { + super(nativeObj, owned, 16); + init(); + } + + protected void setBuffer(ByteBuffer backing, int offset) { + super.setBuffer(backing, offset, 16); + } + + public void read() { + position.read(); + radius = backing.getDouble(8); + } + + public void write() { + position.write(); + backing.putDouble(8, radius); + } + + public int size() { + return 16; + } + } + + public static class ConstCurveFeature extends DisposedStruct { + public PointFloat position; // The center of the circle that this constant + // curve lies upon. + public double radius; // The radius of the circle that this constant curve + // lies upon. + public double startAngle; // When traveling along the constant curve from + // one endpoint to the next in a counterclockwise + // manner, this is the angular component of the + // vector originating at the center of the + // constant curve and pointing towards the first + // endpoint of the constant curve. + public double endAngle; // When traveling along the constant curve from one + // endpoint to the next in a counterclockwise + // manner, this is the angular component of the + // vector originating at the center of the constant + // curve and pointing towards the second endpoint of + // the constant curve. + + private void init() { + position = new PointFloat(backing, 0); + } + + public ConstCurveFeature() { + super(32); + init(); + } + + public ConstCurveFeature(PointFloat position, double radius, double startAngle, double endAngle) { + super(32); + this.position = position; + this.radius = radius; + this.startAngle = startAngle; + this.endAngle = endAngle; + } + + protected ConstCurveFeature(ByteBuffer backing, int offset) { + super(backing, offset, 32); + init(); + } + + protected ConstCurveFeature(long nativeObj, boolean owned) { + super(nativeObj, owned, 32); + init(); + } + + protected void setBuffer(ByteBuffer backing, int offset) { + super.setBuffer(backing, offset, 32); + } + + public void read() { + position.read(); + radius = backing.getDouble(8); + startAngle = backing.getDouble(16); + endAngle = backing.getDouble(24); + } + + public void write() { + position.write(); + backing.putDouble(8, radius); + backing.putDouble(16, startAngle); + backing.putDouble(24, endAngle); + } + + public int size() { + return 32; + } + } + + public static class RectangleFeature extends DisposedStruct { + public PointFloat position; // The center of the rectangle. + public PointFloat[] corner; // The four corners of the rectangle. + public double rotation; // The orientation of the rectangle with respect to + // the horizontal. + public double width; // The width of the rectangle. + public double height; // The height of the rectangle. + + private void init() { + position = new PointFloat(backing, 0); + corner = new PointFloat[4]; + + for (int i = 0, off = 8; i < 4; i++, off += 8) + corner[i] = new PointFloat(backing, off); + } + + public RectangleFeature() { + super(64); + init(); + } + + public RectangleFeature(PointFloat position, PointFloat[] corner, double rotation, + double width, double height) { + super(64); + this.position = position; + this.corner = corner; + this.rotation = rotation; + this.width = width; + this.height = height; + } + + protected RectangleFeature(ByteBuffer backing, int offset) { + super(backing, offset, 64); + init(); + } + + protected RectangleFeature(long nativeObj, boolean owned) { + super(nativeObj, owned, 64); + init(); + } + + protected void setBuffer(ByteBuffer backing, int offset) { + super.setBuffer(backing, offset, 64); + } + + public void read() { + position.read(); + for (PointFloat it : corner) { + it.read(); + } + rotation = backing.getDouble(40); + width = backing.getDouble(48); + height = backing.getDouble(56); + } + + public void write() { + position.write(); + for (PointFloat it : corner) { + it.write(); + } + backing.putDouble(40, rotation); + backing.putDouble(48, width); + backing.putDouble(56, height); + } + + public int size() { + return 64; + } + } + + public static class LegFeature extends DisposedStruct { + public PointFloat position; // The location of the leg feature. + public PointFloat[] corner; // The four corners of the leg feature. + public double rotation; // The orientation of the leg with respect to the + // horizontal. + public double width; // The width of the leg. + public double height; // The height of the leg. + + private void init() { + position = new PointFloat(backing, 0); + corner = new PointFloat[4]; + + for (int i = 0, off = 8; i < 4; i++, off += 8) + corner[i] = new PointFloat(backing, off); + } + + public LegFeature() { + super(64); + init(); + } + + public LegFeature(PointFloat position, PointFloat[] corner, double rotation, double width, + double height) { + super(64); + this.position = position; + this.corner = corner; + this.rotation = rotation; + this.width = width; + this.height = height; + } + + protected LegFeature(ByteBuffer backing, int offset) { + super(backing, offset, 64); + init(); + } + + protected LegFeature(long nativeObj, boolean owned) { + super(nativeObj, owned, 64); + init(); + } + + protected void setBuffer(ByteBuffer backing, int offset) { + super.setBuffer(backing, offset, 64); + } + + public void read() { + position.read(); + for (PointFloat it : corner) { + it.read(); + } + rotation = backing.getDouble(40); + width = backing.getDouble(48); + height = backing.getDouble(56); + } + + public void write() { + position.write(); + for (PointFloat it : corner) { + it.write(); + } + backing.putDouble(40, rotation); + backing.putDouble(48, width); + backing.putDouble(56, height); + } + + public int size() { + return 64; + } + } + + public static class CornerFeature extends DisposedStruct { + public PointFloat position; // The location of the corner feature. + public double rotation; // The angular component of the vector bisecting the + // corner from position. + public double enclosedAngle; // The measure of the enclosed angle of the + // corner. + public int isVirtual; + + private void init() { + position = new PointFloat(backing, 0); + } + + public CornerFeature() { + super(32); + init(); + } + + public CornerFeature(PointFloat position, double rotation, double enclosedAngle, int isVirtual) { + super(32); + this.position = position; + this.rotation = rotation; + this.enclosedAngle = enclosedAngle; + this.isVirtual = isVirtual; + } + + protected CornerFeature(ByteBuffer backing, int offset) { + super(backing, offset, 32); + init(); + } + + protected CornerFeature(long nativeObj, boolean owned) { + super(nativeObj, owned, 32); + init(); + } + + protected void setBuffer(ByteBuffer backing, int offset) { + super.setBuffer(backing, offset, 32); + } + + public void read() { + position.read(); + rotation = backing.getDouble(8); + enclosedAngle = backing.getDouble(16); + isVirtual = backing.getInt(24); + } + + public void write() { + position.write(); + backing.putDouble(8, rotation); + backing.putDouble(16, enclosedAngle); + backing.putInt(24, isVirtual); + } + + public int size() { + return 32; + } + } + + public static class LineFeature extends DisposedStruct { + public PointFloat startPoint; // The starting point of the line. + public PointFloat endPoint; // The ending point of the line. + public double length; // The length of the line measured in pixels from the + // start point to the end point. + public double rotation; // The orientation of the line with respect to the + // horizontal. + + private void init() { + startPoint = new PointFloat(backing, 0); + endPoint = new PointFloat(backing, 8); + } + + public LineFeature() { + super(32); + init(); + } + + public LineFeature(PointFloat startPoint, PointFloat endPoint, double length, double rotation) { + super(32); + this.startPoint = startPoint; + this.endPoint = endPoint; + this.length = length; + this.rotation = rotation; + } + + protected LineFeature(ByteBuffer backing, int offset) { + super(backing, offset, 32); + init(); + } + + protected LineFeature(long nativeObj, boolean owned) { + super(nativeObj, owned, 32); + init(); + } + + protected void setBuffer(ByteBuffer backing, int offset) { + super.setBuffer(backing, offset, 32); + } + + public void read() { + startPoint.read(); + endPoint.read(); + length = backing.getDouble(16); + rotation = backing.getDouble(24); + } + + public void write() { + startPoint.write(); + endPoint.write(); + backing.putDouble(16, length); + backing.putDouble(24, rotation); + } + + public int size() { + return 32; + } + } + + public static class ParallelLinePairFeature extends DisposedStruct { + public PointFloat firstStartPoint; // The starting point of the first line + // of the pair. + public PointFloat firstEndPoint; // The ending point of the first line of + // the pair. + public PointFloat secondStartPoint; // The starting point of the second line + // of the pair. + public PointFloat secondEndPoint; // The ending point of the second line of + // the pair. + public double rotation; // The orientation of the feature with respect to + // the horizontal. + public double distance; // The distance from the first line to the second + // line. + + private void init() { + firstStartPoint = new PointFloat(backing, 0); + firstEndPoint = new PointFloat(backing, 8); + secondStartPoint = new PointFloat(backing, 16); + secondEndPoint = new PointFloat(backing, 24); + } + + public ParallelLinePairFeature() { + super(48); + init(); + } + + public ParallelLinePairFeature(PointFloat firstStartPoint, PointFloat firstEndPoint, + PointFloat secondStartPoint, PointFloat secondEndPoint, double rotation, double distance) { + super(48); + this.firstStartPoint = firstStartPoint; + this.firstEndPoint = firstEndPoint; + this.secondStartPoint = secondStartPoint; + this.secondEndPoint = secondEndPoint; + this.rotation = rotation; + this.distance = distance; + } + + protected ParallelLinePairFeature(ByteBuffer backing, int offset) { + super(backing, offset, 48); + init(); + } + + protected ParallelLinePairFeature(long nativeObj, boolean owned) { + super(nativeObj, owned, 48); + init(); + } + + protected void setBuffer(ByteBuffer backing, int offset) { + super.setBuffer(backing, offset, 48); + } + + public void read() { + firstStartPoint.read(); + firstEndPoint.read(); + secondStartPoint.read(); + secondEndPoint.read(); + rotation = backing.getDouble(32); + distance = backing.getDouble(40); + } + + public void write() { + firstStartPoint.write(); + firstEndPoint.write(); + secondStartPoint.write(); + secondEndPoint.write(); + backing.putDouble(32, rotation); + backing.putDouble(40, distance); + } + + public int size() { + return 48; + } + } + + public static class PairOfParallelLinePairsFeature extends DisposedStruct { + public ParallelLinePairFeature firstParallelLinePair; // The first parallel + // line pair. + public ParallelLinePairFeature secondParallelLinePair; // The second + // parallel line + // pair. + public double rotation; // The orientation of the feature with respect to + // the horizontal. + public double distance; // The distance from the midline of the first + // parallel line pair to the midline of the second + // parallel line pair. + + private void init() { + firstParallelLinePair = new ParallelLinePairFeature(backing, 0); + secondParallelLinePair = new ParallelLinePairFeature(backing, 48); + } + + public PairOfParallelLinePairsFeature() { + super(112); + init(); + } + + public PairOfParallelLinePairsFeature(ParallelLinePairFeature firstParallelLinePair, + ParallelLinePairFeature secondParallelLinePair, double rotation, double distance) { + super(112); + this.firstParallelLinePair = firstParallelLinePair; + this.secondParallelLinePair = secondParallelLinePair; + this.rotation = rotation; + this.distance = distance; + } + + protected PairOfParallelLinePairsFeature(ByteBuffer backing, int offset) { + super(backing, offset, 112); + init(); + } + + protected PairOfParallelLinePairsFeature(long nativeObj, boolean owned) { + super(nativeObj, owned, 112); + init(); + } + + protected void setBuffer(ByteBuffer backing, int offset) { + super.setBuffer(backing, offset, 112); + } + + public void read() { + firstParallelLinePair.read(); + secondParallelLinePair.read(); + rotation = backing.getDouble(96); + distance = backing.getDouble(104); + } + + public void write() { + firstParallelLinePair.write(); + secondParallelLinePair.write(); + backing.putDouble(96, rotation); + backing.putDouble(104, distance); + } + + public int size() { + return 112; + } + } + + public static class FeatureData extends DisposedStruct { + public FeatureType type; // An enumeration representing the type of the + // feature. + public PointFloat[] contourPoints; // A set of points describing the contour + // of the feature. + public CircleFeature circle; // A pointer to a CircleFeature. + public EllipseFeature ellipse; // A pointer to an EllipseFeature. + public ConstCurveFeature constCurve; // A pointer to a ConstCurveFeature. + public RectangleFeature rectangle; // A pointer to a RectangleFeature. + public LegFeature leg; // A pointer to a LegFeature. + public CornerFeature corner; // A pointer to a CornerFeature. + public ParallelLinePairFeature parallelLinePair; // A pointer to a + // ParallelLinePairFeature. + public PairOfParallelLinePairsFeature pairOfParallelLinePairs; // A pointer + // to a + // PairOfParallelLinePairsFeature. + public LineFeature line; // A pointer to a LineFeature. + public ClosedCurveFeature closedCurve; // A pointer to a ClosedCurveFeature. + private ByteBuffer contourPoints_buf; + + private void init() { + contourPoints = new PointFloat[0]; + } + + public FeatureData() { + super(16); + init(); + } + + public FeatureData(FeatureType type, PointFloat[] contourPoints) { + super(16); + this.type = type; + this.contourPoints = contourPoints; + } + + protected FeatureData(ByteBuffer backing, int offset) { + super(backing, offset, 16); + init(); + } + + protected FeatureData(long nativeObj, boolean owned) { + super(nativeObj, owned, 16); + init(); + } + + protected void setBuffer(ByteBuffer backing, int offset) { + super.setBuffer(backing, offset, 16); + } + + public void read() { + type = FeatureType.fromValue(backing.getInt(0)); + int contourPoints_numContourPoints = backing.getInt(8); + long contourPoints_addr = getPointer(backing, 4); + contourPoints = new PointFloat[contourPoints_numContourPoints]; + if (contourPoints_numContourPoints > 0 && contourPoints_addr != 0) { + ByteBuffer bb = newDirectByteBuffer(contourPoints_addr, contourPoints_numContourPoints * 8); + for (int i = 0, off = 0; i < contourPoints_numContourPoints; i++, off += 8) { + contourPoints[i] = new PointFloat(bb, off); + contourPoints[i].read(); + } + } + if (type == FeatureType.CIRCLE_FEATURE) { + long circle_addr = getPointer(backing, 12); + if (circle_addr == 0) + circle = null; + else + circle = new CircleFeature(circle_addr, false); + } + if (type == FeatureType.ELLIPSE_FEATURE) { + long ellipse_addr = getPointer(backing, 12); + if (ellipse_addr == 0) + ellipse = null; + else + ellipse = new EllipseFeature(ellipse_addr, false); + } + if (type == FeatureType.CONST_CURVE_FEATURE) { + long constCurve_addr = getPointer(backing, 12); + if (constCurve_addr == 0) + constCurve = null; + else + constCurve = new ConstCurveFeature(constCurve_addr, false); + } + if (type == FeatureType.RECTANGLE_FEATURE) { + long rectangle_addr = getPointer(backing, 12); + if (rectangle_addr == 0) + rectangle = null; + else + rectangle = new RectangleFeature(rectangle_addr, false); + } + if (type == FeatureType.LEG_FEATURE) { + long leg_addr = getPointer(backing, 12); + if (leg_addr == 0) + leg = null; + else + leg = new LegFeature(leg_addr, false); + } + if (type == FeatureType.CORNER_FEATURE) { + long corner_addr = getPointer(backing, 12); + if (corner_addr == 0) + corner = null; + else + corner = new CornerFeature(corner_addr, false); + } + if (type == FeatureType.PARALLEL_LINE_PAIR_FEATURE) { + long parallelLinePair_addr = getPointer(backing, 12); + if (parallelLinePair_addr == 0) + parallelLinePair = null; + else + parallelLinePair = new ParallelLinePairFeature(parallelLinePair_addr, false); + } + if (type == FeatureType.PAIR_OF_PARALLEL_LINE_PAIRS_FEATURE) { + long pairOfParallelLinePairs_addr = getPointer(backing, 12); + if (pairOfParallelLinePairs_addr == 0) + pairOfParallelLinePairs = null; + else + pairOfParallelLinePairs = + new PairOfParallelLinePairsFeature(pairOfParallelLinePairs_addr, false); + } + if (type == FeatureType.LINE_FEATURE) { + long line_addr = getPointer(backing, 12); + if (line_addr == 0) + line = null; + else + line = new LineFeature(line_addr, false); + } + if (type == FeatureType.CLOSED_CURVE_FEATURE) { + long closedCurve_addr = getPointer(backing, 12); + if (closedCurve_addr == 0) + closedCurve = null; + else + closedCurve = new ClosedCurveFeature(closedCurve_addr, false); + } + } + + public void write() { + if (type != null) + backing.putInt(0, type.getValue()); + contourPoints_buf = + ByteBuffer.allocateDirect(contourPoints.length * 8).order(ByteOrder.nativeOrder()); + for (int i = 0, off = 0; i < contourPoints.length; i++, off += 8) { + contourPoints[i].setBuffer(contourPoints_buf, off); + contourPoints[i].write(); + } + backing.putInt(8, contourPoints.length); + putPointer(backing, 4, contourPoints_buf); + if (type == FeatureType.CIRCLE_FEATURE) { + putPointer(backing, 12, circle); + } + if (type == FeatureType.ELLIPSE_FEATURE) { + putPointer(backing, 12, ellipse); + } + if (type == FeatureType.CONST_CURVE_FEATURE) { + putPointer(backing, 12, constCurve); + } + if (type == FeatureType.RECTANGLE_FEATURE) { + putPointer(backing, 12, rectangle); + } + if (type == FeatureType.LEG_FEATURE) { + putPointer(backing, 12, leg); + } + if (type == FeatureType.CORNER_FEATURE) { + putPointer(backing, 12, corner); + } + if (type == FeatureType.PARALLEL_LINE_PAIR_FEATURE) { + putPointer(backing, 12, parallelLinePair); + } + if (type == FeatureType.PAIR_OF_PARALLEL_LINE_PAIRS_FEATURE) { + putPointer(backing, 12, pairOfParallelLinePairs); + } + if (type == FeatureType.LINE_FEATURE) { + putPointer(backing, 12, line); + } + if (type == FeatureType.CLOSED_CURVE_FEATURE) { + putPointer(backing, 12, closedCurve); + } + } + + public int size() { + return 16; + } + } + + public static class GeometricPatternMatch2 extends DisposedStruct { + public PointFloat position; // The location of the origin of the template in + // the match. + public float rotation; // The rotation of the match relative to the template + // image, in degrees. + public float scale; // The size of the match relative to the size of the + // template image, expressed as a percentage. + public float score; // The accuracy of the match. + public PointFloat[] corner; // An array of four points describing the + // rectangle surrounding the template image. + public int inverse; // This element is TRUE if the match is an inverse of + // the template image. + public float occlusion; // The percentage of the match that is occluded. + public float templateMatchCurveScore; // The accuracy of the match obtained + // by comparing the template curves to + // the curves in the match region. + public float matchTemplateCurveScore; // The accuracy of the match obtained + // by comparing the curves in the + // match region to the template + // curves. + public float correlationScore; // The accuracy of the match obtained by + // comparing the template image to the match + // region using a correlation metric that + // compares the two regions as a function of + // their pixel values. + public String label; // The label corresponding to this match when the match + // is returned by imaqMatchMultipleGeometricPatterns(). + public FeatureData[] featureData; // The features used in this match. + public PointFloat calibratedPosition; // The location of the origin of the + // template in the match. + public float calibratedRotation; // The rotation of the match relative to + // the template image, in degrees. + public PointFloat[] calibratedCorner; // An array of four points describing + // the rectangle surrounding the + // template image. + private ByteBuffer featureData_buf; + + private void init() { + position = new PointFloat(backing, 0); + corner = new PointFloat[4]; + + for (int i = 0, off = 20; i < 4; i++, off += 8) + corner[i] = new PointFloat(backing, off); + featureData = new FeatureData[0]; + calibratedPosition = new PointFloat(backing, 336); + calibratedCorner = new PointFloat[4]; + + for (int i = 0, off = 348; i < 4; i++, off += 8) + calibratedCorner[i] = new PointFloat(backing, off); + } + + public GeometricPatternMatch2() { + super(380); + init(); + } + + public GeometricPatternMatch2(PointFloat position, double rotation, double scale, double score, + PointFloat[] corner, int inverse, double occlusion, double templateMatchCurveScore, + double matchTemplateCurveScore, double correlationScore, String label, + FeatureData[] featureData, PointFloat calibratedPosition, double calibratedRotation, + PointFloat[] calibratedCorner) { + super(380); + this.position = position; + this.rotation = (float) rotation; + this.scale = (float) scale; + this.score = (float) score; + this.corner = corner; + this.inverse = inverse; + this.occlusion = (float) occlusion; + this.templateMatchCurveScore = (float) templateMatchCurveScore; + this.matchTemplateCurveScore = (float) matchTemplateCurveScore; + this.correlationScore = (float) correlationScore; + this.label = label; + this.featureData = featureData; + this.calibratedPosition = calibratedPosition; + this.calibratedRotation = (float) calibratedRotation; + this.calibratedCorner = calibratedCorner; + } + + protected GeometricPatternMatch2(ByteBuffer backing, int offset) { + super(backing, offset, 380); + init(); + } + + protected GeometricPatternMatch2(long nativeObj, boolean owned) { + super(nativeObj, owned, 380); + init(); + } + + protected void setBuffer(ByteBuffer backing, int offset) { + super.setBuffer(backing, offset, 380); + } + + public void read() { + position.read(); + rotation = backing.getFloat(8); + scale = backing.getFloat(12); + score = backing.getFloat(16); + for (PointFloat it : corner) { + it.read(); + } + inverse = backing.getInt(52); + occlusion = backing.getFloat(56); + templateMatchCurveScore = backing.getFloat(60); + matchTemplateCurveScore = backing.getFloat(64); + correlationScore = backing.getFloat(68); + { + byte[] bytes = new byte[256]; + getBytes(backing, bytes, 72, 256); + int len; + for (len = 0; len < bytes.length && bytes[len] != 0; len++) { + } + try { + label = new String(bytes, 0, len, "UTF-8"); + } catch (UnsupportedEncodingException e) { + label = ""; + } + } + int featureData_numFeatureData = backing.getInt(332); + long featureData_addr = getPointer(backing, 328); + featureData = new FeatureData[featureData_numFeatureData]; + if (featureData_numFeatureData > 0 && featureData_addr != 0) { + ByteBuffer bb = newDirectByteBuffer(featureData_addr, featureData_numFeatureData * 16); + for (int i = 0, off = 0; i < featureData_numFeatureData; i++, off += 16) { + featureData[i] = new FeatureData(bb, off); + featureData[i].read(); + } + } + calibratedPosition.read(); + calibratedRotation = backing.getFloat(344); + for (PointFloat it : calibratedCorner) { + it.read(); + } + } + + public void write() { + position.write(); + backing.putFloat(8, rotation); + backing.putFloat(12, scale); + backing.putFloat(16, score); + for (PointFloat it : corner) { + it.write(); + } + backing.putInt(52, inverse); + backing.putFloat(56, occlusion); + backing.putFloat(60, templateMatchCurveScore); + backing.putFloat(64, matchTemplateCurveScore); + backing.putFloat(68, correlationScore); + if (label != null) { + byte[] bytes; + try { + bytes = label.getBytes("UTF-8"); + } catch (UnsupportedEncodingException e) { + bytes = new byte[0]; + } + putBytes(backing, bytes, 72, bytes.length); + for (int i = bytes.length; i < 256; i++) + backing.put(i, (byte) 0); // fill with zero + } + featureData_buf = + ByteBuffer.allocateDirect(featureData.length * 16).order(ByteOrder.nativeOrder()); + for (int i = 0, off = 0; i < featureData.length; i++, off += 16) { + featureData[i].setBuffer(featureData_buf, off); + featureData[i].write(); + } + backing.putInt(332, featureData.length); + putPointer(backing, 328, featureData_buf); + calibratedPosition.write(); + backing.putFloat(344, calibratedRotation); + for (PointFloat it : calibratedCorner) { + it.write(); + } + } + + public int size() { + return 380; + } + } + + public static class ClosedCurveFeature extends DisposedStruct { + public PointFloat position; // The center of the closed curve feature. + public double arcLength; // The arc length of the closed curve feature. + + private void init() { + position = new PointFloat(backing, 0); + } + + public ClosedCurveFeature() { + super(16); + init(); + } + + public ClosedCurveFeature(PointFloat position, double arcLength) { + super(16); + this.position = position; + this.arcLength = arcLength; + } + + protected ClosedCurveFeature(ByteBuffer backing, int offset) { + super(backing, offset, 16); + init(); + } + + protected ClosedCurveFeature(long nativeObj, boolean owned) { + super(nativeObj, owned, 16); + init(); + } + + protected void setBuffer(ByteBuffer backing, int offset) { + super.setBuffer(backing, offset, 16); + } + + public void read() { + position.read(); + arcLength = backing.getDouble(8); + } + + public void write() { + position.write(); + backing.putDouble(8, arcLength); + } + + public int size() { + return 16; + } + } + + public static class LineMatch extends DisposedStruct { + public PointFloat startPoint; // The starting point of the matched line. + public PointFloat endPoint; // The ending point of the matched line. + public double length; // The length of the line measured in pixels from the + // start point to the end point. + public double rotation; // The orientation of the matched line. + public double score; // The score of the matched line. + + private void init() { + startPoint = new PointFloat(backing, 0); + endPoint = new PointFloat(backing, 8); + } + + public LineMatch() { + super(40); + init(); + } + + public LineMatch(PointFloat startPoint, PointFloat endPoint, double length, double rotation, + double score) { + super(40); + this.startPoint = startPoint; + this.endPoint = endPoint; + this.length = length; + this.rotation = rotation; + this.score = score; + } + + protected LineMatch(ByteBuffer backing, int offset) { + super(backing, offset, 40); + init(); + } + + protected LineMatch(long nativeObj, boolean owned) { + super(nativeObj, owned, 40); + init(); + } + + protected void setBuffer(ByteBuffer backing, int offset) { + super.setBuffer(backing, offset, 40); + } + + public void read() { + startPoint.read(); + endPoint.read(); + length = backing.getDouble(16); + rotation = backing.getDouble(24); + score = backing.getDouble(32); + } + + public void write() { + startPoint.write(); + endPoint.write(); + backing.putDouble(16, length); + backing.putDouble(24, rotation); + backing.putDouble(32, score); + } + + public int size() { + return 40; + } + } + + public static class LineDescriptor extends DisposedStruct { + public double minLength; // Specifies the minimum length of a line the + // function will return. + public double maxLength; // Specifies the maximum length of a line the + // function will return. + + private void init() { + + } + + public LineDescriptor() { + super(16); + init(); + } + + public LineDescriptor(double minLength, double maxLength) { + super(16); + this.minLength = minLength; + this.maxLength = maxLength; + } + + protected LineDescriptor(ByteBuffer backing, int offset) { + super(backing, offset, 16); + init(); + } + + protected LineDescriptor(long nativeObj, boolean owned) { + super(nativeObj, owned, 16); + init(); + } + + protected void setBuffer(ByteBuffer backing, int offset) { + super.setBuffer(backing, offset, 16); + } + + public void read() { + minLength = backing.getDouble(0); + maxLength = backing.getDouble(8); + } + + public void write() { + backing.putDouble(0, minLength); + backing.putDouble(8, maxLength); + } + + public int size() { + return 16; + } + } + + public static class RectangleDescriptor extends DisposedStruct { + public double minWidth; // Specifies the minimum width of a rectangle the + // algorithm will return. + public double maxWidth; // Specifies the maximum width of a rectangle the + // algorithm will return. + public double minHeight; // Specifies the minimum height of a rectangle the + // algorithm will return. + public double maxHeight; // Specifies the maximum height of a rectangle the + // algorithm will return. + + private void init() { + + } + + public RectangleDescriptor() { + super(32); + init(); + } + + public RectangleDescriptor(double minWidth, double maxWidth, double minHeight, double maxHeight) { + super(32); + this.minWidth = minWidth; + this.maxWidth = maxWidth; + this.minHeight = minHeight; + this.maxHeight = maxHeight; + } + + protected RectangleDescriptor(ByteBuffer backing, int offset) { + super(backing, offset, 32); + init(); + } + + protected RectangleDescriptor(long nativeObj, boolean owned) { + super(nativeObj, owned, 32); + init(); + } + + protected void setBuffer(ByteBuffer backing, int offset) { + super.setBuffer(backing, offset, 32); + } + + public void read() { + minWidth = backing.getDouble(0); + maxWidth = backing.getDouble(8); + minHeight = backing.getDouble(16); + maxHeight = backing.getDouble(24); + } + + public void write() { + backing.putDouble(0, minWidth); + backing.putDouble(8, maxWidth); + backing.putDouble(16, minHeight); + backing.putDouble(24, maxHeight); + } + + public int size() { + return 32; + } + } + + public static class RectangleMatch extends DisposedStruct { + public PointFloat[] corner; // The corners of the matched rectangle. + public double rotation; // The orientation of the matched rectangle. + public double width; // The width of the matched rectangle. + public double height; // The height of the matched rectangle. + public double score; // The score of the matched rectangle. + + private void init() { + corner = new PointFloat[4]; + + for (int i = 0, off = 0; i < 4; i++, off += 8) + corner[i] = new PointFloat(backing, off); + } + + public RectangleMatch() { + super(64); + init(); + } + + public RectangleMatch(PointFloat[] corner, double rotation, double width, double height, + double score) { + super(64); + this.corner = corner; + this.rotation = rotation; + this.width = width; + this.height = height; + this.score = score; + } + + protected RectangleMatch(ByteBuffer backing, int offset) { + super(backing, offset, 64); + init(); + } + + protected RectangleMatch(long nativeObj, boolean owned) { + super(nativeObj, owned, 64); + init(); + } + + protected void setBuffer(ByteBuffer backing, int offset) { + super.setBuffer(backing, offset, 64); + } + + public void read() { + for (PointFloat it : corner) { + it.read(); + } + rotation = backing.getDouble(32); + width = backing.getDouble(40); + height = backing.getDouble(48); + score = backing.getDouble(56); + } + + public void write() { + for (PointFloat it : corner) { + it.write(); + } + backing.putDouble(32, rotation); + backing.putDouble(40, width); + backing.putDouble(48, height); + backing.putDouble(56, score); + } + + public int size() { + return 64; + } + } + + public static class EllipseDescriptor extends DisposedStruct { + public double minMajorRadius; // Specifies the minimum length of the + // semi-major axis of an ellipse the function + // will return. + public double maxMajorRadius; // Specifies the maximum length of the + // semi-major axis of an ellipse the function + // will return. + public double minMinorRadius; // Specifies the minimum length of the + // semi-minor axis of an ellipse the function + // will return. + public double maxMinorRadius; // Specifies the maximum length of the + // semi-minor axis of an ellipse the function + // will return. + + private void init() { + + } + + public EllipseDescriptor() { + super(32); + init(); + } + + public EllipseDescriptor(double minMajorRadius, double maxMajorRadius, double minMinorRadius, + double maxMinorRadius) { + super(32); + this.minMajorRadius = minMajorRadius; + this.maxMajorRadius = maxMajorRadius; + this.minMinorRadius = minMinorRadius; + this.maxMinorRadius = maxMinorRadius; + } + + protected EllipseDescriptor(ByteBuffer backing, int offset) { + super(backing, offset, 32); + init(); + } + + protected EllipseDescriptor(long nativeObj, boolean owned) { + super(nativeObj, owned, 32); + init(); + } + + protected void setBuffer(ByteBuffer backing, int offset) { + super.setBuffer(backing, offset, 32); + } + + public void read() { + minMajorRadius = backing.getDouble(0); + maxMajorRadius = backing.getDouble(8); + minMinorRadius = backing.getDouble(16); + maxMinorRadius = backing.getDouble(24); + } + + public void write() { + backing.putDouble(0, minMajorRadius); + backing.putDouble(8, maxMajorRadius); + backing.putDouble(16, minMinorRadius); + backing.putDouble(24, maxMinorRadius); + } + + public int size() { + return 32; + } + } + + public static class EllipseMatch extends DisposedStruct { + public PointFloat position; // The location of the center of the matched + // ellipse. + public double rotation; // The orientation of the matched ellipse. + public double majorRadius; // The length of the semi-major axis of the + // matched ellipse. + public double minorRadius; // The length of the semi-minor axis of the + // matched ellipse. + public double score; // The score of the matched ellipse. + + private void init() { + position = new PointFloat(backing, 0); + } + + public EllipseMatch() { + super(40); + init(); + } + + public EllipseMatch(PointFloat position, double rotation, double majorRadius, + double minorRadius, double score) { + super(40); + this.position = position; + this.rotation = rotation; + this.majorRadius = majorRadius; + this.minorRadius = minorRadius; + this.score = score; + } + + protected EllipseMatch(ByteBuffer backing, int offset) { + super(backing, offset, 40); + init(); + } + + protected EllipseMatch(long nativeObj, boolean owned) { + super(nativeObj, owned, 40); + init(); + } + + protected void setBuffer(ByteBuffer backing, int offset) { + super.setBuffer(backing, offset, 40); + } + + public void read() { + position.read(); + rotation = backing.getDouble(8); + majorRadius = backing.getDouble(16); + minorRadius = backing.getDouble(24); + score = backing.getDouble(32); + } + + public void write() { + position.write(); + backing.putDouble(8, rotation); + backing.putDouble(16, majorRadius); + backing.putDouble(24, minorRadius); + backing.putDouble(32, score); + } + + public int size() { + return 40; + } + } + + public static class CircleMatch extends DisposedStruct { + public PointFloat position; // The location of the center of the matched + // circle. + public double radius; // The radius of the matched circle. + public double score; // The score of the matched circle. + + private void init() { + position = new PointFloat(backing, 0); + } + + public CircleMatch() { + super(24); + init(); + } + + public CircleMatch(PointFloat position, double radius, double score) { + super(24); + this.position = position; + this.radius = radius; + this.score = score; + } + + protected CircleMatch(ByteBuffer backing, int offset) { + super(backing, offset, 24); + init(); + } + + protected CircleMatch(long nativeObj, boolean owned) { + super(nativeObj, owned, 24); + init(); + } + + protected void setBuffer(ByteBuffer backing, int offset) { + super.setBuffer(backing, offset, 24); + } + + public void read() { + position.read(); + radius = backing.getDouble(8); + score = backing.getDouble(16); + } + + public void write() { + position.write(); + backing.putDouble(8, radius); + backing.putDouble(16, score); + } + + public int size() { + return 24; + } + } + + public static class CircleDescriptor extends DisposedStruct { + public double minRadius; // Specifies the minimum radius of a circle the + // function will return. + public double maxRadius; // Specifies the maximum radius of a circle the + // function will return. + + private void init() { + + } + + public CircleDescriptor() { + super(16); + init(); + } + + public CircleDescriptor(double minRadius, double maxRadius) { + super(16); + this.minRadius = minRadius; + this.maxRadius = maxRadius; + } + + protected CircleDescriptor(ByteBuffer backing, int offset) { + super(backing, offset, 16); + init(); + } + + protected CircleDescriptor(long nativeObj, boolean owned) { + super(nativeObj, owned, 16); + init(); + } + + protected void setBuffer(ByteBuffer backing, int offset) { + super.setBuffer(backing, offset, 16); + } + + public void read() { + minRadius = backing.getDouble(0); + maxRadius = backing.getDouble(8); + } + + public void write() { + backing.putDouble(0, minRadius); + backing.putDouble(8, maxRadius); + } + + public int size() { + return 16; + } + } + + public static class ShapeDetectionOptions extends DisposedStruct { + public int mode; // Specifies the method used when looking for the shape in + // the image. + public RangeFloat[] angleRanges; // An array of angle ranges, in degrees, + // where each range specifies how much you + // expect the shape to be rotated in the + // image. + public RangeFloat scaleRange; // A range that specifies the sizes of the + // shapes you expect to be in the image, + // expressed as a ratio percentage + // representing the size of the pattern in the + // image divided by size of the original + // pattern multiplied by 100. + public double minMatchScore; + private ByteBuffer angleRanges_buf; + + private void init() { + angleRanges = new RangeFloat[0]; + scaleRange = new RangeFloat(backing, 12); + } + + public ShapeDetectionOptions() { + super(32); + init(); + } + + public ShapeDetectionOptions(int mode, RangeFloat[] angleRanges, RangeFloat scaleRange, + double minMatchScore) { + super(32); + this.mode = mode; + this.angleRanges = angleRanges; + this.scaleRange = scaleRange; + this.minMatchScore = minMatchScore; + } + + protected ShapeDetectionOptions(ByteBuffer backing, int offset) { + super(backing, offset, 32); + init(); + } + + protected ShapeDetectionOptions(long nativeObj, boolean owned) { + super(nativeObj, owned, 32); + init(); + } + + protected void setBuffer(ByteBuffer backing, int offset) { + super.setBuffer(backing, offset, 32); + } + + public void read() { + mode = backing.getInt(0); + int angleRanges_numAngleRanges = backing.getInt(8); + long angleRanges_addr = getPointer(backing, 4); + angleRanges = new RangeFloat[angleRanges_numAngleRanges]; + if (angleRanges_numAngleRanges > 0 && angleRanges_addr != 0) { + ByteBuffer bb = newDirectByteBuffer(angleRanges_addr, angleRanges_numAngleRanges * 8); + for (int i = 0, off = 0; i < angleRanges_numAngleRanges; i++, off += 8) { + angleRanges[i] = new RangeFloat(bb, off); + angleRanges[i].read(); + } + } + scaleRange.read(); + minMatchScore = backing.getDouble(24); + } + + public void write() { + backing.putInt(0, mode); + angleRanges_buf = + ByteBuffer.allocateDirect(angleRanges.length * 8).order(ByteOrder.nativeOrder()); + for (int i = 0, off = 0; i < angleRanges.length; i++, off += 8) { + angleRanges[i].setBuffer(angleRanges_buf, off); + angleRanges[i].write(); + } + backing.putInt(8, angleRanges.length); + putPointer(backing, 4, angleRanges_buf); + scaleRange.write(); + backing.putDouble(24, minMatchScore); + } + + public int size() { + return 32; + } + } + + public static class Curve extends DisposedStruct { + public PointFloat[] points; // The points on the curve. + public int closed; // This element is TRUE if the curve is closed and FALSE + // if the curve is open. + public double curveLength; // The length of the curve. + public double minEdgeStrength; // The lowest edge strength detected on the + // curve. + public double maxEdgeStrength; // The highest edge strength detected on the + // curve. + public double averageEdgeStrength; // The average of all edge strengths + // detected on the curve. + private ByteBuffer points_buf; + + private void init() { + points = new PointFloat[0]; + } + + public Curve() { + super(48); + init(); + } + + public Curve(PointFloat[] points, int closed, double curveLength, double minEdgeStrength, + double maxEdgeStrength, double averageEdgeStrength) { + super(48); + this.points = points; + this.closed = closed; + this.curveLength = curveLength; + this.minEdgeStrength = minEdgeStrength; + this.maxEdgeStrength = maxEdgeStrength; + this.averageEdgeStrength = averageEdgeStrength; + } + + protected Curve(ByteBuffer backing, int offset) { + super(backing, offset, 48); + init(); + } + + protected Curve(long nativeObj, boolean owned) { + super(nativeObj, owned, 48); + init(); + } + + protected void setBuffer(ByteBuffer backing, int offset) { + super.setBuffer(backing, offset, 48); + } + + public void read() { + int points_numPoints = backing.getInt(4); + long points_addr = getPointer(backing, 0); + points = new PointFloat[points_numPoints]; + if (points_numPoints > 0 && points_addr != 0) { + ByteBuffer bb = newDirectByteBuffer(points_addr, points_numPoints * 8); + for (int i = 0, off = 0; i < points_numPoints; i++, off += 8) { + points[i] = new PointFloat(bb, off); + points[i].read(); + } + } + closed = backing.getInt(8); + curveLength = backing.getDouble(16); + minEdgeStrength = backing.getDouble(24); + maxEdgeStrength = backing.getDouble(32); + averageEdgeStrength = backing.getDouble(40); + } + + public void write() { + points_buf = ByteBuffer.allocateDirect(points.length * 8).order(ByteOrder.nativeOrder()); + for (int i = 0, off = 0; i < points.length; i++, off += 8) { + points[i].setBuffer(points_buf, off); + points[i].write(); + } + backing.putInt(4, points.length); + putPointer(backing, 0, points_buf); + backing.putInt(8, closed); + backing.putDouble(16, curveLength); + backing.putDouble(24, minEdgeStrength); + backing.putDouble(32, maxEdgeStrength); + backing.putDouble(40, averageEdgeStrength); + } + + public int size() { + return 48; + } + } + + public static class CurveOptions extends DisposedStruct { + public ExtractionMode extractionMode; // Specifies the method the function + // uses to identify curves in the + // image. + public int threshold; // Specifies the minimum contrast a seed point must + // have in order to begin a curve. + public EdgeFilterSize filterSize; // Specifies the width of the edge filter + // the function uses to identify curves in + // the image. + public int minLength; // Specifies the length, in pixels, of the smallest + // curve the function will extract. + public int rowStepSize; // Specifies the distance, in the y direction, + // between lines the function inspects for curve + // seed points. + public int columnStepSize; // Specifies the distance, in the x direction, + // between columns the function inspects for + // curve seed points. + public int maxEndPointGap; // Specifies the maximum gap, in pixels, between + // the endpoints of a curve that the function + // identifies as a closed curve. + public int onlyClosed; // Set this element to TRUE to specify that the + // function should only identify closed curves in the + // image. + public int subpixelAccuracy; // Set this element to TRUE to specify that the + // function identifies the location of curves + // with subpixel accuracy by interpolating + // between points to find the crossing of + // threshold. + + private void init() { + + } + + public CurveOptions() { + super(36); + init(); + } + + public CurveOptions(ExtractionMode extractionMode, int threshold, EdgeFilterSize filterSize, + int minLength, int rowStepSize, int columnStepSize, int maxEndPointGap, int onlyClosed, + int subpixelAccuracy) { + super(36); + this.extractionMode = extractionMode; + this.threshold = threshold; + this.filterSize = filterSize; + this.minLength = minLength; + this.rowStepSize = rowStepSize; + this.columnStepSize = columnStepSize; + this.maxEndPointGap = maxEndPointGap; + this.onlyClosed = onlyClosed; + this.subpixelAccuracy = subpixelAccuracy; + } + + protected CurveOptions(ByteBuffer backing, int offset) { + super(backing, offset, 36); + init(); + } + + protected CurveOptions(long nativeObj, boolean owned) { + super(nativeObj, owned, 36); + init(); + } + + protected void setBuffer(ByteBuffer backing, int offset) { + super.setBuffer(backing, offset, 36); + } + + public void read() { + extractionMode = ExtractionMode.fromValue(backing.getInt(0)); + threshold = backing.getInt(4); + filterSize = EdgeFilterSize.fromValue(backing.getInt(8)); + minLength = backing.getInt(12); + rowStepSize = backing.getInt(16); + columnStepSize = backing.getInt(20); + maxEndPointGap = backing.getInt(24); + onlyClosed = backing.getInt(28); + subpixelAccuracy = backing.getInt(32); + } + + public void write() { + if (extractionMode != null) + backing.putInt(0, extractionMode.getValue()); + backing.putInt(4, threshold); + if (filterSize != null) + backing.putInt(8, filterSize.getValue()); + backing.putInt(12, minLength); + backing.putInt(16, rowStepSize); + backing.putInt(20, columnStepSize); + backing.putInt(24, maxEndPointGap); + backing.putInt(28, onlyClosed); + backing.putInt(32, subpixelAccuracy); + } + + public int size() { + return 36; + } + } + + public static class Barcode2DInfo extends DisposedStruct { + public Barcode2DType type; // The type of the 2D barcode. + public int binary; // This element is TRUE if the 2D barcode contains binary + // data and FALSE if the 2D barcode contains text data. + public byte[] data; // The data encoded in the 2D barcode. + public PointFloat[] boundingBox; // An array of four points describing the + // rectangle surrounding the 2D barcode. + public int numErrorsCorrected; // The number of errors the function + // corrected when decoding the 2D barcode. + public int numErasuresCorrected; // The number of erasures the function + // corrected when decoding the 2D barcode. + public int rows; // The number of rows in the 2D barcode. + public int columns; // The number of columns in the 2D barcode. + private ByteBuffer data_buf; + + private void init() { + data = new byte[0]; + boundingBox = new PointFloat[4]; + + for (int i = 0, off = 16; i < 4; i++, off += 8) + boundingBox[i] = new PointFloat(backing, off); + } + + public Barcode2DInfo() { + super(64); + init(); + } + + public Barcode2DInfo(Barcode2DType type, int binary, byte[] data, PointFloat[] boundingBox, + int numErrorsCorrected, int numErasuresCorrected, int rows, int columns) { + super(64); + this.type = type; + this.binary = binary; + this.data = data; + this.boundingBox = boundingBox; + this.numErrorsCorrected = numErrorsCorrected; + this.numErasuresCorrected = numErasuresCorrected; + this.rows = rows; + this.columns = columns; + } + + protected Barcode2DInfo(ByteBuffer backing, int offset) { + super(backing, offset, 64); + init(); + } + + protected Barcode2DInfo(long nativeObj, boolean owned) { + super(nativeObj, owned, 64); + init(); + } + + protected void setBuffer(ByteBuffer backing, int offset) { + super.setBuffer(backing, offset, 64); + } + + public void read() { + type = Barcode2DType.fromValue(backing.getInt(0)); + binary = backing.getInt(4); + int data_dataLength = backing.getInt(12); + long data_addr = getPointer(backing, 8); + data = new byte[data_dataLength]; + if (data_dataLength > 0 && data_addr != 0) { + getBytes(newDirectByteBuffer(data_addr, data_dataLength), data, 0, data_dataLength); + } + for (PointFloat it : boundingBox) { + it.read(); + } + numErrorsCorrected = backing.getInt(48); + numErasuresCorrected = backing.getInt(52); + rows = backing.getInt(56); + columns = backing.getInt(60); + } + + public void write() { + if (type != null) + backing.putInt(0, type.getValue()); + backing.putInt(4, binary); + data_buf = ByteBuffer.allocateDirect(data.length); + putBytes(data_buf, data, 0, data.length); + backing.putInt(12, data.length); + putPointer(backing, 8, data_buf); + for (PointFloat it : boundingBox) { + it.write(); + } + backing.putInt(48, numErrorsCorrected); + backing.putInt(52, numErasuresCorrected); + backing.putInt(56, rows); + backing.putInt(60, columns); + } + + public int size() { + return 64; + } + } + + public static class DataMatrixOptions extends DisposedStruct { + public Barcode2DSearchMode searchMode; // Specifies the mode the function + // uses to search for barcodes. + public Barcode2DContrast contrast; // Specifies the contrast of the barcodes + // that the function searches for. + public Barcode2DCellShape cellShape; // Specifies the shape of the barcode + // data cells, which affects how the + // function decodes the barcode. + public Barcode2DShape barcodeShape; // Specifies the shape of the barcodes + // that the function searches for. + public DataMatrixSubtype subtype; // Specifies the Data Matrix subtypes of + // the barcodes that the function searches + // for. + + private void init() { + + } + + public DataMatrixOptions() { + super(20); + init(); + } + + public DataMatrixOptions(Barcode2DSearchMode searchMode, Barcode2DContrast contrast, + Barcode2DCellShape cellShape, Barcode2DShape barcodeShape, DataMatrixSubtype subtype) { + super(20); + this.searchMode = searchMode; + this.contrast = contrast; + this.cellShape = cellShape; + this.barcodeShape = barcodeShape; + this.subtype = subtype; + } + + protected DataMatrixOptions(ByteBuffer backing, int offset) { + super(backing, offset, 20); + init(); + } + + protected DataMatrixOptions(long nativeObj, boolean owned) { + super(nativeObj, owned, 20); + init(); + } + + protected void setBuffer(ByteBuffer backing, int offset) { + super.setBuffer(backing, offset, 20); + } + + public void read() { + searchMode = Barcode2DSearchMode.fromValue(backing.getInt(0)); + contrast = Barcode2DContrast.fromValue(backing.getInt(4)); + cellShape = Barcode2DCellShape.fromValue(backing.getInt(8)); + barcodeShape = Barcode2DShape.fromValue(backing.getInt(12)); + subtype = DataMatrixSubtype.fromValue(backing.getInt(16)); + } + + public void write() { + if (searchMode != null) + backing.putInt(0, searchMode.getValue()); + if (contrast != null) + backing.putInt(4, contrast.getValue()); + if (cellShape != null) + backing.putInt(8, cellShape.getValue()); + if (barcodeShape != null) + backing.putInt(12, barcodeShape.getValue()); + if (subtype != null) + backing.putInt(16, subtype.getValue()); + } + + public int size() { + return 20; + } + } + + public static class ClassifierAccuracyReport extends DisposedStruct { + public float accuracy; // The overall accuracy of the classifier, from 0 to + // 1000. + public String[] classNames; // The names of the classes of this classifier. + public double[] classAccuracy; // An array of size elements that contains + // accuracy information for each class. + public double[] classPredictiveValue; // An array containing size elements + // that contains the predictive values + // of each class. + private ByteBuffer classNames_buf; + private ByteBuffer[] classNames_bufs; + private ByteBuffer classAccuracy_buf; + private ByteBuffer classPredictiveValue_buf; + + private void init() { + classNames = new String[0]; + classAccuracy = new double[0]; + classPredictiveValue = new double[0]; + } + + public ClassifierAccuracyReport() { + super(24); + init(); + } + + public ClassifierAccuracyReport(double accuracy, String[] classNames, double[] classAccuracy, + double[] classPredictiveValue) { + super(24); + this.accuracy = (float) accuracy; + this.classNames = classNames; + this.classAccuracy = classAccuracy; + this.classPredictiveValue = classPredictiveValue; + } + + protected ClassifierAccuracyReport(ByteBuffer backing, int offset) { + super(backing, offset, 24); + init(); + } + + protected ClassifierAccuracyReport(long nativeObj, boolean owned) { + super(nativeObj, owned, 24); + init(); + } + + protected void setBuffer(ByteBuffer backing, int offset) { + super.setBuffer(backing, offset, 24); + } + + public void read() { + accuracy = backing.getFloat(4); + int classNames_size = backing.getInt(0); + long classNames_addr = getPointer(backing, 8); + classNames = new String[classNames_size]; + if (classNames_size > 0 && classNames_addr != 0) { + ByteBuffer bb = newDirectByteBuffer(classNames_addr, classNames_size * 4); + for (int i = 0, off = 0; i < classNames_size; i++, off += 4) { + long addr = getPointer(bb, off); + if (addr == 0) + classNames[i] = null; + else { + ByteBuffer bb2 = newDirectByteBuffer(addr, 1000); // FIXME + while (bb2.get() != 0) { + } + byte[] bytes = new byte[bb2.position() - 1]; + bb2.rewind(); + getBytes(bb2, bytes, 0, bytes.length); + try { + classNames[i] = new String(bytes, "UTF-8"); + } catch (UnsupportedEncodingException e) { + classNames[i] = ""; + } + } + } + } + int classAccuracy_size = backing.getInt(0); + long classAccuracy_addr = getPointer(backing, 12); + classAccuracy = new double[classAccuracy_size]; + if (classAccuracy_size > 0 && classAccuracy_addr != 0) { + newDirectByteBuffer(classAccuracy_addr, classAccuracy_size * 8).asDoubleBuffer().get( + classAccuracy); + } + int classPredictiveValue_size = backing.getInt(0); + long classPredictiveValue_addr = getPointer(backing, 16); + classPredictiveValue = new double[classPredictiveValue_size]; + if (classPredictiveValue_size > 0 && classPredictiveValue_addr != 0) { + newDirectByteBuffer(classPredictiveValue_addr, classPredictiveValue_size * 8) + .asDoubleBuffer().get(classPredictiveValue); + } + } + + public void write() { + backing.putFloat(4, accuracy); + classNames_buf = + ByteBuffer.allocateDirect(classNames.length * 4).order(ByteOrder.nativeOrder()); + for (int i = 0, off = 0; i < classNames.length; i++, off += 4) { + if (classNames[i] == null) + putPointer(classNames_buf, off, 0); + else { + byte[] bytes; + try { + bytes = classNames[i].getBytes("UTF-8"); + } catch (UnsupportedEncodingException e) { + bytes = new byte[0]; + } + classNames_bufs[i] = ByteBuffer.allocateDirect(bytes.length + 1); + putBytes(classNames_bufs[i], bytes, 0, bytes.length).put(bytes.length, (byte) 0); + putPointer(classNames_buf, off, getByteBufferAddress(classNames_bufs[i])); + } + } + backing.putInt(0, classNames.length); + putPointer(backing, 8, classNames_buf); + classAccuracy_buf = + ByteBuffer.allocateDirect(classAccuracy.length * 8).order(ByteOrder.nativeOrder()); + classAccuracy_buf.asDoubleBuffer().put(classAccuracy).rewind(); + backing.putInt(0, classAccuracy.length); + putPointer(backing, 12, classAccuracy_buf); + classPredictiveValue_buf = + ByteBuffer.allocateDirect(classPredictiveValue.length * 8).order(ByteOrder.nativeOrder()); + classPredictiveValue_buf.asDoubleBuffer().put(classPredictiveValue).rewind(); + backing.putInt(0, classPredictiveValue.length); + putPointer(backing, 16, classPredictiveValue_buf); + } + + public int size() { + return 24; + } + } + + public static class NearestNeighborClassResult extends DisposedStruct { + public String className; // The name of the class. + public float standardDeviation; // The standard deviation of the members of + // this class. + public int count; // The number of samples in this class. + private ByteBuffer className_buf; + + private void init() { + + } + + public NearestNeighborClassResult() { + super(12); + init(); + } + + public NearestNeighborClassResult(String className, double standardDeviation, int count) { + super(12); + this.className = className; + this.standardDeviation = (float) standardDeviation; + this.count = count; + } + + protected NearestNeighborClassResult(ByteBuffer backing, int offset) { + super(backing, offset, 12); + init(); + } + + protected NearestNeighborClassResult(long nativeObj, boolean owned) { + super(nativeObj, owned, 12); + init(); + } + + protected void setBuffer(ByteBuffer backing, int offset) { + super.setBuffer(backing, offset, 12); + } + + public void read() { + long className_addr = getPointer(backing, 0); + if (className_addr == 0) + className = null; + else { + ByteBuffer bb = newDirectByteBuffer(className_addr, 1000); // FIXME + while (bb.get() != 0) { + } + byte[] bytes = new byte[bb.position() - 1]; + getBytes(bb, bytes, 0, bytes.length); + try { + className = new String(bytes, "UTF-8"); + } catch (UnsupportedEncodingException e) { + className = ""; + } + } + + standardDeviation = backing.getFloat(4); + count = backing.getInt(8); + } + + public void write() { + if (className != null) { + byte[] className_bytes; + try { + className_bytes = className.getBytes("UTF-8"); + } catch (UnsupportedEncodingException e) { + className_bytes = new byte[0]; + } + className_buf = ByteBuffer.allocateDirect(className_bytes.length + 1); + putBytes(className_buf, className_bytes, 0, className_bytes.length).put( + className_bytes.length, (byte) 0); + } + putPointer(backing, 0, className == null ? 0 : getByteBufferAddress(className_buf)); + backing.putFloat(4, standardDeviation); + backing.putInt(8, count); + } + + public int size() { + return 12; + } + } + + public static class NearestNeighborTrainingReport extends DisposedStruct { + public NearestNeighborClassResult[] allScores; // All classes and their + // scores. + private ByteBuffer allScores_buf; + + private void init() { + allScores = new NearestNeighborClassResult[0]; + } + + public NearestNeighborTrainingReport() { + super(12); + init(); + } + + public NearestNeighborTrainingReport(NearestNeighborClassResult[] allScores) { + super(12); + this.allScores = allScores; + } + + protected NearestNeighborTrainingReport(ByteBuffer backing, int offset) { + super(backing, offset, 12); + init(); + } + + protected NearestNeighborTrainingReport(long nativeObj, boolean owned) { + super(nativeObj, owned, 12); + init(); + } + + protected void setBuffer(ByteBuffer backing, int offset) { + super.setBuffer(backing, offset, 12); + } + + public void read() { + int allScores_allScoresSize = backing.getInt(8); + long allScores_addr = getPointer(backing, 4); + allScores = new NearestNeighborClassResult[allScores_allScoresSize]; + if (allScores_allScoresSize > 0 && allScores_addr != 0) { + ByteBuffer bb = newDirectByteBuffer(allScores_addr, allScores_allScoresSize * 12); + for (int i = 0, off = 0; i < allScores_allScoresSize; i++, off += 12) { + allScores[i] = new NearestNeighborClassResult(bb, off); + allScores[i].read(); + } + } + } + + public void write() { + allScores_buf = + ByteBuffer.allocateDirect(allScores.length * 12).order(ByteOrder.nativeOrder()); + for (int i = 0, off = 0; i < allScores.length; i++, off += 12) { + allScores[i].setBuffer(allScores_buf, off); + allScores[i].write(); + } + backing.putInt(8, allScores.length); + putPointer(backing, 4, allScores_buf); + } + + public int size() { + return 12; + } + } + + public static class ParticleClassifierPreprocessingOptions extends DisposedStruct { + public int manualThreshold; // Set this element to TRUE to specify the + // threshold range manually. + public RangeFloat manualThresholdRange; // If a manual threshold is being + // done, the range of pixels to + // keep. + public ThresholdMethod autoThresholdMethod; // If an automatic threshold is + // being done, the method used + // to calculate the threshold + // range. + public RangeFloat limits; // The limits on the automatic threshold range. + public ParticleType particleType; // Specifies what kind of particles to + // look for. + public int rejectBorder; // Set this element to TRUE to reject border + // particles. + public int numErosions; // The number of erosions to perform. + + private void init() { + manualThresholdRange = new RangeFloat(backing, 4); + limits = new RangeFloat(backing, 16); + } + + public ParticleClassifierPreprocessingOptions() { + super(36); + init(); + } + + public ParticleClassifierPreprocessingOptions(int manualThreshold, + RangeFloat manualThresholdRange, ThresholdMethod autoThresholdMethod, RangeFloat limits, + ParticleType particleType, int rejectBorder, int numErosions) { + super(36); + this.manualThreshold = manualThreshold; + this.manualThresholdRange = manualThresholdRange; + this.autoThresholdMethod = autoThresholdMethod; + this.limits = limits; + this.particleType = particleType; + this.rejectBorder = rejectBorder; + this.numErosions = numErosions; + } + + protected ParticleClassifierPreprocessingOptions(ByteBuffer backing, int offset) { + super(backing, offset, 36); + init(); + } + + protected ParticleClassifierPreprocessingOptions(long nativeObj, boolean owned) { + super(nativeObj, owned, 36); + init(); + } + + protected void setBuffer(ByteBuffer backing, int offset) { + super.setBuffer(backing, offset, 36); + } + + public void read() { + manualThreshold = backing.getInt(0); + manualThresholdRange.read(); + autoThresholdMethod = ThresholdMethod.fromValue(backing.getInt(12)); + limits.read(); + particleType = ParticleType.fromValue(backing.getInt(24)); + rejectBorder = backing.getInt(28); + numErosions = backing.getInt(32); + } + + public void write() { + backing.putInt(0, manualThreshold); + manualThresholdRange.write(); + if (autoThresholdMethod != null) + backing.putInt(12, autoThresholdMethod.getValue()); + limits.write(); + if (particleType != null) + backing.putInt(24, particleType.getValue()); + backing.putInt(28, rejectBorder); + backing.putInt(32, numErosions); + } + + public int size() { + return 36; + } + } + + public static class ClassifierSampleInfo extends DisposedStruct { + public String className; // The name of the class this sample is in. + public double[] featureVector; // The feature vector of this sample, or NULL + // if this is not a custom classifier + // session. + public Image thumbnail; // A thumbnail image of this sample, or NULL if no + // image was specified. + private ByteBuffer className_buf; + private ByteBuffer featureVector_buf; + + private void init() { + featureVector = new double[0]; + } + + public ClassifierSampleInfo() { + super(16); + init(); + } + + public ClassifierSampleInfo(String className, double[] featureVector, Image thumbnail) { + super(16); + this.className = className; + this.featureVector = featureVector; + this.thumbnail = thumbnail; + } + + protected ClassifierSampleInfo(ByteBuffer backing, int offset) { + super(backing, offset, 16); + init(); + } + + protected ClassifierSampleInfo(long nativeObj, boolean owned) { + super(nativeObj, owned, 16); + init(); + } + + protected void setBuffer(ByteBuffer backing, int offset) { + super.setBuffer(backing, offset, 16); + } + + public void read() { + long className_addr = getPointer(backing, 0); + if (className_addr == 0) + className = null; + else { + ByteBuffer bb = newDirectByteBuffer(className_addr, 1000); // FIXME + while (bb.get() != 0) { + } + byte[] bytes = new byte[bb.position() - 1]; + getBytes(bb, bytes, 0, bytes.length); + try { + className = new String(bytes, "UTF-8"); + } catch (UnsupportedEncodingException e) { + className = ""; + } + } + + int featureVector_featureVectorSize = backing.getInt(8); + long featureVector_addr = getPointer(backing, 4); + featureVector = new double[featureVector_featureVectorSize]; + if (featureVector_featureVectorSize > 0 && featureVector_addr != 0) { + newDirectByteBuffer(featureVector_addr, featureVector_featureVectorSize * 8) + .asDoubleBuffer().get(featureVector); + } + long thumbnail_addr = getPointer(backing, 12); + if (thumbnail_addr == 0) + thumbnail = null; + else + thumbnail = new Image(thumbnail_addr, false); + } + + public void write() { + if (className != null) { + byte[] className_bytes; + try { + className_bytes = className.getBytes("UTF-8"); + } catch (UnsupportedEncodingException e) { + className_bytes = new byte[0]; + } + className_buf = ByteBuffer.allocateDirect(className_bytes.length + 1); + putBytes(className_buf, className_bytes, 0, className_bytes.length).put( + className_bytes.length, (byte) 0); + } + putPointer(backing, 0, className == null ? 0 : getByteBufferAddress(className_buf)); + featureVector_buf = + ByteBuffer.allocateDirect(featureVector.length * 8).order(ByteOrder.nativeOrder()); + featureVector_buf.asDoubleBuffer().put(featureVector).rewind(); + backing.putInt(8, featureVector.length); + putPointer(backing, 4, featureVector_buf); + putPointer(backing, 12, thumbnail); + } + + public int size() { + return 16; + } + } + + public static class ClassScore extends DisposedStruct { + public String className; // The name of the class. + public float distance; // The distance from the item to this class. + private ByteBuffer className_buf; + + private void init() { + + } + + public ClassScore() { + super(8); + init(); + } + + public ClassScore(String className, double distance) { + super(8); + this.className = className; + this.distance = (float) distance; + } + + protected ClassScore(ByteBuffer backing, int offset) { + super(backing, offset, 8); + init(); + } + + protected ClassScore(long nativeObj, boolean owned) { + super(nativeObj, owned, 8); + init(); + } + + protected void setBuffer(ByteBuffer backing, int offset) { + super.setBuffer(backing, offset, 8); + } + + public void read() { + long className_addr = getPointer(backing, 0); + if (className_addr == 0) + className = null; + else { + ByteBuffer bb = newDirectByteBuffer(className_addr, 1000); // FIXME + while (bb.get() != 0) { + } + byte[] bytes = new byte[bb.position() - 1]; + getBytes(bb, bytes, 0, bytes.length); + try { + className = new String(bytes, "UTF-8"); + } catch (UnsupportedEncodingException e) { + className = ""; + } + } + + distance = backing.getFloat(4); + } + + public void write() { + if (className != null) { + byte[] className_bytes; + try { + className_bytes = className.getBytes("UTF-8"); + } catch (UnsupportedEncodingException e) { + className_bytes = new byte[0]; + } + className_buf = ByteBuffer.allocateDirect(className_bytes.length + 1); + putBytes(className_buf, className_bytes, 0, className_bytes.length).put( + className_bytes.length, (byte) 0); + } + putPointer(backing, 0, className == null ? 0 : getByteBufferAddress(className_buf)); + backing.putFloat(4, distance); + } + + public int size() { + return 8; + } + } + + public static class ClassifierReport extends DisposedStruct { + public String bestClassName; // The name of the best class for the sample. + public float classificationScore; // The similarity of the sample and the + // two closest classes in the classifier. + public float identificationScore; // The similarity of the sample and the + // assigned class. + public ClassScore[] allScores; // All classes and their scores. + private ByteBuffer bestClassName_buf; + private ByteBuffer allScores_buf; + + private void init() { + allScores = new ClassScore[0]; + } + + public ClassifierReport() { + super(20); + init(); + } + + public ClassifierReport(String bestClassName, double classificationScore, + double identificationScore, ClassScore[] allScores) { + super(20); + this.bestClassName = bestClassName; + this.classificationScore = (float) classificationScore; + this.identificationScore = (float) identificationScore; + this.allScores = allScores; + } + + protected ClassifierReport(ByteBuffer backing, int offset) { + super(backing, offset, 20); + init(); + } + + protected ClassifierReport(long nativeObj, boolean owned) { + super(nativeObj, owned, 20); + init(); + } + + protected void setBuffer(ByteBuffer backing, int offset) { + super.setBuffer(backing, offset, 20); + } + + public void read() { + long bestClassName_addr = getPointer(backing, 0); + if (bestClassName_addr == 0) + bestClassName = null; + else { + ByteBuffer bb = newDirectByteBuffer(bestClassName_addr, 1000); // FIXME + while (bb.get() != 0) { + } + byte[] bytes = new byte[bb.position() - 1]; + getBytes(bb, bytes, 0, bytes.length); + try { + bestClassName = new String(bytes, "UTF-8"); + } catch (UnsupportedEncodingException e) { + bestClassName = ""; + } + } + + classificationScore = backing.getFloat(4); + identificationScore = backing.getFloat(8); + int allScores_allScoresSize = backing.getInt(16); + long allScores_addr = getPointer(backing, 12); + allScores = new ClassScore[allScores_allScoresSize]; + if (allScores_allScoresSize > 0 && allScores_addr != 0) { + ByteBuffer bb = newDirectByteBuffer(allScores_addr, allScores_allScoresSize * 8); + for (int i = 0, off = 0; i < allScores_allScoresSize; i++, off += 8) { + allScores[i] = new ClassScore(bb, off); + allScores[i].read(); + } + } + } + + public void write() { + if (bestClassName != null) { + byte[] bestClassName_bytes; + try { + bestClassName_bytes = bestClassName.getBytes("UTF-8"); + } catch (UnsupportedEncodingException e) { + bestClassName_bytes = new byte[0]; + } + bestClassName_buf = ByteBuffer.allocateDirect(bestClassName_bytes.length + 1); + putBytes(bestClassName_buf, bestClassName_bytes, 0, bestClassName_bytes.length).put( + bestClassName_bytes.length, (byte) 0); + } + putPointer(backing, 0, bestClassName == null ? 0 : getByteBufferAddress(bestClassName_buf)); + backing.putFloat(4, classificationScore); + backing.putFloat(8, identificationScore); + allScores_buf = + ByteBuffer.allocateDirect(allScores.length * 8).order(ByteOrder.nativeOrder()); + for (int i = 0, off = 0; i < allScores.length; i++, off += 8) { + allScores[i].setBuffer(allScores_buf, off); + allScores[i].write(); + } + backing.putInt(16, allScores.length); + putPointer(backing, 12, allScores_buf); + } + + public int size() { + return 20; + } + } + + public static class NearestNeighborOptions extends DisposedStruct { + public NearestNeighborMethod method; // The method to use. + public NearestNeighborMetric metric; // The metric to use. + public int k; // The value of k, if the IMAQ_K_NEAREST_NEIGHBOR method is + // used. + + private void init() { + + } + + public NearestNeighborOptions() { + super(12); + init(); + } + + public NearestNeighborOptions(NearestNeighborMethod method, NearestNeighborMetric metric, int k) { + super(12); + this.method = method; + this.metric = metric; + this.k = k; + } + + protected NearestNeighborOptions(ByteBuffer backing, int offset) { + super(backing, offset, 12); + init(); + } + + protected NearestNeighborOptions(long nativeObj, boolean owned) { + super(nativeObj, owned, 12); + init(); + } + + protected void setBuffer(ByteBuffer backing, int offset) { + super.setBuffer(backing, offset, 12); + } + + public void read() { + method = NearestNeighborMethod.fromValue(backing.getInt(0)); + metric = NearestNeighborMetric.fromValue(backing.getInt(4)); + k = backing.getInt(8); + } + + public void write() { + if (method != null) + backing.putInt(0, method.getValue()); + if (metric != null) + backing.putInt(4, metric.getValue()); + backing.putInt(8, k); + } + + public int size() { + return 12; + } + } + + public static class ParticleClassifierOptions extends DisposedStruct { + public float scaleDependence; // The relative importance of scale when + // classifying particles. + public float mirrorDependence; // The relative importance of mirror symmetry + // when classifying particles. + + private void init() { + + } + + public ParticleClassifierOptions() { + super(8); + init(); + } + + public ParticleClassifierOptions(double scaleDependence, double mirrorDependence) { + super(8); + this.scaleDependence = (float) scaleDependence; + this.mirrorDependence = (float) mirrorDependence; + } + + protected ParticleClassifierOptions(ByteBuffer backing, int offset) { + super(backing, offset, 8); + init(); + } + + protected ParticleClassifierOptions(long nativeObj, boolean owned) { + super(nativeObj, owned, 8); + init(); + } + + protected void setBuffer(ByteBuffer backing, int offset) { + super.setBuffer(backing, offset, 8); + } + + public void read() { + scaleDependence = backing.getFloat(0); + mirrorDependence = backing.getFloat(4); + } + + public void write() { + backing.putFloat(0, scaleDependence); + backing.putFloat(4, mirrorDependence); + } + + public int size() { + return 8; + } + } + + public static class RGBU64Value extends DisposedStruct { + public int B; // The blue value of the color. + public int G; // The green value of the color. + public int R; // The red value of the color. + public int alpha; // The alpha value of the color, which represents extra + // information about a color image, such as gamma + // correction. + + private void init() { + + } + + public RGBU64Value() { + super(8); + init(); + } + + public RGBU64Value(int B, int G, int R, int alpha) { + super(8); + this.B = B; + this.G = G; + this.R = R; + this.alpha = alpha; + } + + protected RGBU64Value(ByteBuffer backing, int offset) { + super(backing, offset, 8); + init(); + } + + protected RGBU64Value(long nativeObj, boolean owned) { + super(nativeObj, owned, 8); + init(); + } + + protected void setBuffer(ByteBuffer backing, int offset) { + super.setBuffer(backing, offset, 8); + } + + public void read() { + B = (int) (backing.getShort(0) & 0xffff); + G = (int) (backing.getShort(2) & 0xffff); + R = (int) (backing.getShort(4) & 0xffff); + alpha = (int) (backing.getShort(6) & 0xffff); + } + + public void write() { + backing.putShort(0, (short) (B & 0xffff)); + backing.putShort(2, (short) (G & 0xffff)); + backing.putShort(4, (short) (R & 0xffff)); + backing.putShort(6, (short) (alpha & 0xffff)); + } + + public int size() { + return 8; + } + } + + public static class GeometricPatternMatch extends DisposedStruct { + public PointFloat position; // The location of the origin of the template in + // the match. + public float rotation; // The rotation of the match relative to the template + // image, in degrees. + public float scale; // The size of the match relative to the size of the + // template image, expressed as a percentage. + public float score; // The accuracy of the match. + public PointFloat[] corner; // An array of four points describing the + // rectangle surrounding the template image. + public int inverse; // This element is TRUE if the match is an inverse of + // the template image. + public float occlusion; // The percentage of the match that is occluded. + public float templateMatchCurveScore; // The accuracy of the match obtained + // by comparing the template curves to + // the curves in the match region. + public float matchTemplateCurveScore; // The accuracy of the match obtained + // by comparing the curves in the + // match region to the template + // curves. + public float correlationScore; // The accuracy of the match obtained by + // comparing the template image to the match + // region using a correlation metric that + // compares the two regions as a function of + // their pixel values. + + private void init() { + position = new PointFloat(backing, 0); + corner = new PointFloat[4]; + + for (int i = 0, off = 20; i < 4; i++, off += 8) + corner[i] = new PointFloat(backing, off); + } + + public GeometricPatternMatch() { + super(72); + init(); + } + + public GeometricPatternMatch(PointFloat position, double rotation, double scale, double score, + PointFloat[] corner, int inverse, double occlusion, double templateMatchCurveScore, + double matchTemplateCurveScore, double correlationScore) { + super(72); + this.position = position; + this.rotation = (float) rotation; + this.scale = (float) scale; + this.score = (float) score; + this.corner = corner; + this.inverse = inverse; + this.occlusion = (float) occlusion; + this.templateMatchCurveScore = (float) templateMatchCurveScore; + this.matchTemplateCurveScore = (float) matchTemplateCurveScore; + this.correlationScore = (float) correlationScore; + } + + protected GeometricPatternMatch(ByteBuffer backing, int offset) { + super(backing, offset, 72); + init(); + } + + protected GeometricPatternMatch(long nativeObj, boolean owned) { + super(nativeObj, owned, 72); + init(); + } + + protected void setBuffer(ByteBuffer backing, int offset) { + super.setBuffer(backing, offset, 72); + } + + public void read() { + position.read(); + rotation = backing.getFloat(8); + scale = backing.getFloat(12); + score = backing.getFloat(16); + for (PointFloat it : corner) { + it.read(); + } + inverse = backing.getInt(52); + occlusion = backing.getFloat(56); + templateMatchCurveScore = backing.getFloat(60); + matchTemplateCurveScore = backing.getFloat(64); + correlationScore = backing.getFloat(68); + } + + public void write() { + position.write(); + backing.putFloat(8, rotation); + backing.putFloat(12, scale); + backing.putFloat(16, score); + for (PointFloat it : corner) { + it.write(); + } + backing.putInt(52, inverse); + backing.putFloat(56, occlusion); + backing.putFloat(60, templateMatchCurveScore); + backing.putFloat(64, matchTemplateCurveScore); + backing.putFloat(68, correlationScore); + } + + public int size() { + return 72; + } + } + + public static class MatchGeometricPatternAdvancedOptions extends DisposedStruct { + public int minFeaturesUsed; // Specifies the minimum number of features the + // function uses when matching. + public int maxFeaturesUsed; // Specifies the maximum number of features the + // function uses when matching. + public int subpixelIterations; // Specifies the maximum number of + // incremental improvements used to refine + // matches with subpixel information. + public double subpixelTolerance; // Specifies the maximum amount of change, + // in pixels, between consecutive + // incremental improvements in the match + // position before the function stops + // refining the match position. + public int initialMatchListLength; // Specifies the maximum size of the + // match list. + public int matchTemplateCurveScore; // Set this element to TRUE to specify + // that the function should calculate + // the match curve to template curve + // score and return it for each match + // result. + public int correlationScore; // Set this element to TRUE to specify that the + // function should calculate the correlation + // score and return it for each match result. + public double minMatchSeparationDistance; // Specifies the minimum + // separation distance, in pixels, + // between the origins of two + // matches that have unique + // positions. + public double minMatchSeparationAngle; // Specifies the minimum angular + // difference, in degrees, between + // two matches that have unique + // angles. + public double minMatchSeparationScale; // Specifies the minimum difference + // in scale, expressed as a + // percentage, between two matches + // that have unique scales. + public double maxMatchOverlap; // Specifies the maximum amount of overlap, + // expressed as a percentage, allowed between + // the bounding rectangles of two unique + // matches. + public int coarseResult; // Specifies whether you want the function to spend + // less time accurately estimating the location of + // a match. + + private void init() { + + } + + public MatchGeometricPatternAdvancedOptions() { + super(80); + init(); + } + + public MatchGeometricPatternAdvancedOptions(int minFeaturesUsed, int maxFeaturesUsed, + int subpixelIterations, double subpixelTolerance, int initialMatchListLength, + int matchTemplateCurveScore, int correlationScore, double minMatchSeparationDistance, + double minMatchSeparationAngle, double minMatchSeparationScale, double maxMatchOverlap, + int coarseResult) { + super(80); + this.minFeaturesUsed = minFeaturesUsed; + this.maxFeaturesUsed = maxFeaturesUsed; + this.subpixelIterations = subpixelIterations; + this.subpixelTolerance = subpixelTolerance; + this.initialMatchListLength = initialMatchListLength; + this.matchTemplateCurveScore = matchTemplateCurveScore; + this.correlationScore = correlationScore; + this.minMatchSeparationDistance = minMatchSeparationDistance; + this.minMatchSeparationAngle = minMatchSeparationAngle; + this.minMatchSeparationScale = minMatchSeparationScale; + this.maxMatchOverlap = maxMatchOverlap; + this.coarseResult = coarseResult; + } + + protected MatchGeometricPatternAdvancedOptions(ByteBuffer backing, int offset) { + super(backing, offset, 80); + init(); + } + + protected MatchGeometricPatternAdvancedOptions(long nativeObj, boolean owned) { + super(nativeObj, owned, 80); + init(); + } + + protected void setBuffer(ByteBuffer backing, int offset) { + super.setBuffer(backing, offset, 80); + } + + public void read() { + minFeaturesUsed = backing.getInt(0); + maxFeaturesUsed = backing.getInt(4); + subpixelIterations = backing.getInt(8); + subpixelTolerance = backing.getDouble(16); + initialMatchListLength = backing.getInt(24); + matchTemplateCurveScore = backing.getInt(28); + correlationScore = backing.getInt(32); + minMatchSeparationDistance = backing.getDouble(40); + minMatchSeparationAngle = backing.getDouble(48); + minMatchSeparationScale = backing.getDouble(56); + maxMatchOverlap = backing.getDouble(64); + coarseResult = backing.getInt(72); + } + + public void write() { + backing.putInt(0, minFeaturesUsed); + backing.putInt(4, maxFeaturesUsed); + backing.putInt(8, subpixelIterations); + backing.putDouble(16, subpixelTolerance); + backing.putInt(24, initialMatchListLength); + backing.putInt(28, matchTemplateCurveScore); + backing.putInt(32, correlationScore); + backing.putDouble(40, minMatchSeparationDistance); + backing.putDouble(48, minMatchSeparationAngle); + backing.putDouble(56, minMatchSeparationScale); + backing.putDouble(64, maxMatchOverlap); + backing.putInt(72, coarseResult); + } + + public int size() { + return 80; + } + } + + public static class MatchGeometricPatternOptions extends DisposedStruct { + public int mode; // Specifies the method imaqMatchGeometricPattern() uses + // when looking for the pattern in the image. + public int subpixelAccuracy; // Set this element to TRUE to specify that the + // function should calculate match locations + // with subpixel accuracy. + public RangeFloat[] angleRanges; // An array of angle ranges, in degrees, + // where each range specifies how much you + // expect the template to be rotated in the + // image. + public RangeFloat scaleRange; // A range that specifies the sizes of the + // pattern you expect to be in the image, + // expressed as a ratio percentage + // representing the size of the pattern in the + // image divided by size of the original + // pattern multiplied by 100. + public RangeFloat occlusionRange; // A range that specifies the percentage + // of the pattern you expect to be + // occluded in the image. + public int numMatchesRequested; // Number of valid matches expected. + public float minMatchScore; // The minimum score a match can have for the + // function to consider the match valid. + private ByteBuffer angleRanges_buf; + + private void init() { + angleRanges = new RangeFloat[0]; + scaleRange = new RangeFloat(backing, 16); + occlusionRange = new RangeFloat(backing, 24); + } + + public MatchGeometricPatternOptions() { + super(40); + init(); + } + + public MatchGeometricPatternOptions(int mode, int subpixelAccuracy, RangeFloat[] angleRanges, + RangeFloat scaleRange, RangeFloat occlusionRange, int numMatchesRequested, + double minMatchScore) { + super(40); + this.mode = mode; + this.subpixelAccuracy = subpixelAccuracy; + this.angleRanges = angleRanges; + this.scaleRange = scaleRange; + this.occlusionRange = occlusionRange; + this.numMatchesRequested = numMatchesRequested; + this.minMatchScore = (float) minMatchScore; + } + + protected MatchGeometricPatternOptions(ByteBuffer backing, int offset) { + super(backing, offset, 40); + init(); + } + + protected MatchGeometricPatternOptions(long nativeObj, boolean owned) { + super(nativeObj, owned, 40); + init(); + } + + protected void setBuffer(ByteBuffer backing, int offset) { + super.setBuffer(backing, offset, 40); + } + + public void read() { + mode = backing.getInt(0); + subpixelAccuracy = backing.getInt(4); + int angleRanges_numAngleRanges = backing.getInt(12); + long angleRanges_addr = getPointer(backing, 8); + angleRanges = new RangeFloat[angleRanges_numAngleRanges]; + if (angleRanges_numAngleRanges > 0 && angleRanges_addr != 0) { + ByteBuffer bb = newDirectByteBuffer(angleRanges_addr, angleRanges_numAngleRanges * 8); + for (int i = 0, off = 0; i < angleRanges_numAngleRanges; i++, off += 8) { + angleRanges[i] = new RangeFloat(bb, off); + angleRanges[i].read(); + } + } + scaleRange.read(); + occlusionRange.read(); + numMatchesRequested = backing.getInt(32); + minMatchScore = backing.getFloat(36); + } + + public void write() { + backing.putInt(0, mode); + backing.putInt(4, subpixelAccuracy); + angleRanges_buf = + ByteBuffer.allocateDirect(angleRanges.length * 8).order(ByteOrder.nativeOrder()); + for (int i = 0, off = 0; i < angleRanges.length; i++, off += 8) { + angleRanges[i].setBuffer(angleRanges_buf, off); + angleRanges[i].write(); + } + backing.putInt(12, angleRanges.length); + putPointer(backing, 8, angleRanges_buf); + scaleRange.write(); + occlusionRange.write(); + backing.putInt(32, numMatchesRequested); + backing.putFloat(36, minMatchScore); + } + + public int size() { + return 40; + } + } + + public static class LearnGeometricPatternAdvancedOptions extends DisposedStruct { + public int minRectLength; // Specifies the minimum length for each side of a + // rectangular feature. + public double minRectAspectRatio; // Specifies the minimum aspect ratio of a + // rectangular feature. + public int minRadius; // Specifies the minimum radius for a circular + // feature. + public int minLineLength; // Specifies the minimum length for a linear + // feature. + public double minFeatureStrength; // Specifies the minimum strength for a + // feature. + public int maxFeaturesUsed; // Specifies the maximum number of features the + // function uses when learning. + public int maxPixelDistanceFromLine; // Specifies the maximum number of + // pixels between an edge pixel and a + // linear feature for the function to + // consider that edge pixel as part of + // the linear feature. + + private void init() { + + } + + public LearnGeometricPatternAdvancedOptions() { + super(40); + init(); + } + + public LearnGeometricPatternAdvancedOptions(int minRectLength, double minRectAspectRatio, + int minRadius, int minLineLength, double minFeatureStrength, int maxFeaturesUsed, + int maxPixelDistanceFromLine) { + super(40); + this.minRectLength = minRectLength; + this.minRectAspectRatio = minRectAspectRatio; + this.minRadius = minRadius; + this.minLineLength = minLineLength; + this.minFeatureStrength = minFeatureStrength; + this.maxFeaturesUsed = maxFeaturesUsed; + this.maxPixelDistanceFromLine = maxPixelDistanceFromLine; + } + + protected LearnGeometricPatternAdvancedOptions(ByteBuffer backing, int offset) { + super(backing, offset, 40); + init(); + } + + protected LearnGeometricPatternAdvancedOptions(long nativeObj, boolean owned) { + super(nativeObj, owned, 40); + init(); + } + + protected void setBuffer(ByteBuffer backing, int offset) { + super.setBuffer(backing, offset, 40); + } + + public void read() { + minRectLength = backing.getInt(0); + minRectAspectRatio = backing.getDouble(8); + minRadius = backing.getInt(16); + minLineLength = backing.getInt(20); + minFeatureStrength = backing.getDouble(24); + maxFeaturesUsed = backing.getInt(32); + maxPixelDistanceFromLine = backing.getInt(36); + } + + public void write() { + backing.putInt(0, minRectLength); + backing.putDouble(8, minRectAspectRatio); + backing.putInt(16, minRadius); + backing.putInt(20, minLineLength); + backing.putDouble(24, minFeatureStrength); + backing.putInt(32, maxFeaturesUsed); + backing.putInt(36, maxPixelDistanceFromLine); + } + + public int size() { + return 40; + } + } + + public static class FitEllipseOptions extends DisposedStruct { + public int rejectOutliers; // Whether to use every given point or only a + // subset of the points to fit the ellipse. + public double minScore; // Specifies the required quality of the fitted + // ellipse. + public double pixelRadius; // The acceptable distance, in pixels, that a + // point determined to belong to the ellipse can + // be from the circumference of the ellipse. + public int maxIterations; // Specifies the number of refinement iterations + // you allow the function to perform on the + // initial subset of points. + + private void init() { + + } + + public FitEllipseOptions() { + super(32); + init(); + } + + public FitEllipseOptions(int rejectOutliers, double minScore, double pixelRadius, + int maxIterations) { + super(32); + this.rejectOutliers = rejectOutliers; + this.minScore = minScore; + this.pixelRadius = pixelRadius; + this.maxIterations = maxIterations; + } + + protected FitEllipseOptions(ByteBuffer backing, int offset) { + super(backing, offset, 32); + init(); + } + + protected FitEllipseOptions(long nativeObj, boolean owned) { + super(nativeObj, owned, 32); + init(); + } + + protected void setBuffer(ByteBuffer backing, int offset) { + super.setBuffer(backing, offset, 32); + } + + public void read() { + rejectOutliers = backing.getInt(0); + minScore = backing.getDouble(8); + pixelRadius = backing.getDouble(16); + maxIterations = backing.getInt(24); + } + + public void write() { + backing.putInt(0, rejectOutliers); + backing.putDouble(8, minScore); + backing.putDouble(16, pixelRadius); + backing.putInt(24, maxIterations); + } + + public int size() { + return 32; + } + } + + public static class FitCircleOptions extends DisposedStruct { + public int rejectOutliers; // Whether to use every given point or only a + // subset of the points to fit the circle. + public double minScore; // Specifies the required quality of the fitted + // circle. + public double pixelRadius; // The acceptable distance, in pixels, that a + // point determined to belong to the circle can + // be from the circumference of the circle. + public int maxIterations; // Specifies the number of refinement iterations + // you allow the function to perform on the + // initial subset of points. + + private void init() { + + } + + public FitCircleOptions() { + super(32); + init(); + } + + public FitCircleOptions(int rejectOutliers, double minScore, double pixelRadius, + int maxIterations) { + super(32); + this.rejectOutliers = rejectOutliers; + this.minScore = minScore; + this.pixelRadius = pixelRadius; + this.maxIterations = maxIterations; + } + + protected FitCircleOptions(ByteBuffer backing, int offset) { + super(backing, offset, 32); + init(); + } + + protected FitCircleOptions(long nativeObj, boolean owned) { + super(nativeObj, owned, 32); + init(); + } + + protected void setBuffer(ByteBuffer backing, int offset) { + super.setBuffer(backing, offset, 32); + } + + public void read() { + rejectOutliers = backing.getInt(0); + minScore = backing.getDouble(8); + pixelRadius = backing.getDouble(16); + maxIterations = backing.getInt(24); + } + + public void write() { + backing.putInt(0, rejectOutliers); + backing.putDouble(8, minScore); + backing.putDouble(16, pixelRadius); + backing.putInt(24, maxIterations); + } + + public int size() { + return 32; + } + } + + public static class ConstructROIOptions2 extends DisposedStruct { + public int windowNumber; // The window number of the image window. + public String windowTitle; // Specifies the message string that the function + // displays in the title bar of the window. + public PaletteType type; // The palette type to use. + public RGBValue[] palette; // If type is IMAQ_PALETTE_USER, this array is + // the palette of colors to use with the window. + public int maxContours; // The maximum number of contours the user will be + // able to select. + private ByteBuffer windowTitle_buf; + private ByteBuffer palette_buf; + + private void init() { + palette = new RGBValue[0]; + } + + public ConstructROIOptions2() { + super(24); + init(); + } + + public ConstructROIOptions2(int windowNumber, String windowTitle, PaletteType type, + RGBValue[] palette, int maxContours) { + super(24); + this.windowNumber = windowNumber; + this.windowTitle = windowTitle; + this.type = type; + this.palette = palette; + this.maxContours = maxContours; + } + + protected ConstructROIOptions2(ByteBuffer backing, int offset) { + super(backing, offset, 24); + init(); + } + + protected ConstructROIOptions2(long nativeObj, boolean owned) { + super(nativeObj, owned, 24); + init(); + } + + protected void setBuffer(ByteBuffer backing, int offset) { + super.setBuffer(backing, offset, 24); + } + + public void read() { + windowNumber = backing.getInt(0); + long windowTitle_addr = getPointer(backing, 4); + if (windowTitle_addr == 0) + windowTitle = null; + else { + ByteBuffer bb = newDirectByteBuffer(windowTitle_addr, 1000); // FIXME + while (bb.get() != 0) { + } + byte[] bytes = new byte[bb.position() - 1]; + getBytes(bb, bytes, 0, bytes.length); + try { + windowTitle = new String(bytes, "UTF-8"); + } catch (UnsupportedEncodingException e) { + windowTitle = ""; + } + } + + type = PaletteType.fromValue(backing.getInt(8)); + int palette_numColors = backing.getInt(16); + long palette_addr = getPointer(backing, 12); + palette = new RGBValue[palette_numColors]; + if (palette_numColors > 0 && palette_addr != 0) { + ByteBuffer bb = newDirectByteBuffer(palette_addr, palette_numColors * 4); + for (int i = 0, off = 0; i < palette_numColors; i++, off += 4) { + palette[i] = new RGBValue(bb, off); + palette[i].read(); + } + } + maxContours = backing.getInt(20); + } + + public void write() { + backing.putInt(0, windowNumber); + if (windowTitle != null) { + byte[] windowTitle_bytes; + try { + windowTitle_bytes = windowTitle.getBytes("UTF-8"); + } catch (UnsupportedEncodingException e) { + windowTitle_bytes = new byte[0]; + } + windowTitle_buf = ByteBuffer.allocateDirect(windowTitle_bytes.length + 1); + putBytes(windowTitle_buf, windowTitle_bytes, 0, windowTitle_bytes.length).put( + windowTitle_bytes.length, (byte) 0); + } + putPointer(backing, 4, windowTitle == null ? 0 : getByteBufferAddress(windowTitle_buf)); + if (type != null) + backing.putInt(8, type.getValue()); + palette_buf = ByteBuffer.allocateDirect(palette.length * 4).order(ByteOrder.nativeOrder()); + for (int i = 0, off = 0; i < palette.length; i++, off += 4) { + palette[i].setBuffer(palette_buf, off); + palette[i].write(); + } + backing.putInt(16, palette.length); + putPointer(backing, 12, palette_buf); + backing.putInt(20, maxContours); + } + + public int size() { + return 24; + } + } + + public static class HSLValue extends DisposedStruct { + public short L; // The color luminance. + public short S; // The color saturation. + public short H; // The color hue. + public short alpha; // The alpha value of the color, which represents extra + // information about a color image, such as gamma + // correction. + + private void init() { + + } + + public HSLValue() { + super(4); + init(); + } + + public HSLValue(int L, int S, int H, int alpha) { + super(4); + this.L = (short) L; + this.S = (short) S; + this.H = (short) H; + this.alpha = (short) alpha; + } + + protected HSLValue(ByteBuffer backing, int offset) { + super(backing, offset, 4); + init(); + } + + protected HSLValue(long nativeObj, boolean owned) { + super(nativeObj, owned, 4); + init(); + } + + protected void setBuffer(ByteBuffer backing, int offset) { + super.setBuffer(backing, offset, 4); + } + + public void read() { + L = (short) (backing.get(0) & 0xff); + S = (short) (backing.get(1) & 0xff); + H = (short) (backing.get(2) & 0xff); + alpha = (short) (backing.get(3) & 0xff); + } + + public void write() { + backing.put(0, (byte) (L & 0xff)); + backing.put(1, (byte) (S & 0xff)); + backing.put(2, (byte) (H & 0xff)); + backing.put(3, (byte) (alpha & 0xff)); + } + + public int size() { + return 4; + } + } + + public static class HSVValue extends DisposedStruct { + public short V; // The color value. + public short S; // The color saturation. + public short H; // The color hue. + public short alpha; // The alpha value of the color, which represents extra + // information about a color image, such as gamma + // correction. + + private void init() { + + } + + public HSVValue() { + super(4); + init(); + } + + public HSVValue(int V, int S, int H, int alpha) { + super(4); + this.V = (short) V; + this.S = (short) S; + this.H = (short) H; + this.alpha = (short) alpha; + } + + protected HSVValue(ByteBuffer backing, int offset) { + super(backing, offset, 4); + init(); + } + + protected HSVValue(long nativeObj, boolean owned) { + super(nativeObj, owned, 4); + init(); + } + + protected void setBuffer(ByteBuffer backing, int offset) { + super.setBuffer(backing, offset, 4); + } + + public void read() { + V = (short) (backing.get(0) & 0xff); + S = (short) (backing.get(1) & 0xff); + H = (short) (backing.get(2) & 0xff); + alpha = (short) (backing.get(3) & 0xff); + } + + public void write() { + backing.put(0, (byte) (V & 0xff)); + backing.put(1, (byte) (S & 0xff)); + backing.put(2, (byte) (H & 0xff)); + backing.put(3, (byte) (alpha & 0xff)); + } + + public int size() { + return 4; + } + } + + public static class HSIValue extends DisposedStruct { + public short I; // The color intensity. + public short S; // The color saturation. + public short H; // The color hue. + public short alpha; // The alpha value of the color, which represents extra + // information about a color image, such as gamma + // correction. + + private void init() { + + } + + public HSIValue() { + super(4); + init(); + } + + public HSIValue(int I, int S, int H, int alpha) { + super(4); + this.I = (short) I; + this.S = (short) S; + this.H = (short) H; + this.alpha = (short) alpha; + } + + protected HSIValue(ByteBuffer backing, int offset) { + super(backing, offset, 4); + init(); + } + + protected HSIValue(long nativeObj, boolean owned) { + super(nativeObj, owned, 4); + init(); + } + + protected void setBuffer(ByteBuffer backing, int offset) { + super.setBuffer(backing, offset, 4); + } + + public void read() { + I = (short) (backing.get(0) & 0xff); + S = (short) (backing.get(1) & 0xff); + H = (short) (backing.get(2) & 0xff); + alpha = (short) (backing.get(3) & 0xff); + } + + public void write() { + backing.put(0, (byte) (I & 0xff)); + backing.put(1, (byte) (S & 0xff)); + backing.put(2, (byte) (H & 0xff)); + backing.put(3, (byte) (alpha & 0xff)); + } + + public int size() { + return 4; + } + } + + public static class CIELabValue extends DisposedStruct { + public double b; // The yellow/blue information of the color. + public double a; // The red/green information of the color. + public double L; // The color lightness. + public short alpha; // The alpha value of the color, which represents extra + // information about a color image, such as gamma + // correction. + + private void init() { + + } + + public CIELabValue() { + super(32); + init(); + } + + public CIELabValue(double b, double a, double L, int alpha) { + super(32); + this.b = b; + this.a = a; + this.L = L; + this.alpha = (short) alpha; + } + + protected CIELabValue(ByteBuffer backing, int offset) { + super(backing, offset, 32); + init(); + } + + protected CIELabValue(long nativeObj, boolean owned) { + super(nativeObj, owned, 32); + init(); + } + + protected void setBuffer(ByteBuffer backing, int offset) { + super.setBuffer(backing, offset, 32); + } + + public void read() { + b = backing.getDouble(0); + a = backing.getDouble(8); + L = backing.getDouble(16); + alpha = (short) (backing.get(24) & 0xff); + } + + public void write() { + backing.putDouble(0, b); + backing.putDouble(8, a); + backing.putDouble(16, L); + backing.put(24, (byte) (alpha & 0xff)); + } + + public int size() { + return 32; + } + } + + public static class CIEXYZValue extends DisposedStruct { + public double Z; // The Z color information. + public double Y; // The color luminance. + public double X; // The X color information. + public short alpha; // The alpha value of the color, which represents extra + // information about a color image, such as gamma + // correction. + + private void init() { + + } + + public CIEXYZValue() { + super(32); + init(); + } + + public CIEXYZValue(double Z, double Y, double X, int alpha) { + super(32); + this.Z = Z; + this.Y = Y; + this.X = X; + this.alpha = (short) alpha; + } + + protected CIEXYZValue(ByteBuffer backing, int offset) { + super(backing, offset, 32); + init(); + } + + protected CIEXYZValue(long nativeObj, boolean owned) { + super(nativeObj, owned, 32); + init(); + } + + protected void setBuffer(ByteBuffer backing, int offset) { + super.setBuffer(backing, offset, 32); + } + + public void read() { + Z = backing.getDouble(0); + Y = backing.getDouble(8); + X = backing.getDouble(16); + alpha = (short) (backing.get(24) & 0xff); + } + + public void write() { + backing.putDouble(0, Z); + backing.putDouble(8, Y); + backing.putDouble(16, X); + backing.put(24, (byte) (alpha & 0xff)); + } + + public int size() { + return 32; + } + } + + public static class BestEllipse2 extends DisposedStruct { + public PointFloat center; // The coordinate location of the center of the + // ellipse. + public PointFloat majorAxisStart; // The coordinate location of the start of + // the major axis of the ellipse. + public PointFloat majorAxisEnd; // The coordinate location of the end of the + // major axis of the ellipse. + public PointFloat minorAxisStart; // The coordinate location of the start of + // the minor axis of the ellipse. + public PointFloat minorAxisEnd; // The coordinate location of the end of the + // minor axis of the ellipse. + public double area; // The area of the ellipse. + public double perimeter; // The length of the perimeter of the ellipse. + public double error; // Represents the least square error of the fitted + // ellipse to the entire set of points. + public int valid; // This element is TRUE if the function achieved the + // minimum score within the number of allowed refinement + // iterations and FALSE if the function did not achieve + // the minimum score. + public int[] pointsUsed; // An array of the indexes for the points array + // indicating which points the function used to fit + // the ellipse. + private ByteBuffer pointsUsed_buf; + + private void init() { + center = new PointFloat(backing, 0); + majorAxisStart = new PointFloat(backing, 8); + majorAxisEnd = new PointFloat(backing, 16); + minorAxisStart = new PointFloat(backing, 24); + minorAxisEnd = new PointFloat(backing, 32); + pointsUsed = new int[0]; + } + + public BestEllipse2() { + super(80); + init(); + } + + public BestEllipse2(PointFloat center, PointFloat majorAxisStart, PointFloat majorAxisEnd, + PointFloat minorAxisStart, PointFloat minorAxisEnd, double area, double perimeter, + double error, int valid, int[] pointsUsed) { + super(80); + this.center = center; + this.majorAxisStart = majorAxisStart; + this.majorAxisEnd = majorAxisEnd; + this.minorAxisStart = minorAxisStart; + this.minorAxisEnd = minorAxisEnd; + this.area = area; + this.perimeter = perimeter; + this.error = error; + this.valid = valid; + this.pointsUsed = pointsUsed; + } + + protected BestEllipse2(ByteBuffer backing, int offset) { + super(backing, offset, 80); + init(); + } + + protected BestEllipse2(long nativeObj, boolean owned) { + super(nativeObj, owned, 80); + init(); + } + + protected void setBuffer(ByteBuffer backing, int offset) { + super.setBuffer(backing, offset, 80); + } + + public void read() { + center.read(); + majorAxisStart.read(); + majorAxisEnd.read(); + minorAxisStart.read(); + minorAxisEnd.read(); + area = backing.getDouble(40); + perimeter = backing.getDouble(48); + error = backing.getDouble(56); + valid = backing.getInt(64); + int pointsUsed_numPointsUsed = backing.getInt(72); + long pointsUsed_addr = getPointer(backing, 68); + pointsUsed = new int[pointsUsed_numPointsUsed]; + if (pointsUsed_numPointsUsed > 0 && pointsUsed_addr != 0) { + newDirectByteBuffer(pointsUsed_addr, pointsUsed_numPointsUsed * 4).asIntBuffer().get( + pointsUsed); + } + } + + public void write() { + center.write(); + majorAxisStart.write(); + majorAxisEnd.write(); + minorAxisStart.write(); + minorAxisEnd.write(); + backing.putDouble(40, area); + backing.putDouble(48, perimeter); + backing.putDouble(56, error); + backing.putInt(64, valid); + pointsUsed_buf = + ByteBuffer.allocateDirect(pointsUsed.length * 4).order(ByteOrder.nativeOrder()); + pointsUsed_buf.asIntBuffer().put(pointsUsed).rewind(); + backing.putInt(72, pointsUsed.length); + putPointer(backing, 68, pointsUsed_buf); + } + + public int size() { + return 80; + } + } + + public static class LearnPatternAdvancedOptions extends DisposedStruct { + public LearnPatternAdvancedShiftOptions shiftOptions; // Use this element to + // control the + // behavior of + // imaqLearnPattern2() + // during the + // shift-invariant + // learning phase. + public LearnPatternAdvancedRotationOptions rotationOptions; // Use this + // element to + // control the + // behavior of + // imaqLearnPattern2()during + // the + // rotation-invariant + // learning + // phase. + + private void init() { + + } + + public LearnPatternAdvancedOptions() { + super(8); + init(); + } + + public LearnPatternAdvancedOptions(LearnPatternAdvancedShiftOptions shiftOptions, + LearnPatternAdvancedRotationOptions rotationOptions) { + super(8); + this.shiftOptions = shiftOptions; + this.rotationOptions = rotationOptions; + } + + protected LearnPatternAdvancedOptions(ByteBuffer backing, int offset) { + super(backing, offset, 8); + init(); + } + + protected LearnPatternAdvancedOptions(long nativeObj, boolean owned) { + super(nativeObj, owned, 8); + init(); + } + + protected void setBuffer(ByteBuffer backing, int offset) { + super.setBuffer(backing, offset, 8); + } + + public void read() { + long shiftOptions_addr = getPointer(backing, 0); + if (shiftOptions_addr == 0) + shiftOptions = null; + else + shiftOptions = new LearnPatternAdvancedShiftOptions(shiftOptions_addr, false); + long rotationOptions_addr = getPointer(backing, 4); + if (rotationOptions_addr == 0) + rotationOptions = null; + else + rotationOptions = new LearnPatternAdvancedRotationOptions(rotationOptions_addr, false); + } + + public void write() { + putPointer(backing, 0, shiftOptions); + putPointer(backing, 4, rotationOptions); + } + + public int size() { + return 8; + } + } + + public static class AVIInfo extends DisposedStruct { + public int width; // The width of each frame. + public int height; // The height of each frame. + public ImageType imageType; // The type of images this AVI contains. + public int numFrames; // The number of frames in the AVI. + public int framesPerSecond; // The number of frames per second this AVI + // should be shown at. + public String filterName; // The name of the compression filter used to + // create this AVI. + public int hasData; // Specifies whether this AVI has data attached to each + // frame or not. + public int maxDataSize; // If this AVI has data, the maximum size of the + // data in each frame. + private ByteBuffer filterName_buf; + + private void init() { + + } + + public AVIInfo() { + super(32); + init(); + } + + public AVIInfo(int width, int height, ImageType imageType, int numFrames, int framesPerSecond, + String filterName, int hasData, int maxDataSize) { + super(32); + this.width = width; + this.height = height; + this.imageType = imageType; + this.numFrames = numFrames; + this.framesPerSecond = framesPerSecond; + this.filterName = filterName; + this.hasData = hasData; + this.maxDataSize = maxDataSize; + } + + protected AVIInfo(ByteBuffer backing, int offset) { + super(backing, offset, 32); + init(); + } + + protected AVIInfo(long nativeObj, boolean owned) { + super(nativeObj, owned, 32); + init(); + } + + protected void setBuffer(ByteBuffer backing, int offset) { + super.setBuffer(backing, offset, 32); + } + + public void read() { + width = backing.getInt(0); + height = backing.getInt(4); + imageType = ImageType.fromValue(backing.getInt(8)); + numFrames = backing.getInt(12); + framesPerSecond = backing.getInt(16); + long filterName_addr = getPointer(backing, 20); + if (filterName_addr == 0) + filterName = null; + else { + ByteBuffer bb = newDirectByteBuffer(filterName_addr, 1000); // FIXME + while (bb.get() != 0) { + } + byte[] bytes = new byte[bb.position() - 1]; + getBytes(bb, bytes, 0, bytes.length); + try { + filterName = new String(bytes, "UTF-8"); + } catch (UnsupportedEncodingException e) { + filterName = ""; + } + } + + hasData = backing.getInt(24); + maxDataSize = backing.getInt(28); + } + + public void write() { + backing.putInt(0, width); + backing.putInt(4, height); + if (imageType != null) + backing.putInt(8, imageType.getValue()); + backing.putInt(12, numFrames); + backing.putInt(16, framesPerSecond); + if (filterName != null) { + byte[] filterName_bytes; + try { + filterName_bytes = filterName.getBytes("UTF-8"); + } catch (UnsupportedEncodingException e) { + filterName_bytes = new byte[0]; + } + filterName_buf = ByteBuffer.allocateDirect(filterName_bytes.length + 1); + putBytes(filterName_buf, filterName_bytes, 0, filterName_bytes.length).put( + filterName_bytes.length, (byte) 0); + } + putPointer(backing, 20, filterName == null ? 0 : getByteBufferAddress(filterName_buf)); + backing.putInt(24, hasData); + backing.putInt(28, maxDataSize); + } + + public int size() { + return 32; + } + } + + public static class LearnPatternAdvancedShiftOptions extends DisposedStruct { + public int initialStepSize; // The largest number of image pixels to shift + // the sample across the inspection image during + // the initial phase of shift-invariant + // matching. + public int initialSampleSize; // Specifies the number of template pixels + // that you want to include in a sample for + // the initial phase of shift-invariant + // matching. + public double initialSampleSizeFactor; // Specifies the size of the sample + // for the initial phase of + // shift-invariant matching as a + // percent of the template size, in + // pixels. + public int finalSampleSize; // Specifies the number of template pixels you + // want to add to initialSampleSize for the + // final phase of shift-invariant matching. + public double finalSampleSizeFactor; // Specifies the size of the sample for + // the final phase of shift-invariant + // matching as a percent of the edge + // points in the template, in pixels. + public int subpixelSampleSize; // Specifies the number of template pixels + // that you want to include in a sample for + // the subpixel phase of shift-invariant + // matching. + public double subpixelSampleSizeFactor; // Specifies the size of the sample + // for the subpixel phase of + // shift-invariant matching as a + // percent of the template size, in + // pixels. + + private void init() { + + } + + public LearnPatternAdvancedShiftOptions() { + super(48); + init(); + } + + public LearnPatternAdvancedShiftOptions(int initialStepSize, int initialSampleSize, + double initialSampleSizeFactor, int finalSampleSize, double finalSampleSizeFactor, + int subpixelSampleSize, double subpixelSampleSizeFactor) { + super(48); + this.initialStepSize = initialStepSize; + this.initialSampleSize = initialSampleSize; + this.initialSampleSizeFactor = initialSampleSizeFactor; + this.finalSampleSize = finalSampleSize; + this.finalSampleSizeFactor = finalSampleSizeFactor; + this.subpixelSampleSize = subpixelSampleSize; + this.subpixelSampleSizeFactor = subpixelSampleSizeFactor; + } + + protected LearnPatternAdvancedShiftOptions(ByteBuffer backing, int offset) { + super(backing, offset, 48); + init(); + } + + protected LearnPatternAdvancedShiftOptions(long nativeObj, boolean owned) { + super(nativeObj, owned, 48); + init(); + } + + protected void setBuffer(ByteBuffer backing, int offset) { + super.setBuffer(backing, offset, 48); + } + + public void read() { + initialStepSize = backing.getInt(0); + initialSampleSize = backing.getInt(4); + initialSampleSizeFactor = backing.getDouble(8); + finalSampleSize = backing.getInt(16); + finalSampleSizeFactor = backing.getDouble(24); + subpixelSampleSize = backing.getInt(32); + subpixelSampleSizeFactor = backing.getDouble(40); + } + + public void write() { + backing.putInt(0, initialStepSize); + backing.putInt(4, initialSampleSize); + backing.putDouble(8, initialSampleSizeFactor); + backing.putInt(16, finalSampleSize); + backing.putDouble(24, finalSampleSizeFactor); + backing.putInt(32, subpixelSampleSize); + backing.putDouble(40, subpixelSampleSizeFactor); + } + + public int size() { + return 48; + } + } + + public static class LearnPatternAdvancedRotationOptions extends DisposedStruct { + public SearchStrategy searchStrategySupport; // Specifies the aggressiveness + // of the rotation search + // strategy available during + // the matching phase. + public int initialStepSize; // The largest number of image pixels to shift + // the sample across the inspection image during + // the initial phase of matching. + public int initialSampleSize; // Specifies the number of template pixels + // that you want to include in a sample for + // the initial phase of rotation-invariant + // matching. + public double initialSampleSizeFactor; // Specifies the size of the sample + // for the initial phase of + // rotation-invariant matching as a + // percent of the template size, in + // pixels. + public int initialAngularAccuracy; // Sets the angle accuracy, in degrees, + // to use during the initial phase of + // rotation-invariant matching. + public int finalSampleSize; // Specifies the number of template pixels you + // want to add to initialSampleSize for the + // final phase of rotation-invariant matching. + public double finalSampleSizeFactor; // Specifies the size of the sample for + // the final phase of + // rotation-invariant matching as a + // percent of the edge points in the + // template, in pixels. + public int finalAngularAccuracy; // Sets the angle accuracy, in degrees, to + // use during the final phase of the + // rotation-invariant matching. + public int subpixelSampleSize; // Specifies the number of template pixels + // that you want to include in a sample for + // the subpixel phase of rotation-invariant + // matching. + public double subpixelSampleSizeFactor; // Specifies the size of the sample + // for the subpixel phase of + // rotation-invariant matching as a + // percent of the template size, in + // pixels. + + private void init() { + + } + + public LearnPatternAdvancedRotationOptions() { + super(56); + init(); + } + + public LearnPatternAdvancedRotationOptions(SearchStrategy searchStrategySupport, + int initialStepSize, int initialSampleSize, double initialSampleSizeFactor, + int initialAngularAccuracy, int finalSampleSize, double finalSampleSizeFactor, + int finalAngularAccuracy, int subpixelSampleSize, double subpixelSampleSizeFactor) { + super(56); + this.searchStrategySupport = searchStrategySupport; + this.initialStepSize = initialStepSize; + this.initialSampleSize = initialSampleSize; + this.initialSampleSizeFactor = initialSampleSizeFactor; + this.initialAngularAccuracy = initialAngularAccuracy; + this.finalSampleSize = finalSampleSize; + this.finalSampleSizeFactor = finalSampleSizeFactor; + this.finalAngularAccuracy = finalAngularAccuracy; + this.subpixelSampleSize = subpixelSampleSize; + this.subpixelSampleSizeFactor = subpixelSampleSizeFactor; + } + + protected LearnPatternAdvancedRotationOptions(ByteBuffer backing, int offset) { + super(backing, offset, 56); + init(); + } + + protected LearnPatternAdvancedRotationOptions(long nativeObj, boolean owned) { + super(nativeObj, owned, 56); + init(); + } + + protected void setBuffer(ByteBuffer backing, int offset) { + super.setBuffer(backing, offset, 56); + } + + public void read() { + searchStrategySupport = SearchStrategy.fromValue(backing.getInt(0)); + initialStepSize = backing.getInt(4); + initialSampleSize = backing.getInt(8); + initialSampleSizeFactor = backing.getDouble(16); + initialAngularAccuracy = backing.getInt(24); + finalSampleSize = backing.getInt(28); + finalSampleSizeFactor = backing.getDouble(32); + finalAngularAccuracy = backing.getInt(40); + subpixelSampleSize = backing.getInt(44); + subpixelSampleSizeFactor = backing.getDouble(48); + } + + public void write() { + if (searchStrategySupport != null) + backing.putInt(0, searchStrategySupport.getValue()); + backing.putInt(4, initialStepSize); + backing.putInt(8, initialSampleSize); + backing.putDouble(16, initialSampleSizeFactor); + backing.putInt(24, initialAngularAccuracy); + backing.putInt(28, finalSampleSize); + backing.putDouble(32, finalSampleSizeFactor); + backing.putInt(40, finalAngularAccuracy); + backing.putInt(44, subpixelSampleSize); + backing.putDouble(48, subpixelSampleSizeFactor); + } + + public int size() { + return 56; + } + } + + public static class MatchPatternAdvancedOptions extends DisposedStruct { + public int subpixelIterations; // Defines the maximum number of incremental + // improvements used to refine matching using + // subpixel information. + public double subpixelTolerance; // Defines the maximum amount of change, in + // pixels, between consecutive incremental + // improvements in the match position that + // you want to trigger the end of the + // refinement process. + public int initialMatchListLength; // Specifies the maximum size of the + // match list. + public int matchListReductionFactor; // Specifies the reduction of the match + // list as matches are refined. + public int initialStepSize; // Specifies the number of pixels to shift the + // sample across the inspection image during the + // initial phase of shift-invariant matching. + public SearchStrategy searchStrategy; // Specifies the aggressiveness of the + // rotation search strategy. + public int intermediateAngularAccuracy; // Specifies the accuracy to use + // during the intermediate phase of + // rotation-invariant matching. + + private void init() { + + } + + public MatchPatternAdvancedOptions() { + super(40); + init(); + } + + public MatchPatternAdvancedOptions(int subpixelIterations, double subpixelTolerance, + int initialMatchListLength, int matchListReductionFactor, int initialStepSize, + SearchStrategy searchStrategy, int intermediateAngularAccuracy) { + super(40); + this.subpixelIterations = subpixelIterations; + this.subpixelTolerance = subpixelTolerance; + this.initialMatchListLength = initialMatchListLength; + this.matchListReductionFactor = matchListReductionFactor; + this.initialStepSize = initialStepSize; + this.searchStrategy = searchStrategy; + this.intermediateAngularAccuracy = intermediateAngularAccuracy; + } + + protected MatchPatternAdvancedOptions(ByteBuffer backing, int offset) { + super(backing, offset, 40); + init(); + } + + protected MatchPatternAdvancedOptions(long nativeObj, boolean owned) { + super(nativeObj, owned, 40); + init(); + } + + protected void setBuffer(ByteBuffer backing, int offset) { + super.setBuffer(backing, offset, 40); + } + + public void read() { + subpixelIterations = backing.getInt(0); + subpixelTolerance = backing.getDouble(8); + initialMatchListLength = backing.getInt(16); + matchListReductionFactor = backing.getInt(20); + initialStepSize = backing.getInt(24); + searchStrategy = SearchStrategy.fromValue(backing.getInt(28)); + intermediateAngularAccuracy = backing.getInt(32); + } + + public void write() { + backing.putInt(0, subpixelIterations); + backing.putDouble(8, subpixelTolerance); + backing.putInt(16, initialMatchListLength); + backing.putInt(20, matchListReductionFactor); + backing.putInt(24, initialStepSize); + if (searchStrategy != null) + backing.putInt(28, searchStrategy.getValue()); + backing.putInt(32, intermediateAngularAccuracy); + } + + public int size() { + return 40; + } + } + + public static class ParticleFilterCriteria2 extends DisposedStruct { + public MeasurementType parameter; // The morphological measurement that the + // function uses for filtering. + public float lower; // The lower bound of the criteria range. + public float upper; // The upper bound of the criteria range. + public int calibrated; // Set this element to TRUE to take calibrated + // measurements. + public int exclude; // Set this element to TRUE to indicate that a match + // occurs when the measurement is outside the criteria + // range. + + private void init() { + + } + + public ParticleFilterCriteria2() { + super(20); + init(); + } + + public ParticleFilterCriteria2(MeasurementType parameter, double lower, double upper, + int calibrated, int exclude) { + super(20); + this.parameter = parameter; + this.lower = (float) lower; + this.upper = (float) upper; + this.calibrated = calibrated; + this.exclude = exclude; + } + + protected ParticleFilterCriteria2(ByteBuffer backing, int offset) { + super(backing, offset, 20); + init(); + } + + protected ParticleFilterCriteria2(long nativeObj, boolean owned) { + super(nativeObj, owned, 20); + init(); + } + + protected void setBuffer(ByteBuffer backing, int offset) { + super.setBuffer(backing, offset, 20); + } + + public void read() { + parameter = MeasurementType.fromValue(backing.getInt(0)); + lower = backing.getFloat(4); + upper = backing.getFloat(8); + calibrated = backing.getInt(12); + exclude = backing.getInt(16); + } + + public void write() { + if (parameter != null) + backing.putInt(0, parameter.getValue()); + backing.putFloat(4, lower); + backing.putFloat(8, upper); + backing.putInt(12, calibrated); + backing.putInt(16, exclude); + } + + public int size() { + return 20; + } + } + + public static class BestCircle2 extends DisposedStruct { + public PointFloat center; // The coordinate location of the center of the + // circle. + public double radius; // The radius of the circle. + public double area; // The area of the circle. + public double perimeter; // The length of the perimeter of the circle. + public double error; // Represents the least square error of the fitted + // circle to the entire set of points. + public int valid; // This element is TRUE if the function achieved the + // minimum score within the number of allowed refinement + // iterations and FALSE if the function did not achieve + // the minimum score. + public int[] pointsUsed; // An array of the indexes for the points array + // indicating which points the function used to fit + // the circle. + private ByteBuffer pointsUsed_buf; + + private void init() { + center = new PointFloat(backing, 0); + pointsUsed = new int[0]; + } + + public BestCircle2() { + super(56); + init(); + } + + public BestCircle2(PointFloat center, double radius, double area, double perimeter, + double error, int valid, int[] pointsUsed) { + super(56); + this.center = center; + this.radius = radius; + this.area = area; + this.perimeter = perimeter; + this.error = error; + this.valid = valid; + this.pointsUsed = pointsUsed; + } + + protected BestCircle2(ByteBuffer backing, int offset) { + super(backing, offset, 56); + init(); + } + + protected BestCircle2(long nativeObj, boolean owned) { + super(nativeObj, owned, 56); + init(); + } + + protected void setBuffer(ByteBuffer backing, int offset) { + super.setBuffer(backing, offset, 56); + } + + public void read() { + center.read(); + radius = backing.getDouble(8); + area = backing.getDouble(16); + perimeter = backing.getDouble(24); + error = backing.getDouble(32); + valid = backing.getInt(40); + int pointsUsed_numPointsUsed = backing.getInt(48); + long pointsUsed_addr = getPointer(backing, 44); + pointsUsed = new int[pointsUsed_numPointsUsed]; + if (pointsUsed_numPointsUsed > 0 && pointsUsed_addr != 0) { + newDirectByteBuffer(pointsUsed_addr, pointsUsed_numPointsUsed * 4).asIntBuffer().get( + pointsUsed); + } + } + + public void write() { + center.write(); + backing.putDouble(8, radius); + backing.putDouble(16, area); + backing.putDouble(24, perimeter); + backing.putDouble(32, error); + backing.putInt(40, valid); + pointsUsed_buf = + ByteBuffer.allocateDirect(pointsUsed.length * 4).order(ByteOrder.nativeOrder()); + pointsUsed_buf.asIntBuffer().put(pointsUsed).rewind(); + backing.putInt(48, pointsUsed.length); + putPointer(backing, 44, pointsUsed_buf); + } + + public int size() { + return 56; + } + } + + public static class OCRSpacingOptions extends DisposedStruct { + public int minCharSpacing; // The minimum number of pixels that must be + // between two characters for NI Vision to train + // or read the characters separately. + public int minCharSize; // The minimum number of pixels required for an + // object to be a potentially identifiable + // character. + public int maxCharSize; // The maximum number of pixels required for an + // object to be a potentially identifiable + // character. + public int maxHorizontalElementSpacing; // The maximum horizontal spacing, + // in pixels, allowed between + // character elements to train or + // read the character elements as a + // single character. + public int maxVerticalElementSpacing; // The maximum vertical element + // spacing in pixels. + public int minBoundingRectWidth; // The minimum possible width, in pixels, + // for a character bounding rectangle. + public int maxBoundingRectWidth; // The maximum possible width, in pixels, + // for a character bounding rectangle. + public int minBoundingRectHeight; // The minimum possible height, in pixels, + // for a character bounding rectangle. + public int maxBoundingRectHeight; // The maximum possible height, in pixels, + // for a character bounding rectangle. + public int autoSplit; // Set this element to TRUE to automatically adjust + // the location of the character bounding rectangle + // when characters overlap vertically. + + private void init() { + + } + + public OCRSpacingOptions() { + super(40); + init(); + } + + public OCRSpacingOptions(int minCharSpacing, int minCharSize, int maxCharSize, + int maxHorizontalElementSpacing, int maxVerticalElementSpacing, int minBoundingRectWidth, + int maxBoundingRectWidth, int minBoundingRectHeight, int maxBoundingRectHeight, + int autoSplit) { + super(40); + this.minCharSpacing = minCharSpacing; + this.minCharSize = minCharSize; + this.maxCharSize = maxCharSize; + this.maxHorizontalElementSpacing = maxHorizontalElementSpacing; + this.maxVerticalElementSpacing = maxVerticalElementSpacing; + this.minBoundingRectWidth = minBoundingRectWidth; + this.maxBoundingRectWidth = maxBoundingRectWidth; + this.minBoundingRectHeight = minBoundingRectHeight; + this.maxBoundingRectHeight = maxBoundingRectHeight; + this.autoSplit = autoSplit; + } + + protected OCRSpacingOptions(ByteBuffer backing, int offset) { + super(backing, offset, 40); + init(); + } + + protected OCRSpacingOptions(long nativeObj, boolean owned) { + super(nativeObj, owned, 40); + init(); + } + + protected void setBuffer(ByteBuffer backing, int offset) { + super.setBuffer(backing, offset, 40); + } + + public void read() { + minCharSpacing = backing.getInt(0); + minCharSize = backing.getInt(4); + maxCharSize = backing.getInt(8); + maxHorizontalElementSpacing = backing.getInt(12); + maxVerticalElementSpacing = backing.getInt(16); + minBoundingRectWidth = backing.getInt(20); + maxBoundingRectWidth = backing.getInt(24); + minBoundingRectHeight = backing.getInt(28); + maxBoundingRectHeight = backing.getInt(32); + autoSplit = backing.getInt(36); + } + + public void write() { + backing.putInt(0, minCharSpacing); + backing.putInt(4, minCharSize); + backing.putInt(8, maxCharSize); + backing.putInt(12, maxHorizontalElementSpacing); + backing.putInt(16, maxVerticalElementSpacing); + backing.putInt(20, minBoundingRectWidth); + backing.putInt(24, maxBoundingRectWidth); + backing.putInt(28, minBoundingRectHeight); + backing.putInt(32, maxBoundingRectHeight); + backing.putInt(36, autoSplit); + } + + public int size() { + return 40; + } + } + + public static class OCRProcessingOptions extends DisposedStruct { + public ThresholdMode mode; // The thresholding mode. + public int lowThreshold; // The low threshold value when you set mode to + // IMAQ_FIXED_RANGE. + public int highThreshold; // The high threshold value when you set mode to + // IMAQ_FIXED_RANGE. + public int blockCount; // The number of blocks for threshold calculation + // algorithms that require blocks. + public int fastThreshold; // Set this element to TRUE to use a faster, less + // accurate threshold calculation algorithm. + public int biModalCalculation; // Set this element to TRUE to calculate both + // the low and high threshold values when + // using the fast thresholding method. + public int darkCharacters; // Set this element to TRUE to read or train dark + // characters on a light background. + public int removeParticlesTouchingROI; // Set this element to TRUE to remove + // the particles touching the ROI. + public int erosionCount; // The number of erosions to perform. + + private void init() { + + } + + public OCRProcessingOptions() { + super(36); + init(); + } + + public OCRProcessingOptions(ThresholdMode mode, int lowThreshold, int highThreshold, + int blockCount, int fastThreshold, int biModalCalculation, int darkCharacters, + int removeParticlesTouchingROI, int erosionCount) { + super(36); + this.mode = mode; + this.lowThreshold = lowThreshold; + this.highThreshold = highThreshold; + this.blockCount = blockCount; + this.fastThreshold = fastThreshold; + this.biModalCalculation = biModalCalculation; + this.darkCharacters = darkCharacters; + this.removeParticlesTouchingROI = removeParticlesTouchingROI; + this.erosionCount = erosionCount; + } + + protected OCRProcessingOptions(ByteBuffer backing, int offset) { + super(backing, offset, 36); + init(); + } + + protected OCRProcessingOptions(long nativeObj, boolean owned) { + super(nativeObj, owned, 36); + init(); + } + + protected void setBuffer(ByteBuffer backing, int offset) { + super.setBuffer(backing, offset, 36); + } + + public void read() { + mode = ThresholdMode.fromValue(backing.getInt(0)); + lowThreshold = backing.getInt(4); + highThreshold = backing.getInt(8); + blockCount = backing.getInt(12); + fastThreshold = backing.getInt(16); + biModalCalculation = backing.getInt(20); + darkCharacters = backing.getInt(24); + removeParticlesTouchingROI = backing.getInt(28); + erosionCount = backing.getInt(32); + } + + public void write() { + if (mode != null) + backing.putInt(0, mode.getValue()); + backing.putInt(4, lowThreshold); + backing.putInt(8, highThreshold); + backing.putInt(12, blockCount); + backing.putInt(16, fastThreshold); + backing.putInt(20, biModalCalculation); + backing.putInt(24, darkCharacters); + backing.putInt(28, removeParticlesTouchingROI); + backing.putInt(32, erosionCount); + } + + public int size() { + return 36; + } + } + + public static class ReadTextOptions extends DisposedStruct { + public String[] validChars; // An array of strings that specifies the valid + // characters. + public byte substitutionChar; // The character to substitute for objects + // that the function cannot match with any of + // the trained characters. + public ReadStrategy readStrategy; // The read strategy, which determines how + // closely the function analyzes images in + // the reading process to match objects + // with trained characters. + public int acceptanceLevel; // The minimum acceptance level at which an + // object is considered a trained character. + public int aspectRatio; // The maximum aspect ratio variance percentage for + // valid characters. + public ReadResolution readResolution; // The read resolution, which + // determines how much of the trained + // character data the function uses to + // match objects to trained + // characters. + private ByteBuffer validChars_buf; + private ByteBuffer[] validChars_bufs; + + private void init() { + validChars = new String[0]; + } + + public ReadTextOptions() { + super(65304); + init(); + } + + public ReadTextOptions(String[] validChars, byte substitutionChar, ReadStrategy readStrategy, + int acceptanceLevel, int aspectRatio, ReadResolution readResolution) { + super(65304); + this.validChars = validChars; + this.substitutionChar = substitutionChar; + this.readStrategy = readStrategy; + this.acceptanceLevel = acceptanceLevel; + this.aspectRatio = aspectRatio; + this.readResolution = readResolution; + } + + protected ReadTextOptions(ByteBuffer backing, int offset) { + super(backing, offset, 65304); + init(); + } + + protected ReadTextOptions(long nativeObj, boolean owned) { + super(nativeObj, owned, 65304); + init(); + } + + protected void setBuffer(ByteBuffer backing, int offset) { + super.setBuffer(backing, offset, 65304); + } + + public void read() { + int validChars_numValidChars = backing.getInt(65280); + long validChars_addr = getPointer(backing, 0); + validChars = new String[validChars_numValidChars]; + if (validChars_numValidChars > 0 && validChars_addr != 0) { + ByteBuffer bb = newDirectByteBuffer(validChars_addr, validChars_numValidChars * 4); + for (int i = 0, off = 0; i < validChars_numValidChars; i++, off += 4) { + long addr = getPointer(bb, off); + if (addr == 0) + validChars[i] = null; + else { + ByteBuffer bb2 = newDirectByteBuffer(addr, 1000); // FIXME + while (bb2.get() != 0) { + } + byte[] bytes = new byte[bb2.position() - 1]; + bb2.rewind(); + getBytes(bb2, bytes, 0, bytes.length); + try { + validChars[i] = new String(bytes, "UTF-8"); + } catch (UnsupportedEncodingException e) { + validChars[i] = ""; + } + } + } + } + substitutionChar = backing.get(65284); + readStrategy = ReadStrategy.fromValue(backing.getInt(65288)); + acceptanceLevel = backing.getInt(65292); + aspectRatio = backing.getInt(65296); + readResolution = ReadResolution.fromValue(backing.getInt(65300)); + } + + public void write() { + validChars_buf = + ByteBuffer.allocateDirect(validChars.length * 4).order(ByteOrder.nativeOrder()); + for (int i = 0, off = 0; i < validChars.length; i++, off += 4) { + if (validChars[i] == null) + putPointer(validChars_buf, off, 0); + else { + byte[] bytes; + try { + bytes = validChars[i].getBytes("UTF-8"); + } catch (UnsupportedEncodingException e) { + bytes = new byte[0]; + } + validChars_bufs[i] = ByteBuffer.allocateDirect(bytes.length + 1); + putBytes(validChars_bufs[i], bytes, 0, bytes.length).put(bytes.length, (byte) 0); + putPointer(validChars_buf, off, getByteBufferAddress(validChars_bufs[i])); + } + } + backing.putInt(65280, validChars.length); + putPointer(backing, 0, validChars_buf); + backing.put(65284, substitutionChar); + if (readStrategy != null) + backing.putInt(65288, readStrategy.getValue()); + backing.putInt(65292, acceptanceLevel); + backing.putInt(65296, aspectRatio); + if (readResolution != null) + backing.putInt(65300, readResolution.getValue()); + } + + public int size() { + return 65304; + } + } + + public static class CharInfo extends DisposedStruct { + public String charValue; // Retrieves the character value of the + // corresponding character in the character set. + public Image charImage; // The image you used to train this character. + public Image internalImage; // The internal representation that NI Vision + // uses to match objects to this character. + private ByteBuffer charValue_buf; + + private void init() { + + } + + public CharInfo() { + super(12); + init(); + } + + public CharInfo(String charValue, Image charImage, Image internalImage) { + super(12); + this.charValue = charValue; + this.charImage = charImage; + this.internalImage = internalImage; + } + + protected CharInfo(ByteBuffer backing, int offset) { + super(backing, offset, 12); + init(); + } + + protected CharInfo(long nativeObj, boolean owned) { + super(nativeObj, owned, 12); + init(); + } + + protected void setBuffer(ByteBuffer backing, int offset) { + super.setBuffer(backing, offset, 12); + } + + public void read() { + long charValue_addr = getPointer(backing, 0); + if (charValue_addr == 0) + charValue = null; + else { + ByteBuffer bb = newDirectByteBuffer(charValue_addr, 1000); // FIXME + while (bb.get() != 0) { + } + byte[] bytes = new byte[bb.position() - 1]; + getBytes(bb, bytes, 0, bytes.length); + try { + charValue = new String(bytes, "UTF-8"); + } catch (UnsupportedEncodingException e) { + charValue = ""; + } + } + + long charImage_addr = getPointer(backing, 4); + if (charImage_addr == 0) + charImage = null; + else + charImage = new Image(charImage_addr, false); + long internalImage_addr = getPointer(backing, 8); + if (internalImage_addr == 0) + internalImage = null; + else + internalImage = new Image(internalImage_addr, false); + } + + public void write() { + if (charValue != null) { + byte[] charValue_bytes; + try { + charValue_bytes = charValue.getBytes("UTF-8"); + } catch (UnsupportedEncodingException e) { + charValue_bytes = new byte[0]; + } + charValue_buf = ByteBuffer.allocateDirect(charValue_bytes.length + 1); + putBytes(charValue_buf, charValue_bytes, 0, charValue_bytes.length).put( + charValue_bytes.length, (byte) 0); + } + putPointer(backing, 0, charValue == null ? 0 : getByteBufferAddress(charValue_buf)); + putPointer(backing, 4, charImage); + putPointer(backing, 8, internalImage); + } + + public int size() { + return 12; + } + } + + public static class Rect extends DisposedStruct { + public int top; // Location of the top edge of the rectangle. + public int left; // Location of the left edge of the rectangle. + public int height; // Height of the rectangle. + public int width; // Width of the rectangle. + + private void init() { + + } + + public Rect() { + super(16); + init(); + } + + public Rect(int top, int left, int height, int width) { + super(16); + this.top = top; + this.left = left; + this.height = height; + this.width = width; + } + + protected Rect(ByteBuffer backing, int offset) { + super(backing, offset, 16); + init(); + } + + protected Rect(long nativeObj, boolean owned) { + super(nativeObj, owned, 16); + init(); + } + + protected void setBuffer(ByteBuffer backing, int offset) { + super.setBuffer(backing, offset, 16); + } + + public void read() { + top = backing.getInt(0); + left = backing.getInt(4); + height = backing.getInt(8); + width = backing.getInt(12); + } + + public void write() { + backing.putInt(0, top); + backing.putInt(4, left); + backing.putInt(8, height); + backing.putInt(12, width); + } + + public int size() { + return 16; + } + } + + public static class CharReport extends DisposedStruct { + public String character; // The character value. + public PointFloat[] corner; // An array of four points that describes the + // rectangle that surrounds the character. + public int reserved; // This element is reserved. + public int lowThreshold; // The minimum value of the threshold range used + // for this character. + public int highThreshold; // The maximum value of the threshold range used + // for this character. + private ByteBuffer character_buf; + + private void init() { + corner = new PointFloat[4]; + + for (int i = 0, off = 4; i < 4; i++, off += 8) + corner[i] = new PointFloat(backing, off); + } + + public CharReport() { + super(48); + init(); + } + + public CharReport(String character, PointFloat[] corner, int reserved, int lowThreshold, + int highThreshold) { + super(48); + this.character = character; + this.corner = corner; + this.reserved = reserved; + this.lowThreshold = lowThreshold; + this.highThreshold = highThreshold; + } + + protected CharReport(ByteBuffer backing, int offset) { + super(backing, offset, 48); + init(); + } + + protected CharReport(long nativeObj, boolean owned) { + super(nativeObj, owned, 48); + init(); + } + + protected void setBuffer(ByteBuffer backing, int offset) { + super.setBuffer(backing, offset, 48); + } + + public void read() { + long character_addr = getPointer(backing, 0); + if (character_addr == 0) + character = null; + else { + ByteBuffer bb = newDirectByteBuffer(character_addr, 1000); // FIXME + while (bb.get() != 0) { + } + byte[] bytes = new byte[bb.position() - 1]; + getBytes(bb, bytes, 0, bytes.length); + try { + character = new String(bytes, "UTF-8"); + } catch (UnsupportedEncodingException e) { + character = ""; + } + } + + for (PointFloat it : corner) { + it.read(); + } + reserved = backing.getInt(36); + lowThreshold = backing.getInt(40); + highThreshold = backing.getInt(44); + } + + public void write() { + if (character != null) { + byte[] character_bytes; + try { + character_bytes = character.getBytes("UTF-8"); + } catch (UnsupportedEncodingException e) { + character_bytes = new byte[0]; + } + character_buf = ByteBuffer.allocateDirect(character_bytes.length + 1); + putBytes(character_buf, character_bytes, 0, character_bytes.length).put( + character_bytes.length, (byte) 0); + } + putPointer(backing, 0, character == null ? 0 : getByteBufferAddress(character_buf)); + for (PointFloat it : corner) { + it.write(); + } + backing.putInt(36, reserved); + backing.putInt(40, lowThreshold); + backing.putInt(44, highThreshold); + } + + public int size() { + return 48; + } + } + + public static class ReadTextReport extends DisposedStruct { + public String readString; // The read string. + public CharReport[] characterReport; // An array of reports describing the + // properties of each identified + // character. + private ByteBuffer readString_buf; + private ByteBuffer characterReport_buf; + + private void init() { + characterReport = new CharReport[0]; + } + + public ReadTextReport() { + super(12); + init(); + } + + public ReadTextReport(String readString, CharReport[] characterReport) { + super(12); + this.readString = readString; + this.characterReport = characterReport; + } + + protected ReadTextReport(ByteBuffer backing, int offset) { + super(backing, offset, 12); + init(); + } + + protected ReadTextReport(long nativeObj, boolean owned) { + super(nativeObj, owned, 12); + init(); + } + + protected void setBuffer(ByteBuffer backing, int offset) { + super.setBuffer(backing, offset, 12); + } + + public void read() { + long readString_addr = getPointer(backing, 0); + if (readString_addr == 0) + readString = null; + else { + ByteBuffer bb = newDirectByteBuffer(readString_addr, 1000); // FIXME + while (bb.get() != 0) { + } + byte[] bytes = new byte[bb.position() - 1]; + getBytes(bb, bytes, 0, bytes.length); + try { + readString = new String(bytes, "UTF-8"); + } catch (UnsupportedEncodingException e) { + readString = ""; + } + } + + int characterReport_numCharacterReports = backing.getInt(8); + long characterReport_addr = getPointer(backing, 4); + characterReport = new CharReport[characterReport_numCharacterReports]; + if (characterReport_numCharacterReports > 0 && characterReport_addr != 0) { + ByteBuffer bb = + newDirectByteBuffer(characterReport_addr, characterReport_numCharacterReports * 48); + for (int i = 0, off = 0; i < characterReport_numCharacterReports; i++, off += 48) { + characterReport[i] = new CharReport(bb, off); + characterReport[i].read(); + } + } + } + + public void write() { + if (readString != null) { + byte[] readString_bytes; + try { + readString_bytes = readString.getBytes("UTF-8"); + } catch (UnsupportedEncodingException e) { + readString_bytes = new byte[0]; + } + readString_buf = ByteBuffer.allocateDirect(readString_bytes.length + 1); + putBytes(readString_buf, readString_bytes, 0, readString_bytes.length).put( + readString_bytes.length, (byte) 0); + } + putPointer(backing, 0, readString == null ? 0 : getByteBufferAddress(readString_buf)); + characterReport_buf = + ByteBuffer.allocateDirect(characterReport.length * 48).order(ByteOrder.nativeOrder()); + for (int i = 0, off = 0; i < characterReport.length; i++, off += 48) { + characterReport[i].setBuffer(characterReport_buf, off); + characterReport[i].write(); + } + backing.putInt(8, characterReport.length); + putPointer(backing, 4, characterReport_buf); + } + + public int size() { + return 12; + } + } + + public static class Point extends DisposedStruct { + public int x; // The x-coordinate of the point. + public int y; // The y-coordinate of the point. + + private void init() { + + } + + public Point() { + super(8); + init(); + } + + public Point(int x, int y) { + super(8); + this.x = x; + this.y = y; + } + + protected Point(ByteBuffer backing, int offset) { + super(backing, offset, 8); + init(); + } + + protected Point(long nativeObj, boolean owned) { + super(nativeObj, owned, 8); + init(); + } + + protected void setBuffer(ByteBuffer backing, int offset) { + super.setBuffer(backing, offset, 8); + } + + public void read() { + x = backing.getInt(0); + y = backing.getInt(4); + } + + public void write() { + backing.putInt(0, x); + backing.putInt(4, y); + } + + public int size() { + return 8; + } + } + + public static class Annulus extends DisposedStruct { + public Point center; // The coordinate location of the center of the + // annulus. + public int innerRadius; // The internal radius of the annulus. + public int outerRadius; // The external radius of the annulus. + public double startAngle; // The start angle, in degrees, of the annulus. + public double endAngle; // The end angle, in degrees, of the annulus. + + private void init() { + center = new Point(backing, 0); + } + + public Annulus() { + super(32); + init(); + } + + public Annulus(Point center, int innerRadius, int outerRadius, double startAngle, + double endAngle) { + super(32); + this.center = center; + this.innerRadius = innerRadius; + this.outerRadius = outerRadius; + this.startAngle = startAngle; + this.endAngle = endAngle; + } + + protected Annulus(ByteBuffer backing, int offset) { + super(backing, offset, 32); + init(); + } + + protected Annulus(long nativeObj, boolean owned) { + super(nativeObj, owned, 32); + init(); + } + + protected void setBuffer(ByteBuffer backing, int offset) { + super.setBuffer(backing, offset, 32); + } + + public void read() { + center.read(); + innerRadius = backing.getInt(8); + outerRadius = backing.getInt(12); + startAngle = backing.getDouble(16); + endAngle = backing.getDouble(24); + } + + public void write() { + center.write(); + backing.putInt(8, innerRadius); + backing.putInt(12, outerRadius); + backing.putDouble(16, startAngle); + backing.putDouble(24, endAngle); + } + + public int size() { + return 32; + } + } + + public static class EdgeLocationReport extends DisposedStruct { + public PointFloat[] edges; // The coordinate location of all edges detected + // by the search line. + private ByteBuffer edges_buf; + + private void init() { + edges = new PointFloat[0]; + } + + public EdgeLocationReport() { + super(8); + init(); + } + + public EdgeLocationReport(PointFloat[] edges) { + super(8); + this.edges = edges; + } + + protected EdgeLocationReport(ByteBuffer backing, int offset) { + super(backing, offset, 8); + init(); + } + + protected EdgeLocationReport(long nativeObj, boolean owned) { + super(nativeObj, owned, 8); + init(); + } + + protected void setBuffer(ByteBuffer backing, int offset) { + super.setBuffer(backing, offset, 8); + } + + public void read() { + int edges_numEdges = backing.getInt(4); + long edges_addr = getPointer(backing, 0); + edges = new PointFloat[edges_numEdges]; + if (edges_numEdges > 0 && edges_addr != 0) { + ByteBuffer bb = newDirectByteBuffer(edges_addr, edges_numEdges * 8); + for (int i = 0, off = 0; i < edges_numEdges; i++, off += 8) { + edges[i] = new PointFloat(bb, off); + edges[i].read(); + } + } + } + + public void write() { + edges_buf = ByteBuffer.allocateDirect(edges.length * 8).order(ByteOrder.nativeOrder()); + for (int i = 0, off = 0; i < edges.length; i++, off += 8) { + edges[i].setBuffer(edges_buf, off); + edges[i].write(); + } + backing.putInt(4, edges.length); + putPointer(backing, 0, edges_buf); + } + + public int size() { + return 8; + } + } + + public static class EdgeOptions extends DisposedStruct { + public int threshold; // Specifies the threshold value for the contrast of + // the edge. + public int width; // The number of pixels that the function averages to find + // the contrast at either side of the edge. + public int steepness; // The span, in pixels, of the slope of the edge + // projected along the path specified by the input + // points. + public InterpolationMethod subpixelType; // The method for interpolating. + public int subpixelDivisions; // The number of samples the function obtains + // from a pixel. + + private void init() { + + } + + public EdgeOptions() { + super(20); + init(); + } + + public EdgeOptions(int threshold, int width, int steepness, InterpolationMethod subpixelType, + int subpixelDivisions) { + super(20); + this.threshold = threshold; + this.width = width; + this.steepness = steepness; + this.subpixelType = subpixelType; + this.subpixelDivisions = subpixelDivisions; + } + + protected EdgeOptions(ByteBuffer backing, int offset) { + super(backing, offset, 20); + init(); + } + + protected EdgeOptions(long nativeObj, boolean owned) { + super(nativeObj, owned, 20); + init(); + } + + protected void setBuffer(ByteBuffer backing, int offset) { + super.setBuffer(backing, offset, 20); + } + + public void read() { + threshold = backing.getInt(0); + width = backing.getInt(4); + steepness = backing.getInt(8); + subpixelType = InterpolationMethod.fromValue(backing.getInt(12)); + subpixelDivisions = backing.getInt(16); + } + + public void write() { + backing.putInt(0, threshold); + backing.putInt(4, width); + backing.putInt(8, steepness); + if (subpixelType != null) + backing.putInt(12, subpixelType.getValue()); + backing.putInt(16, subpixelDivisions); + } + + public int size() { + return 20; + } + } + + public static class EdgeReport extends DisposedStruct { + public float location; // The location of the edge from the first point in + // the points array. + public float contrast; // The contrast at the edge. + public PolarityType polarity; // The polarity of the edge. + public float reserved; // This element is reserved. + public PointFloat coordinate; // The coordinates of the edge. + + private void init() { + coordinate = new PointFloat(backing, 20); + } + + public EdgeReport() { + super(32); + init(); + } + + public EdgeReport(double location, double contrast, PolarityType polarity, double reserved, + PointFloat coordinate) { + super(32); + this.location = (float) location; + this.contrast = (float) contrast; + this.polarity = polarity; + this.reserved = (float) reserved; + this.coordinate = coordinate; + } + + protected EdgeReport(ByteBuffer backing, int offset) { + super(backing, offset, 32); + init(); + } + + protected EdgeReport(long nativeObj, boolean owned) { + super(nativeObj, owned, 32); + init(); + } + + protected void setBuffer(ByteBuffer backing, int offset) { + super.setBuffer(backing, offset, 32); + } + + public void read() { + location = backing.getFloat(0); + contrast = backing.getFloat(4); + polarity = PolarityType.fromValue(backing.getInt(8)); + reserved = backing.getFloat(16); + coordinate.read(); + } + + public void write() { + backing.putFloat(0, location); + backing.putFloat(4, contrast); + if (polarity != null) + backing.putInt(8, polarity.getValue()); + backing.putFloat(16, reserved); + coordinate.write(); + } + + public int size() { + return 32; + } + } + + public static class ExtremeReport extends DisposedStruct { + public double location; // The locations of the extreme. + public double amplitude; // The amplitude of the extreme. + public double secondDerivative; // The second derivative of the extreme. + + private void init() { + + } + + public ExtremeReport() { + super(24); + init(); + } + + public ExtremeReport(double location, double amplitude, double secondDerivative) { + super(24); + this.location = location; + this.amplitude = amplitude; + this.secondDerivative = secondDerivative; + } + + protected ExtremeReport(ByteBuffer backing, int offset) { + super(backing, offset, 24); + init(); + } + + protected ExtremeReport(long nativeObj, boolean owned) { + super(nativeObj, owned, 24); + init(); + } + + protected void setBuffer(ByteBuffer backing, int offset) { + super.setBuffer(backing, offset, 24); + } + + public void read() { + location = backing.getDouble(0); + amplitude = backing.getDouble(8); + secondDerivative = backing.getDouble(16); + } + + public void write() { + backing.putDouble(0, location); + backing.putDouble(8, amplitude); + backing.putDouble(16, secondDerivative); + } + + public int size() { + return 24; + } + } + + public static class FitLineOptions extends DisposedStruct { + public float minScore; // Specifies the required quality of the fitted line. + public float pixelRadius; // Specifies the neighborhood pixel relationship + // for the initial subset of points being used. + public int numRefinements; // Specifies the number of refinement iterations + // you allow the function to perform on the + // initial subset of points. + + private void init() { + + } + + public FitLineOptions() { + super(12); + init(); + } + + public FitLineOptions(double minScore, double pixelRadius, int numRefinements) { + super(12); + this.minScore = (float) minScore; + this.pixelRadius = (float) pixelRadius; + this.numRefinements = numRefinements; + } + + protected FitLineOptions(ByteBuffer backing, int offset) { + super(backing, offset, 12); + init(); + } + + protected FitLineOptions(long nativeObj, boolean owned) { + super(nativeObj, owned, 12); + init(); + } + + protected void setBuffer(ByteBuffer backing, int offset) { + super.setBuffer(backing, offset, 12); + } + + public void read() { + minScore = backing.getFloat(0); + pixelRadius = backing.getFloat(4); + numRefinements = backing.getInt(8); + } + + public void write() { + backing.putFloat(0, minScore); + backing.putFloat(4, pixelRadius); + backing.putInt(8, numRefinements); + } + + public int size() { + return 12; + } + } + + public static class DisplayMapping extends DisposedStruct { + public MappingMethod method; // Describes the method for converting 16-bit + // pixels to 8-bit pixels. + public int minimumValue; // When method is IMAQ_RANGE, minimumValue + // represents the value that is mapped to 0. + public int maximumValue; // When method is IMAQ_RANGE, maximumValue + // represents the value that is mapped to 255. + public int shiftCount; // When method is IMAQ_DOWNSHIFT, shiftCount + // represents the number of bits the function + // right-shifts the 16-bit pixel values. + + private void init() { + + } + + public DisplayMapping() { + super(16); + init(); + } + + public DisplayMapping(MappingMethod method, int minimumValue, int maximumValue, int shiftCount) { + super(16); + this.method = method; + this.minimumValue = minimumValue; + this.maximumValue = maximumValue; + this.shiftCount = shiftCount; + } + + protected DisplayMapping(ByteBuffer backing, int offset) { + super(backing, offset, 16); + init(); + } + + protected DisplayMapping(long nativeObj, boolean owned) { + super(nativeObj, owned, 16); + init(); + } + + protected void setBuffer(ByteBuffer backing, int offset) { + super.setBuffer(backing, offset, 16); + } + + public void read() { + method = MappingMethod.fromValue(backing.getInt(0)); + minimumValue = backing.getInt(4); + maximumValue = backing.getInt(8); + shiftCount = backing.getInt(12); + } + + public void write() { + if (method != null) + backing.putInt(0, method.getValue()); + backing.putInt(4, minimumValue); + backing.putInt(8, maximumValue); + backing.putInt(12, shiftCount); + } + + public int size() { + return 16; + } + } + + public static class DetectExtremesOptions extends DisposedStruct { + public double threshold; // Defines which extremes are too small. + public int width; // Specifies the number of consecutive data points the + // function uses in the quadratic least-squares fit. + + private void init() { + + } + + public DetectExtremesOptions() { + super(16); + init(); + } + + public DetectExtremesOptions(double threshold, int width) { + super(16); + this.threshold = threshold; + this.width = width; + } + + protected DetectExtremesOptions(ByteBuffer backing, int offset) { + super(backing, offset, 16); + init(); + } + + protected DetectExtremesOptions(long nativeObj, boolean owned) { + super(nativeObj, owned, 16); + init(); + } + + protected void setBuffer(ByteBuffer backing, int offset) { + super.setBuffer(backing, offset, 16); + } + + public void read() { + threshold = backing.getDouble(0); + width = backing.getInt(8); + } + + public void write() { + backing.putDouble(0, threshold); + backing.putInt(8, width); + } + + public int size() { + return 16; + } + } + + public static class ImageInfo extends DisposedStruct { + public CalibrationUnit imageUnit; // If you set calibration information with + // imaqSetSimpleCalibrationInfo(), + // imageUnit is the calibration unit. + public float stepX; // If you set calibration information with + // imaqSetCalibrationInfo(), stepX is the distance in + // the calibration unit between two pixels in the x + // direction. + public float stepY; // If you set calibration information with + // imaqSetCalibrationInfo(), stepY is the distance in + // the calibration unit between two pixels in the y + // direction. + public ImageType imageType; // The type of the image. + public int xRes; // The number of columns in the image. + public int yRes; // The number of rows in the image. + public int xOffset; // If you set mask offset information with + // imaqSetMaskOffset(), xOffset is the offset of the + // mask origin in the x direction. + public int yOffset; // If you set mask offset information with + // imaqSetMaskOffset(), yOffset is the offset of the + // mask origin in the y direction. + public int border; // The number of border pixels around the image. + public int pixelsPerLine; // The number of pixels stored for each line of + // the image. + + private void init() { + + } + + public ImageInfo() { + super(52); + init(); + } + + public ImageInfo(CalibrationUnit imageUnit, double stepX, double stepY, ImageType imageType, + int xRes, int yRes, int xOffset, int yOffset, int border, int pixelsPerLine) { + super(52); + this.imageUnit = imageUnit; + this.stepX = (float) stepX; + this.stepY = (float) stepY; + this.imageType = imageType; + this.xRes = xRes; + this.yRes = yRes; + this.xOffset = xOffset; + this.yOffset = yOffset; + this.border = border; + this.pixelsPerLine = pixelsPerLine; + } + + protected ImageInfo(ByteBuffer backing, int offset) { + super(backing, offset, 52); + init(); + } + + protected ImageInfo(long nativeObj, boolean owned) { + super(nativeObj, owned, 52); + init(); + } + + protected void setBuffer(ByteBuffer backing, int offset) { + super.setBuffer(backing, offset, 52); + } + + public void read() { + imageUnit = CalibrationUnit.fromValue(backing.getInt(0)); + stepX = backing.getFloat(4); + stepY = backing.getFloat(8); + imageType = ImageType.fromValue(backing.getInt(12)); + xRes = backing.getInt(16); + yRes = backing.getInt(20); + xOffset = backing.getInt(24); + yOffset = backing.getInt(28); + border = backing.getInt(32); + pixelsPerLine = backing.getInt(36); + } + + public void write() { + if (imageUnit != null) + backing.putInt(0, imageUnit.getValue()); + backing.putFloat(4, stepX); + backing.putFloat(8, stepY); + if (imageType != null) + backing.putInt(12, imageType.getValue()); + backing.putInt(16, xRes); + backing.putInt(20, yRes); + backing.putInt(24, xOffset); + backing.putInt(28, yOffset); + backing.putInt(32, border); + backing.putInt(36, pixelsPerLine); + } + + public int size() { + return 52; + } + } + + public static class LCDOptions extends DisposedStruct { + public int litSegments; // Set this parameter to TRUE if the segments are + // brighter than the background. + public float threshold; // Determines whether a segment is ON or OFF. + public int sign; // Indicates whether the function must read the sign of the + // indicator. + public int decimalPoint; // Determines whether to look for a decimal + // separator after each digit. + + private void init() { + + } + + public LCDOptions() { + super(16); + init(); + } + + public LCDOptions(int litSegments, double threshold, int sign, int decimalPoint) { + super(16); + this.litSegments = litSegments; + this.threshold = (float) threshold; + this.sign = sign; + this.decimalPoint = decimalPoint; + } + + protected LCDOptions(ByteBuffer backing, int offset) { + super(backing, offset, 16); + init(); + } + + protected LCDOptions(long nativeObj, boolean owned) { + super(nativeObj, owned, 16); + init(); + } + + protected void setBuffer(ByteBuffer backing, int offset) { + super.setBuffer(backing, offset, 16); + } + + public void read() { + litSegments = backing.getInt(0); + threshold = backing.getFloat(4); + sign = backing.getInt(8); + decimalPoint = backing.getInt(12); + } + + public void write() { + backing.putInt(0, litSegments); + backing.putFloat(4, threshold); + backing.putInt(8, sign); + backing.putInt(12, decimalPoint); + } + + public int size() { + return 16; + } + } + + public static class LCDReport extends DisposedStruct { + public String text; // A string of the characters of the LCD. + public LCDSegments[] segmentInfo; // An array of LCDSegment structures + // describing which segments of each digit + // are on. + private ByteBuffer text_buf; + private ByteBuffer segmentInfo_buf; + + private void init() { + segmentInfo = new LCDSegments[0]; + } + + public LCDReport() { + super(16); + init(); + } + + public LCDReport(String text, LCDSegments[] segmentInfo) { + super(16); + this.text = text; + this.segmentInfo = segmentInfo; + } + + protected LCDReport(ByteBuffer backing, int offset) { + super(backing, offset, 16); + init(); + } + + protected LCDReport(long nativeObj, boolean owned) { + super(nativeObj, owned, 16); + init(); + } + + protected void setBuffer(ByteBuffer backing, int offset) { + super.setBuffer(backing, offset, 16); + } + + public void read() { + long text_addr = getPointer(backing, 0); + if (text_addr == 0) + text = null; + else { + ByteBuffer bb = newDirectByteBuffer(text_addr, 1000); // FIXME + while (bb.get() != 0) { + } + byte[] bytes = new byte[bb.position() - 1]; + getBytes(bb, bytes, 0, bytes.length); + try { + text = new String(bytes, "UTF-8"); + } catch (UnsupportedEncodingException e) { + text = ""; + } + } + + int segmentInfo_numCharacters = backing.getInt(8); + long segmentInfo_addr = getPointer(backing, 4); + segmentInfo = new LCDSegments[segmentInfo_numCharacters]; + if (segmentInfo_numCharacters > 0 && segmentInfo_addr != 0) { + ByteBuffer bb = newDirectByteBuffer(segmentInfo_addr, segmentInfo_numCharacters * 4); + for (int i = 0, off = 0; i < segmentInfo_numCharacters; i++, off += 4) { + segmentInfo[i] = new LCDSegments(bb, off); + segmentInfo[i].read(); + } + } + } + + public void write() { + if (text != null) { + byte[] text_bytes; + try { + text_bytes = text.getBytes("UTF-8"); + } catch (UnsupportedEncodingException e) { + text_bytes = new byte[0]; + } + text_buf = ByteBuffer.allocateDirect(text_bytes.length + 1); + putBytes(text_buf, text_bytes, 0, text_bytes.length).put(text_bytes.length, (byte) 0); + } + putPointer(backing, 0, text == null ? 0 : getByteBufferAddress(text_buf)); + segmentInfo_buf = + ByteBuffer.allocateDirect(segmentInfo.length * 4).order(ByteOrder.nativeOrder()); + for (int i = 0, off = 0; i < segmentInfo.length; i++, off += 4) { + segmentInfo[i].setBuffer(segmentInfo_buf, off); + segmentInfo[i].write(); + } + backing.putInt(8, segmentInfo.length); + putPointer(backing, 4, segmentInfo_buf); + } + + public int size() { + return 16; + } + } + + public static class LCDSegments extends DisposedStruct { + + + private void init() { + + } + + public LCDSegments() { + super(4); + init(); + } + + protected LCDSegments(ByteBuffer backing, int offset) { + super(backing, offset, 4); + init(); + } + + protected LCDSegments(long nativeObj, boolean owned) { + super(nativeObj, owned, 4); + init(); + } + + protected void setBuffer(ByteBuffer backing, int offset) { + super.setBuffer(backing, offset, 4); + } + + public void read() { + + } + + public void write() { + + } + + public int size() { + return 4; + } + } + + public static class LearnCalibrationOptions extends DisposedStruct { + public CalibrationMode mode; // Specifies the type of algorithm you want to + // use to reduce distortion in your image. + public ScalingMethod method; // Defines the scaling method correction + // functions use to correct the image. + public CalibrationROI roi; // Specifies the ROI correction functions use + // when correcting an image. + public int learnMap; // Set this element to TRUE if you want the function to + // calculate and store an error map during the learning + // process. + public int learnTable; // Set this element to TRUE if you want the function + // to calculate and store the correction table. + + private void init() { + + } + + public LearnCalibrationOptions() { + super(20); + init(); + } + + public LearnCalibrationOptions(CalibrationMode mode, ScalingMethod method, CalibrationROI roi, + int learnMap, int learnTable) { + super(20); + this.mode = mode; + this.method = method; + this.roi = roi; + this.learnMap = learnMap; + this.learnTable = learnTable; + } + + protected LearnCalibrationOptions(ByteBuffer backing, int offset) { + super(backing, offset, 20); + init(); + } + + protected LearnCalibrationOptions(long nativeObj, boolean owned) { + super(nativeObj, owned, 20); + init(); + } + + protected void setBuffer(ByteBuffer backing, int offset) { + super.setBuffer(backing, offset, 20); + } + + public void read() { + mode = CalibrationMode.fromValue(backing.getInt(0)); + method = ScalingMethod.fromValue(backing.getInt(4)); + roi = CalibrationROI.fromValue(backing.getInt(8)); + learnMap = backing.getInt(12); + learnTable = backing.getInt(16); + } + + public void write() { + if (mode != null) + backing.putInt(0, mode.getValue()); + if (method != null) + backing.putInt(4, method.getValue()); + if (roi != null) + backing.putInt(8, roi.getValue()); + backing.putInt(12, learnMap); + backing.putInt(16, learnTable); + } + + public int size() { + return 20; + } + } + + public static class LearnColorPatternOptions extends DisposedStruct { + public LearningMode learnMode; // Specifies the invariance mode the function + // uses when learning the pattern. + public ImageFeatureMode featureMode; // Specifies the features the function + // uses when learning the color + // pattern. + public int threshold; // Specifies the saturation threshold the function + // uses to distinguish between two colors that have + // the same hue values. + public ColorIgnoreMode ignoreMode; // Specifies whether the function + // excludes certain colors from the color + // features of the template image. + public ColorInformation[] colorsToIgnore; // An array of ColorInformation + // structures providing a set of + // colors to exclude from the + // color features of the template + // image. + private ByteBuffer colorsToIgnore_buf; + + private void init() { + colorsToIgnore = new ColorInformation[0]; + } + + public LearnColorPatternOptions() { + super(24); + init(); + } + + public LearnColorPatternOptions(LearningMode learnMode, ImageFeatureMode featureMode, + int threshold, ColorIgnoreMode ignoreMode, ColorInformation[] colorsToIgnore) { + super(24); + this.learnMode = learnMode; + this.featureMode = featureMode; + this.threshold = threshold; + this.ignoreMode = ignoreMode; + this.colorsToIgnore = colorsToIgnore; + } + + protected LearnColorPatternOptions(ByteBuffer backing, int offset) { + super(backing, offset, 24); + init(); + } + + protected LearnColorPatternOptions(long nativeObj, boolean owned) { + super(nativeObj, owned, 24); + init(); + } + + protected void setBuffer(ByteBuffer backing, int offset) { + super.setBuffer(backing, offset, 24); + } + + public void read() { + learnMode = LearningMode.fromValue(backing.getInt(0)); + featureMode = ImageFeatureMode.fromValue(backing.getInt(4)); + threshold = backing.getInt(8); + ignoreMode = ColorIgnoreMode.fromValue(backing.getInt(12)); + int colorsToIgnore_numColorsToIgnore = backing.getInt(20); + long colorsToIgnore_addr = getPointer(backing, 16); + colorsToIgnore = new ColorInformation[colorsToIgnore_numColorsToIgnore]; + if (colorsToIgnore_numColorsToIgnore > 0 && colorsToIgnore_addr != 0) { + ByteBuffer bb = + newDirectByteBuffer(colorsToIgnore_addr, colorsToIgnore_numColorsToIgnore * 12); + for (int i = 0, off = 0; i < colorsToIgnore_numColorsToIgnore; i++, off += 12) { + colorsToIgnore[i] = new ColorInformation(bb, off); + colorsToIgnore[i].read(); + } + } + } + + public void write() { + if (learnMode != null) + backing.putInt(0, learnMode.getValue()); + if (featureMode != null) + backing.putInt(4, featureMode.getValue()); + backing.putInt(8, threshold); + if (ignoreMode != null) + backing.putInt(12, ignoreMode.getValue()); + colorsToIgnore_buf = + ByteBuffer.allocateDirect(colorsToIgnore.length * 12).order(ByteOrder.nativeOrder()); + for (int i = 0, off = 0; i < colorsToIgnore.length; i++, off += 12) { + colorsToIgnore[i].setBuffer(colorsToIgnore_buf, off); + colorsToIgnore[i].write(); + } + backing.putInt(20, colorsToIgnore.length); + putPointer(backing, 16, colorsToIgnore_buf); + } + + public int size() { + return 24; + } + } + + public static class Line extends DisposedStruct { + public Point start; // The coordinate location of the start of the line. + public Point end; // The coordinate location of the end of the line. + + private void init() { + start = new Point(backing, 0); + end = new Point(backing, 8); + } + + public Line() { + super(16); + init(); + } + + public Line(Point start, Point end) { + super(16); + this.start = start; + this.end = end; + } + + protected Line(ByteBuffer backing, int offset) { + super(backing, offset, 16); + init(); + } + + protected Line(long nativeObj, boolean owned) { + super(nativeObj, owned, 16); + init(); + } + + protected void setBuffer(ByteBuffer backing, int offset) { + super.setBuffer(backing, offset, 16); + } + + public void read() { + start.read(); + end.read(); + } + + public void write() { + start.write(); + end.write(); + } + + public int size() { + return 16; + } + } + + public static class LinearAverages extends DisposedStruct { + public float[] columnAverages; // An array containing the mean pixel value + // of each column. + public float[] rowAverages; // An array containing the mean pixel value of + // each row. + public float[] risingDiagAverages; // An array containing the mean pixel + // value of each diagonal running from + // the lower left to the upper right of + // the inspected area of the image. + public float[] fallingDiagAverages; // An array containing the mean pixel + // value of each diagonal running from + // the upper left to the lower right of + // the inspected area of the image. + private ByteBuffer columnAverages_buf; + private ByteBuffer rowAverages_buf; + private ByteBuffer risingDiagAverages_buf; + private ByteBuffer fallingDiagAverages_buf; + + private void init() { + columnAverages = new float[0]; + rowAverages = new float[0]; + risingDiagAverages = new float[0]; + fallingDiagAverages = new float[0]; + } + + public LinearAverages() { + super(32); + init(); + } + + public LinearAverages(float[] columnAverages, float[] rowAverages, float[] risingDiagAverages, + float[] fallingDiagAverages) { + super(32); + this.columnAverages = columnAverages; + this.rowAverages = rowAverages; + this.risingDiagAverages = risingDiagAverages; + this.fallingDiagAverages = fallingDiagAverages; + } + + protected LinearAverages(ByteBuffer backing, int offset) { + super(backing, offset, 32); + init(); + } + + protected LinearAverages(long nativeObj, boolean owned) { + super(nativeObj, owned, 32); + init(); + } + + protected void setBuffer(ByteBuffer backing, int offset) { + super.setBuffer(backing, offset, 32); + } + + public void read() { + int columnAverages_columnCount = backing.getInt(4); + long columnAverages_addr = getPointer(backing, 0); + columnAverages = new float[columnAverages_columnCount]; + if (columnAverages_columnCount > 0 && columnAverages_addr != 0) { + newDirectByteBuffer(columnAverages_addr, columnAverages_columnCount * 4).asFloatBuffer() + .get(columnAverages); + } + int rowAverages_rowCount = backing.getInt(12); + long rowAverages_addr = getPointer(backing, 8); + rowAverages = new float[rowAverages_rowCount]; + if (rowAverages_rowCount > 0 && rowAverages_addr != 0) { + newDirectByteBuffer(rowAverages_addr, rowAverages_rowCount * 4).asFloatBuffer().get( + rowAverages); + } + int risingDiagAverages_risingDiagCount = backing.getInt(20); + long risingDiagAverages_addr = getPointer(backing, 16); + risingDiagAverages = new float[risingDiagAverages_risingDiagCount]; + if (risingDiagAverages_risingDiagCount > 0 && risingDiagAverages_addr != 0) { + newDirectByteBuffer(risingDiagAverages_addr, risingDiagAverages_risingDiagCount * 4) + .asFloatBuffer().get(risingDiagAverages); + } + int fallingDiagAverages_fallingDiagCount = backing.getInt(28); + long fallingDiagAverages_addr = getPointer(backing, 24); + fallingDiagAverages = new float[fallingDiagAverages_fallingDiagCount]; + if (fallingDiagAverages_fallingDiagCount > 0 && fallingDiagAverages_addr != 0) { + newDirectByteBuffer(fallingDiagAverages_addr, fallingDiagAverages_fallingDiagCount * 4) + .asFloatBuffer().get(fallingDiagAverages); + } + } + + public void write() { + columnAverages_buf = + ByteBuffer.allocateDirect(columnAverages.length * 4).order(ByteOrder.nativeOrder()); + columnAverages_buf.asFloatBuffer().put(columnAverages).rewind(); + backing.putInt(4, columnAverages.length); + putPointer(backing, 0, columnAverages_buf); + rowAverages_buf = + ByteBuffer.allocateDirect(rowAverages.length * 4).order(ByteOrder.nativeOrder()); + rowAverages_buf.asFloatBuffer().put(rowAverages).rewind(); + backing.putInt(12, rowAverages.length); + putPointer(backing, 8, rowAverages_buf); + risingDiagAverages_buf = + ByteBuffer.allocateDirect(risingDiagAverages.length * 4).order(ByteOrder.nativeOrder()); + risingDiagAverages_buf.asFloatBuffer().put(risingDiagAverages).rewind(); + backing.putInt(20, risingDiagAverages.length); + putPointer(backing, 16, risingDiagAverages_buf); + fallingDiagAverages_buf = + ByteBuffer.allocateDirect(fallingDiagAverages.length * 4).order(ByteOrder.nativeOrder()); + fallingDiagAverages_buf.asFloatBuffer().put(fallingDiagAverages).rewind(); + backing.putInt(28, fallingDiagAverages.length); + putPointer(backing, 24, fallingDiagAverages_buf); + } + + public int size() { + return 32; + } + } + + public static class LineProfile extends DisposedStruct { + public float[] profileData; // An array containing the value of each pixel + // in the line. + public Rect boundingBox; // The bounding rectangle of the line. + public float min; // The smallest pixel value in the line profile. + public float max; // The largest pixel value in the line profile. + public float mean; // The mean value of the pixels in the line profile. + public float stdDev; // The standard deviation of the line profile. + private ByteBuffer profileData_buf; + + private void init() { + profileData = new float[0]; + boundingBox = new Rect(backing, 4); + } + + public LineProfile() { + super(40); + init(); + } + + public LineProfile(float[] profileData, Rect boundingBox, double min, double max, double mean, + double stdDev) { + super(40); + this.profileData = profileData; + this.boundingBox = boundingBox; + this.min = (float) min; + this.max = (float) max; + this.mean = (float) mean; + this.stdDev = (float) stdDev; + } + + protected LineProfile(ByteBuffer backing, int offset) { + super(backing, offset, 40); + init(); + } + + protected LineProfile(long nativeObj, boolean owned) { + super(nativeObj, owned, 40); + init(); + } + + protected void setBuffer(ByteBuffer backing, int offset) { + super.setBuffer(backing, offset, 40); + } + + public void read() { + int profileData_dataCount = backing.getInt(36); + long profileData_addr = getPointer(backing, 0); + profileData = new float[profileData_dataCount]; + if (profileData_dataCount > 0 && profileData_addr != 0) { + newDirectByteBuffer(profileData_addr, profileData_dataCount * 4).asFloatBuffer().get( + profileData); + } + boundingBox.read(); + min = backing.getFloat(20); + max = backing.getFloat(24); + mean = backing.getFloat(28); + stdDev = backing.getFloat(32); + } + + public void write() { + profileData_buf = + ByteBuffer.allocateDirect(profileData.length * 4).order(ByteOrder.nativeOrder()); + profileData_buf.asFloatBuffer().put(profileData).rewind(); + backing.putInt(36, profileData.length); + putPointer(backing, 0, profileData_buf); + boundingBox.write(); + backing.putFloat(20, min); + backing.putFloat(24, max); + backing.putFloat(28, mean); + backing.putFloat(32, stdDev); + } + + public int size() { + return 40; + } + } + + public static class MatchColorPatternOptions extends DisposedStruct { + public MatchingMode matchMode; // Specifies the method to use when looking + // for the color pattern in the image. + public ImageFeatureMode featureMode; // Specifies the features to use when + // looking for the color pattern in the + // image. + public int minContrast; // Specifies the minimum contrast expected in the + // image. + public int subpixelAccuracy; // Set this parameter to TRUE to return areas + // in the image that match the pattern area + // with subpixel accuracy. + public RotationAngleRange[] angleRanges; // An array of angle ranges, in + // degrees, where each range + // specifies how much you expect + // the pattern to be rotated in the + // image. + public double colorWeight; // Determines the percent contribution of the + // color score to the final color pattern + // matching score. + public ColorSensitivity sensitivity; // Specifies the sensitivity of the + // color information in the image. + public SearchStrategy strategy; // Specifies how the color features of the + // image are used during the search phase. + public int numMatchesRequested; // Number of valid matches expected. + public float minMatchScore; // The minimum score a match can have for the + // function to consider the match valid. + private ByteBuffer angleRanges_buf; + + private void init() { + angleRanges = new RotationAngleRange[0]; + } + + public MatchColorPatternOptions() { + super(48); + init(); + } + + public MatchColorPatternOptions(MatchingMode matchMode, ImageFeatureMode featureMode, + int minContrast, int subpixelAccuracy, RotationAngleRange[] angleRanges, + double colorWeight, ColorSensitivity sensitivity, SearchStrategy strategy, + int numMatchesRequested, double minMatchScore) { + super(48); + this.matchMode = matchMode; + this.featureMode = featureMode; + this.minContrast = minContrast; + this.subpixelAccuracy = subpixelAccuracy; + this.angleRanges = angleRanges; + this.colorWeight = colorWeight; + this.sensitivity = sensitivity; + this.strategy = strategy; + this.numMatchesRequested = numMatchesRequested; + this.minMatchScore = (float) minMatchScore; + } + + protected MatchColorPatternOptions(ByteBuffer backing, int offset) { + super(backing, offset, 48); + init(); + } + + protected MatchColorPatternOptions(long nativeObj, boolean owned) { + super(nativeObj, owned, 48); + init(); + } + + protected void setBuffer(ByteBuffer backing, int offset) { + super.setBuffer(backing, offset, 48); + } + + public void read() { + matchMode = MatchingMode.fromValue(backing.getInt(0)); + featureMode = ImageFeatureMode.fromValue(backing.getInt(4)); + minContrast = backing.getInt(8); + subpixelAccuracy = backing.getInt(12); + int angleRanges_numRanges = backing.getInt(20); + long angleRanges_addr = getPointer(backing, 16); + angleRanges = new RotationAngleRange[angleRanges_numRanges]; + if (angleRanges_numRanges > 0 && angleRanges_addr != 0) { + ByteBuffer bb = newDirectByteBuffer(angleRanges_addr, angleRanges_numRanges * 8); + for (int i = 0, off = 0; i < angleRanges_numRanges; i++, off += 8) { + angleRanges[i] = new RotationAngleRange(bb, off); + angleRanges[i].read(); + } + } + colorWeight = backing.getDouble(24); + sensitivity = ColorSensitivity.fromValue(backing.getInt(32)); + strategy = SearchStrategy.fromValue(backing.getInt(36)); + numMatchesRequested = backing.getInt(40); + minMatchScore = backing.getFloat(44); + } + + public void write() { + if (matchMode != null) + backing.putInt(0, matchMode.getValue()); + if (featureMode != null) + backing.putInt(4, featureMode.getValue()); + backing.putInt(8, minContrast); + backing.putInt(12, subpixelAccuracy); + angleRanges_buf = + ByteBuffer.allocateDirect(angleRanges.length * 8).order(ByteOrder.nativeOrder()); + for (int i = 0, off = 0; i < angleRanges.length; i++, off += 8) { + angleRanges[i].setBuffer(angleRanges_buf, off); + angleRanges[i].write(); + } + backing.putInt(20, angleRanges.length); + putPointer(backing, 16, angleRanges_buf); + backing.putDouble(24, colorWeight); + if (sensitivity != null) + backing.putInt(32, sensitivity.getValue()); + if (strategy != null) + backing.putInt(36, strategy.getValue()); + backing.putInt(40, numMatchesRequested); + backing.putFloat(44, minMatchScore); + } + + public int size() { + return 48; + } + } + + public static class HistogramReport extends DisposedStruct { + public int[] histogram; // An array describing the number of pixels that + // fell into each class. + public float min; // The smallest pixel value that the function classified. + public float max; // The largest pixel value that the function classified. + public float start; // The smallest pixel value that fell into the first + // class. + public float width; // The size of each class. + public float mean; // The mean value of the pixels that the function + // classified. + public float stdDev; // The standard deviation of the pixels that the + // function classified. + public int numPixels; // The number of pixels that the function classified. + private ByteBuffer histogram_buf; + + private void init() { + histogram = new int[0]; + } + + public HistogramReport() { + super(36); + init(); + } + + public HistogramReport(int[] histogram, double min, double max, double start, double width, + double mean, double stdDev, int numPixels) { + super(36); + this.histogram = histogram; + this.min = (float) min; + this.max = (float) max; + this.start = (float) start; + this.width = (float) width; + this.mean = (float) mean; + this.stdDev = (float) stdDev; + this.numPixels = numPixels; + } + + protected HistogramReport(ByteBuffer backing, int offset) { + super(backing, offset, 36); + init(); + } + + protected HistogramReport(long nativeObj, boolean owned) { + super(nativeObj, owned, 36); + init(); + } + + protected void setBuffer(ByteBuffer backing, int offset) { + super.setBuffer(backing, offset, 36); + } + + public void read() { + int histogram_histogramCount = backing.getInt(4); + long histogram_addr = getPointer(backing, 0); + histogram = new int[histogram_histogramCount]; + if (histogram_histogramCount > 0 && histogram_addr != 0) { + newDirectByteBuffer(histogram_addr, histogram_histogramCount * 4).asIntBuffer().get( + histogram); + } + min = backing.getFloat(8); + max = backing.getFloat(12); + start = backing.getFloat(16); + width = backing.getFloat(20); + mean = backing.getFloat(24); + stdDev = backing.getFloat(28); + numPixels = backing.getInt(32); + } + + public void write() { + histogram_buf = + ByteBuffer.allocateDirect(histogram.length * 4).order(ByteOrder.nativeOrder()); + histogram_buf.asIntBuffer().put(histogram).rewind(); + backing.putInt(4, histogram.length); + putPointer(backing, 0, histogram_buf); + backing.putFloat(8, min); + backing.putFloat(12, max); + backing.putFloat(16, start); + backing.putFloat(20, width); + backing.putFloat(24, mean); + backing.putFloat(28, stdDev); + backing.putInt(32, numPixels); + } + + public int size() { + return 36; + } + } + + public static class ArcInfo extends DisposedStruct { + public Rect boundingBox; // The coordinate location of the bounding box of + // the arc. + public double startAngle; // The counterclockwise angle from the x-axis in + // degrees to the start of the arc. + public double endAngle; // The counterclockwise angle from the x-axis in + // degrees to the end of the arc. + + private void init() { + boundingBox = new Rect(backing, 0); + } + + public ArcInfo() { + super(32); + init(); + } + + public ArcInfo(Rect boundingBox, double startAngle, double endAngle) { + super(32); + this.boundingBox = boundingBox; + this.startAngle = startAngle; + this.endAngle = endAngle; + } + + protected ArcInfo(ByteBuffer backing, int offset) { + super(backing, offset, 32); + init(); + } + + protected ArcInfo(long nativeObj, boolean owned) { + super(nativeObj, owned, 32); + init(); + } + + protected void setBuffer(ByteBuffer backing, int offset) { + super.setBuffer(backing, offset, 32); + } + + public void read() { + boundingBox.read(); + startAngle = backing.getDouble(16); + endAngle = backing.getDouble(24); + } + + public void write() { + boundingBox.write(); + backing.putDouble(16, startAngle); + backing.putDouble(24, endAngle); + } + + public int size() { + return 32; + } + } + + public static class AxisReport extends DisposedStruct { + public PointFloat origin; // The origin of the coordinate system, which is + // the intersection of the two axes of the + // coordinate system. + public PointFloat mainAxisEnd; // The end of the main axis, which is the + // result of the computation of the + // intersection of the main axis with the + // rectangular search area. + public PointFloat secondaryAxisEnd; // The end of the secondary axis, which + // is the result of the computation of + // the intersection of the secondary + // axis with the rectangular search + // area. + + private void init() { + origin = new PointFloat(backing, 0); + mainAxisEnd = new PointFloat(backing, 8); + secondaryAxisEnd = new PointFloat(backing, 16); + } + + public AxisReport() { + super(24); + init(); + } + + public AxisReport(PointFloat origin, PointFloat mainAxisEnd, PointFloat secondaryAxisEnd) { + super(24); + this.origin = origin; + this.mainAxisEnd = mainAxisEnd; + this.secondaryAxisEnd = secondaryAxisEnd; + } + + protected AxisReport(ByteBuffer backing, int offset) { + super(backing, offset, 24); + init(); + } + + protected AxisReport(long nativeObj, boolean owned) { + super(nativeObj, owned, 24); + init(); + } + + protected void setBuffer(ByteBuffer backing, int offset) { + super.setBuffer(backing, offset, 24); + } + + public void read() { + origin.read(); + mainAxisEnd.read(); + secondaryAxisEnd.read(); + } + + public void write() { + origin.write(); + mainAxisEnd.write(); + secondaryAxisEnd.write(); + } + + public int size() { + return 24; + } + } + + public static class BarcodeInfo extends DisposedStruct { + public String outputString; // A string containing the decoded barcode data. + public int size; // The size of the output string. + public byte outputChar1; // The contents of this character depend on the + // barcode type. + public byte outputChar2; // The contents of this character depend on the + // barcode type. + public double confidenceLevel; // A quality measure of the decoded barcode + // ranging from 0 to 100, with 100 being the + // best. + public BarcodeType type; // The type of barcode. + private ByteBuffer outputString_buf; + + private void init() { + + } + + public BarcodeInfo() { + super(32); + init(); + } + + public BarcodeInfo(String outputString, int size, byte outputChar1, byte outputChar2, + double confidenceLevel, BarcodeType type) { + super(32); + this.outputString = outputString; + this.size = size; + this.outputChar1 = outputChar1; + this.outputChar2 = outputChar2; + this.confidenceLevel = confidenceLevel; + this.type = type; + } + + protected BarcodeInfo(ByteBuffer backing, int offset) { + super(backing, offset, 32); + init(); + } + + protected BarcodeInfo(long nativeObj, boolean owned) { + super(nativeObj, owned, 32); + init(); + } + + protected void setBuffer(ByteBuffer backing, int offset) { + super.setBuffer(backing, offset, 32); + } + + public void read() { + long outputString_addr = getPointer(backing, 0); + if (outputString_addr == 0) + outputString = null; + else { + ByteBuffer bb = newDirectByteBuffer(outputString_addr, 1000); // FIXME + while (bb.get() != 0) { + } + byte[] bytes = new byte[bb.position() - 1]; + getBytes(bb, bytes, 0, bytes.length); + try { + outputString = new String(bytes, "UTF-8"); + } catch (UnsupportedEncodingException e) { + outputString = ""; + } + } + + size = backing.getInt(4); + outputChar1 = backing.get(8); + outputChar2 = backing.get(9); + confidenceLevel = backing.getDouble(16); + type = BarcodeType.fromValue(backing.getInt(24)); + } + + public void write() { + if (outputString != null) { + byte[] outputString_bytes; + try { + outputString_bytes = outputString.getBytes("UTF-8"); + } catch (UnsupportedEncodingException e) { + outputString_bytes = new byte[0]; + } + outputString_buf = ByteBuffer.allocateDirect(outputString_bytes.length + 1); + putBytes(outputString_buf, outputString_bytes, 0, outputString_bytes.length).put( + outputString_bytes.length, (byte) 0); + } + putPointer(backing, 0, outputString == null ? 0 : getByteBufferAddress(outputString_buf)); + backing.putInt(4, size); + backing.put(8, outputChar1); + backing.put(9, outputChar2); + backing.putDouble(16, confidenceLevel); + if (type != null) + backing.putInt(24, type.getValue()); + } + + public int size() { + return 32; + } + } + + public static class BCGOptions extends DisposedStruct { + public float brightness; // Adjusts the brightness of the image. + public float contrast; // Adjusts the contrast of the image. + public float gamma; // Performs gamma correction. + + private void init() { + + } + + public BCGOptions() { + super(12); + init(); + } + + public BCGOptions(double brightness, double contrast, double gamma) { + super(12); + this.brightness = (float) brightness; + this.contrast = (float) contrast; + this.gamma = (float) gamma; + } + + protected BCGOptions(ByteBuffer backing, int offset) { + super(backing, offset, 12); + init(); + } + + protected BCGOptions(long nativeObj, boolean owned) { + super(nativeObj, owned, 12); + init(); + } + + protected void setBuffer(ByteBuffer backing, int offset) { + super.setBuffer(backing, offset, 12); + } + + public void read() { + brightness = backing.getFloat(0); + contrast = backing.getFloat(4); + gamma = backing.getFloat(8); + } + + public void write() { + backing.putFloat(0, brightness); + backing.putFloat(4, contrast); + backing.putFloat(8, gamma); + } + + public int size() { + return 12; + } + } + + public static class BestCircle extends DisposedStruct { + public PointFloat center; // The coordinate location of the center of the + // circle. + public double radius; // The radius of the circle. + public double area; // The area of the circle. + public double perimeter; // The length of the perimeter of the circle. + public double error; // Represents the least square error of the fitted + // circle to the entire set of points. + + private void init() { + center = new PointFloat(backing, 0); + } + + public BestCircle() { + super(40); + init(); + } + + public BestCircle(PointFloat center, double radius, double area, double perimeter, double error) { + super(40); + this.center = center; + this.radius = radius; + this.area = area; + this.perimeter = perimeter; + this.error = error; + } + + protected BestCircle(ByteBuffer backing, int offset) { + super(backing, offset, 40); + init(); + } + + protected BestCircle(long nativeObj, boolean owned) { + super(nativeObj, owned, 40); + init(); + } + + protected void setBuffer(ByteBuffer backing, int offset) { + super.setBuffer(backing, offset, 40); + } + + public void read() { + center.read(); + radius = backing.getDouble(8); + area = backing.getDouble(16); + perimeter = backing.getDouble(24); + error = backing.getDouble(32); + } + + public void write() { + center.write(); + backing.putDouble(8, radius); + backing.putDouble(16, area); + backing.putDouble(24, perimeter); + backing.putDouble(32, error); + } + + public int size() { + return 40; + } + } + + public static class BestEllipse extends DisposedStruct { + public PointFloat center; // The coordinate location of the center of the + // ellipse. + public PointFloat majorAxisStart; // The coordinate location of the start of + // the major axis of the ellipse. + public PointFloat majorAxisEnd; // The coordinate location of the end of the + // major axis of the ellipse. + public PointFloat minorAxisStart; // The coordinate location of the start of + // the minor axis of the ellipse. + public PointFloat minorAxisEnd; // The coordinate location of the end of the + // minor axis of the ellipse. + public double area; // The area of the ellipse. + public double perimeter; // The length of the perimeter of the ellipse. + + private void init() { + center = new PointFloat(backing, 0); + majorAxisStart = new PointFloat(backing, 8); + majorAxisEnd = new PointFloat(backing, 16); + minorAxisStart = new PointFloat(backing, 24); + minorAxisEnd = new PointFloat(backing, 32); + } + + public BestEllipse() { + super(56); + init(); + } + + public BestEllipse(PointFloat center, PointFloat majorAxisStart, PointFloat majorAxisEnd, + PointFloat minorAxisStart, PointFloat minorAxisEnd, double area, double perimeter) { + super(56); + this.center = center; + this.majorAxisStart = majorAxisStart; + this.majorAxisEnd = majorAxisEnd; + this.minorAxisStart = minorAxisStart; + this.minorAxisEnd = minorAxisEnd; + this.area = area; + this.perimeter = perimeter; + } + + protected BestEllipse(ByteBuffer backing, int offset) { + super(backing, offset, 56); + init(); + } + + protected BestEllipse(long nativeObj, boolean owned) { + super(nativeObj, owned, 56); + init(); + } + + protected void setBuffer(ByteBuffer backing, int offset) { + super.setBuffer(backing, offset, 56); + } + + public void read() { + center.read(); + majorAxisStart.read(); + majorAxisEnd.read(); + minorAxisStart.read(); + minorAxisEnd.read(); + area = backing.getDouble(40); + perimeter = backing.getDouble(48); + } + + public void write() { + center.write(); + majorAxisStart.write(); + majorAxisEnd.write(); + minorAxisStart.write(); + minorAxisEnd.write(); + backing.putDouble(40, area); + backing.putDouble(48, perimeter); + } + + public int size() { + return 56; + } + } + + public static class BestLine extends DisposedStruct { + public PointFloat start; // The coordinate location of the start of the + // line. + public PointFloat end; // The coordinate location of the end of the line. + public LineEquation equation; // Defines the three coefficients of the + // equation of the best fit line. + public int valid; // This element is TRUE if the function achieved the + // minimum score within the number of allowed refinement + // iterations and FALSE if the function did not achieve + // the minimum score. + public double error; // Represents the least square error of the fitted line + // to the entire set of points. + public int[] pointsUsed; // An array of the indexes for the points array + // indicating which points the function used to fit + // the line. + private ByteBuffer pointsUsed_buf; + + private void init() { + start = new PointFloat(backing, 0); + end = new PointFloat(backing, 8); + equation = new LineEquation(backing, 16); + pointsUsed = new int[0]; + } + + public BestLine() { + super(64); + init(); + } + + public BestLine(PointFloat start, PointFloat end, LineEquation equation, int valid, + double error, int[] pointsUsed) { + super(64); + this.start = start; + this.end = end; + this.equation = equation; + this.valid = valid; + this.error = error; + this.pointsUsed = pointsUsed; + } + + protected BestLine(ByteBuffer backing, int offset) { + super(backing, offset, 64); + init(); + } + + protected BestLine(long nativeObj, boolean owned) { + super(nativeObj, owned, 64); + init(); + } + + protected void setBuffer(ByteBuffer backing, int offset) { + super.setBuffer(backing, offset, 64); + } + + public void read() { + start.read(); + end.read(); + equation.read(); + valid = backing.getInt(40); + error = backing.getDouble(48); + int pointsUsed_numPointsUsed = backing.getInt(60); + long pointsUsed_addr = getPointer(backing, 56); + pointsUsed = new int[pointsUsed_numPointsUsed]; + if (pointsUsed_numPointsUsed > 0 && pointsUsed_addr != 0) { + newDirectByteBuffer(pointsUsed_addr, pointsUsed_numPointsUsed * 4).asIntBuffer().get( + pointsUsed); + } + } + + public void write() { + start.write(); + end.write(); + equation.write(); + backing.putInt(40, valid); + backing.putDouble(48, error); + pointsUsed_buf = + ByteBuffer.allocateDirect(pointsUsed.length * 4).order(ByteOrder.nativeOrder()); + pointsUsed_buf.asIntBuffer().put(pointsUsed).rewind(); + backing.putInt(60, pointsUsed.length); + putPointer(backing, 56, pointsUsed_buf); + } + + public int size() { + return 64; + } + } + + public static class BrowserOptions extends DisposedStruct { + public int width; // The width to make the browser. + public int height; // The height to make the browser image. + public int imagesPerLine; // The number of images to place on a single line. + public RGBValue backgroundColor; // The background color of the browser. + public int frameSize; // Specifies the number of pixels with which to border + // each thumbnail. + public BrowserFrameStyle style; // The style for the frame around each + // thumbnail. + public float ratio; // Specifies the width to height ratio of each + // thumbnail. + public RGBValue focusColor; // The color to use to display focused cells. + + private void init() { + backgroundColor = new RGBValue(backing, 12); + focusColor = new RGBValue(backing, 28); + } + + public BrowserOptions() { + super(32); + init(); + } + + public BrowserOptions(int width, int height, int imagesPerLine, RGBValue backgroundColor, + int frameSize, BrowserFrameStyle style, double ratio, RGBValue focusColor) { + super(32); + this.width = width; + this.height = height; + this.imagesPerLine = imagesPerLine; + this.backgroundColor = backgroundColor; + this.frameSize = frameSize; + this.style = style; + this.ratio = (float) ratio; + this.focusColor = focusColor; + } + + protected BrowserOptions(ByteBuffer backing, int offset) { + super(backing, offset, 32); + init(); + } + + protected BrowserOptions(long nativeObj, boolean owned) { + super(nativeObj, owned, 32); + init(); + } + + protected void setBuffer(ByteBuffer backing, int offset) { + super.setBuffer(backing, offset, 32); + } + + public void read() { + width = backing.getInt(0); + height = backing.getInt(4); + imagesPerLine = backing.getInt(8); + backgroundColor.read(); + frameSize = backing.getInt(16); + style = BrowserFrameStyle.fromValue(backing.getInt(20)); + ratio = backing.getFloat(24); + focusColor.read(); + } + + public void write() { + backing.putInt(0, width); + backing.putInt(4, height); + backing.putInt(8, imagesPerLine); + backgroundColor.write(); + backing.putInt(16, frameSize); + if (style != null) + backing.putInt(20, style.getValue()); + backing.putFloat(24, ratio); + focusColor.write(); + } + + public int size() { + return 32; + } + } + + public static class CoordinateSystem extends DisposedStruct { + public PointFloat origin; // The origin of the coordinate system. + public float angle; // The angle, in degrees, of the x-axis of the + // coordinate system relative to the image x-axis. + public AxisOrientation axisOrientation; // The direction of the y-axis of + // the coordinate reference system. + + private void init() { + origin = new PointFloat(backing, 0); + } + + public CoordinateSystem() { + super(16); + init(); + } + + public CoordinateSystem(PointFloat origin, double angle, AxisOrientation axisOrientation) { + super(16); + this.origin = origin; + this.angle = (float) angle; + this.axisOrientation = axisOrientation; + } + + protected CoordinateSystem(ByteBuffer backing, int offset) { + super(backing, offset, 16); + init(); + } + + protected CoordinateSystem(long nativeObj, boolean owned) { + super(nativeObj, owned, 16); + init(); + } + + protected void setBuffer(ByteBuffer backing, int offset) { + super.setBuffer(backing, offset, 16); + } + + public void read() { + origin.read(); + angle = backing.getFloat(8); + axisOrientation = AxisOrientation.fromValue(backing.getInt(12)); + } + + public void write() { + origin.write(); + backing.putFloat(8, angle); + if (axisOrientation != null) + backing.putInt(12, axisOrientation.getValue()); + } + + public int size() { + return 16; + } + } + + public static class CalibrationInfo extends DisposedStruct { + public int mapColumns; // The number of columns in the error map. + public int mapRows; // The number of rows in the error map. + public ROI userRoi; // Specifies the ROI the user provided when learning the + // calibration. + public ROI calibrationRoi; // Specifies the ROI that corresponds to the + // region of the image where the calibration + // information is accurate. + public LearnCalibrationOptions options; // Specifies the calibration options + // the user provided when learning + // the calibration. + public GridDescriptor grid; // Specifies the scaling constants for the + // image. + public CoordinateSystem system; // Specifies the coordinate system for the + // real world coordinates. + public RangeFloat range; // The range of the grayscale the function used to + // represent the circles in the grid image. + public float quality; // The quality score of the learning process, which is + // a value between 0-1000. + + private void init() { + options = new LearnCalibrationOptions(backing, 20); + grid = new GridDescriptor(backing, 40); + system = new CoordinateSystem(backing, 52); + range = new RangeFloat(backing, 68); + } + + public CalibrationInfo() { + super(80); + init(); + } + + public CalibrationInfo(int mapColumns, int mapRows, ROI userRoi, ROI calibrationRoi, + LearnCalibrationOptions options, GridDescriptor grid, CoordinateSystem system, + RangeFloat range, double quality) { + super(80); + this.mapColumns = mapColumns; + this.mapRows = mapRows; + this.userRoi = userRoi; + this.calibrationRoi = calibrationRoi; + this.options = options; + this.grid = grid; + this.system = system; + this.range = range; + this.quality = (float) quality; + } + + protected CalibrationInfo(ByteBuffer backing, int offset) { + super(backing, offset, 80); + init(); + } + + protected CalibrationInfo(long nativeObj, boolean owned) { + super(nativeObj, owned, 80); + init(); + } + + protected void setBuffer(ByteBuffer backing, int offset) { + super.setBuffer(backing, offset, 80); + } + + public void read() { + mapColumns = backing.getInt(4); + mapRows = backing.getInt(8); + long userRoi_addr = getPointer(backing, 12); + if (userRoi_addr == 0) + userRoi = null; + else + userRoi = new ROI(userRoi_addr, false); + long calibrationRoi_addr = getPointer(backing, 16); + if (calibrationRoi_addr == 0) + calibrationRoi = null; + else + calibrationRoi = new ROI(calibrationRoi_addr, false); + options.read(); + grid.read(); + system.read(); + range.read(); + quality = backing.getFloat(76); + } + + public void write() { + backing.putInt(4, mapColumns); + backing.putInt(8, mapRows); + putPointer(backing, 12, userRoi); + putPointer(backing, 16, calibrationRoi); + options.write(); + grid.write(); + system.write(); + range.write(); + backing.putFloat(76, quality); + } + + public int size() { + return 80; + } + } + + public static class CalibrationPoints extends DisposedStruct { + public PointFloat[] pixelCoordinates; // The array of pixel coordinates. + public PointFloat[] realWorldCoordinates; // The array of corresponding + // real-world coordinates. + private ByteBuffer pixelCoordinates_buf; + private ByteBuffer realWorldCoordinates_buf; + + private void init() { + pixelCoordinates = new PointFloat[0]; + realWorldCoordinates = new PointFloat[0]; + } + + public CalibrationPoints() { + super(12); + init(); + } + + public CalibrationPoints(PointFloat[] pixelCoordinates, PointFloat[] realWorldCoordinates) { + super(12); + this.pixelCoordinates = pixelCoordinates; + this.realWorldCoordinates = realWorldCoordinates; + } + + protected CalibrationPoints(ByteBuffer backing, int offset) { + super(backing, offset, 12); + init(); + } + + protected CalibrationPoints(long nativeObj, boolean owned) { + super(nativeObj, owned, 12); + init(); + } + + protected void setBuffer(ByteBuffer backing, int offset) { + super.setBuffer(backing, offset, 12); + } + + public void read() { + int pixelCoordinates_numCoordinates = backing.getInt(8); + long pixelCoordinates_addr = getPointer(backing, 0); + pixelCoordinates = new PointFloat[pixelCoordinates_numCoordinates]; + if (pixelCoordinates_numCoordinates > 0 && pixelCoordinates_addr != 0) { + ByteBuffer bb = + newDirectByteBuffer(pixelCoordinates_addr, pixelCoordinates_numCoordinates * 8); + for (int i = 0, off = 0; i < pixelCoordinates_numCoordinates; i++, off += 8) { + pixelCoordinates[i] = new PointFloat(bb, off); + pixelCoordinates[i].read(); + } + } + int realWorldCoordinates_numCoordinates = backing.getInt(8); + long realWorldCoordinates_addr = getPointer(backing, 4); + realWorldCoordinates = new PointFloat[realWorldCoordinates_numCoordinates]; + if (realWorldCoordinates_numCoordinates > 0 && realWorldCoordinates_addr != 0) { + ByteBuffer bb = + newDirectByteBuffer(realWorldCoordinates_addr, realWorldCoordinates_numCoordinates * 8); + for (int i = 0, off = 0; i < realWorldCoordinates_numCoordinates; i++, off += 8) { + realWorldCoordinates[i] = new PointFloat(bb, off); + realWorldCoordinates[i].read(); + } + } + } + + public void write() { + pixelCoordinates_buf = + ByteBuffer.allocateDirect(pixelCoordinates.length * 8).order(ByteOrder.nativeOrder()); + for (int i = 0, off = 0; i < pixelCoordinates.length; i++, off += 8) { + pixelCoordinates[i].setBuffer(pixelCoordinates_buf, off); + pixelCoordinates[i].write(); + } + backing.putInt(8, pixelCoordinates.length); + putPointer(backing, 0, pixelCoordinates_buf); + realWorldCoordinates_buf = + ByteBuffer.allocateDirect(realWorldCoordinates.length * 8).order(ByteOrder.nativeOrder()); + for (int i = 0, off = 0; i < realWorldCoordinates.length; i++, off += 8) { + realWorldCoordinates[i].setBuffer(realWorldCoordinates_buf, off); + realWorldCoordinates[i].write(); + } + backing.putInt(8, realWorldCoordinates.length); + putPointer(backing, 4, realWorldCoordinates_buf); + } + + public int size() { + return 12; + } + } + + public static class CaliperOptions extends DisposedStruct { + public TwoEdgePolarityType polarity; // Specifies the edge polarity of the + // edge pairs. + public float separation; // The distance between edge pairs. + public float separationDeviation; // Sets the range around the separation + // value. + + private void init() { + + } + + public CaliperOptions() { + super(12); + init(); + } + + public CaliperOptions(TwoEdgePolarityType polarity, double separation, + double separationDeviation) { + super(12); + this.polarity = polarity; + this.separation = (float) separation; + this.separationDeviation = (float) separationDeviation; + } + + protected CaliperOptions(ByteBuffer backing, int offset) { + super(backing, offset, 12); + init(); + } + + protected CaliperOptions(long nativeObj, boolean owned) { + super(nativeObj, owned, 12); + init(); + } + + protected void setBuffer(ByteBuffer backing, int offset) { + super.setBuffer(backing, offset, 12); + } + + public void read() { + polarity = TwoEdgePolarityType.fromValue(backing.getInt(0)); + separation = backing.getFloat(4); + separationDeviation = backing.getFloat(8); + } + + public void write() { + if (polarity != null) + backing.putInt(0, polarity.getValue()); + backing.putFloat(4, separation); + backing.putFloat(8, separationDeviation); + } + + public int size() { + return 12; + } + } + + public static class CaliperReport extends DisposedStruct { + public float edge1Contrast; // The contrast of the first edge. + public PointFloat edge1Coord; // The coordinates of the first edge. + public float edge2Contrast; // The contrast of the second edge. + public PointFloat edge2Coord; // The coordinates of the second edge. + public float separation; // The distance between the two edges. + + private void init() { + edge1Coord = new PointFloat(backing, 4); + edge2Coord = new PointFloat(backing, 16); + } + + public CaliperReport() { + super(32); + init(); + } + + public CaliperReport(double edge1Contrast, PointFloat edge1Coord, double edge2Contrast, + PointFloat edge2Coord, double separation) { + super(32); + this.edge1Contrast = (float) edge1Contrast; + this.edge1Coord = edge1Coord; + this.edge2Contrast = (float) edge2Contrast; + this.edge2Coord = edge2Coord; + this.separation = (float) separation; + } + + protected CaliperReport(ByteBuffer backing, int offset) { + super(backing, offset, 32); + init(); + } + + protected CaliperReport(long nativeObj, boolean owned) { + super(nativeObj, owned, 32); + init(); + } + + protected void setBuffer(ByteBuffer backing, int offset) { + super.setBuffer(backing, offset, 32); + } + + public void read() { + edge1Contrast = backing.getFloat(0); + edge1Coord.read(); + edge2Contrast = backing.getFloat(12); + edge2Coord.read(); + separation = backing.getFloat(24); + } + + public void write() { + backing.putFloat(0, edge1Contrast); + edge1Coord.write(); + backing.putFloat(12, edge2Contrast); + edge2Coord.write(); + backing.putFloat(24, separation); + } + + public int size() { + return 32; + } + } + + public static class DrawTextOptions extends DisposedStruct { + public String fontName; // The font name to use. + public int fontSize; // The size of the font. + public int bold; // Set this parameter to TRUE to bold text. + public int italic; // Set this parameter to TRUE to italicize text. + public int underline; // Set this parameter to TRUE to underline text. + public int strikeout; // Set this parameter to TRUE to strikeout text. + public TextAlignment textAlignment; // Sets the alignment of text. + public FontColor fontColor; // Sets the font color. + + private void init() { + + } + + public DrawTextOptions() { + super(60); + init(); + } + + public DrawTextOptions(String fontName, int fontSize, int bold, int italic, int underline, + int strikeout, TextAlignment textAlignment, FontColor fontColor) { + super(60); + this.fontName = fontName; + this.fontSize = fontSize; + this.bold = bold; + this.italic = italic; + this.underline = underline; + this.strikeout = strikeout; + this.textAlignment = textAlignment; + this.fontColor = fontColor; + } + + protected DrawTextOptions(ByteBuffer backing, int offset) { + super(backing, offset, 60); + init(); + } + + protected DrawTextOptions(long nativeObj, boolean owned) { + super(nativeObj, owned, 60); + init(); + } + + protected void setBuffer(ByteBuffer backing, int offset) { + super.setBuffer(backing, offset, 60); + } + + public void read() { + { + byte[] bytes = new byte[32]; + getBytes(backing, bytes, 0, 32); + int len; + for (len = 0; len < bytes.length && bytes[len] != 0; len++) { + } + try { + fontName = new String(bytes, 0, len, "UTF-8"); + } catch (UnsupportedEncodingException e) { + fontName = ""; + } + } + fontSize = backing.getInt(32); + bold = backing.getInt(36); + italic = backing.getInt(40); + underline = backing.getInt(44); + strikeout = backing.getInt(48); + textAlignment = TextAlignment.fromValue(backing.getInt(52)); + fontColor = FontColor.fromValue(backing.getInt(56)); + } + + public void write() { + if (fontName != null) { + byte[] bytes; + try { + bytes = fontName.getBytes("UTF-8"); + } catch (UnsupportedEncodingException e) { + bytes = new byte[0]; + } + putBytes(backing, bytes, 0, bytes.length); + for (int i = bytes.length; i < 32; i++) + backing.put(i, (byte) 0); // fill with zero + } + backing.putInt(32, fontSize); + backing.putInt(36, bold); + backing.putInt(40, italic); + backing.putInt(44, underline); + backing.putInt(48, strikeout); + if (textAlignment != null) + backing.putInt(52, textAlignment.getValue()); + if (fontColor != null) + backing.putInt(56, fontColor.getValue()); + } + + public int size() { + return 60; + } + } + + public static class CircleReport extends DisposedStruct { + public Point center; // The coordinate point of the center of the circle. + public int radius; // The radius of the circle, in pixels. + public int area; // The area of the circle, in pixels. + + private void init() { + center = new Point(backing, 0); + } + + public CircleReport() { + super(16); + init(); + } + + public CircleReport(Point center, int radius, int area) { + super(16); + this.center = center; + this.radius = radius; + this.area = area; + } + + protected CircleReport(ByteBuffer backing, int offset) { + super(backing, offset, 16); + init(); + } + + protected CircleReport(long nativeObj, boolean owned) { + super(nativeObj, owned, 16); + init(); + } + + protected void setBuffer(ByteBuffer backing, int offset) { + super.setBuffer(backing, offset, 16); + } + + public void read() { + center.read(); + radius = backing.getInt(8); + area = backing.getInt(12); + } + + public void write() { + center.write(); + backing.putInt(8, radius); + backing.putInt(12, area); + } + + public int size() { + return 16; + } + } + + public static class ClosedContour extends DisposedStruct { + public Point[] points; // The points that make up the closed contour. + private ByteBuffer points_buf; + + private void init() { + points = new Point[0]; + } + + public ClosedContour() { + super(8); + init(); + } + + public ClosedContour(Point[] points) { + super(8); + this.points = points; + } + + protected ClosedContour(ByteBuffer backing, int offset) { + super(backing, offset, 8); + init(); + } + + protected ClosedContour(long nativeObj, boolean owned) { + super(nativeObj, owned, 8); + init(); + } + + protected void setBuffer(ByteBuffer backing, int offset) { + super.setBuffer(backing, offset, 8); + } + + public void read() { + int points_numPoints = backing.getInt(4); + long points_addr = getPointer(backing, 0); + points = new Point[points_numPoints]; + if (points_numPoints > 0 && points_addr != 0) { + ByteBuffer bb = newDirectByteBuffer(points_addr, points_numPoints * 8); + for (int i = 0, off = 0; i < points_numPoints; i++, off += 8) { + points[i] = new Point(bb, off); + points[i].read(); + } + } + } + + public void write() { + points_buf = ByteBuffer.allocateDirect(points.length * 8).order(ByteOrder.nativeOrder()); + for (int i = 0, off = 0; i < points.length; i++, off += 8) { + points[i].setBuffer(points_buf, off); + points[i].write(); + } + backing.putInt(4, points.length); + putPointer(backing, 0, points_buf); + } + + public int size() { + return 8; + } + } + + public static class ColorHistogramReport extends DisposedStruct { + public HistogramReport plane1; // The histogram report of the first color + // plane. + public HistogramReport plane2; // The histogram report of the second plane. + public HistogramReport plane3; // The histogram report of the third plane. + + private void init() { + plane1 = new HistogramReport(backing, 0); + plane2 = new HistogramReport(backing, 36); + plane3 = new HistogramReport(backing, 72); + } + + public ColorHistogramReport() { + super(108); + init(); + } + + public ColorHistogramReport(HistogramReport plane1, HistogramReport plane2, + HistogramReport plane3) { + super(108); + this.plane1 = plane1; + this.plane2 = plane2; + this.plane3 = plane3; + } + + protected ColorHistogramReport(ByteBuffer backing, int offset) { + super(backing, offset, 108); + init(); + } + + protected ColorHistogramReport(long nativeObj, boolean owned) { + super(nativeObj, owned, 108); + init(); + } + + protected void setBuffer(ByteBuffer backing, int offset) { + super.setBuffer(backing, offset, 108); + } + + public void read() { + plane1.read(); + plane2.read(); + plane3.read(); + } + + public void write() { + plane1.write(); + plane2.write(); + plane3.write(); + } + + public int size() { + return 108; + } + } + + public static class ColorInformation extends DisposedStruct { + public int saturation; // The saturation level the function uses to learn + // the color information. + public double[] info; // An array of color information that represents the + // color spectrum analysis of a region of an image in + // a compact form. + private ByteBuffer info_buf; + + private void init() { + info = new double[0]; + } + + public ColorInformation() { + super(12); + init(); + } + + public ColorInformation(int saturation, double[] info) { + super(12); + this.saturation = saturation; + this.info = info; + } + + protected ColorInformation(ByteBuffer backing, int offset) { + super(backing, offset, 12); + init(); + } + + protected ColorInformation(long nativeObj, boolean owned) { + super(nativeObj, owned, 12); + init(); + } + + protected void setBuffer(ByteBuffer backing, int offset) { + super.setBuffer(backing, offset, 12); + } + + public void read() { + saturation = backing.getInt(4); + int info_infoCount = backing.getInt(0); + long info_addr = getPointer(backing, 8); + info = new double[info_infoCount]; + if (info_infoCount > 0 && info_addr != 0) { + newDirectByteBuffer(info_addr, info_infoCount * 8).asDoubleBuffer().get(info); + } + } + + public void write() { + backing.putInt(4, saturation); + info_buf = ByteBuffer.allocateDirect(info.length * 8).order(ByteOrder.nativeOrder()); + info_buf.asDoubleBuffer().put(info).rewind(); + backing.putInt(0, info.length); + putPointer(backing, 8, info_buf); + } + + public int size() { + return 12; + } + } + + public static class Complex extends DisposedStruct { + public float r; // The real part of the value. + public float i; // The imaginary part of the value. + + private void init() { + + } + + public Complex() { + super(8); + init(); + } + + public Complex(double r, double i) { + super(8); + this.r = (float) r; + this.i = (float) i; + } + + protected Complex(ByteBuffer backing, int offset) { + super(backing, offset, 8); + init(); + } + + protected Complex(long nativeObj, boolean owned) { + super(nativeObj, owned, 8); + init(); + } + + protected void setBuffer(ByteBuffer backing, int offset) { + super.setBuffer(backing, offset, 8); + } + + public void read() { + r = backing.getFloat(0); + i = backing.getFloat(4); + } + + public void write() { + backing.putFloat(0, r); + backing.putFloat(4, i); + } + + public int size() { + return 8; + } + } + + public static class ConcentricRakeReport extends DisposedStruct { + public ArcInfo[] rakeArcs; // An array containing the location of each + // concentric arc line used for edge detection. + public PointFloat[] firstEdges; // The coordinate location of all edges + // detected as first edges. + public PointFloat[] lastEdges; // The coordinate location of all edges + // detected as last edges. + public EdgeLocationReport[] allEdges; // An array of reports describing the + // location of the edges located by + // each concentric rake arc line. + public int[] linesWithEdges; // An array of indices into the rakeArcs array + // indicating the concentric rake arc lines on + // which the function detected at least one + // edge. + private ByteBuffer rakeArcs_buf; + private ByteBuffer firstEdges_buf; + private ByteBuffer lastEdges_buf; + private ByteBuffer allEdges_buf; + private ByteBuffer linesWithEdges_buf; + + private void init() { + rakeArcs = new ArcInfo[0]; + firstEdges = new PointFloat[0]; + lastEdges = new PointFloat[0]; + allEdges = new EdgeLocationReport[0]; + linesWithEdges = new int[0]; + } + + public ConcentricRakeReport() { + super(36); + init(); + } + + public ConcentricRakeReport(ArcInfo[] rakeArcs, PointFloat[] firstEdges, + PointFloat[] lastEdges, EdgeLocationReport[] allEdges, int[] linesWithEdges) { + super(36); + this.rakeArcs = rakeArcs; + this.firstEdges = firstEdges; + this.lastEdges = lastEdges; + this.allEdges = allEdges; + this.linesWithEdges = linesWithEdges; + } + + protected ConcentricRakeReport(ByteBuffer backing, int offset) { + super(backing, offset, 36); + init(); + } + + protected ConcentricRakeReport(long nativeObj, boolean owned) { + super(nativeObj, owned, 36); + init(); + } + + protected void setBuffer(ByteBuffer backing, int offset) { + super.setBuffer(backing, offset, 36); + } + + public void read() { + int rakeArcs_numArcs = backing.getInt(4); + long rakeArcs_addr = getPointer(backing, 0); + rakeArcs = new ArcInfo[rakeArcs_numArcs]; + if (rakeArcs_numArcs > 0 && rakeArcs_addr != 0) { + ByteBuffer bb = newDirectByteBuffer(rakeArcs_addr, rakeArcs_numArcs * 32); + for (int i = 0, off = 0; i < rakeArcs_numArcs; i++, off += 32) { + rakeArcs[i] = new ArcInfo(bb, off); + rakeArcs[i].read(); + } + } + int firstEdges_numFirstEdges = backing.getInt(12); + long firstEdges_addr = getPointer(backing, 8); + firstEdges = new PointFloat[firstEdges_numFirstEdges]; + if (firstEdges_numFirstEdges > 0 && firstEdges_addr != 0) { + ByteBuffer bb = newDirectByteBuffer(firstEdges_addr, firstEdges_numFirstEdges * 8); + for (int i = 0, off = 0; i < firstEdges_numFirstEdges; i++, off += 8) { + firstEdges[i] = new PointFloat(bb, off); + firstEdges[i].read(); + } + } + int lastEdges_numLastEdges = backing.getInt(20); + long lastEdges_addr = getPointer(backing, 16); + lastEdges = new PointFloat[lastEdges_numLastEdges]; + if (lastEdges_numLastEdges > 0 && lastEdges_addr != 0) { + ByteBuffer bb = newDirectByteBuffer(lastEdges_addr, lastEdges_numLastEdges * 8); + for (int i = 0, off = 0; i < lastEdges_numLastEdges; i++, off += 8) { + lastEdges[i] = new PointFloat(bb, off); + lastEdges[i].read(); + } + } + int allEdges_numLinesWithEdges = backing.getInt(32); + long allEdges_addr = getPointer(backing, 24); + allEdges = new EdgeLocationReport[allEdges_numLinesWithEdges]; + if (allEdges_numLinesWithEdges > 0 && allEdges_addr != 0) { + ByteBuffer bb = newDirectByteBuffer(allEdges_addr, allEdges_numLinesWithEdges * 8); + for (int i = 0, off = 0; i < allEdges_numLinesWithEdges; i++, off += 8) { + allEdges[i] = new EdgeLocationReport(bb, off); + allEdges[i].read(); + } + } + int linesWithEdges_numLinesWithEdges = backing.getInt(32); + long linesWithEdges_addr = getPointer(backing, 28); + linesWithEdges = new int[linesWithEdges_numLinesWithEdges]; + if (linesWithEdges_numLinesWithEdges > 0 && linesWithEdges_addr != 0) { + newDirectByteBuffer(linesWithEdges_addr, linesWithEdges_numLinesWithEdges * 4) + .asIntBuffer().get(linesWithEdges); + } + } + + public void write() { + rakeArcs_buf = ByteBuffer.allocateDirect(rakeArcs.length * 32).order(ByteOrder.nativeOrder()); + for (int i = 0, off = 0; i < rakeArcs.length; i++, off += 32) { + rakeArcs[i].setBuffer(rakeArcs_buf, off); + rakeArcs[i].write(); + } + backing.putInt(4, rakeArcs.length); + putPointer(backing, 0, rakeArcs_buf); + firstEdges_buf = + ByteBuffer.allocateDirect(firstEdges.length * 8).order(ByteOrder.nativeOrder()); + for (int i = 0, off = 0; i < firstEdges.length; i++, off += 8) { + firstEdges[i].setBuffer(firstEdges_buf, off); + firstEdges[i].write(); + } + backing.putInt(12, firstEdges.length); + putPointer(backing, 8, firstEdges_buf); + lastEdges_buf = + ByteBuffer.allocateDirect(lastEdges.length * 8).order(ByteOrder.nativeOrder()); + for (int i = 0, off = 0; i < lastEdges.length; i++, off += 8) { + lastEdges[i].setBuffer(lastEdges_buf, off); + lastEdges[i].write(); + } + backing.putInt(20, lastEdges.length); + putPointer(backing, 16, lastEdges_buf); + allEdges_buf = ByteBuffer.allocateDirect(allEdges.length * 8).order(ByteOrder.nativeOrder()); + for (int i = 0, off = 0; i < allEdges.length; i++, off += 8) { + allEdges[i].setBuffer(allEdges_buf, off); + allEdges[i].write(); + } + backing.putInt(32, allEdges.length); + putPointer(backing, 24, allEdges_buf); + linesWithEdges_buf = + ByteBuffer.allocateDirect(linesWithEdges.length * 4).order(ByteOrder.nativeOrder()); + linesWithEdges_buf.asIntBuffer().put(linesWithEdges).rewind(); + backing.putInt(32, linesWithEdges.length); + putPointer(backing, 28, linesWithEdges_buf); + } + + public int size() { + return 36; + } + } + + public static class ConstructROIOptions extends DisposedStruct { + public int windowNumber; // The window number of the image window. + public String windowTitle; // Specifies the message string that the function + // displays in the title bar of the window. + public PaletteType type; // The palette type to use. + public RGBValue[] palette; // If type is IMAQ_PALETTE_USER, this array is + // the palette of colors to use with the window. + private ByteBuffer windowTitle_buf; + private ByteBuffer palette_buf; + + private void init() { + palette = new RGBValue[0]; + } + + public ConstructROIOptions() { + super(20); + init(); + } + + public ConstructROIOptions(int windowNumber, String windowTitle, PaletteType type, + RGBValue[] palette) { + super(20); + this.windowNumber = windowNumber; + this.windowTitle = windowTitle; + this.type = type; + this.palette = palette; + } + + protected ConstructROIOptions(ByteBuffer backing, int offset) { + super(backing, offset, 20); + init(); + } + + protected ConstructROIOptions(long nativeObj, boolean owned) { + super(nativeObj, owned, 20); + init(); + } + + protected void setBuffer(ByteBuffer backing, int offset) { + super.setBuffer(backing, offset, 20); + } + + public void read() { + windowNumber = backing.getInt(0); + long windowTitle_addr = getPointer(backing, 4); + if (windowTitle_addr == 0) + windowTitle = null; + else { + ByteBuffer bb = newDirectByteBuffer(windowTitle_addr, 1000); // FIXME + while (bb.get() != 0) { + } + byte[] bytes = new byte[bb.position() - 1]; + getBytes(bb, bytes, 0, bytes.length); + try { + windowTitle = new String(bytes, "UTF-8"); + } catch (UnsupportedEncodingException e) { + windowTitle = ""; + } + } + + type = PaletteType.fromValue(backing.getInt(8)); + int palette_numColors = backing.getInt(16); + long palette_addr = getPointer(backing, 12); + palette = new RGBValue[palette_numColors]; + if (palette_numColors > 0 && palette_addr != 0) { + ByteBuffer bb = newDirectByteBuffer(palette_addr, palette_numColors * 4); + for (int i = 0, off = 0; i < palette_numColors; i++, off += 4) { + palette[i] = new RGBValue(bb, off); + palette[i].read(); + } + } + } + + public void write() { + backing.putInt(0, windowNumber); + if (windowTitle != null) { + byte[] windowTitle_bytes; + try { + windowTitle_bytes = windowTitle.getBytes("UTF-8"); + } catch (UnsupportedEncodingException e) { + windowTitle_bytes = new byte[0]; + } + windowTitle_buf = ByteBuffer.allocateDirect(windowTitle_bytes.length + 1); + putBytes(windowTitle_buf, windowTitle_bytes, 0, windowTitle_bytes.length).put( + windowTitle_bytes.length, (byte) 0); + } + putPointer(backing, 4, windowTitle == null ? 0 : getByteBufferAddress(windowTitle_buf)); + if (type != null) + backing.putInt(8, type.getValue()); + palette_buf = ByteBuffer.allocateDirect(palette.length * 4).order(ByteOrder.nativeOrder()); + for (int i = 0, off = 0; i < palette.length; i++, off += 4) { + palette[i].setBuffer(palette_buf, off); + palette[i].write(); + } + backing.putInt(16, palette.length); + putPointer(backing, 12, palette_buf); + } + + public int size() { + return 20; + } + } + + public static class ContourInfo extends DisposedStruct { + public ContourType type; // The contour type. + public Point[] points; // The points describing the contour. + public RGBValue contourColor; // The contour color. + private ByteBuffer points_buf; + + private void init() { + points = new Point[0]; + contourColor = new RGBValue(backing, 12); + } + + public ContourInfo() { + super(16); + init(); + } + + public ContourInfo(ContourType type, Point[] points, RGBValue contourColor) { + super(16); + this.type = type; + this.points = points; + this.contourColor = contourColor; + } + + protected ContourInfo(ByteBuffer backing, int offset) { + super(backing, offset, 16); + init(); + } + + protected ContourInfo(long nativeObj, boolean owned) { + super(nativeObj, owned, 16); + init(); + } + + protected void setBuffer(ByteBuffer backing, int offset) { + super.setBuffer(backing, offset, 16); + } + + public void read() { + type = ContourType.fromValue(backing.getInt(0)); + int points_numPoints = backing.getInt(4); + long points_addr = getPointer(backing, 8); + points = new Point[points_numPoints]; + if (points_numPoints > 0 && points_addr != 0) { + ByteBuffer bb = newDirectByteBuffer(points_addr, points_numPoints * 8); + for (int i = 0, off = 0; i < points_numPoints; i++, off += 8) { + points[i] = new Point(bb, off); + points[i].read(); + } + } + contourColor.read(); + } + + public void write() { + if (type != null) + backing.putInt(0, type.getValue()); + points_buf = ByteBuffer.allocateDirect(points.length * 8).order(ByteOrder.nativeOrder()); + for (int i = 0, off = 0; i < points.length; i++, off += 8) { + points[i].setBuffer(points_buf, off); + points[i].write(); + } + backing.putInt(4, points.length); + putPointer(backing, 8, points_buf); + contourColor.write(); + } + + public int size() { + return 16; + } + } + + public static class ContourInfo2 extends DisposedStruct { + public ContourType type; // The contour type. + public RGBValue color; // The contour color. + public Point point; // Use this member when the contour is of type + // IMAQ_POINT. + public Line line; // Use this member when the contour is of type IMAQ_LINE. + public Rect rect; // Use this member when the contour is of type IMAQ_RECT. + public Rect ovalBoundingBox; // Use this member when the contour is of type + // IMAQ_OVAL. + public ClosedContour closedContour; // Use this member when the contour is + // of type IMAQ_CLOSED_CONTOUR. + public OpenContour openContour; // Use this member when the contour is of + // type IMAQ_OPEN_CONTOUR. + public Annulus annulus; // Use this member when the contour is of type + // IMAQ_ANNULUS. + public RotatedRect rotatedRect; // Use this member when the contour is of + // type IMAQ_ROTATED_RECT. + + private void init() { + color = new RGBValue(backing, 4); + } + + public ContourInfo2() { + super(12); + init(); + } + + public ContourInfo2(ContourType type, RGBValue color) { + super(12); + this.type = type; + this.color = color; + } + + protected ContourInfo2(ByteBuffer backing, int offset) { + super(backing, offset, 12); + init(); + } + + protected ContourInfo2(long nativeObj, boolean owned) { + super(nativeObj, owned, 12); + init(); + } + + protected void setBuffer(ByteBuffer backing, int offset) { + super.setBuffer(backing, offset, 12); + } + + public void read() { + type = ContourType.fromValue(backing.getInt(0)); + color.read(); + if (type == ContourType.POINT) { + long point_addr = getPointer(backing, 8); + if (point_addr == 0) + point = null; + else + point = new Point(point_addr, false); + } + if (type == ContourType.LINE) { + long line_addr = getPointer(backing, 8); + if (line_addr == 0) + line = null; + else + line = new Line(line_addr, false); + } + if (type == ContourType.RECT) { + long rect_addr = getPointer(backing, 8); + if (rect_addr == 0) + rect = null; + else + rect = new Rect(rect_addr, false); + } + if (type == ContourType.OVAL) { + long ovalBoundingBox_addr = getPointer(backing, 8); + if (ovalBoundingBox_addr == 0) + ovalBoundingBox = null; + else + ovalBoundingBox = new Rect(ovalBoundingBox_addr, false); + } + if (type == ContourType.CLOSED_CONTOUR) { + long closedContour_addr = getPointer(backing, 8); + if (closedContour_addr == 0) + closedContour = null; + else + closedContour = new ClosedContour(closedContour_addr, false); + } + if (type == ContourType.OPEN_CONTOUR) { + long openContour_addr = getPointer(backing, 8); + if (openContour_addr == 0) + openContour = null; + else + openContour = new OpenContour(openContour_addr, false); + } + if (type == ContourType.ANNULUS) { + long annulus_addr = getPointer(backing, 8); + if (annulus_addr == 0) + annulus = null; + else + annulus = new Annulus(annulus_addr, false); + } + if (type == ContourType.ROTATED_RECT) { + long rotatedRect_addr = getPointer(backing, 8); + if (rotatedRect_addr == 0) + rotatedRect = null; + else + rotatedRect = new RotatedRect(rotatedRect_addr, false); + } + } + + public void write() { + if (type != null) + backing.putInt(0, type.getValue()); + color.write(); + if (type == ContourType.POINT) { + putPointer(backing, 8, point); + } + if (type == ContourType.LINE) { + putPointer(backing, 8, line); + } + if (type == ContourType.RECT) { + putPointer(backing, 8, rect); + } + if (type == ContourType.OVAL) { + putPointer(backing, 8, ovalBoundingBox); + } + if (type == ContourType.CLOSED_CONTOUR) { + putPointer(backing, 8, closedContour); + } + if (type == ContourType.OPEN_CONTOUR) { + putPointer(backing, 8, openContour); + } + if (type == ContourType.ANNULUS) { + putPointer(backing, 8, annulus); + } + if (type == ContourType.ROTATED_RECT) { + putPointer(backing, 8, rotatedRect); + } + } + + public int size() { + return 12; + } + } + + public static class ContourPoint extends DisposedStruct { + public double x; // The x-coordinate value in the image. + public double y; // The y-coordinate value in the image. + public double curvature; // The change in slope at this edge point of the + // segment. + public double xDisplacement; // The x displacement of the current edge pixel + // from a cubic spline fit of the current edge + // segment. + public double yDisplacement; // The y displacement of the current edge pixel + // from a cubic spline fit of the current edge + // segment. + + private void init() { + + } + + public ContourPoint() { + super(40); + init(); + } + + public ContourPoint(double x, double y, double curvature, double xDisplacement, + double yDisplacement) { + super(40); + this.x = x; + this.y = y; + this.curvature = curvature; + this.xDisplacement = xDisplacement; + this.yDisplacement = yDisplacement; + } + + protected ContourPoint(ByteBuffer backing, int offset) { + super(backing, offset, 40); + init(); + } + + protected ContourPoint(long nativeObj, boolean owned) { + super(nativeObj, owned, 40); + init(); + } + + protected void setBuffer(ByteBuffer backing, int offset) { + super.setBuffer(backing, offset, 40); + } + + public void read() { + x = backing.getDouble(0); + y = backing.getDouble(8); + curvature = backing.getDouble(16); + xDisplacement = backing.getDouble(24); + yDisplacement = backing.getDouble(32); + } + + public void write() { + backing.putDouble(0, x); + backing.putDouble(8, y); + backing.putDouble(16, curvature); + backing.putDouble(24, xDisplacement); + backing.putDouble(32, yDisplacement); + } + + public int size() { + return 40; + } + } + + public static class CoordinateTransform extends DisposedStruct { + public Point initialOrigin; // The origin of the initial coordinate system. + public float initialAngle; // The angle, in degrees, of the x-axis of the + // initial coordinate system relative to the + // image x-axis. + public Point finalOrigin; // The origin of the final coordinate system. + public float finalAngle; // The angle, in degrees, of the x-axis of the + // final coordinate system relative to the image + // x-axis. + + private void init() { + initialOrigin = new Point(backing, 0); + finalOrigin = new Point(backing, 12); + } + + public CoordinateTransform() { + super(24); + init(); + } + + public CoordinateTransform(Point initialOrigin, double initialAngle, Point finalOrigin, + double finalAngle) { + super(24); + this.initialOrigin = initialOrigin; + this.initialAngle = (float) initialAngle; + this.finalOrigin = finalOrigin; + this.finalAngle = (float) finalAngle; + } + + protected CoordinateTransform(ByteBuffer backing, int offset) { + super(backing, offset, 24); + init(); + } + + protected CoordinateTransform(long nativeObj, boolean owned) { + super(nativeObj, owned, 24); + init(); + } + + protected void setBuffer(ByteBuffer backing, int offset) { + super.setBuffer(backing, offset, 24); + } + + public void read() { + initialOrigin.read(); + initialAngle = backing.getFloat(8); + finalOrigin.read(); + finalAngle = backing.getFloat(20); + } + + public void write() { + initialOrigin.write(); + backing.putFloat(8, initialAngle); + finalOrigin.write(); + backing.putFloat(20, finalAngle); + } + + public int size() { + return 24; + } + } + + public static class CoordinateTransform2 extends DisposedStruct { + public CoordinateSystem referenceSystem; // Defines the coordinate system + // for input coordinates. + public CoordinateSystem measurementSystem; // Defines the coordinate system + // in which the function should + // perform measurements. + + private void init() { + referenceSystem = new CoordinateSystem(backing, 0); + measurementSystem = new CoordinateSystem(backing, 16); + } + + public CoordinateTransform2() { + super(32); + init(); + } + + public CoordinateTransform2(CoordinateSystem referenceSystem, CoordinateSystem measurementSystem) { + super(32); + this.referenceSystem = referenceSystem; + this.measurementSystem = measurementSystem; + } + + protected CoordinateTransform2(ByteBuffer backing, int offset) { + super(backing, offset, 32); + init(); + } + + protected CoordinateTransform2(long nativeObj, boolean owned) { + super(nativeObj, owned, 32); + init(); + } + + protected void setBuffer(ByteBuffer backing, int offset) { + super.setBuffer(backing, offset, 32); + } + + public void read() { + referenceSystem.read(); + measurementSystem.read(); + } + + public void write() { + referenceSystem.write(); + measurementSystem.write(); + } + + public int size() { + return 32; + } + } + + public static class CannyOptions extends DisposedStruct { + public float sigma; // The sigma of the Gaussian smoothing filter that the + // function applies to the image before edge detection. + public float upperThreshold; // The upper fraction of pixel values in the + // image from which the function chooses a seed + // or starting point of an edge segment. + public float lowerThreshold; // The function multiplies this value by + // upperThreshold to determine the lower + // threshold for all the pixels in an edge + // segment. + public int windowSize; // The window size of the Gaussian filter that the + // function applies to the image. + + private void init() { + + } + + public CannyOptions() { + super(16); + init(); + } + + public CannyOptions(double sigma, double upperThreshold, double lowerThreshold, int windowSize) { + super(16); + this.sigma = (float) sigma; + this.upperThreshold = (float) upperThreshold; + this.lowerThreshold = (float) lowerThreshold; + this.windowSize = windowSize; + } + + protected CannyOptions(ByteBuffer backing, int offset) { + super(backing, offset, 16); + init(); + } + + protected CannyOptions(long nativeObj, boolean owned) { + super(nativeObj, owned, 16); + init(); + } + + protected void setBuffer(ByteBuffer backing, int offset) { + super.setBuffer(backing, offset, 16); + } + + public void read() { + sigma = backing.getFloat(0); + upperThreshold = backing.getFloat(4); + lowerThreshold = backing.getFloat(8); + windowSize = backing.getInt(12); + } + + public void write() { + backing.putFloat(0, sigma); + backing.putFloat(4, upperThreshold); + backing.putFloat(8, lowerThreshold); + backing.putInt(12, windowSize); + } + + public int size() { + return 16; + } + } + + public static class Range extends DisposedStruct { + public int minValue; // The minimum value of the range. + public int maxValue; // The maximum value of the range. + + private void init() { + + } + + public Range() { + super(8); + init(); + } + + public Range(int minValue, int maxValue) { + super(8); + this.minValue = minValue; + this.maxValue = maxValue; + } + + protected Range(ByteBuffer backing, int offset) { + super(backing, offset, 8); + init(); + } + + protected Range(long nativeObj, boolean owned) { + super(nativeObj, owned, 8); + init(); + } + + protected void setBuffer(ByteBuffer backing, int offset) { + super.setBuffer(backing, offset, 8); + } + + public void read() { + minValue = backing.getInt(0); + maxValue = backing.getInt(4); + } + + public void write() { + backing.putInt(0, minValue); + backing.putInt(4, maxValue); + } + + public int size() { + return 8; + } + } + + public static class UserPointSymbol extends DisposedStruct { + public int cols; // Number of columns in the symbol. + public int rows; // Number of rows in the symbol. + + private void init() { + + } + + public UserPointSymbol() { + super(12); + init(); + } + + public UserPointSymbol(int cols, int rows) { + super(12); + this.cols = cols; + this.rows = rows; + } + + protected UserPointSymbol(ByteBuffer backing, int offset) { + super(backing, offset, 12); + init(); + } + + protected UserPointSymbol(long nativeObj, boolean owned) { + super(nativeObj, owned, 12); + init(); + } + + protected void setBuffer(ByteBuffer backing, int offset) { + super.setBuffer(backing, offset, 12); + } + + public void read() { + cols = backing.getInt(0); + rows = backing.getInt(4); + } + + public void write() { + backing.putInt(0, cols); + backing.putInt(4, rows); + } + + public int size() { + return 12; + } + } + + public static class View3DOptions extends DisposedStruct { + public int sizeReduction; // A divisor the function uses when determining + // the final height and width of the 3D image. + public int maxHeight; // Defines the maximum height of a pixel from the + // image source drawn in 3D. + public Direction3D direction; // Defines the 3D orientation. + public float alpha; // Determines the angle between the horizontal and the + // baseline. + public float beta; // Determines the angle between the horizontal and the + // second baseline. + public int border; // Defines the border size. + public int background; // Defines the background color. + public Plane3D plane; // Indicates the view a function uses to show complex + // images. + + private void init() { + + } + + public View3DOptions() { + super(32); + init(); + } + + public View3DOptions(int sizeReduction, int maxHeight, Direction3D direction, double alpha, + double beta, int border, int background, Plane3D plane) { + super(32); + this.sizeReduction = sizeReduction; + this.maxHeight = maxHeight; + this.direction = direction; + this.alpha = (float) alpha; + this.beta = (float) beta; + this.border = border; + this.background = background; + this.plane = plane; + } + + protected View3DOptions(ByteBuffer backing, int offset) { + super(backing, offset, 32); + init(); + } + + protected View3DOptions(long nativeObj, boolean owned) { + super(nativeObj, owned, 32); + init(); + } + + protected void setBuffer(ByteBuffer backing, int offset) { + super.setBuffer(backing, offset, 32); + } + + public void read() { + sizeReduction = backing.getInt(0); + maxHeight = backing.getInt(4); + direction = Direction3D.fromValue(backing.getInt(8)); + alpha = backing.getFloat(12); + beta = backing.getFloat(16); + border = backing.getInt(20); + background = backing.getInt(24); + plane = Plane3D.fromValue(backing.getInt(28)); + } + + public void write() { + backing.putInt(0, sizeReduction); + backing.putInt(4, maxHeight); + if (direction != null) + backing.putInt(8, direction.getValue()); + backing.putFloat(12, alpha); + backing.putFloat(16, beta); + backing.putInt(20, border); + backing.putInt(24, background); + if (plane != null) + backing.putInt(28, plane.getValue()); + } + + public int size() { + return 32; + } + } + + public static class MatchPatternOptions extends DisposedStruct { + public MatchingMode mode; // Specifies the method to use when looking for + // the pattern in the image. + public int minContrast; // Specifies the minimum contrast expected in the + // image. + public int subpixelAccuracy; // Set this element to TRUE to return areas in + // the image that match the pattern area with + // subpixel accuracy. + public RotationAngleRange[] angleRanges; // An array of angle ranges, in + // degrees, where each range + // specifies how much you expect + // the pattern to be rotated in the + // image. + public int numMatchesRequested; // Number of valid matches expected. + public int matchFactor; // Controls the number of potential matches that the + // function examines. + public float minMatchScore; // The minimum score a match can have for the + // function to consider the match valid. + private ByteBuffer angleRanges_buf; + + private void init() { + angleRanges = new RotationAngleRange[0]; + } + + public MatchPatternOptions() { + super(32); + init(); + } + + public MatchPatternOptions(MatchingMode mode, int minContrast, int subpixelAccuracy, + RotationAngleRange[] angleRanges, int numMatchesRequested, int matchFactor, + double minMatchScore) { + super(32); + this.mode = mode; + this.minContrast = minContrast; + this.subpixelAccuracy = subpixelAccuracy; + this.angleRanges = angleRanges; + this.numMatchesRequested = numMatchesRequested; + this.matchFactor = matchFactor; + this.minMatchScore = (float) minMatchScore; + } + + protected MatchPatternOptions(ByteBuffer backing, int offset) { + super(backing, offset, 32); + init(); + } + + protected MatchPatternOptions(long nativeObj, boolean owned) { + super(nativeObj, owned, 32); + init(); + } + + protected void setBuffer(ByteBuffer backing, int offset) { + super.setBuffer(backing, offset, 32); + } + + public void read() { + mode = MatchingMode.fromValue(backing.getInt(0)); + minContrast = backing.getInt(4); + subpixelAccuracy = backing.getInt(8); + int angleRanges_numRanges = backing.getInt(16); + long angleRanges_addr = getPointer(backing, 12); + angleRanges = new RotationAngleRange[angleRanges_numRanges]; + if (angleRanges_numRanges > 0 && angleRanges_addr != 0) { + ByteBuffer bb = newDirectByteBuffer(angleRanges_addr, angleRanges_numRanges * 8); + for (int i = 0, off = 0; i < angleRanges_numRanges; i++, off += 8) { + angleRanges[i] = new RotationAngleRange(bb, off); + angleRanges[i].read(); + } + } + numMatchesRequested = backing.getInt(20); + matchFactor = backing.getInt(24); + minMatchScore = backing.getFloat(28); + } + + public void write() { + if (mode != null) + backing.putInt(0, mode.getValue()); + backing.putInt(4, minContrast); + backing.putInt(8, subpixelAccuracy); + angleRanges_buf = + ByteBuffer.allocateDirect(angleRanges.length * 8).order(ByteOrder.nativeOrder()); + for (int i = 0, off = 0; i < angleRanges.length; i++, off += 8) { + angleRanges[i].setBuffer(angleRanges_buf, off); + angleRanges[i].write(); + } + backing.putInt(16, angleRanges.length); + putPointer(backing, 12, angleRanges_buf); + backing.putInt(20, numMatchesRequested); + backing.putInt(24, matchFactor); + backing.putFloat(28, minMatchScore); + } + + public int size() { + return 32; + } + } + + public static class TIFFFileOptions extends DisposedStruct { + public int rowsPerStrip; // Indicates the number of rows that the function + // writes per strip. + public PhotometricMode photoInterp; // Designates which photometric + // interpretation to use. + public TIFFCompressionType compressionType; // Indicates the type of + // compression to use on the + // TIFF file. + + private void init() { + + } + + public TIFFFileOptions() { + super(12); + init(); + } + + public TIFFFileOptions(int rowsPerStrip, PhotometricMode photoInterp, + TIFFCompressionType compressionType) { + super(12); + this.rowsPerStrip = rowsPerStrip; + this.photoInterp = photoInterp; + this.compressionType = compressionType; + } + + protected TIFFFileOptions(ByteBuffer backing, int offset) { + super(backing, offset, 12); + init(); + } + + protected TIFFFileOptions(long nativeObj, boolean owned) { + super(nativeObj, owned, 12); + init(); + } + + protected void setBuffer(ByteBuffer backing, int offset) { + super.setBuffer(backing, offset, 12); + } + + public void read() { + rowsPerStrip = backing.getInt(0); + photoInterp = PhotometricMode.fromValue(backing.getInt(4)); + compressionType = TIFFCompressionType.fromValue(backing.getInt(8)); + } + + public void write() { + backing.putInt(0, rowsPerStrip); + if (photoInterp != null) + backing.putInt(4, photoInterp.getValue()); + if (compressionType != null) + backing.putInt(8, compressionType.getValue()); + } + + public int size() { + return 12; + } + } + + public static class OpenContour extends DisposedStruct { + public Point[] points; // The points that make up the open contour. + private ByteBuffer points_buf; + + private void init() { + points = new Point[0]; + } + + public OpenContour() { + super(8); + init(); + } + + public OpenContour(Point[] points) { + super(8); + this.points = points; + } + + protected OpenContour(ByteBuffer backing, int offset) { + super(backing, offset, 8); + init(); + } + + protected OpenContour(long nativeObj, boolean owned) { + super(nativeObj, owned, 8); + init(); + } + + protected void setBuffer(ByteBuffer backing, int offset) { + super.setBuffer(backing, offset, 8); + } + + public void read() { + int points_numPoints = backing.getInt(4); + long points_addr = getPointer(backing, 0); + points = new Point[points_numPoints]; + if (points_numPoints > 0 && points_addr != 0) { + ByteBuffer bb = newDirectByteBuffer(points_addr, points_numPoints * 8); + for (int i = 0, off = 0; i < points_numPoints; i++, off += 8) { + points[i] = new Point(bb, off); + points[i].read(); + } + } + } + + public void write() { + points_buf = ByteBuffer.allocateDirect(points.length * 8).order(ByteOrder.nativeOrder()); + for (int i = 0, off = 0; i < points.length; i++, off += 8) { + points[i].setBuffer(points_buf, off); + points[i].write(); + } + backing.putInt(4, points.length); + putPointer(backing, 0, points_buf); + } + + public int size() { + return 8; + } + } + + public static class OverlayTextOptions extends DisposedStruct { + public String fontName; // The name of the font to use. + public int fontSize; // The size of the font. + public int bold; // Set this element to TRUE to bold the text. + public int italic; // Set this element to TRUE to italicize the text. + public int underline; // Set this element to TRUE to underline the text. + public int strikeout; // Set this element to TRUE to strikeout the text. + public TextAlignment horizontalTextAlignment; // Sets the alignment of the + // text. + public VerticalTextAlignment verticalTextAlignment; // Sets the vertical + // alignment for the + // text. + public RGBValue backgroundColor; // Sets the color for the text background + // pixels. + public double angle; // The counterclockwise angle, in degrees, of the text + // relative to the x-axis. + private ByteBuffer fontName_buf; + + private void init() { + backgroundColor = new RGBValue(backing, 32); + } + + public OverlayTextOptions() { + super(48); + init(); + } + + public OverlayTextOptions(String fontName, int fontSize, int bold, int italic, int underline, + int strikeout, TextAlignment horizontalTextAlignment, + VerticalTextAlignment verticalTextAlignment, RGBValue backgroundColor, double angle) { + super(48); + this.fontName = fontName; + this.fontSize = fontSize; + this.bold = bold; + this.italic = italic; + this.underline = underline; + this.strikeout = strikeout; + this.horizontalTextAlignment = horizontalTextAlignment; + this.verticalTextAlignment = verticalTextAlignment; + this.backgroundColor = backgroundColor; + this.angle = angle; + } + + protected OverlayTextOptions(ByteBuffer backing, int offset) { + super(backing, offset, 48); + init(); + } + + protected OverlayTextOptions(long nativeObj, boolean owned) { + super(nativeObj, owned, 48); + init(); + } + + protected void setBuffer(ByteBuffer backing, int offset) { + super.setBuffer(backing, offset, 48); + } + + public void read() { + long fontName_addr = getPointer(backing, 0); + if (fontName_addr == 0) + fontName = null; + else { + ByteBuffer bb = newDirectByteBuffer(fontName_addr, 1000); // FIXME + while (bb.get() != 0) { + } + byte[] bytes = new byte[bb.position() - 1]; + getBytes(bb, bytes, 0, bytes.length); + try { + fontName = new String(bytes, "UTF-8"); + } catch (UnsupportedEncodingException e) { + fontName = ""; + } + } + + fontSize = backing.getInt(4); + bold = backing.getInt(8); + italic = backing.getInt(12); + underline = backing.getInt(16); + strikeout = backing.getInt(20); + horizontalTextAlignment = TextAlignment.fromValue(backing.getInt(24)); + verticalTextAlignment = VerticalTextAlignment.fromValue(backing.getInt(28)); + backgroundColor.read(); + angle = backing.getDouble(40); + } + + public void write() { + if (fontName != null) { + byte[] fontName_bytes; + try { + fontName_bytes = fontName.getBytes("UTF-8"); + } catch (UnsupportedEncodingException e) { + fontName_bytes = new byte[0]; + } + fontName_buf = ByteBuffer.allocateDirect(fontName_bytes.length + 1); + putBytes(fontName_buf, fontName_bytes, 0, fontName_bytes.length).put(fontName_bytes.length, + (byte) 0); + } + putPointer(backing, 0, fontName == null ? 0 : getByteBufferAddress(fontName_buf)); + backing.putInt(4, fontSize); + backing.putInt(8, bold); + backing.putInt(12, italic); + backing.putInt(16, underline); + backing.putInt(20, strikeout); + if (horizontalTextAlignment != null) + backing.putInt(24, horizontalTextAlignment.getValue()); + if (verticalTextAlignment != null) + backing.putInt(28, verticalTextAlignment.getValue()); + backgroundColor.write(); + backing.putDouble(40, angle); + } + + public int size() { + return 48; + } + } + + public static class ParticleFilterCriteria extends DisposedStruct { + public MeasurementValue parameter; // The morphological measurement that the + // function uses for filtering. + public float lower; // The lower bound of the criteria range. + public float upper; // The upper bound of the criteria range. + public int exclude; // Set this element to TRUE to indicate that a match + // occurs when the value is outside the criteria range. + + private void init() { + + } + + public ParticleFilterCriteria() { + super(16); + init(); + } + + public ParticleFilterCriteria(MeasurementValue parameter, double lower, double upper, + int exclude) { + super(16); + this.parameter = parameter; + this.lower = (float) lower; + this.upper = (float) upper; + this.exclude = exclude; + } + + protected ParticleFilterCriteria(ByteBuffer backing, int offset) { + super(backing, offset, 16); + init(); + } + + protected ParticleFilterCriteria(long nativeObj, boolean owned) { + super(nativeObj, owned, 16); + init(); + } + + protected void setBuffer(ByteBuffer backing, int offset) { + super.setBuffer(backing, offset, 16); + } + + public void read() { + parameter = MeasurementValue.fromValue(backing.getInt(0)); + lower = backing.getFloat(4); + upper = backing.getFloat(8); + exclude = backing.getInt(12); + } + + public void write() { + if (parameter != null) + backing.putInt(0, parameter.getValue()); + backing.putFloat(4, lower); + backing.putFloat(8, upper); + backing.putInt(12, exclude); + } + + public int size() { + return 16; + } + } + + public static class ParticleReport extends DisposedStruct { + public int area; // The number of pixels in the particle. + public float calibratedArea; // The size of the particle, calibrated to the + // calibration information of the image. + public float perimeter; // The length of the perimeter, calibrated to the + // calibration information of the image. + public int numHoles; // The number of holes in the particle. + public int areaOfHoles; // The total surface area, in pixels, of all the + // holes in a particle. + public float perimeterOfHoles; // The length of the perimeter of all the + // holes in the particle calibrated to the + // calibration information of the image. + public Rect boundingBox; // The smallest rectangle that encloses the + // particle. + public float sigmaX; // The sum of the particle pixels on the x-axis. + public float sigmaY; // The sum of the particle pixels on the y-axis. + public float sigmaXX; // The sum of the particle pixels on the x-axis, + // squared. + public float sigmaYY; // The sum of the particle pixels on the y-axis, + // squared. + public float sigmaXY; // The sum of the particle pixels on the x-axis and + // y-axis. + public int longestLength; // The length of the longest horizontal line + // segment. + public Point longestPoint; // The location of the leftmost pixel of the + // longest segment in the particle. + public int projectionX; // The length of the particle when projected onto + // the x-axis. + public int projectionY; // The length of the particle when projected onto + // the y-axis. + public int connect8; // This element is TRUE if the function used + // connectivity-8 to determine if particles are + // touching. + + private void init() { + boundingBox = new Rect(backing, 24); + longestPoint = new Point(backing, 64); + } + + public ParticleReport() { + super(84); + init(); + } + + public ParticleReport(int area, double calibratedArea, double perimeter, int numHoles, + int areaOfHoles, double perimeterOfHoles, Rect boundingBox, double sigmaX, double sigmaY, + double sigmaXX, double sigmaYY, double sigmaXY, int longestLength, Point longestPoint, + int projectionX, int projectionY, int connect8) { + super(84); + this.area = area; + this.calibratedArea = (float) calibratedArea; + this.perimeter = (float) perimeter; + this.numHoles = numHoles; + this.areaOfHoles = areaOfHoles; + this.perimeterOfHoles = (float) perimeterOfHoles; + this.boundingBox = boundingBox; + this.sigmaX = (float) sigmaX; + this.sigmaY = (float) sigmaY; + this.sigmaXX = (float) sigmaXX; + this.sigmaYY = (float) sigmaYY; + this.sigmaXY = (float) sigmaXY; + this.longestLength = longestLength; + this.longestPoint = longestPoint; + this.projectionX = projectionX; + this.projectionY = projectionY; + this.connect8 = connect8; + } + + protected ParticleReport(ByteBuffer backing, int offset) { + super(backing, offset, 84); + init(); + } + + protected ParticleReport(long nativeObj, boolean owned) { + super(nativeObj, owned, 84); + init(); + } + + protected void setBuffer(ByteBuffer backing, int offset) { + super.setBuffer(backing, offset, 84); + } + + public void read() { + area = backing.getInt(0); + calibratedArea = backing.getFloat(4); + perimeter = backing.getFloat(8); + numHoles = backing.getInt(12); + areaOfHoles = backing.getInt(16); + perimeterOfHoles = backing.getFloat(20); + boundingBox.read(); + sigmaX = backing.getFloat(40); + sigmaY = backing.getFloat(44); + sigmaXX = backing.getFloat(48); + sigmaYY = backing.getFloat(52); + sigmaXY = backing.getFloat(56); + longestLength = backing.getInt(60); + longestPoint.read(); + projectionX = backing.getInt(72); + projectionY = backing.getInt(76); + connect8 = backing.getInt(80); + } + + public void write() { + backing.putInt(0, area); + backing.putFloat(4, calibratedArea); + backing.putFloat(8, perimeter); + backing.putInt(12, numHoles); + backing.putInt(16, areaOfHoles); + backing.putFloat(20, perimeterOfHoles); + boundingBox.write(); + backing.putFloat(40, sigmaX); + backing.putFloat(44, sigmaY); + backing.putFloat(48, sigmaXX); + backing.putFloat(52, sigmaYY); + backing.putFloat(56, sigmaXY); + backing.putInt(60, longestLength); + longestPoint.write(); + backing.putInt(72, projectionX); + backing.putInt(76, projectionY); + backing.putInt(80, connect8); + } + + public int size() { + return 84; + } + } + + public static class PatternMatch extends DisposedStruct { + public PointFloat position; // The location of the center of the match. + public float rotation; // The rotation of the match relative to the template + // image, in degrees. + public float scale; // The size of the match relative to the size of the + // template image, expressed as a percentage. + public float score; // The accuracy of the match. + public PointFloat[] corner; // An array of four points describing the + // rectangle surrounding the template image. + + private void init() { + position = new PointFloat(backing, 0); + corner = new PointFloat[4]; + + for (int i = 0, off = 20; i < 4; i++, off += 8) + corner[i] = new PointFloat(backing, off); + } + + public PatternMatch() { + super(52); + init(); + } + + public PatternMatch(PointFloat position, double rotation, double scale, double score, + PointFloat[] corner) { + super(52); + this.position = position; + this.rotation = (float) rotation; + this.scale = (float) scale; + this.score = (float) score; + this.corner = corner; + } + + protected PatternMatch(ByteBuffer backing, int offset) { + super(backing, offset, 52); + init(); + } + + protected PatternMatch(long nativeObj, boolean owned) { + super(nativeObj, owned, 52); + init(); + } + + protected void setBuffer(ByteBuffer backing, int offset) { + super.setBuffer(backing, offset, 52); + } + + public void read() { + position.read(); + rotation = backing.getFloat(8); + scale = backing.getFloat(12); + score = backing.getFloat(16); + for (PointFloat it : corner) { + it.read(); + } + } + + public void write() { + position.write(); + backing.putFloat(8, rotation); + backing.putFloat(12, scale); + backing.putFloat(16, score); + for (PointFloat it : corner) { + it.write(); + } + } + + public int size() { + return 52; + } + } + + public static class QuantifyData extends DisposedStruct { + public float mean; // The mean value of the pixel values. + public float stdDev; // The standard deviation of the pixel values. + public float min; // The smallest pixel value. + public float max; // The largest pixel value. + public float calibratedArea; // The area, calibrated to the calibration + // information of the image. + public int pixelArea; // The area, in number of pixels. + public float relativeSize; // The proportion, expressed as a percentage, of + // the associated region relative to the whole + // image. + + private void init() { + + } + + public QuantifyData() { + super(28); + init(); + } + + public QuantifyData(double mean, double stdDev, double min, double max, double calibratedArea, + int pixelArea, double relativeSize) { + super(28); + this.mean = (float) mean; + this.stdDev = (float) stdDev; + this.min = (float) min; + this.max = (float) max; + this.calibratedArea = (float) calibratedArea; + this.pixelArea = pixelArea; + this.relativeSize = (float) relativeSize; + } + + protected QuantifyData(ByteBuffer backing, int offset) { + super(backing, offset, 28); + init(); + } + + protected QuantifyData(long nativeObj, boolean owned) { + super(nativeObj, owned, 28); + init(); + } + + protected void setBuffer(ByteBuffer backing, int offset) { + super.setBuffer(backing, offset, 28); + } + + public void read() { + mean = backing.getFloat(0); + stdDev = backing.getFloat(4); + min = backing.getFloat(8); + max = backing.getFloat(12); + calibratedArea = backing.getFloat(16); + pixelArea = backing.getInt(20); + relativeSize = backing.getFloat(24); + } + + public void write() { + backing.putFloat(0, mean); + backing.putFloat(4, stdDev); + backing.putFloat(8, min); + backing.putFloat(12, max); + backing.putFloat(16, calibratedArea); + backing.putInt(20, pixelArea); + backing.putFloat(24, relativeSize); + } + + public int size() { + return 28; + } + } + + public static class QuantifyReport extends DisposedStruct { + public QuantifyData global; // Statistical data of the whole image. + public QuantifyData[] regions; // An array of QuantifyData structures + // containing statistical data of each region + // of the image. + private ByteBuffer regions_buf; + + private void init() { + global = new QuantifyData(backing, 0); + regions = new QuantifyData[0]; + } + + public QuantifyReport() { + super(36); + init(); + } + + public QuantifyReport(QuantifyData global, QuantifyData[] regions) { + super(36); + this.global = global; + this.regions = regions; + } + + protected QuantifyReport(ByteBuffer backing, int offset) { + super(backing, offset, 36); + init(); + } + + protected QuantifyReport(long nativeObj, boolean owned) { + super(nativeObj, owned, 36); + init(); + } + + protected void setBuffer(ByteBuffer backing, int offset) { + super.setBuffer(backing, offset, 36); + } + + public void read() { + global.read(); + int regions_regionCount = backing.getInt(32); + long regions_addr = getPointer(backing, 28); + regions = new QuantifyData[regions_regionCount]; + if (regions_regionCount > 0 && regions_addr != 0) { + ByteBuffer bb = newDirectByteBuffer(regions_addr, regions_regionCount * 28); + for (int i = 0, off = 0; i < regions_regionCount; i++, off += 28) { + regions[i] = new QuantifyData(bb, off); + regions[i].read(); + } + } + } + + public void write() { + global.write(); + regions_buf = ByteBuffer.allocateDirect(regions.length * 28).order(ByteOrder.nativeOrder()); + for (int i = 0, off = 0; i < regions.length; i++, off += 28) { + regions[i].setBuffer(regions_buf, off); + regions[i].write(); + } + backing.putInt(32, regions.length); + putPointer(backing, 28, regions_buf); + } + + public int size() { + return 36; + } + } + + public static class RakeOptions extends DisposedStruct { + public int threshold; // Specifies the threshold value for the contrast of + // the edge. + public int width; // The number of pixels that the function averages to find + // the contrast at either side of the edge. + public int steepness; // The span, in pixels, of the slope of the edge + // projected along the path specified by the input + // points. + public int subsamplingRatio; // Specifies the number of pixels that separate + // two consecutive search lines. + public InterpolationMethod subpixelType; // The method for interpolating. + public int subpixelDivisions; // The number of samples the function obtains + // from a pixel. + + private void init() { + + } + + public RakeOptions() { + super(24); + init(); + } + + public RakeOptions(int threshold, int width, int steepness, int subsamplingRatio, + InterpolationMethod subpixelType, int subpixelDivisions) { + super(24); + this.threshold = threshold; + this.width = width; + this.steepness = steepness; + this.subsamplingRatio = subsamplingRatio; + this.subpixelType = subpixelType; + this.subpixelDivisions = subpixelDivisions; + } + + protected RakeOptions(ByteBuffer backing, int offset) { + super(backing, offset, 24); + init(); + } + + protected RakeOptions(long nativeObj, boolean owned) { + super(nativeObj, owned, 24); + init(); + } + + protected void setBuffer(ByteBuffer backing, int offset) { + super.setBuffer(backing, offset, 24); + } + + public void read() { + threshold = backing.getInt(0); + width = backing.getInt(4); + steepness = backing.getInt(8); + subsamplingRatio = backing.getInt(12); + subpixelType = InterpolationMethod.fromValue(backing.getInt(16)); + subpixelDivisions = backing.getInt(20); + } + + public void write() { + backing.putInt(0, threshold); + backing.putInt(4, width); + backing.putInt(8, steepness); + backing.putInt(12, subsamplingRatio); + if (subpixelType != null) + backing.putInt(16, subpixelType.getValue()); + backing.putInt(20, subpixelDivisions); + } + + public int size() { + return 24; + } + } + + public static class RakeReport extends DisposedStruct { + public LineFloat[] rakeLines; // The coordinate location of each of the rake + // lines used by the function. + public PointFloat[] firstEdges; // The coordinate location of all edges + // detected as first edges. + public PointFloat[] lastEdges; // The coordinate location of all edges + // detected as last edges. + public EdgeLocationReport[] allEdges; // An array of reports describing the + // location of the edges located by + // each rake line. + public int[] linesWithEdges; // An array of indices into the rakeLines array + // indicating the rake lines on which the + // function detected at least one edge. + private ByteBuffer rakeLines_buf; + private ByteBuffer firstEdges_buf; + private ByteBuffer lastEdges_buf; + private ByteBuffer allEdges_buf; + private ByteBuffer linesWithEdges_buf; + + private void init() { + rakeLines = new LineFloat[0]; + firstEdges = new PointFloat[0]; + lastEdges = new PointFloat[0]; + allEdges = new EdgeLocationReport[0]; + linesWithEdges = new int[0]; + } + + public RakeReport() { + super(36); + init(); + } + + public RakeReport(LineFloat[] rakeLines, PointFloat[] firstEdges, PointFloat[] lastEdges, + EdgeLocationReport[] allEdges, int[] linesWithEdges) { + super(36); + this.rakeLines = rakeLines; + this.firstEdges = firstEdges; + this.lastEdges = lastEdges; + this.allEdges = allEdges; + this.linesWithEdges = linesWithEdges; + } + + protected RakeReport(ByteBuffer backing, int offset) { + super(backing, offset, 36); + init(); + } + + protected RakeReport(long nativeObj, boolean owned) { + super(nativeObj, owned, 36); + init(); + } + + protected void setBuffer(ByteBuffer backing, int offset) { + super.setBuffer(backing, offset, 36); + } + + public void read() { + int rakeLines_numRakeLines = backing.getInt(4); + long rakeLines_addr = getPointer(backing, 0); + rakeLines = new LineFloat[rakeLines_numRakeLines]; + if (rakeLines_numRakeLines > 0 && rakeLines_addr != 0) { + ByteBuffer bb = newDirectByteBuffer(rakeLines_addr, rakeLines_numRakeLines * 16); + for (int i = 0, off = 0; i < rakeLines_numRakeLines; i++, off += 16) { + rakeLines[i] = new LineFloat(bb, off); + rakeLines[i].read(); + } + } + int firstEdges_numFirstEdges = backing.getInt(12); + long firstEdges_addr = getPointer(backing, 8); + firstEdges = new PointFloat[firstEdges_numFirstEdges]; + if (firstEdges_numFirstEdges > 0 && firstEdges_addr != 0) { + ByteBuffer bb = newDirectByteBuffer(firstEdges_addr, firstEdges_numFirstEdges * 8); + for (int i = 0, off = 0; i < firstEdges_numFirstEdges; i++, off += 8) { + firstEdges[i] = new PointFloat(bb, off); + firstEdges[i].read(); + } + } + int lastEdges_numLastEdges = backing.getInt(20); + long lastEdges_addr = getPointer(backing, 16); + lastEdges = new PointFloat[lastEdges_numLastEdges]; + if (lastEdges_numLastEdges > 0 && lastEdges_addr != 0) { + ByteBuffer bb = newDirectByteBuffer(lastEdges_addr, lastEdges_numLastEdges * 8); + for (int i = 0, off = 0; i < lastEdges_numLastEdges; i++, off += 8) { + lastEdges[i] = new PointFloat(bb, off); + lastEdges[i].read(); + } + } + int allEdges_numLinesWithEdges = backing.getInt(32); + long allEdges_addr = getPointer(backing, 24); + allEdges = new EdgeLocationReport[allEdges_numLinesWithEdges]; + if (allEdges_numLinesWithEdges > 0 && allEdges_addr != 0) { + ByteBuffer bb = newDirectByteBuffer(allEdges_addr, allEdges_numLinesWithEdges * 8); + for (int i = 0, off = 0; i < allEdges_numLinesWithEdges; i++, off += 8) { + allEdges[i] = new EdgeLocationReport(bb, off); + allEdges[i].read(); + } + } + int linesWithEdges_numLinesWithEdges = backing.getInt(32); + long linesWithEdges_addr = getPointer(backing, 28); + linesWithEdges = new int[linesWithEdges_numLinesWithEdges]; + if (linesWithEdges_numLinesWithEdges > 0 && linesWithEdges_addr != 0) { + newDirectByteBuffer(linesWithEdges_addr, linesWithEdges_numLinesWithEdges * 4) + .asIntBuffer().get(linesWithEdges); + } + } + + public void write() { + rakeLines_buf = + ByteBuffer.allocateDirect(rakeLines.length * 16).order(ByteOrder.nativeOrder()); + for (int i = 0, off = 0; i < rakeLines.length; i++, off += 16) { + rakeLines[i].setBuffer(rakeLines_buf, off); + rakeLines[i].write(); + } + backing.putInt(4, rakeLines.length); + putPointer(backing, 0, rakeLines_buf); + firstEdges_buf = + ByteBuffer.allocateDirect(firstEdges.length * 8).order(ByteOrder.nativeOrder()); + for (int i = 0, off = 0; i < firstEdges.length; i++, off += 8) { + firstEdges[i].setBuffer(firstEdges_buf, off); + firstEdges[i].write(); + } + backing.putInt(12, firstEdges.length); + putPointer(backing, 8, firstEdges_buf); + lastEdges_buf = + ByteBuffer.allocateDirect(lastEdges.length * 8).order(ByteOrder.nativeOrder()); + for (int i = 0, off = 0; i < lastEdges.length; i++, off += 8) { + lastEdges[i].setBuffer(lastEdges_buf, off); + lastEdges[i].write(); + } + backing.putInt(20, lastEdges.length); + putPointer(backing, 16, lastEdges_buf); + allEdges_buf = ByteBuffer.allocateDirect(allEdges.length * 8).order(ByteOrder.nativeOrder()); + for (int i = 0, off = 0; i < allEdges.length; i++, off += 8) { + allEdges[i].setBuffer(allEdges_buf, off); + allEdges[i].write(); + } + backing.putInt(32, allEdges.length); + putPointer(backing, 24, allEdges_buf); + linesWithEdges_buf = + ByteBuffer.allocateDirect(linesWithEdges.length * 4).order(ByteOrder.nativeOrder()); + linesWithEdges_buf.asIntBuffer().put(linesWithEdges).rewind(); + backing.putInt(32, linesWithEdges.length); + putPointer(backing, 28, linesWithEdges_buf); + } + + public int size() { + return 36; + } + } + + public static class TransformReport extends DisposedStruct { + public PointFloat[] points; // An array of transformed coordinates. + public int[] validPoints; // An array of values that describe the validity + // of each of the coordinates according to the + // region of interest you calibrated using either + // imaqLearnCalibrationGrid() or + // imaqLearnCalibrationPoints(). + private ByteBuffer points_buf; + private ByteBuffer validPoints_buf; + + private void init() { + points = new PointFloat[0]; + validPoints = new int[0]; + } + + public TransformReport() { + super(12); + init(); + } + + public TransformReport(PointFloat[] points, int[] validPoints) { + super(12); + this.points = points; + this.validPoints = validPoints; + } + + protected TransformReport(ByteBuffer backing, int offset) { + super(backing, offset, 12); + init(); + } + + protected TransformReport(long nativeObj, boolean owned) { + super(nativeObj, owned, 12); + init(); + } + + protected void setBuffer(ByteBuffer backing, int offset) { + super.setBuffer(backing, offset, 12); + } + + public void read() { + int points_numPoints = backing.getInt(8); + long points_addr = getPointer(backing, 0); + points = new PointFloat[points_numPoints]; + if (points_numPoints > 0 && points_addr != 0) { + ByteBuffer bb = newDirectByteBuffer(points_addr, points_numPoints * 8); + for (int i = 0, off = 0; i < points_numPoints; i++, off += 8) { + points[i] = new PointFloat(bb, off); + points[i].read(); + } + } + int validPoints_numPoints = backing.getInt(8); + long validPoints_addr = getPointer(backing, 4); + validPoints = new int[validPoints_numPoints]; + if (validPoints_numPoints > 0 && validPoints_addr != 0) { + newDirectByteBuffer(validPoints_addr, validPoints_numPoints * 4).asIntBuffer().get( + validPoints); + } + } + + public void write() { + points_buf = ByteBuffer.allocateDirect(points.length * 8).order(ByteOrder.nativeOrder()); + for (int i = 0, off = 0; i < points.length; i++, off += 8) { + points[i].setBuffer(points_buf, off); + points[i].write(); + } + backing.putInt(8, points.length); + putPointer(backing, 0, points_buf); + validPoints_buf = + ByteBuffer.allocateDirect(validPoints.length * 4).order(ByteOrder.nativeOrder()); + validPoints_buf.asIntBuffer().put(validPoints).rewind(); + backing.putInt(8, validPoints.length); + putPointer(backing, 4, validPoints_buf); + } + + public int size() { + return 12; + } + } + + public static class ShapeReport extends DisposedStruct { + public Rect coordinates; // The bounding rectangle of the object. + public Point centroid; // The coordinate location of the centroid of the + // object. + public int size; // The size, in pixels, of the object. + public double score; // A value ranging between 1 and 1,000 that specifies + // how similar the object in the image is to the + // template. + + private void init() { + coordinates = new Rect(backing, 0); + centroid = new Point(backing, 16); + } + + public ShapeReport() { + super(40); + init(); + } + + public ShapeReport(Rect coordinates, Point centroid, int size, double score) { + super(40); + this.coordinates = coordinates; + this.centroid = centroid; + this.size = size; + this.score = score; + } + + protected ShapeReport(ByteBuffer backing, int offset) { + super(backing, offset, 40); + init(); + } + + protected ShapeReport(long nativeObj, boolean owned) { + super(nativeObj, owned, 40); + init(); + } + + protected void setBuffer(ByteBuffer backing, int offset) { + super.setBuffer(backing, offset, 40); + } + + public void read() { + coordinates.read(); + centroid.read(); + size = backing.getInt(24); + score = backing.getDouble(32); + } + + public void write() { + coordinates.write(); + centroid.write(); + backing.putInt(24, size); + backing.putDouble(32, score); + } + + public int size() { + return 40; + } + } + + public static class MeterArc extends DisposedStruct { + public PointFloat needleBase; // The coordinate location of the base of the + // meter needle. + public PointFloat[] arcCoordPoints; // An array of points describing the + // coordinate location of the meter arc. + public int needleColor; // This element is TRUE when the meter has a + // light-colored needle on a dark background. + private ByteBuffer arcCoordPoints_buf; + + private void init() { + needleBase = new PointFloat(backing, 0); + arcCoordPoints = new PointFloat[0]; + } + + public MeterArc() { + super(20); + init(); + } + + public MeterArc(PointFloat needleBase, PointFloat[] arcCoordPoints, int needleColor) { + super(20); + this.needleBase = needleBase; + this.arcCoordPoints = arcCoordPoints; + this.needleColor = needleColor; + } + + protected MeterArc(ByteBuffer backing, int offset) { + super(backing, offset, 20); + init(); + } + + protected MeterArc(long nativeObj, boolean owned) { + super(nativeObj, owned, 20); + init(); + } + + protected void setBuffer(ByteBuffer backing, int offset) { + super.setBuffer(backing, offset, 20); + } + + public void read() { + needleBase.read(); + int arcCoordPoints_numOfArcCoordPoints = backing.getInt(12); + long arcCoordPoints_addr = getPointer(backing, 8); + arcCoordPoints = new PointFloat[arcCoordPoints_numOfArcCoordPoints]; + if (arcCoordPoints_numOfArcCoordPoints > 0 && arcCoordPoints_addr != 0) { + ByteBuffer bb = + newDirectByteBuffer(arcCoordPoints_addr, arcCoordPoints_numOfArcCoordPoints * 8); + for (int i = 0, off = 0; i < arcCoordPoints_numOfArcCoordPoints; i++, off += 8) { + arcCoordPoints[i] = new PointFloat(bb, off); + arcCoordPoints[i].read(); + } + } + needleColor = backing.getInt(16); + } + + public void write() { + needleBase.write(); + arcCoordPoints_buf = + ByteBuffer.allocateDirect(arcCoordPoints.length * 8).order(ByteOrder.nativeOrder()); + for (int i = 0, off = 0; i < arcCoordPoints.length; i++, off += 8) { + arcCoordPoints[i].setBuffer(arcCoordPoints_buf, off); + arcCoordPoints[i].write(); + } + backing.putInt(12, arcCoordPoints.length); + putPointer(backing, 8, arcCoordPoints_buf); + backing.putInt(16, needleColor); + } + + public int size() { + return 20; + } + } + + public static class ThresholdData extends DisposedStruct { + public float rangeMin; // The lower boundary of the range to keep. + public float rangeMax; // The upper boundary of the range to keep. + public float newValue; // If useNewValue is TRUE, newValue is the + // replacement value for pixels within the range. + public int useNewValue; // If TRUE, the function sets pixel values within + // [rangeMin, rangeMax] to the value specified in + // newValue. + + private void init() { + + } + + public ThresholdData() { + super(16); + init(); + } + + public ThresholdData(double rangeMin, double rangeMax, double newValue, int useNewValue) { + super(16); + this.rangeMin = (float) rangeMin; + this.rangeMax = (float) rangeMax; + this.newValue = (float) newValue; + this.useNewValue = useNewValue; + } + + protected ThresholdData(ByteBuffer backing, int offset) { + super(backing, offset, 16); + init(); + } + + protected ThresholdData(long nativeObj, boolean owned) { + super(nativeObj, owned, 16); + init(); + } + + protected void setBuffer(ByteBuffer backing, int offset) { + super.setBuffer(backing, offset, 16); + } + + public void read() { + rangeMin = backing.getFloat(0); + rangeMax = backing.getFloat(4); + newValue = backing.getFloat(8); + useNewValue = backing.getInt(12); + } + + public void write() { + backing.putFloat(0, rangeMin); + backing.putFloat(4, rangeMax); + backing.putFloat(8, newValue); + backing.putInt(12, useNewValue); + } + + public int size() { + return 16; + } + } + + public static class StructuringElement extends DisposedStruct { + public int matrixCols; // Number of columns in the matrix. + public int matrixRows; // Number of rows in the matrix. + public int hexa; // Set this element to TRUE if you specify a hexagonal + // structuring element in kernel. + + private void init() { + + } + + public StructuringElement() { + super(16); + init(); + } + + public StructuringElement(int matrixCols, int matrixRows, int hexa) { + super(16); + this.matrixCols = matrixCols; + this.matrixRows = matrixRows; + this.hexa = hexa; + } + + protected StructuringElement(ByteBuffer backing, int offset) { + super(backing, offset, 16); + init(); + } + + protected StructuringElement(long nativeObj, boolean owned) { + super(nativeObj, owned, 16); + init(); + } + + protected void setBuffer(ByteBuffer backing, int offset) { + super.setBuffer(backing, offset, 16); + } + + public void read() { + matrixCols = backing.getInt(0); + matrixRows = backing.getInt(4); + hexa = backing.getInt(8); + } + + public void write() { + backing.putInt(0, matrixCols); + backing.putInt(4, matrixRows); + backing.putInt(8, hexa); + } + + public int size() { + return 16; + } + } + + public static class SpokeReport extends DisposedStruct { + public LineFloat[] spokeLines; // The coordinate location of each of the + // spoke lines used by the function. + public PointFloat[] firstEdges; // The coordinate location of all edges + // detected as first edges. + public PointFloat[] lastEdges; // The coordinate location of all edges + // detected as last edges. + public EdgeLocationReport[] allEdges; // An array of reports describing the + // location of the edges located by + // each spoke line. + public int[] linesWithEdges; // An array of indices into the spokeLines + // array indicating the rake lines on which the + // function detected at least one edge. + private ByteBuffer spokeLines_buf; + private ByteBuffer firstEdges_buf; + private ByteBuffer lastEdges_buf; + private ByteBuffer allEdges_buf; + private ByteBuffer linesWithEdges_buf; + + private void init() { + spokeLines = new LineFloat[0]; + firstEdges = new PointFloat[0]; + lastEdges = new PointFloat[0]; + allEdges = new EdgeLocationReport[0]; + linesWithEdges = new int[0]; + } + + public SpokeReport() { + super(36); + init(); + } + + public SpokeReport(LineFloat[] spokeLines, PointFloat[] firstEdges, PointFloat[] lastEdges, + EdgeLocationReport[] allEdges, int[] linesWithEdges) { + super(36); + this.spokeLines = spokeLines; + this.firstEdges = firstEdges; + this.lastEdges = lastEdges; + this.allEdges = allEdges; + this.linesWithEdges = linesWithEdges; + } + + protected SpokeReport(ByteBuffer backing, int offset) { + super(backing, offset, 36); + init(); + } + + protected SpokeReport(long nativeObj, boolean owned) { + super(nativeObj, owned, 36); + init(); + } + + protected void setBuffer(ByteBuffer backing, int offset) { + super.setBuffer(backing, offset, 36); + } + + public void read() { + int spokeLines_numSpokeLines = backing.getInt(4); + long spokeLines_addr = getPointer(backing, 0); + spokeLines = new LineFloat[spokeLines_numSpokeLines]; + if (spokeLines_numSpokeLines > 0 && spokeLines_addr != 0) { + ByteBuffer bb = newDirectByteBuffer(spokeLines_addr, spokeLines_numSpokeLines * 16); + for (int i = 0, off = 0; i < spokeLines_numSpokeLines; i++, off += 16) { + spokeLines[i] = new LineFloat(bb, off); + spokeLines[i].read(); + } + } + int firstEdges_numFirstEdges = backing.getInt(12); + long firstEdges_addr = getPointer(backing, 8); + firstEdges = new PointFloat[firstEdges_numFirstEdges]; + if (firstEdges_numFirstEdges > 0 && firstEdges_addr != 0) { + ByteBuffer bb = newDirectByteBuffer(firstEdges_addr, firstEdges_numFirstEdges * 8); + for (int i = 0, off = 0; i < firstEdges_numFirstEdges; i++, off += 8) { + firstEdges[i] = new PointFloat(bb, off); + firstEdges[i].read(); + } + } + int lastEdges_numLastEdges = backing.getInt(20); + long lastEdges_addr = getPointer(backing, 16); + lastEdges = new PointFloat[lastEdges_numLastEdges]; + if (lastEdges_numLastEdges > 0 && lastEdges_addr != 0) { + ByteBuffer bb = newDirectByteBuffer(lastEdges_addr, lastEdges_numLastEdges * 8); + for (int i = 0, off = 0; i < lastEdges_numLastEdges; i++, off += 8) { + lastEdges[i] = new PointFloat(bb, off); + lastEdges[i].read(); + } + } + int allEdges_numLinesWithEdges = backing.getInt(32); + long allEdges_addr = getPointer(backing, 24); + allEdges = new EdgeLocationReport[allEdges_numLinesWithEdges]; + if (allEdges_numLinesWithEdges > 0 && allEdges_addr != 0) { + ByteBuffer bb = newDirectByteBuffer(allEdges_addr, allEdges_numLinesWithEdges * 8); + for (int i = 0, off = 0; i < allEdges_numLinesWithEdges; i++, off += 8) { + allEdges[i] = new EdgeLocationReport(bb, off); + allEdges[i].read(); + } + } + int linesWithEdges_numLinesWithEdges = backing.getInt(32); + long linesWithEdges_addr = getPointer(backing, 28); + linesWithEdges = new int[linesWithEdges_numLinesWithEdges]; + if (linesWithEdges_numLinesWithEdges > 0 && linesWithEdges_addr != 0) { + newDirectByteBuffer(linesWithEdges_addr, linesWithEdges_numLinesWithEdges * 4) + .asIntBuffer().get(linesWithEdges); + } + } + + public void write() { + spokeLines_buf = + ByteBuffer.allocateDirect(spokeLines.length * 16).order(ByteOrder.nativeOrder()); + for (int i = 0, off = 0; i < spokeLines.length; i++, off += 16) { + spokeLines[i].setBuffer(spokeLines_buf, off); + spokeLines[i].write(); + } + backing.putInt(4, spokeLines.length); + putPointer(backing, 0, spokeLines_buf); + firstEdges_buf = + ByteBuffer.allocateDirect(firstEdges.length * 8).order(ByteOrder.nativeOrder()); + for (int i = 0, off = 0; i < firstEdges.length; i++, off += 8) { + firstEdges[i].setBuffer(firstEdges_buf, off); + firstEdges[i].write(); + } + backing.putInt(12, firstEdges.length); + putPointer(backing, 8, firstEdges_buf); + lastEdges_buf = + ByteBuffer.allocateDirect(lastEdges.length * 8).order(ByteOrder.nativeOrder()); + for (int i = 0, off = 0; i < lastEdges.length; i++, off += 8) { + lastEdges[i].setBuffer(lastEdges_buf, off); + lastEdges[i].write(); + } + backing.putInt(20, lastEdges.length); + putPointer(backing, 16, lastEdges_buf); + allEdges_buf = ByteBuffer.allocateDirect(allEdges.length * 8).order(ByteOrder.nativeOrder()); + for (int i = 0, off = 0; i < allEdges.length; i++, off += 8) { + allEdges[i].setBuffer(allEdges_buf, off); + allEdges[i].write(); + } + backing.putInt(32, allEdges.length); + putPointer(backing, 24, allEdges_buf); + linesWithEdges_buf = + ByteBuffer.allocateDirect(linesWithEdges.length * 4).order(ByteOrder.nativeOrder()); + linesWithEdges_buf.asIntBuffer().put(linesWithEdges).rewind(); + backing.putInt(32, linesWithEdges.length); + putPointer(backing, 28, linesWithEdges_buf); + } + + public int size() { + return 36; + } + } + + public static class SimpleEdgeOptions extends DisposedStruct { + public LevelType type; // Determines how the function evaluates the + // threshold and hysteresis values. + public int threshold; // The pixel value at which an edge occurs. + public int hysteresis; // A value that helps determine edges in noisy + // images. + public EdgeProcess process; // Determines which edges the function looks + // for. + public int subpixel; // Set this element to TRUE to find edges with subpixel + // accuracy by interpolating between points to find the + // crossing of the given threshold. + + private void init() { + + } + + public SimpleEdgeOptions() { + super(20); + init(); + } + + public SimpleEdgeOptions(LevelType type, int threshold, int hysteresis, EdgeProcess process, + int subpixel) { + super(20); + this.type = type; + this.threshold = threshold; + this.hysteresis = hysteresis; + this.process = process; + this.subpixel = subpixel; + } + + protected SimpleEdgeOptions(ByteBuffer backing, int offset) { + super(backing, offset, 20); + init(); + } + + protected SimpleEdgeOptions(long nativeObj, boolean owned) { + super(nativeObj, owned, 20); + init(); + } + + protected void setBuffer(ByteBuffer backing, int offset) { + super.setBuffer(backing, offset, 20); + } + + public void read() { + type = LevelType.fromValue(backing.getInt(0)); + threshold = backing.getInt(4); + hysteresis = backing.getInt(8); + process = EdgeProcess.fromValue(backing.getInt(12)); + subpixel = backing.getInt(16); + } + + public void write() { + if (type != null) + backing.putInt(0, type.getValue()); + backing.putInt(4, threshold); + backing.putInt(8, hysteresis); + if (process != null) + backing.putInt(12, process.getValue()); + backing.putInt(16, subpixel); + } + + public int size() { + return 20; + } + } + + public static class SelectParticleCriteria extends DisposedStruct { + public MeasurementValue parameter; // The morphological measurement that the + // function uses for filtering. + public float lower; // The lower boundary of the criteria range. + public float upper; // The upper boundary of the criteria range. + + private void init() { + + } + + public SelectParticleCriteria() { + super(12); + init(); + } + + public SelectParticleCriteria(MeasurementValue parameter, double lower, double upper) { + super(12); + this.parameter = parameter; + this.lower = (float) lower; + this.upper = (float) upper; + } + + protected SelectParticleCriteria(ByteBuffer backing, int offset) { + super(backing, offset, 12); + init(); + } + + protected SelectParticleCriteria(long nativeObj, boolean owned) { + super(nativeObj, owned, 12); + init(); + } + + protected void setBuffer(ByteBuffer backing, int offset) { + super.setBuffer(backing, offset, 12); + } + + public void read() { + parameter = MeasurementValue.fromValue(backing.getInt(0)); + lower = backing.getFloat(4); + upper = backing.getFloat(8); + } + + public void write() { + if (parameter != null) + backing.putInt(0, parameter.getValue()); + backing.putFloat(4, lower); + backing.putFloat(8, upper); + } + + public int size() { + return 12; + } + } + + public static class SegmentInfo extends DisposedStruct { + public int numberOfPoints; // The number of points in the segment. + public int isOpen; // If TRUE, the contour is open. + public double weight; // The significance of the edge in terms of the gray + // values that constitute the edge. + public ContourPoint points; // The points of the segment. + + private void init() { + + } + + public SegmentInfo() { + super(24); + init(); + } + + public SegmentInfo(int numberOfPoints, int isOpen, double weight, ContourPoint points) { + super(24); + this.numberOfPoints = numberOfPoints; + this.isOpen = isOpen; + this.weight = weight; + this.points = points; + } + + protected SegmentInfo(ByteBuffer backing, int offset) { + super(backing, offset, 24); + init(); + } + + protected SegmentInfo(long nativeObj, boolean owned) { + super(nativeObj, owned, 24); + init(); + } + + protected void setBuffer(ByteBuffer backing, int offset) { + super.setBuffer(backing, offset, 24); + } + + public void read() { + numberOfPoints = backing.getInt(0); + isOpen = backing.getInt(4); + weight = backing.getDouble(8); + long points_addr = getPointer(backing, 16); + if (points_addr == 0) + points = null; + else + points = new ContourPoint(points_addr, false); + } + + public void write() { + backing.putInt(0, numberOfPoints); + backing.putInt(4, isOpen); + backing.putDouble(8, weight); + putPointer(backing, 16, points); + } + + public int size() { + return 24; + } + } + + public static class RotationAngleRange extends DisposedStruct { + public float lower; // The lowest amount of rotation, in degrees, a valid + // pattern can have. + public float upper; // The highest amount of rotation, in degrees, a valid + // pattern can have. + + private void init() { + + } + + public RotationAngleRange() { + super(8); + init(); + } + + public RotationAngleRange(double lower, double upper) { + super(8); + this.lower = (float) lower; + this.upper = (float) upper; + } + + protected RotationAngleRange(ByteBuffer backing, int offset) { + super(backing, offset, 8); + init(); + } + + protected RotationAngleRange(long nativeObj, boolean owned) { + super(nativeObj, owned, 8); + init(); + } + + protected void setBuffer(ByteBuffer backing, int offset) { + super.setBuffer(backing, offset, 8); + } + + public void read() { + lower = backing.getFloat(0); + upper = backing.getFloat(4); + } + + public void write() { + backing.putFloat(0, lower); + backing.putFloat(4, upper); + } + + public int size() { + return 8; + } + } + + public static class RotatedRect extends DisposedStruct { + public int top; // Location of the top edge of the rectangle before + // rotation. + public int left; // Location of the left edge of the rectangle before + // rotation. + public int height; // Height of the rectangle. + public int width; // Width of the rectangle. + public double angle; // The rotation, in degrees, of the rectangle. + + private void init() { + + } + + public RotatedRect() { + super(24); + init(); + } + + public RotatedRect(int top, int left, int height, int width, double angle) { + super(24); + this.top = top; + this.left = left; + this.height = height; + this.width = width; + this.angle = angle; + } + + protected RotatedRect(ByteBuffer backing, int offset) { + super(backing, offset, 24); + init(); + } + + protected RotatedRect(long nativeObj, boolean owned) { + super(nativeObj, owned, 24); + init(); + } + + protected void setBuffer(ByteBuffer backing, int offset) { + super.setBuffer(backing, offset, 24); + } + + public void read() { + top = backing.getInt(0); + left = backing.getInt(4); + height = backing.getInt(8); + width = backing.getInt(12); + angle = backing.getDouble(16); + } + + public void write() { + backing.putInt(0, top); + backing.putInt(4, left); + backing.putInt(8, height); + backing.putInt(12, width); + backing.putDouble(16, angle); + } + + public int size() { + return 24; + } + } + + public static class ROIProfile extends DisposedStruct { + public LineProfile report; // Quantifying information about the points along + // the edge of each contour in the ROI. + public Point pixels; // An array of the points along the edge of each + // contour in the ROI. + + private void init() { + report = new LineProfile(backing, 0); + } + + public ROIProfile() { + super(44); + init(); + } + + public ROIProfile(LineProfile report, Point pixels) { + super(44); + this.report = report; + this.pixels = pixels; + } + + protected ROIProfile(ByteBuffer backing, int offset) { + super(backing, offset, 44); + init(); + } + + protected ROIProfile(long nativeObj, boolean owned) { + super(nativeObj, owned, 44); + init(); + } + + protected void setBuffer(ByteBuffer backing, int offset) { + super.setBuffer(backing, offset, 44); + } + + public void read() { + report.read(); + long pixels_addr = getPointer(backing, 40); + if (pixels_addr == 0) + pixels = null; + else + pixels = new Point(pixels_addr, false); + } + + public void write() { + report.write(); + putPointer(backing, 40, pixels); + } + + public int size() { + return 44; + } + } + + public static class ToolWindowOptions extends DisposedStruct { + public int showSelectionTool; // If TRUE, the selection tool becomes + // visible. + public int showZoomTool; // If TRUE, the zoom tool becomes visible. + public int showPointTool; // If TRUE, the point tool becomes visible. + public int showLineTool; // If TRUE, the line tool becomes visible. + public int showRectangleTool; // If TRUE, the rectangle tool becomes + // visible. + public int showOvalTool; // If TRUE, the oval tool becomes visible. + public int showPolygonTool; // If TRUE, the polygon tool becomes visible. + public int showClosedFreehandTool; // If TRUE, the closed freehand tool + // becomes visible. + public int showPolyLineTool; // If TRUE, the polyline tool becomes visible. + public int showFreehandTool; // If TRUE, the freehand tool becomes visible. + public int showAnnulusTool; // If TRUE, the annulus becomes visible. + public int showRotatedRectangleTool; // If TRUE, the rotated rectangle tool + // becomes visible. + public int showPanTool; // If TRUE, the pan tool becomes visible. + public int showZoomOutTool; // If TRUE, the zoom out tool becomes visible. + + private void init() { + + } + + public ToolWindowOptions() { + super(68); + init(); + } + + public ToolWindowOptions(int showSelectionTool, int showZoomTool, int showPointTool, + int showLineTool, int showRectangleTool, int showOvalTool, int showPolygonTool, + int showClosedFreehandTool, int showPolyLineTool, int showFreehandTool, + int showAnnulusTool, int showRotatedRectangleTool, int showPanTool, int showZoomOutTool) { + super(68); + this.showSelectionTool = showSelectionTool; + this.showZoomTool = showZoomTool; + this.showPointTool = showPointTool; + this.showLineTool = showLineTool; + this.showRectangleTool = showRectangleTool; + this.showOvalTool = showOvalTool; + this.showPolygonTool = showPolygonTool; + this.showClosedFreehandTool = showClosedFreehandTool; + this.showPolyLineTool = showPolyLineTool; + this.showFreehandTool = showFreehandTool; + this.showAnnulusTool = showAnnulusTool; + this.showRotatedRectangleTool = showRotatedRectangleTool; + this.showPanTool = showPanTool; + this.showZoomOutTool = showZoomOutTool; + } + + protected ToolWindowOptions(ByteBuffer backing, int offset) { + super(backing, offset, 68); + init(); + } + + protected ToolWindowOptions(long nativeObj, boolean owned) { + super(nativeObj, owned, 68); + init(); + } + + protected void setBuffer(ByteBuffer backing, int offset) { + super.setBuffer(backing, offset, 68); + } + + public void read() { + showSelectionTool = backing.getInt(0); + showZoomTool = backing.getInt(4); + showPointTool = backing.getInt(8); + showLineTool = backing.getInt(12); + showRectangleTool = backing.getInt(16); + showOvalTool = backing.getInt(20); + showPolygonTool = backing.getInt(24); + showClosedFreehandTool = backing.getInt(28); + showPolyLineTool = backing.getInt(32); + showFreehandTool = backing.getInt(36); + showAnnulusTool = backing.getInt(40); + showRotatedRectangleTool = backing.getInt(44); + showPanTool = backing.getInt(48); + showZoomOutTool = backing.getInt(52); + } + + public void write() { + backing.putInt(0, showSelectionTool); + backing.putInt(4, showZoomTool); + backing.putInt(8, showPointTool); + backing.putInt(12, showLineTool); + backing.putInt(16, showRectangleTool); + backing.putInt(20, showOvalTool); + backing.putInt(24, showPolygonTool); + backing.putInt(28, showClosedFreehandTool); + backing.putInt(32, showPolyLineTool); + backing.putInt(36, showFreehandTool); + backing.putInt(40, showAnnulusTool); + backing.putInt(44, showRotatedRectangleTool); + backing.putInt(48, showPanTool); + backing.putInt(52, showZoomOutTool); + } + + public int size() { + return 68; + } + } + + public static class SpokeOptions extends DisposedStruct { + public int threshold; // Specifies the threshold value for the contrast of + // the edge. + public int width; // The number of pixels that the function averages to find + // the contrast at either side of the edge. + public int steepness; // The span, in pixels, of the slope of the edge + // projected along the path specified by the input + // points. + public double subsamplingRatio; // The angle, in degrees, between each + // radial search line in the spoke. + public InterpolationMethod subpixelType; // The method for interpolating. + public int subpixelDivisions; // The number of samples the function obtains + // from a pixel. + + private void init() { + + } + + public SpokeOptions() { + super(32); + init(); + } + + public SpokeOptions(int threshold, int width, int steepness, double subsamplingRatio, + InterpolationMethod subpixelType, int subpixelDivisions) { + super(32); + this.threshold = threshold; + this.width = width; + this.steepness = steepness; + this.subsamplingRatio = subsamplingRatio; + this.subpixelType = subpixelType; + this.subpixelDivisions = subpixelDivisions; + } + + protected SpokeOptions(ByteBuffer backing, int offset) { + super(backing, offset, 32); + init(); + } + + protected SpokeOptions(long nativeObj, boolean owned) { + super(nativeObj, owned, 32); + init(); + } + + protected void setBuffer(ByteBuffer backing, int offset) { + super.setBuffer(backing, offset, 32); + } + + public void read() { + threshold = backing.getInt(0); + width = backing.getInt(4); + steepness = backing.getInt(8); + subsamplingRatio = backing.getDouble(16); + subpixelType = InterpolationMethod.fromValue(backing.getInt(24)); + subpixelDivisions = backing.getInt(28); + } + + public void write() { + backing.putInt(0, threshold); + backing.putInt(4, width); + backing.putInt(8, steepness); + backing.putDouble(16, subsamplingRatio); + if (subpixelType != null) + backing.putInt(24, subpixelType.getValue()); + backing.putInt(28, subpixelDivisions); + } + + public int size() { + return 32; + } + } + + /** + * Globals + */ + public static final Rect NO_RECT = new Rect(0, 0, 0x7FFFFFFF, 0x7FFFFFFF); + public static final RotatedRect NO_ROTATED_RECT = + new RotatedRect(0, 0, 0x7FFFFFFF, 0x7FFFFFFF, 0); + public static final Point NO_POINT = new Point(-1, -1); + public static final PointFloat NO_POINT_FLOAT = new PointFloat(-1.0, -1.0); + public static final PointFloat NO_OFFSET = new PointFloat(0.0, 0.0); + public static final RGBValue RGB_TRANSPARENT = new RGBValue(0, 0, 0, 1); + public static final RGBValue RGB_RED = new RGBValue(0, 0, 255, 0); + public static final RGBValue RGB_BLUE = new RGBValue(255, 0, 0, 0); + public static final RGBValue RGB_GREEN = new RGBValue(0, 255, 0, 0); + public static final RGBValue RGB_YELLOW = new RGBValue(0, 255, 255, 0); + public static final RGBValue RGB_WHITE = new RGBValue(255, 255, 255, 0); + public static final RGBValue RGB_BLACK = new RGBValue(0, 0, 0, 0); + + /** + * Logical functions + */ + + public static void imaqAnd(Image dest, Image sourceA, Image sourceB) { + + _imaqAnd(dest.getAddress(), sourceA.getAddress(), sourceB.getAddress()); + + } + + private static native void _imaqAnd(long dest, long sourceA, long sourceB); + + public static void imaqCompare(Image dest, Image source, Image compareImage, + ComparisonFunction compare) { + + _imaqCompare(dest.getAddress(), source.getAddress(), compareImage.getAddress(), + compare.getValue()); + + } + + private static native void _imaqCompare(long dest, long source, long compareImage, int compare); + + public static void imaqLogicalDifference(Image dest, Image sourceA, Image sourceB) { + + _imaqLogicalDifference(dest.getAddress(), sourceA.getAddress(), sourceB.getAddress()); + + } + + private static native void _imaqLogicalDifference(long dest, long sourceA, long sourceB); + + public static void imaqNand(Image dest, Image sourceA, Image sourceB) { + + _imaqNand(dest.getAddress(), sourceA.getAddress(), sourceB.getAddress()); + + } + + private static native void _imaqNand(long dest, long sourceA, long sourceB); + + public static void imaqNor(Image dest, Image sourceA, Image sourceB) { + + _imaqNor(dest.getAddress(), sourceA.getAddress(), sourceB.getAddress()); + + } + + private static native void _imaqNor(long dest, long sourceA, long sourceB); + + public static void imaqOr(Image dest, Image sourceA, Image sourceB) { + + _imaqOr(dest.getAddress(), sourceA.getAddress(), sourceB.getAddress()); + + } + + private static native void _imaqOr(long dest, long sourceA, long sourceB); + + public static void imaqXnor(Image dest, Image sourceA, Image sourceB) { + + _imaqXnor(dest.getAddress(), sourceA.getAddress(), sourceB.getAddress()); + + } + + private static native void _imaqXnor(long dest, long sourceA, long sourceB); + + public static void imaqXor(Image dest, Image sourceA, Image sourceB) { + + _imaqXor(dest.getAddress(), sourceA.getAddress(), sourceB.getAddress()); + + } + + private static native void _imaqXor(long dest, long sourceA, long sourceB); + + /** + * Particle Analysis functions + */ + + public static int imaqCountParticles(Image image, int connectivity8) { + ByteBuffer rv_buf = ByteBuffer.allocateDirect(8).order(ByteOrder.nativeOrder()); + long rv_addr = getByteBufferAddress(rv_buf); + _imaqCountParticles(image.getAddress(), connectivity8, rv_addr + 0); + int numParticles; + numParticles = rv_buf.getInt(0); + return numParticles; + } + + private static native void _imaqCountParticles(long image, int connectivity8, long numParticles); + + public static double imaqMeasureParticle(Image image, int particleNumber, int calibrated, + MeasurementType measurement) { + ByteBuffer rv_buf = ByteBuffer.allocateDirect(8).order(ByteOrder.nativeOrder()); + long rv_addr = getByteBufferAddress(rv_buf); + _imaqMeasureParticle(image.getAddress(), particleNumber, calibrated, measurement.getValue(), + rv_addr + 0); + double value; + value = rv_buf.getDouble(0); + return value; + } + + private static native void _imaqMeasureParticle(long image, int particleNumber, int calibrated, + int measurement, long value); + + public static MeasureParticlesReport imaqMeasureParticles(Image image, + MeasureParticlesCalibrationMode calibrationMode, MeasurementType[] measurements) { + int numMeasurements = measurements.length; + ByteBuffer measurements_buf = null; + measurements_buf = + ByteBuffer.allocateDirect(measurements.length * 4).order(ByteOrder.nativeOrder()); + for (int i = 0, off = 0; i < measurements.length; i++, off += 4) { + if (measurements != null) + measurements_buf.putInt(off, measurements[i].getValue()); + } + long jn_rv = + _imaqMeasureParticles(image.getAddress(), calibrationMode.getValue(), + getByteBufferAddress(measurements_buf), numMeasurements); + + return new MeasureParticlesReport(jn_rv, true); + } + + private static native long _imaqMeasureParticles(long image, int calibrationMode, + long measurements, int numMeasurements); + + public static int imaqParticleFilter4(Image dest, Image source, + ParticleFilterCriteria2[] criteria, ParticleFilterOptions2 options, ROI roi) { + int criteriaCount = criteria.length; + ByteBuffer criteria_buf = null; + criteria_buf = ByteBuffer.allocateDirect(criteria.length * 20).order(ByteOrder.nativeOrder()); + for (int i = 0, off = 0; i < criteria.length; i++, off += 20) { + criteria[i].setBuffer(criteria_buf, off); + criteria[i].write(); + } + ByteBuffer rv_buf = ByteBuffer.allocateDirect(8).order(ByteOrder.nativeOrder()); + long rv_addr = getByteBufferAddress(rv_buf); + _imaqParticleFilter4(dest.getAddress(), source.getAddress(), + getByteBufferAddress(criteria_buf), criteriaCount, options.getAddress(), roi == null ? 0 + : roi.getAddress(), rv_addr + 0); + int numParticles; + numParticles = rv_buf.getInt(0); + return numParticles; + } + + private static native void _imaqParticleFilter4(long dest, long source, long criteria, + int criteriaCount, long options, long roi, long numParticles); + + /** + * Morphology functions + */ + + public static void imaqConvexHull(Image dest, Image source, int connectivity8) { + + _imaqConvexHull(dest.getAddress(), source.getAddress(), connectivity8); + + } + + private static native void _imaqConvexHull(long dest, long source, int connectivity8); + + public static void imaqDanielssonDistance(Image dest, Image source) { + + _imaqDanielssonDistance(dest.getAddress(), source.getAddress()); + + } + + private static native void _imaqDanielssonDistance(long dest, long source); + + public static void imaqFillHoles(Image dest, Image source, int connectivity8) { + + _imaqFillHoles(dest.getAddress(), source.getAddress(), connectivity8); + + } + + private static native void _imaqFillHoles(long dest, long source, int connectivity8); + + public static class FindCirclesResult { + public CircleReport[] array; + private long array_addr; + + private FindCirclesResult(ByteBuffer rv_buf, long jn_rv) { + array_addr = jn_rv; + int array_numCircles; + array_numCircles = rv_buf.getInt(0); + array = new CircleReport[array_numCircles]; + if (array_numCircles > 0 && array_addr != 0) { + ByteBuffer bb = newDirectByteBuffer(array_addr, array_numCircles * 16); + for (int i = 0, off = 0; i < array_numCircles; i++, off += 16) { + array[i] = new CircleReport(bb, off); + array[i].read(); + } + } + } + + @Override + protected void finalize() throws Throwable { + imaqDispose(array_addr); + super.finalize(); + } + } + + public static FindCirclesResult imaqFindCircles(Image dest, Image source, float minRadius, + float maxRadius) { + ByteBuffer rv_buf = ByteBuffer.allocateDirect(8).order(ByteOrder.nativeOrder()); + long rv_addr = getByteBufferAddress(rv_buf); + long jn_rv = + _imaqFindCircles(dest.getAddress(), source.getAddress(), minRadius, maxRadius, rv_addr + 0); + FindCirclesResult rv = new FindCirclesResult(rv_buf, jn_rv); + return rv; + } + + private static native long _imaqFindCircles(long dest, long source, float minRadius, + float maxRadius, long numCircles); + + public static int imaqLabel2(Image dest, Image source, int connectivity8) { + ByteBuffer rv_buf = ByteBuffer.allocateDirect(8).order(ByteOrder.nativeOrder()); + long rv_addr = getByteBufferAddress(rv_buf); + _imaqLabel2(dest.getAddress(), source.getAddress(), connectivity8, rv_addr + 0); + int particleCount; + particleCount = rv_buf.getInt(0); + return particleCount; + } + + private static native void _imaqLabel2(long dest, long source, int connectivity8, + long particleCount); + + public static void imaqMorphology(Image dest, Image source, MorphologyMethod method, + StructuringElement structuringElement) { + + _imaqMorphology(dest.getAddress(), source.getAddress(), method.getValue(), + structuringElement == null ? 0 : structuringElement.getAddress()); + + } + + private static native void _imaqMorphology(long dest, long source, int method, + long structuringElement); + + public static void imaqRejectBorder(Image dest, Image source, int connectivity8) { + + _imaqRejectBorder(dest.getAddress(), source.getAddress(), connectivity8); + + } + + private static native void _imaqRejectBorder(long dest, long source, int connectivity8); + + public static void imaqSegmentation(Image dest, Image source) { + + _imaqSegmentation(dest.getAddress(), source.getAddress()); + + } + + private static native void _imaqSegmentation(long dest, long source); + + public static void imaqSeparation(Image dest, Image source, int erosions, + StructuringElement structuringElement) { + + _imaqSeparation(dest.getAddress(), source.getAddress(), erosions, + structuringElement == null ? 0 : structuringElement.getAddress()); + + } + + private static native void _imaqSeparation(long dest, long source, int erosions, + long structuringElement); + + public static void imaqSimpleDistance(Image dest, Image source, + StructuringElement structuringElement) { + + _imaqSimpleDistance(dest.getAddress(), source.getAddress(), structuringElement == null ? 0 + : structuringElement.getAddress()); + + } + + private static native void _imaqSimpleDistance(long dest, long source, long structuringElement); + + public static void imaqSizeFilter(Image dest, Image source, int connectivity8, int erosions, + SizeType keepSize, StructuringElement structuringElement) { + + _imaqSizeFilter(dest.getAddress(), source.getAddress(), connectivity8, erosions, + keepSize.getValue(), structuringElement == null ? 0 : structuringElement.getAddress()); + + } + + private static native void _imaqSizeFilter(long dest, long source, int connectivity8, + int erosions, int keepSize, long structuringElement); + + public static void imaqSkeleton(Image dest, Image source, SkeletonMethod method) { + + _imaqSkeleton(dest.getAddress(), source.getAddress(), method.getValue()); + + } + + private static native void _imaqSkeleton(long dest, long source, int method); + + /** + * Acquisition functions + */ + + /** + * Arithmetic functions + */ + + public static void imaqAbsoluteDifference(Image dest, Image sourceA, Image sourceB) { + + _imaqAbsoluteDifference(dest.getAddress(), sourceA.getAddress(), sourceB.getAddress()); + + } + + private static native void _imaqAbsoluteDifference(long dest, long sourceA, long sourceB); + + public static void imaqAdd(Image dest, Image sourceA, Image sourceB) { + + _imaqAdd(dest.getAddress(), sourceA.getAddress(), sourceB.getAddress()); + + } + + private static native void _imaqAdd(long dest, long sourceA, long sourceB); + + public static void imaqAverage(Image dest, Image sourceA, Image sourceB) { + + _imaqAverage(dest.getAddress(), sourceA.getAddress(), sourceB.getAddress()); + + } + + private static native void _imaqAverage(long dest, long sourceA, long sourceB); + + public static void imaqDivide2(Image dest, Image sourceA, Image sourceB, RoundingMode roundingMode) { + + _imaqDivide2(dest.getAddress(), sourceA.getAddress(), sourceB.getAddress(), + roundingMode.getValue()); + + } + + private static native void _imaqDivide2(long dest, long sourceA, long sourceB, int roundingMode); + + public static void imaqMax(Image dest, Image sourceA, Image sourceB) { + + _imaqMax(dest.getAddress(), sourceA.getAddress(), sourceB.getAddress()); + + } + + private static native void _imaqMax(long dest, long sourceA, long sourceB); + + public static void imaqMin(Image dest, Image sourceA, Image sourceB) { + + _imaqMin(dest.getAddress(), sourceA.getAddress(), sourceB.getAddress()); + + } + + private static native void _imaqMin(long dest, long sourceA, long sourceB); + + public static void imaqModulo(Image dest, Image sourceA, Image sourceB) { + + _imaqModulo(dest.getAddress(), sourceA.getAddress(), sourceB.getAddress()); + + } + + private static native void _imaqModulo(long dest, long sourceA, long sourceB); + + public static void imaqMulDiv(Image dest, Image sourceA, Image sourceB, float value) { + + _imaqMulDiv(dest.getAddress(), sourceA.getAddress(), sourceB.getAddress(), value); + + } + + private static native void _imaqMulDiv(long dest, long sourceA, long sourceB, float value); + + public static void imaqMultiply(Image dest, Image sourceA, Image sourceB) { + + _imaqMultiply(dest.getAddress(), sourceA.getAddress(), sourceB.getAddress()); + + } + + private static native void _imaqMultiply(long dest, long sourceA, long sourceB); + + public static void imaqSubtract(Image dest, Image sourceA, Image sourceB) { + + _imaqSubtract(dest.getAddress(), sourceA.getAddress(), sourceB.getAddress()); + + } + + private static native void _imaqSubtract(long dest, long sourceA, long sourceB); + + /** + * Caliper functions + */ + + public static class CaliperToolResult { + public CaliperReport[] array; + private long array_addr; + + private CaliperToolResult(ByteBuffer rv_buf, long jn_rv) { + array_addr = jn_rv; + int array_numEdgePairs; + array_numEdgePairs = rv_buf.getInt(0); + array = new CaliperReport[array_numEdgePairs]; + if (array_numEdgePairs > 0 && array_addr != 0) { + ByteBuffer bb = newDirectByteBuffer(array_addr, array_numEdgePairs * 32); + for (int i = 0, off = 0; i < array_numEdgePairs; i++, off += 32) { + array[i] = new CaliperReport(bb, off); + array[i].read(); + } + } + } + + @Override + protected void finalize() throws Throwable { + imaqDispose(array_addr); + super.finalize(); + } + } + + public static CaliperToolResult imaqCaliperTool(Image image, Point[] points, + EdgeOptions edgeOptions, CaliperOptions caliperOptions) { + int numPoints = points.length; + ByteBuffer points_buf = null; + points_buf = ByteBuffer.allocateDirect(points.length * 8).order(ByteOrder.nativeOrder()); + for (int i = 0, off = 0; i < points.length; i++, off += 8) { + points[i].setBuffer(points_buf, off); + points[i].write(); + } + ByteBuffer rv_buf = ByteBuffer.allocateDirect(8).order(ByteOrder.nativeOrder()); + long rv_addr = getByteBufferAddress(rv_buf); + long jn_rv = + _imaqCaliperTool(image.getAddress(), getByteBufferAddress(points_buf), numPoints, + edgeOptions.getAddress(), caliperOptions.getAddress(), rv_addr + 0); + CaliperToolResult rv = new CaliperToolResult(rv_buf, jn_rv); + return rv; + } + + private static native long _imaqCaliperTool(long image, long points, int numPoints, + long edgeOptions, long caliperOptions, long numEdgePairs); + + public static class ConcentricRake2Result { + public EdgeOptions2 edgeOptions; + public ConcentricRakeReport2 val; + + private ConcentricRake2Result(ByteBuffer rv_buf) { + edgeOptions = new EdgeOptions2(rv_buf, 0); + edgeOptions.read(); + } + } + + public static ConcentricRake2Result imaqConcentricRake2(Image image, ROI roi, + ConcentricRakeDirection direction, EdgeProcess process, int stepSize) { + ByteBuffer rv_buf = ByteBuffer.allocateDirect(8).order(ByteOrder.nativeOrder()); + long rv_addr = getByteBufferAddress(rv_buf); + long jn_rv = + _imaqConcentricRake2(image.getAddress(), roi.getAddress(), direction.getValue(), + process.getValue(), stepSize, rv_addr + 0); + ConcentricRake2Result rv = new ConcentricRake2Result(rv_buf); + rv.val = new ConcentricRakeReport2(jn_rv, true); + return rv; + } + + private static native long _imaqConcentricRake2(long image, long roi, int direction, int process, + int stepSize, long edgeOptions); + + public static class DetectExtremesResult { + public ExtremeReport[] array; + private long array_addr; + + private DetectExtremesResult(ByteBuffer rv_buf, long jn_rv) { + array_addr = jn_rv; + int array_numExtremes; + array_numExtremes = rv_buf.getInt(0); + array = new ExtremeReport[array_numExtremes]; + if (array_numExtremes > 0 && array_addr != 0) { + ByteBuffer bb = newDirectByteBuffer(array_addr, array_numExtremes * 24); + for (int i = 0, off = 0; i < array_numExtremes; i++, off += 24) { + array[i] = new ExtremeReport(bb, off); + array[i].read(); + } + } + } + + @Override + protected void finalize() throws Throwable { + imaqDispose(array_addr); + super.finalize(); + } + } + + public static DetectExtremesResult imaqDetectExtremes(double[] pixels, DetectionMode mode, + DetectExtremesOptions options) { + int numPixels = pixels.length; + ByteBuffer pixels_buf = null; + pixels_buf = ByteBuffer.allocateDirect(pixels.length * 8).order(ByteOrder.nativeOrder()); + pixels_buf.asDoubleBuffer().put(pixels).rewind(); + ByteBuffer rv_buf = ByteBuffer.allocateDirect(8).order(ByteOrder.nativeOrder()); + long rv_addr = getByteBufferAddress(rv_buf); + long jn_rv = + _imaqDetectExtremes(getByteBufferAddress(pixels_buf), numPixels, mode.getValue(), + options.getAddress(), rv_addr + 0); + DetectExtremesResult rv = new DetectExtremesResult(rv_buf, jn_rv); + return rv; + } + + private static native long _imaqDetectExtremes(long pixels, int numPixels, int mode, + long options, long numExtremes); + + public static double imaqDetectRotation(Image referenceImage, Image testImage, + PointFloat referenceCenter, PointFloat testCenter, int radius, float precision) { + ByteBuffer rv_buf = ByteBuffer.allocateDirect(8).order(ByteOrder.nativeOrder()); + long rv_addr = getByteBufferAddress(rv_buf); + _imaqDetectRotation(referenceImage.getAddress(), testImage.getAddress(), + referenceCenter.getAddress(), testCenter.getAddress(), radius, precision, rv_addr + 0); + double angle; + angle = rv_buf.getDouble(0); + return angle; + } + + private static native void _imaqDetectRotation(long referenceImage, long testImage, + long referenceCenter, long testCenter, int radius, float precision, long angle); + + public static class EdgeTool4Result { + public EdgeOptions2 edgeOptions; + public EdgeReport2 val; + + private EdgeTool4Result(ByteBuffer rv_buf) { + edgeOptions = new EdgeOptions2(rv_buf, 0); + edgeOptions.read(); + } + } + + public static EdgeTool4Result imaqEdgeTool4(Image image, ROI roi, EdgeProcess processType, + int reverseDirection) { + ByteBuffer rv_buf = ByteBuffer.allocateDirect(8).order(ByteOrder.nativeOrder()); + long rv_addr = getByteBufferAddress(rv_buf); + long jn_rv = + _imaqEdgeTool4(image.getAddress(), roi.getAddress(), processType.getValue(), rv_addr + 0, + reverseDirection); + EdgeTool4Result rv = new EdgeTool4Result(rv_buf); + rv.val = new EdgeReport2(jn_rv, true); + return rv; + } + + private static native long _imaqEdgeTool4(long image, long roi, int processType, + long edgeOptions, int reverseDirection); + + public static FindEdgeReport imaqFindEdge2(Image image, ROI roi, CoordinateSystem baseSystem, + CoordinateSystem newSystem, FindEdgeOptions2 findEdgeOptions, + StraightEdgeOptions straightEdgeOptions) { + + long jn_rv = + _imaqFindEdge2(image.getAddress(), roi.getAddress(), baseSystem.getAddress(), + newSystem.getAddress(), findEdgeOptions.getAddress(), straightEdgeOptions.getAddress()); + + return new FindEdgeReport(jn_rv, true); + } + + private static native long _imaqFindEdge2(long image, long roi, long baseSystem, long newSystem, + long findEdgeOptions, long straightEdgeOptions); + + public static class FindTransformRect2Result { + public CoordinateSystem baseSystem; + public CoordinateSystem newSystem; + public AxisReport axisReport; + + private FindTransformRect2Result(ByteBuffer rv_buf) { + baseSystem = new CoordinateSystem(rv_buf, 0); + baseSystem.read(); + newSystem = new CoordinateSystem(rv_buf, 8); + newSystem.read(); + axisReport = new AxisReport(rv_buf, 16); + axisReport.read(); + } + } + + public static FindTransformRect2Result imaqFindTransformRect2(Image image, ROI roi, + FindTransformMode mode, FindTransformRectOptions2 findTransformOptions, + StraightEdgeOptions straightEdgeOptions) { + ByteBuffer rv_buf = ByteBuffer.allocateDirect(8 + 8 + 8).order(ByteOrder.nativeOrder()); + long rv_addr = getByteBufferAddress(rv_buf); + _imaqFindTransformRect2(image.getAddress(), roi.getAddress(), mode.getValue(), rv_addr + 0, + rv_addr + 8, findTransformOptions.getAddress(), straightEdgeOptions.getAddress(), + rv_addr + 16); + FindTransformRect2Result rv = new FindTransformRect2Result(rv_buf); + return rv; + } + + private static native void _imaqFindTransformRect2(long image, long roi, int mode, + long baseSystem, long newSystem, long findTransformOptions, long straightEdgeOptions, + long axisReport); + + public static class FindTransformRects2Result { + public CoordinateSystem baseSystem; + public CoordinateSystem newSystem; + public AxisReport axisReport; + + private FindTransformRects2Result(ByteBuffer rv_buf) { + baseSystem = new CoordinateSystem(rv_buf, 0); + baseSystem.read(); + newSystem = new CoordinateSystem(rv_buf, 8); + newSystem.read(); + axisReport = new AxisReport(rv_buf, 16); + axisReport.read(); + } + } + + public static FindTransformRects2Result imaqFindTransformRects2(Image image, ROI primaryROI, + ROI secondaryROI, FindTransformMode mode, FindTransformRectsOptions2 findTransformOptions, + StraightEdgeOptions primaryStraightEdgeOptions, + StraightEdgeOptions secondaryStraightEdgeOptions) { + ByteBuffer rv_buf = ByteBuffer.allocateDirect(8 + 8 + 8).order(ByteOrder.nativeOrder()); + long rv_addr = getByteBufferAddress(rv_buf); + _imaqFindTransformRects2(image.getAddress(), primaryROI.getAddress(), + secondaryROI.getAddress(), mode.getValue(), rv_addr + 0, rv_addr + 8, + findTransformOptions.getAddress(), primaryStraightEdgeOptions.getAddress(), + secondaryStraightEdgeOptions.getAddress(), rv_addr + 16); + FindTransformRects2Result rv = new FindTransformRects2Result(rv_buf); + return rv; + } + + private static native void _imaqFindTransformRects2(long image, long primaryROI, + long secondaryROI, int mode, long baseSystem, long newSystem, long findTransformOptions, + long primaryStraightEdgeOptions, long secondaryStraightEdgeOptions, long axisReport); + + public static float imaqLineGaugeTool2(Image image, Point start, Point end, + LineGaugeMethod method, EdgeOptions edgeOptions, CoordinateTransform2 transform) { + ByteBuffer rv_buf = ByteBuffer.allocateDirect(8).order(ByteOrder.nativeOrder()); + long rv_addr = getByteBufferAddress(rv_buf); + _imaqLineGaugeTool2(image.getAddress(), start.getAddress(), end.getAddress(), + method.getValue(), edgeOptions.getAddress(), transform.getAddress(), rv_addr + 0); + float distance; + distance = rv_buf.getFloat(0); + return distance; + } + + private static native void _imaqLineGaugeTool2(long image, long start, long end, int method, + long edgeOptions, long transform, long distance); + + public static class Rake2Result { + public EdgeOptions2 edgeOptions; + public RakeReport2 val; + + private Rake2Result(ByteBuffer rv_buf) { + edgeOptions = new EdgeOptions2(rv_buf, 0); + edgeOptions.read(); + } + } + + public static Rake2Result imaqRake2(Image image, ROI roi, RakeDirection direction, + EdgeProcess process, int stepSize) { + ByteBuffer rv_buf = ByteBuffer.allocateDirect(8).order(ByteOrder.nativeOrder()); + long rv_addr = getByteBufferAddress(rv_buf); + long jn_rv = + _imaqRake2(image.getAddress(), roi.getAddress(), direction.getValue(), process.getValue(), + stepSize, rv_addr + 0); + Rake2Result rv = new Rake2Result(rv_buf); + rv.val = new RakeReport2(jn_rv, true); + return rv; + } + + private static native long _imaqRake2(long image, long roi, int direction, int process, + int stepSize, long edgeOptions); + + public static class SimpleEdgeResult { + public PointFloat[] array; + private long array_addr; + + private SimpleEdgeResult(ByteBuffer rv_buf, long jn_rv) { + array_addr = jn_rv; + int array_numEdges; + array_numEdges = rv_buf.getInt(0); + array = new PointFloat[array_numEdges]; + if (array_numEdges > 0 && array_addr != 0) { + ByteBuffer bb = newDirectByteBuffer(array_addr, array_numEdges * 8); + for (int i = 0, off = 0; i < array_numEdges; i++, off += 8) { + array[i] = new PointFloat(bb, off); + array[i].read(); + } + } + } + + @Override + protected void finalize() throws Throwable { + imaqDispose(array_addr); + super.finalize(); + } + } + + public static SimpleEdgeResult imaqSimpleEdge(Image image, Point[] points, + SimpleEdgeOptions options) { + int numPoints = points.length; + ByteBuffer points_buf = null; + points_buf = ByteBuffer.allocateDirect(points.length * 8).order(ByteOrder.nativeOrder()); + for (int i = 0, off = 0; i < points.length; i++, off += 8) { + points[i].setBuffer(points_buf, off); + points[i].write(); + } + ByteBuffer rv_buf = ByteBuffer.allocateDirect(8).order(ByteOrder.nativeOrder()); + long rv_addr = getByteBufferAddress(rv_buf); + long jn_rv = + _imaqSimpleEdge(image.getAddress(), getByteBufferAddress(points_buf), numPoints, + options.getAddress(), rv_addr + 0); + SimpleEdgeResult rv = new SimpleEdgeResult(rv_buf, jn_rv); + return rv; + } + + private static native long _imaqSimpleEdge(long image, long points, int numPoints, long options, + long numEdges); + + public static class Spoke2Result { + public EdgeOptions2 edgeOptions; + public SpokeReport2 val; + + private Spoke2Result(ByteBuffer rv_buf) { + edgeOptions = new EdgeOptions2(rv_buf, 0); + edgeOptions.read(); + } + } + + public static Spoke2Result imaqSpoke2(Image image, ROI roi, SpokeDirection direction, + EdgeProcess process, int stepSize) { + ByteBuffer rv_buf = ByteBuffer.allocateDirect(8).order(ByteOrder.nativeOrder()); + long rv_addr = getByteBufferAddress(rv_buf); + long jn_rv = + _imaqSpoke2(image.getAddress(), roi.getAddress(), direction.getValue(), process.getValue(), + stepSize, rv_addr + 0); + Spoke2Result rv = new Spoke2Result(rv_buf); + rv.val = new SpokeReport2(jn_rv, true); + return rv; + } + + private static native long _imaqSpoke2(long image, long roi, int direction, int process, + int stepSize, long edgeOptions); + + public static StraightEdgeReport2 imaqStraightEdge(Image image, ROI roi, + SearchDirection searchDirection, EdgeOptions2 edgeOptions, + StraightEdgeOptions straightEdgeOptions) { + + long jn_rv = + _imaqStraightEdge(image.getAddress(), roi.getAddress(), searchDirection.getValue(), + edgeOptions.getAddress(), straightEdgeOptions.getAddress()); + + return new StraightEdgeReport2(jn_rv, true); + } + + private static native long _imaqStraightEdge(long image, long roi, int searchDirection, + long edgeOptions, long straightEdgeOptions); + + public static StraightEdgeReport2 imaqStraightEdge2(Image image, ROI roi, + SearchDirection searchDirection, EdgeOptions2 edgeOptions, + StraightEdgeOptions straightEdgeOptions, int optimizedMode) { + + long jn_rv = + _imaqStraightEdge2(image.getAddress(), roi.getAddress(), searchDirection.getValue(), + edgeOptions.getAddress(), straightEdgeOptions.getAddress(), optimizedMode); + + return new StraightEdgeReport2(jn_rv, true); + } + + private static native long _imaqStraightEdge2(long image, long roi, int searchDirection, + long edgeOptions, long straightEdgeOptions, int optimizedMode); + + /** + * Spatial Filters functions + */ + + public static void imaqCannyEdgeFilter(Image dest, Image source, CannyOptions options) { + + _imaqCannyEdgeFilter(dest.getAddress(), source.getAddress(), + options == null ? 0 : options.getAddress()); + + } + + private static native void _imaqCannyEdgeFilter(long dest, long source, long options); + + public static void imaqCorrelate(Image dest, Image source, Image templateImage, Rect rect) { + + _imaqCorrelate(dest.getAddress(), source.getAddress(), templateImage.getAddress(), + rect.getAddress()); + + } + + private static native void _imaqCorrelate(long dest, long source, long templateImage, long rect); + + public static void imaqEdgeFilter(Image dest, Image source, OutlineMethod method, Image mask) { + + _imaqEdgeFilter(dest.getAddress(), source.getAddress(), method.getValue(), mask == null ? 0 + : mask.getAddress()); + + } + + private static native void _imaqEdgeFilter(long dest, long source, int method, long mask); + + public static void imaqLowPass(Image dest, Image source, int width, int height, float tolerance, + Image mask) { + + _imaqLowPass(dest.getAddress(), source.getAddress(), width, height, tolerance, mask == null ? 0 + : mask.getAddress()); + + } + + private static native void _imaqLowPass(long dest, long source, int width, int height, + float tolerance, long mask); + + public static void imaqMedianFilter(Image dest, Image source, int width, int height, Image mask) { + + _imaqMedianFilter(dest.getAddress(), source.getAddress(), width, height, mask == null ? 0 + : mask.getAddress()); + + } + + private static native void _imaqMedianFilter(long dest, long source, int width, int height, + long mask); + + public static void imaqNthOrderFilter(Image dest, Image source, int width, int height, int n, + Image mask) { + + _imaqNthOrderFilter(dest.getAddress(), source.getAddress(), width, height, n, mask == null ? 0 + : mask.getAddress()); + + } + + private static native void _imaqNthOrderFilter(long dest, long source, int width, int height, + int n, long mask); + + /** + * Drawing functions + */ + + public static void imaqDrawLineOnImage(Image dest, Image source, DrawMode mode, Point start, + Point end, float newPixelValue) { + + _imaqDrawLineOnImage(dest.getAddress(), source.getAddress(), mode.getValue(), + start.getAddress(), end.getAddress(), newPixelValue); + + } + + private static native void _imaqDrawLineOnImage(long dest, long source, int mode, long start, + long end, float newPixelValue); + + public static void imaqDrawShapeOnImage(Image dest, Image source, Rect rect, DrawMode mode, + ShapeMode shape, float newPixelValue) { + + _imaqDrawShapeOnImage(dest.getAddress(), source.getAddress(), rect.getAddress(), + mode.getValue(), shape.getValue(), newPixelValue); + + } + + private static native void _imaqDrawShapeOnImage(long dest, long source, long rect, int mode, + int shape, float newPixelValue); + + /** + * Interlacing functions + */ + + public static void imaqInterlaceCombine(Image frame, Image odd, Image even) { + + _imaqInterlaceCombine(frame.getAddress(), odd.getAddress(), even.getAddress()); + + } + + private static native void _imaqInterlaceCombine(long frame, long odd, long even); + + public static void imaqInterlaceSeparate(Image frame, Image odd, Image even) { + + _imaqInterlaceSeparate(frame.getAddress(), odd == null ? 0 : odd.getAddress(), even == null ? 0 + : even.getAddress()); + + } + + private static native void _imaqInterlaceSeparate(long frame, long odd, long even); + + /** + * Image Information functions + */ + + public static class EnumerateCustomKeysResult { + public String[] array; + private long array_addr; + + private EnumerateCustomKeysResult(ByteBuffer rv_buf, long jn_rv) { + array_addr = jn_rv; + int array_size; + array_size = rv_buf.getInt(0); + array = new String[array_size]; + if (array_size > 0 && array_addr != 0) { + ByteBuffer bb = newDirectByteBuffer(array_addr, array_size * 4); + for (int i = 0, off = 0; i < array_size; i++, off += 4) { + long addr = getPointer(bb, off); + if (addr == 0) + array[i] = null; + else { + ByteBuffer bb2 = newDirectByteBuffer(addr, 1000); // FIXME + while (bb2.get() != 0) { + } + byte[] bytes = new byte[bb2.position() - 1]; + bb2.rewind(); + getBytes(bb2, bytes, 0, bytes.length); + try { + array[i] = new String(bytes, "UTF-8"); + } catch (UnsupportedEncodingException e) { + array[i] = ""; + } + } + } + } + } + + @Override + protected void finalize() throws Throwable { + imaqDispose(array_addr); + super.finalize(); + } + } + + public static EnumerateCustomKeysResult imaqEnumerateCustomKeys(Image image) { + ByteBuffer rv_buf = ByteBuffer.allocateDirect(8).order(ByteOrder.nativeOrder()); + long rv_addr = getByteBufferAddress(rv_buf); + long jn_rv = _imaqEnumerateCustomKeys(image.getAddress(), rv_addr + 0); + EnumerateCustomKeysResult rv = new EnumerateCustomKeysResult(rv_buf, jn_rv); + return rv; + } + + private static native long _imaqEnumerateCustomKeys(long image, long size); + + public static int imaqGetBitDepth(Image image) { + ByteBuffer rv_buf = ByteBuffer.allocateDirect(8).order(ByteOrder.nativeOrder()); + long rv_addr = getByteBufferAddress(rv_buf); + _imaqGetBitDepth(image.getAddress(), rv_addr + 0); + int bitDepth; + bitDepth = rv_buf.getInt(0); + return bitDepth; + } + + private static native void _imaqGetBitDepth(long image, long bitDepth); + + public static int imaqGetBytesPerPixel(Image image) { + ByteBuffer rv_buf = ByteBuffer.allocateDirect(8).order(ByteOrder.nativeOrder()); + long rv_addr = getByteBufferAddress(rv_buf); + _imaqGetBytesPerPixel(image.getAddress(), rv_addr + 0); + int byteCount; + byteCount = rv_buf.getInt(0); + return byteCount; + } + + private static native void _imaqGetBytesPerPixel(long image, long byteCount); + + public static ImageInfo imaqGetImageInfo(Image image) { + ByteBuffer rv_buf = ByteBuffer.allocateDirect(8).order(ByteOrder.nativeOrder()); + long rv_addr = getByteBufferAddress(rv_buf); + _imaqGetImageInfo(image.getAddress(), rv_addr + 0); + ImageInfo info; + info = new ImageInfo(rv_buf, 0); + info.read(); + return info; + } + + private static native void _imaqGetImageInfo(long image, long info); + + public static class GetImageSizeResult { + public int width; + public int height; + + private GetImageSizeResult(ByteBuffer rv_buf) { + width = rv_buf.getInt(0); + height = rv_buf.getInt(8); + } + } + + public static GetImageSizeResult imaqGetImageSize(Image image) { + ByteBuffer rv_buf = ByteBuffer.allocateDirect(8 + 8).order(ByteOrder.nativeOrder()); + long rv_addr = getByteBufferAddress(rv_buf); + _imaqGetImageSize(image.getAddress(), rv_addr + 0, rv_addr + 8); + GetImageSizeResult rv = new GetImageSizeResult(rv_buf); + return rv; + } + + private static native void _imaqGetImageSize(long image, long width, long height); + + public static ImageType imaqGetImageType(Image image) { + ByteBuffer rv_buf = ByteBuffer.allocateDirect(8).order(ByteOrder.nativeOrder()); + long rv_addr = getByteBufferAddress(rv_buf); + _imaqGetImageType(image.getAddress(), rv_addr + 0); + ImageType type; + type = ImageType.fromValue(rv_buf.getInt(0)); + return type; + } + + private static native void _imaqGetImageType(long image, long type); + + public static Point imaqGetMaskOffset(Image image) { + ByteBuffer rv_buf = ByteBuffer.allocateDirect(8).order(ByteOrder.nativeOrder()); + long rv_addr = getByteBufferAddress(rv_buf); + _imaqGetMaskOffset(image.getAddress(), rv_addr + 0); + Point offset; + offset = new Point(rv_buf, 0); + offset.read(); + return offset; + } + + private static native void _imaqGetMaskOffset(long image, long offset); + + public static int imaqGetVisionInfoTypes(Image image) { + ByteBuffer rv_buf = ByteBuffer.allocateDirect(8).order(ByteOrder.nativeOrder()); + long rv_addr = getByteBufferAddress(rv_buf); + _imaqGetVisionInfoTypes(image.getAddress(), rv_addr + 0); + int present; + present = rv_buf.getInt(0); + return present; + } + + private static native void _imaqGetVisionInfoTypes(long image, long present); + + public static int imaqIsImageEmpty(Image image) { + ByteBuffer rv_buf = ByteBuffer.allocateDirect(8).order(ByteOrder.nativeOrder()); + long rv_addr = getByteBufferAddress(rv_buf); + _imaqIsImageEmpty(image.getAddress(), rv_addr + 0); + int empty; + empty = rv_buf.getInt(0); + return empty; + } + + private static native void _imaqIsImageEmpty(long image, long empty); + + public static RawData imaqReadCustomData(Image image, String key) { + ByteBuffer key_buf = null; + if (key != null) { + byte[] key_bytes; + try { + key_bytes = key.getBytes("UTF-8"); + } catch (UnsupportedEncodingException e) { + key_bytes = new byte[0]; + } + key_buf = ByteBuffer.allocateDirect(key_bytes.length + 1); + putBytes(key_buf, key_bytes, 0, key_bytes.length).put(key_bytes.length, (byte) 0); + } + ByteBuffer rv_buf = ByteBuffer.allocateDirect(8).order(ByteOrder.nativeOrder()); + long rv_addr = getByteBufferAddress(rv_buf); + long jn_rv = + _imaqReadCustomData(image.getAddress(), key == null ? 0 : getByteBufferAddress(key_buf), + rv_addr + 0); + int size; + RawData val; + size = rv_buf.getInt(0); + val = new RawData(jn_rv, false, size); + return val; + } + + private static native long _imaqReadCustomData(long image, long key, long size); + + public static void imaqRemoveCustomData(Image image, String key) { + ByteBuffer key_buf = null; + if (key != null) { + byte[] key_bytes; + try { + key_bytes = key.getBytes("UTF-8"); + } catch (UnsupportedEncodingException e) { + key_bytes = new byte[0]; + } + key_buf = ByteBuffer.allocateDirect(key_bytes.length + 1); + putBytes(key_buf, key_bytes, 0, key_bytes.length).put(key_bytes.length, (byte) 0); + } + _imaqRemoveCustomData(image.getAddress(), key == null ? 0 : getByteBufferAddress(key_buf)); + + } + + private static native void _imaqRemoveCustomData(long image, long key); + + public static void imaqRemoveVisionInfo2(Image image, int info) { + + _imaqRemoveVisionInfo2(image.getAddress(), info); + + } + + private static native void _imaqRemoveVisionInfo2(long image, int info); + + public static void imaqSetBitDepth(Image image, int bitDepth) { + + _imaqSetBitDepth(image.getAddress(), bitDepth); + + } + + private static native void _imaqSetBitDepth(long image, int bitDepth); + + public static void imaqSetImageSize(Image image, int width, int height) { + + _imaqSetImageSize(image.getAddress(), width, height); + + } + + private static native void _imaqSetImageSize(long image, int width, int height); + + public static void imaqSetMaskOffset(Image image, Point offset) { + + _imaqSetMaskOffset(image.getAddress(), offset.getAddress()); + + } + + private static native void _imaqSetMaskOffset(long image, long offset); + + public static void imaqWriteCustomData(Image image, String key, RawData data, int size) { + ByteBuffer key_buf = null; + if (key != null) { + byte[] key_bytes; + try { + key_bytes = key.getBytes("UTF-8"); + } catch (UnsupportedEncodingException e) { + key_bytes = new byte[0]; + } + key_buf = ByteBuffer.allocateDirect(key_bytes.length + 1); + putBytes(key_buf, key_bytes, 0, key_bytes.length).put(key_bytes.length, (byte) 0); + } + _imaqWriteCustomData(image.getAddress(), key == null ? 0 : getByteBufferAddress(key_buf), + data.getAddress(), size); + + } + + private static native void _imaqWriteCustomData(long image, long key, long data, int size); + + /** + * Display functions + */ + + /** + * Image Manipulation functions + */ + + public static void imaqCopyRect(Image dest, Image source, Rect rect, Point destLoc) { + + _imaqCopyRect(dest.getAddress(), source.getAddress(), rect.getAddress(), destLoc.getAddress()); + + } + + private static native void _imaqCopyRect(long dest, long source, long rect, long destLoc); + + public static void imaqDuplicate(Image dest, Image source) { + + _imaqDuplicate(dest.getAddress(), source.getAddress()); + + } + + private static native void _imaqDuplicate(long dest, long source); + + public static RawData imaqFlatten(Image image, FlattenType type, CompressionType compression, + int quality) { + ByteBuffer rv_buf = ByteBuffer.allocateDirect(8).order(ByteOrder.nativeOrder()); + long rv_addr = getByteBufferAddress(rv_buf); + long jn_rv = + _imaqFlatten(image.getAddress(), type.getValue(), compression.getValue(), quality, + rv_addr + 0); + int size; + RawData val; + size = rv_buf.getInt(0); + val = new RawData(jn_rv, true, size); + return val; + } + + private static native long _imaqFlatten(long image, int type, int compression, int quality, + long size); + + public static void imaqFlip(Image dest, Image source, FlipAxis axis) { + + _imaqFlip(dest.getAddress(), source.getAddress(), axis.getValue()); + + } + + private static native void _imaqFlip(long dest, long source, int axis); + + public static void imaqMask(Image dest, Image source, Image mask) { + + _imaqMask(dest.getAddress(), source.getAddress(), mask.getAddress()); + + } + + private static native void _imaqMask(long dest, long source, long mask); + + public static void imaqResample(Image dest, Image source, int newWidth, int newHeight, + InterpolationMethod method, Rect rect) { + + _imaqResample(dest.getAddress(), source.getAddress(), newWidth, newHeight, method.getValue(), + rect.getAddress()); + + } + + private static native void _imaqResample(long dest, long source, int newWidth, int newHeight, + int method, long rect); + + public static void imaqScale(Image dest, Image source, int xScale, int yScale, + ScalingMode scaleMode, Rect rect) { + + _imaqScale(dest.getAddress(), source.getAddress(), xScale, yScale, scaleMode.getValue(), + rect.getAddress()); + + } + + private static native void _imaqScale(long dest, long source, int xScale, int yScale, + int scaleMode, long rect); + + public static void imaqTranspose(Image dest, Image source) { + + _imaqTranspose(dest.getAddress(), source.getAddress()); + + } + + private static native void _imaqTranspose(long dest, long source); + + public static void imaqUnflatten(Image image, RawData data, int size) { + + _imaqUnflatten(image.getAddress(), data.getAddress(), size); + + } + + private static native void _imaqUnflatten(long image, long data, int size); + + public static void imaqUnwrapImage(Image dest, Image source, Annulus annulus, + RectOrientation orientation, InterpolationMethod method) { + + _imaqUnwrapImage(dest.getAddress(), source.getAddress(), annulus.getAddress(), + orientation.getValue(), method.getValue()); + + } + + private static native void _imaqUnwrapImage(long dest, long source, long annulus, + int orientation, int method); + + public static void imaqView3D(Image dest, Image source, View3DOptions options) { + + _imaqView3D(dest.getAddress(), source.getAddress(), options.getAddress()); + + } + + private static native void _imaqView3D(long dest, long source, long options); + + /** + * File I/O functions + */ + + public static class GetFileInfoResult { + public CalibrationUnit calibrationUnit; + public float calibrationX; + public float calibrationY; + public int width; + public int height; + public ImageType imageType; + + private GetFileInfoResult(ByteBuffer rv_buf) { + calibrationUnit = CalibrationUnit.fromValue(rv_buf.getInt(0)); + calibrationX = rv_buf.getFloat(8); + calibrationY = rv_buf.getFloat(16); + width = rv_buf.getInt(24); + height = rv_buf.getInt(32); + imageType = ImageType.fromValue(rv_buf.getInt(40)); + } + } + + public static GetFileInfoResult imaqGetFileInfo(String fileName) { + ByteBuffer fileName_buf = null; + if (fileName != null) { + byte[] fileName_bytes; + try { + fileName_bytes = fileName.getBytes("UTF-8"); + } catch (UnsupportedEncodingException e) { + fileName_bytes = new byte[0]; + } + fileName_buf = ByteBuffer.allocateDirect(fileName_bytes.length + 1); + putBytes(fileName_buf, fileName_bytes, 0, fileName_bytes.length).put(fileName_bytes.length, + (byte) 0); + } + ByteBuffer rv_buf = + ByteBuffer.allocateDirect(8 + 8 + 8 + 8 + 8 + 8).order(ByteOrder.nativeOrder()); + long rv_addr = getByteBufferAddress(rv_buf); + _imaqGetFileInfo(fileName == null ? 0 : getByteBufferAddress(fileName_buf), rv_addr + 0, + rv_addr + 8, rv_addr + 16, rv_addr + 24, rv_addr + 32, rv_addr + 40); + GetFileInfoResult rv = new GetFileInfoResult(rv_buf); + return rv; + } + + private static native void _imaqGetFileInfo(long fileName, long calibrationUnit, + long calibrationX, long calibrationY, long width, long height, long imageType); + + public static void imaqReadFile(Image image, String fileName) { + ByteBuffer fileName_buf; + byte[] fileName_bytes; + try { + fileName_bytes = fileName.getBytes("UTF-8"); + } catch (UnsupportedEncodingException e) { + fileName_bytes = new byte[0]; + } + fileName_buf = ByteBuffer.allocateDirect(fileName_bytes.length + 1); + putBytes(fileName_buf, fileName_bytes, 0, fileName_bytes.length).put(fileName_bytes.length, + (byte) 0); + _imaqReadFile(image.getAddress(), getByteBufferAddress(fileName_buf), 0, 0); + } + + private static native void _imaqReadFile(long image, long fileName, long colorTable, + long numColors); + + public static class ReadVisionFileResult { + public RGBValue colorTable; + public int numColors; + + private ReadVisionFileResult(ByteBuffer rv_buf) { + colorTable = new RGBValue(rv_buf, 0); + colorTable.read(); + numColors = rv_buf.getInt(8); + } + } + + public static ReadVisionFileResult imaqReadVisionFile(Image image, String fileName) { + ByteBuffer fileName_buf = null; + if (fileName != null) { + byte[] fileName_bytes; + try { + fileName_bytes = fileName.getBytes("UTF-8"); + } catch (UnsupportedEncodingException e) { + fileName_bytes = new byte[0]; + } + fileName_buf = ByteBuffer.allocateDirect(fileName_bytes.length + 1); + putBytes(fileName_buf, fileName_bytes, 0, fileName_bytes.length).put(fileName_bytes.length, + (byte) 0); + } + ByteBuffer rv_buf = ByteBuffer.allocateDirect(8 + 8).order(ByteOrder.nativeOrder()); + long rv_addr = getByteBufferAddress(rv_buf); + _imaqReadVisionFile(image.getAddress(), fileName == null ? 0 + : getByteBufferAddress(fileName_buf), rv_addr + 0, rv_addr + 8); + ReadVisionFileResult rv = new ReadVisionFileResult(rv_buf); + return rv; + } + + private static native void _imaqReadVisionFile(long image, long fileName, long colorTable, + long numColors); + + public static void imaqWriteBMPFile(Image image, String fileName, int compress, + RGBValue colorTable) { + ByteBuffer fileName_buf = null; + if (fileName != null) { + byte[] fileName_bytes; + try { + fileName_bytes = fileName.getBytes("UTF-8"); + } catch (UnsupportedEncodingException e) { + fileName_bytes = new byte[0]; + } + fileName_buf = ByteBuffer.allocateDirect(fileName_bytes.length + 1); + putBytes(fileName_buf, fileName_bytes, 0, fileName_bytes.length).put(fileName_bytes.length, + (byte) 0); + } + _imaqWriteBMPFile(image.getAddress(), + fileName == null ? 0 : getByteBufferAddress(fileName_buf), compress, colorTable == null ? 0 + : colorTable.getAddress()); + + } + + private static native void _imaqWriteBMPFile(long image, long fileName, int compress, + long colorTable); + + public static void imaqWriteFile(Image image, String fileName, RGBValue colorTable) { + ByteBuffer fileName_buf = null; + if (fileName != null) { + byte[] fileName_bytes; + try { + fileName_bytes = fileName.getBytes("UTF-8"); + } catch (UnsupportedEncodingException e) { + fileName_bytes = new byte[0]; + } + fileName_buf = ByteBuffer.allocateDirect(fileName_bytes.length + 1); + putBytes(fileName_buf, fileName_bytes, 0, fileName_bytes.length).put(fileName_bytes.length, + (byte) 0); + } + _imaqWriteFile(image.getAddress(), fileName == null ? 0 : getByteBufferAddress(fileName_buf), + colorTable == null ? 0 : colorTable.getAddress()); + + } + + private static native void _imaqWriteFile(long image, long fileName, long colorTable); + + public static void imaqWriteJPEGFile(Image image, String fileName, int quality, RawData colorTable) { + ByteBuffer fileName_buf = null; + if (fileName != null) { + byte[] fileName_bytes; + try { + fileName_bytes = fileName.getBytes("UTF-8"); + } catch (UnsupportedEncodingException e) { + fileName_bytes = new byte[0]; + } + fileName_buf = ByteBuffer.allocateDirect(fileName_bytes.length + 1); + putBytes(fileName_buf, fileName_bytes, 0, fileName_bytes.length).put(fileName_bytes.length, + (byte) 0); + } + _imaqWriteJPEGFile(image.getAddress(), fileName == null ? 0 + : getByteBufferAddress(fileName_buf), quality, + colorTable == null ? 0 : colorTable.getAddress()); + + } + + private static native void _imaqWriteJPEGFile(long image, long fileName, int quality, + long colorTable); + + public static void imaqWritePNGFile2(Image image, String fileName, int compressionSpeed, + RGBValue colorTable, int useBitDepth) { + ByteBuffer fileName_buf = null; + if (fileName != null) { + byte[] fileName_bytes; + try { + fileName_bytes = fileName.getBytes("UTF-8"); + } catch (UnsupportedEncodingException e) { + fileName_bytes = new byte[0]; + } + fileName_buf = ByteBuffer.allocateDirect(fileName_bytes.length + 1); + putBytes(fileName_buf, fileName_bytes, 0, fileName_bytes.length).put(fileName_bytes.length, + (byte) 0); + } + _imaqWritePNGFile2(image.getAddress(), fileName == null ? 0 + : getByteBufferAddress(fileName_buf), compressionSpeed, + colorTable == null ? 0 : colorTable.getAddress(), useBitDepth); + + } + + private static native void _imaqWritePNGFile2(long image, long fileName, int compressionSpeed, + long colorTable, int useBitDepth); + + public static void imaqWriteTIFFFile(Image image, String fileName, TIFFFileOptions options, + RGBValue colorTable) { + ByteBuffer fileName_buf = null; + if (fileName != null) { + byte[] fileName_bytes; + try { + fileName_bytes = fileName.getBytes("UTF-8"); + } catch (UnsupportedEncodingException e) { + fileName_bytes = new byte[0]; + } + fileName_buf = ByteBuffer.allocateDirect(fileName_bytes.length + 1); + putBytes(fileName_buf, fileName_bytes, 0, fileName_bytes.length).put(fileName_bytes.length, + (byte) 0); + } + _imaqWriteTIFFFile(image.getAddress(), fileName == null ? 0 + : getByteBufferAddress(fileName_buf), options == null ? 0 : options.getAddress(), + colorTable == null ? 0 : colorTable.getAddress()); + + } + + private static native void _imaqWriteTIFFFile(long image, long fileName, long options, + long colorTable); + + public static void imaqWriteVisionFile(Image image, String fileName, RGBValue colorTable) { + ByteBuffer fileName_buf = null; + if (fileName != null) { + byte[] fileName_bytes; + try { + fileName_bytes = fileName.getBytes("UTF-8"); + } catch (UnsupportedEncodingException e) { + fileName_bytes = new byte[0]; + } + fileName_buf = ByteBuffer.allocateDirect(fileName_bytes.length + 1); + putBytes(fileName_buf, fileName_bytes, 0, fileName_bytes.length).put(fileName_bytes.length, + (byte) 0); + } + _imaqWriteVisionFile(image.getAddress(), fileName == null ? 0 + : getByteBufferAddress(fileName_buf), colorTable.getAddress()); + + } + + private static native void _imaqWriteVisionFile(long image, long fileName, long colorTable); + + /** + * Analytic Geometry functions + */ + + public static CoordinateSystem imaqBuildCoordinateSystem(Point points, ReferenceMode mode, + AxisOrientation orientation) { + ByteBuffer rv_buf = ByteBuffer.allocateDirect(8).order(ByteOrder.nativeOrder()); + long rv_addr = getByteBufferAddress(rv_buf); + _imaqBuildCoordinateSystem(points.getAddress(), mode.getValue(), orientation.getValue(), + rv_addr + 0); + CoordinateSystem system; + system = new CoordinateSystem(rv_buf, 0); + system.read(); + return system; + } + + private static native void _imaqBuildCoordinateSystem(long points, int mode, int orientation, + long system); + + public static BestCircle2 imaqFitCircle2(PointFloat[] points, FitCircleOptions options) { + int numPoints = points.length; + ByteBuffer points_buf = null; + points_buf = ByteBuffer.allocateDirect(points.length * 8).order(ByteOrder.nativeOrder()); + for (int i = 0, off = 0; i < points.length; i++, off += 8) { + points[i].setBuffer(points_buf, off); + points[i].write(); + } + long jn_rv = _imaqFitCircle2(getByteBufferAddress(points_buf), numPoints, options.getAddress()); + + return new BestCircle2(jn_rv, true); + } + + private static native long _imaqFitCircle2(long points, int numPoints, long options); + + public static BestEllipse2 imaqFitEllipse2(PointFloat[] points, FitEllipseOptions options) { + int numPoints = points.length; + ByteBuffer points_buf = null; + points_buf = ByteBuffer.allocateDirect(points.length * 8).order(ByteOrder.nativeOrder()); + for (int i = 0, off = 0; i < points.length; i++, off += 8) { + points[i].setBuffer(points_buf, off); + points[i].write(); + } + long jn_rv = + _imaqFitEllipse2(getByteBufferAddress(points_buf), numPoints, options.getAddress()); + + return new BestEllipse2(jn_rv, true); + } + + private static native long _imaqFitEllipse2(long points, int numPoints, long options); + + public static BestLine imaqFitLine(PointFloat[] points, FitLineOptions options) { + int numPoints = points.length; + ByteBuffer points_buf = null; + points_buf = ByteBuffer.allocateDirect(points.length * 8).order(ByteOrder.nativeOrder()); + for (int i = 0, off = 0; i < points.length; i++, off += 8) { + points[i].setBuffer(points_buf, off); + points[i].write(); + } + long jn_rv = _imaqFitLine(getByteBufferAddress(points_buf), numPoints, options.getAddress()); + + return new BestLine(jn_rv, true); + } + + private static native long _imaqFitLine(long points, int numPoints, long options); + + public static float imaqGetAngle(PointFloat start1, PointFloat end1, PointFloat start2, + PointFloat end2) { + ByteBuffer rv_buf = ByteBuffer.allocateDirect(8).order(ByteOrder.nativeOrder()); + long rv_addr = getByteBufferAddress(rv_buf); + _imaqGetAngle(start1.getAddress(), end1.getAddress(), start2.getAddress(), end2.getAddress(), + rv_addr + 0); + float angle; + angle = rv_buf.getFloat(0); + return angle; + } + + private static native void _imaqGetAngle(long start1, long end1, long start2, long end2, + long angle); + + public static class GetBisectingLineResult { + public PointFloat bisectStart; + public PointFloat bisectEnd; + + private GetBisectingLineResult(ByteBuffer rv_buf) { + bisectStart = new PointFloat(rv_buf, 0); + bisectStart.read(); + bisectEnd = new PointFloat(rv_buf, 8); + bisectEnd.read(); + } + } + + public static GetBisectingLineResult imaqGetBisectingLine(PointFloat start1, PointFloat end1, + PointFloat start2, PointFloat end2) { + ByteBuffer rv_buf = ByteBuffer.allocateDirect(8 + 8).order(ByteOrder.nativeOrder()); + long rv_addr = getByteBufferAddress(rv_buf); + _imaqGetBisectingLine(start1.getAddress(), end1.getAddress(), start2.getAddress(), + end2.getAddress(), rv_addr + 0, rv_addr + 8); + GetBisectingLineResult rv = new GetBisectingLineResult(rv_buf); + return rv; + } + + private static native void _imaqGetBisectingLine(long start1, long end1, long start2, long end2, + long bisectStart, long bisectEnd); + + public static float imaqGetDistance(PointFloat point1, PointFloat point2) { + ByteBuffer rv_buf = ByteBuffer.allocateDirect(8).order(ByteOrder.nativeOrder()); + long rv_addr = getByteBufferAddress(rv_buf); + _imaqGetDistance(point1.getAddress(), point2.getAddress(), rv_addr + 0); + float distance; + distance = rv_buf.getFloat(0); + return distance; + } + + private static native void _imaqGetDistance(long point1, long point2, long distance); + + public static PointFloat imaqGetIntersection(PointFloat start1, PointFloat end1, + PointFloat start2, PointFloat end2) { + ByteBuffer rv_buf = ByteBuffer.allocateDirect(8).order(ByteOrder.nativeOrder()); + long rv_addr = getByteBufferAddress(rv_buf); + _imaqGetIntersection(start1.getAddress(), end1.getAddress(), start2.getAddress(), + end2.getAddress(), rv_addr + 0); + PointFloat intersection; + intersection = new PointFloat(rv_buf, 0); + intersection.read(); + return intersection; + } + + private static native void _imaqGetIntersection(long start1, long end1, long start2, long end2, + long intersection); + + public static class GetMidLineResult { + public PointFloat midLineStart; + public PointFloat midLineEnd; + + private GetMidLineResult(ByteBuffer rv_buf) { + midLineStart = new PointFloat(rv_buf, 0); + midLineStart.read(); + midLineEnd = new PointFloat(rv_buf, 8); + midLineEnd.read(); + } + } + + public static GetMidLineResult imaqGetMidLine(PointFloat refLineStart, PointFloat refLineEnd, + PointFloat point) { + ByteBuffer rv_buf = ByteBuffer.allocateDirect(8 + 8).order(ByteOrder.nativeOrder()); + long rv_addr = getByteBufferAddress(rv_buf); + _imaqGetMidLine(refLineStart.getAddress(), refLineEnd.getAddress(), point.getAddress(), + rv_addr + 0, rv_addr + 8); + GetMidLineResult rv = new GetMidLineResult(rv_buf); + return rv; + } + + private static native void _imaqGetMidLine(long refLineStart, long refLineEnd, long point, + long midLineStart, long midLineEnd); + + public static class GetPerpendicularLineResult { + public PointFloat perpLineStart; + public PointFloat perpLineEnd; + public double distance; + + private GetPerpendicularLineResult(ByteBuffer rv_buf) { + perpLineStart = new PointFloat(rv_buf, 0); + perpLineStart.read(); + perpLineEnd = new PointFloat(rv_buf, 8); + perpLineEnd.read(); + distance = rv_buf.getDouble(16); + } + } + + public static GetPerpendicularLineResult imaqGetPerpendicularLine(PointFloat refLineStart, + PointFloat refLineEnd, PointFloat point) { + ByteBuffer rv_buf = ByteBuffer.allocateDirect(8 + 8 + 8).order(ByteOrder.nativeOrder()); + long rv_addr = getByteBufferAddress(rv_buf); + _imaqGetPerpendicularLine(refLineStart.getAddress(), refLineEnd.getAddress(), + point.getAddress(), rv_addr + 0, rv_addr + 8, rv_addr + 16); + GetPerpendicularLineResult rv = new GetPerpendicularLineResult(rv_buf); + return rv; + } + + private static native void _imaqGetPerpendicularLine(long refLineStart, long refLineEnd, + long point, long perpLineStart, long perpLineEnd, long distance); + + public static class GetPointsOnContourResult { + public SegmentInfo[] array; + private long array_addr; + + private GetPointsOnContourResult(ByteBuffer rv_buf, long jn_rv) { + array_addr = jn_rv; + int array_numSegments; + array_numSegments = rv_buf.getInt(0); + array = new SegmentInfo[array_numSegments]; + if (array_numSegments > 0 && array_addr != 0) { + ByteBuffer bb = newDirectByteBuffer(array_addr, array_numSegments * 24); + for (int i = 0, off = 0; i < array_numSegments; i++, off += 24) { + array[i] = new SegmentInfo(bb, off); + array[i].read(); + } + } + } + + @Override + protected void finalize() throws Throwable { + imaqDispose(array_addr); + super.finalize(); + } + } + + public static GetPointsOnContourResult imaqGetPointsOnContour(Image image) { + ByteBuffer rv_buf = ByteBuffer.allocateDirect(8).order(ByteOrder.nativeOrder()); + long rv_addr = getByteBufferAddress(rv_buf); + long jn_rv = _imaqGetPointsOnContour(image.getAddress(), rv_addr + 0); + GetPointsOnContourResult rv = new GetPointsOnContourResult(rv_buf, jn_rv); + return rv; + } + + private static native long _imaqGetPointsOnContour(long image, long numSegments); + + public static class GetPointsOnLineResult { + public Point[] array; + private long array_addr; + + private GetPointsOnLineResult(ByteBuffer rv_buf, long jn_rv) { + array_addr = jn_rv; + int array_numPoints; + array_numPoints = rv_buf.getInt(0); + array = new Point[array_numPoints]; + if (array_numPoints > 0 && array_addr != 0) { + ByteBuffer bb = newDirectByteBuffer(array_addr, array_numPoints * 8); + for (int i = 0, off = 0; i < array_numPoints; i++, off += 8) { + array[i] = new Point(bb, off); + array[i].read(); + } + } + } + + @Override + protected void finalize() throws Throwable { + imaqDispose(array_addr); + super.finalize(); + } + } + + public static GetPointsOnLineResult imaqGetPointsOnLine(Point start, Point end) { + ByteBuffer rv_buf = ByteBuffer.allocateDirect(8).order(ByteOrder.nativeOrder()); + long rv_addr = getByteBufferAddress(rv_buf); + long jn_rv = _imaqGetPointsOnLine(start.getAddress(), end.getAddress(), rv_addr + 0); + GetPointsOnLineResult rv = new GetPointsOnLineResult(rv_buf, jn_rv); + return rv; + } + + private static native long _imaqGetPointsOnLine(long start, long end, long numPoints); + + public static float imaqGetPolygonArea(PointFloat points, int numPoints) { + ByteBuffer rv_buf = ByteBuffer.allocateDirect(8).order(ByteOrder.nativeOrder()); + long rv_addr = getByteBufferAddress(rv_buf); + _imaqGetPolygonArea(points.getAddress(), numPoints, rv_addr + 0); + float area; + area = rv_buf.getFloat(0); + return area; + } + + private static native void _imaqGetPolygonArea(long points, int numPoints, long area); + + public static class InterpolatePointsResult { + public float[] array; + private long array_addr; + + private InterpolatePointsResult(ByteBuffer rv_buf, long jn_rv) { + array_addr = jn_rv; + int array_interpCount; + array_interpCount = rv_buf.getInt(0); + array = new float[array_interpCount]; + if (array_interpCount > 0 && array_addr != 0) { + newDirectByteBuffer(array_addr, array_interpCount * 4).asFloatBuffer().get(array); + } + } + + @Override + protected void finalize() throws Throwable { + imaqDispose(array_addr); + super.finalize(); + } + } + + public static InterpolatePointsResult imaqInterpolatePoints(Image image, Point[] points, + InterpolationMethod method, int subpixel) { + int numPoints = points.length; + ByteBuffer points_buf = null; + points_buf = ByteBuffer.allocateDirect(points.length * 8).order(ByteOrder.nativeOrder()); + for (int i = 0, off = 0; i < points.length; i++, off += 8) { + points[i].setBuffer(points_buf, off); + points[i].write(); + } + ByteBuffer rv_buf = ByteBuffer.allocateDirect(8).order(ByteOrder.nativeOrder()); + long rv_addr = getByteBufferAddress(rv_buf); + long jn_rv = + _imaqInterpolatePoints(image.getAddress(), getByteBufferAddress(points_buf), numPoints, + method.getValue(), subpixel, rv_addr + 0); + InterpolatePointsResult rv = new InterpolatePointsResult(rv_buf, jn_rv); + return rv; + } + + private static native long _imaqInterpolatePoints(long image, long points, int numPoints, + int method, int subpixel, long interpCount); + + /** + * Clipboard functions + */ + + /** + * Border functions + */ + + public static void imaqFillBorder(Image image, BorderMethod method) { + + _imaqFillBorder(image.getAddress(), method.getValue()); + + } + + private static native void _imaqFillBorder(long image, int method); + + public static int imaqGetBorderSize(Image image) { + ByteBuffer rv_buf = ByteBuffer.allocateDirect(8).order(ByteOrder.nativeOrder()); + long rv_addr = getByteBufferAddress(rv_buf); + _imaqGetBorderSize(image.getAddress(), rv_addr + 0); + int borderSize; + borderSize = rv_buf.getInt(0); + return borderSize; + } + + private static native void _imaqGetBorderSize(long image, long borderSize); + + public static void imaqSetBorderSize(Image image, int size) { + + _imaqSetBorderSize(image.getAddress(), size); + + } + + private static native void _imaqSetBorderSize(long image, int size); + + /** + * Image Management functions + */ + + public static void imaqArrayToImage(Image image, RawData array, int numCols, int numRows) { + + _imaqArrayToImage(image.getAddress(), array.getAddress(), numCols, numRows); + + } + + private static native void _imaqArrayToImage(long image, long array, int numCols, int numRows); + + public static Image imaqCreateImage(ImageType type, int borderSize) { + + long jn_rv = _imaqCreateImage(type.getValue(), borderSize); + + return new Image(jn_rv, true); + } + + private static native long _imaqCreateImage(int type, int borderSize); + + /** + * Color Processing functions + */ + + public static void imaqColorBCGTransform(Image dest, Image source, BCGOptions redOptions, + BCGOptions greenOptions, BCGOptions blueOptions, Image mask) { + + _imaqColorBCGTransform(dest.getAddress(), source.getAddress(), redOptions == null ? 0 + : redOptions.getAddress(), greenOptions == null ? 0 : greenOptions.getAddress(), + blueOptions == null ? 0 : blueOptions.getAddress(), mask == null ? 0 : mask.getAddress()); + + } + + private static native void _imaqColorBCGTransform(long dest, long source, long redOptions, + long greenOptions, long blueOptions, long mask); + + public static void imaqColorEqualize(Image dest, Image source, int colorEqualization) { + + _imaqColorEqualize(dest.getAddress(), source.getAddress(), colorEqualization); + + } + + private static native void _imaqColorEqualize(long dest, long source, int colorEqualization); + + public static ColorHistogramReport imaqColorHistogram2(Image image, int numClasses, + ColorMode mode, CIEXYZValue whiteReference, Image mask) { + + long jn_rv = + _imaqColorHistogram2(image.getAddress(), numClasses, mode.getValue(), + whiteReference.getAddress(), mask == null ? 0 : mask.getAddress()); + + return new ColorHistogramReport(jn_rv, true); + } + + private static native long _imaqColorHistogram2(long image, int numClasses, int mode, + long whiteReference, long mask); + + public static void imaqColorThreshold(Image dest, Image source, int replaceValue, ColorMode mode, + Range plane1Range, Range plane2Range, Range plane3Range) { + + _imaqColorThreshold(dest.getAddress(), source.getAddress(), replaceValue, mode.getValue(), + plane1Range == null ? 0 : plane1Range.getAddress(), + plane2Range == null ? 0 : plane2Range.getAddress(), + plane3Range == null ? 0 : plane3Range.getAddress()); + + } + + private static native void _imaqColorThreshold(long dest, long source, int replaceValue, + int mode, long plane1Range, long plane2Range, long plane3Range); + + public static SupervisedColorSegmentationReport imaqSupervisedColorSegmentation( + ClassifierSession session, Image labelImage, Image srcImage, ROI roi, ROILabel labelIn, + int numLabelIn, int maxDistance, int minIdentificationScore, + ColorSegmenationOptions segmentOptions) { + + long jn_rv = + _imaqSupervisedColorSegmentation(session.getAddress(), labelImage.getAddress(), + srcImage.getAddress(), roi.getAddress(), labelIn.getAddress(), numLabelIn, maxDistance, + minIdentificationScore, segmentOptions.getAddress()); + + return new SupervisedColorSegmentationReport(jn_rv, true); + } + + private static native long _imaqSupervisedColorSegmentation(long session, long labelImage, + long srcImage, long roi, long labelIn, int numLabelIn, int maxDistance, + int minIdentificationScore, long segmentOptions); + + public static int imaqGetColorSegmentationMaxDistance(ClassifierSession session, + ColorSegmenationOptions segmentOptions, SegmentationDistanceLevel distLevel) { + ByteBuffer rv_buf = ByteBuffer.allocateDirect(8).order(ByteOrder.nativeOrder()); + long rv_addr = getByteBufferAddress(rv_buf); + _imaqGetColorSegmentationMaxDistance(session.getAddress(), segmentOptions.getAddress(), + distLevel.getValue(), rv_addr + 0); + int maxDistance; + maxDistance = rv_buf.getInt(0); + return maxDistance; + } + + private static native void _imaqGetColorSegmentationMaxDistance(long session, + long segmentOptions, int distLevel, long maxDistance); + + /** + * Transform functions + */ + + public static void imaqBCGTransform(Image dest, Image source, BCGOptions options, Image mask) { + + _imaqBCGTransform(dest.getAddress(), source.getAddress(), options.getAddress(), + mask == null ? 0 : mask.getAddress()); + + } + + private static native void _imaqBCGTransform(long dest, long source, long options, long mask); + + public static void imaqEqualize(Image dest, Image source, float min, float max, Image mask) { + + _imaqEqualize(dest.getAddress(), source.getAddress(), min, max, + mask == null ? 0 : mask.getAddress()); + + } + + private static native void _imaqEqualize(long dest, long source, float min, float max, long mask); + + public static void imaqInverse(Image dest, Image source, Image mask) { + + _imaqInverse(dest.getAddress(), source.getAddress(), mask == null ? 0 : mask.getAddress()); + + } + + private static native void _imaqInverse(long dest, long source, long mask); + + public static void imaqMathTransform(Image dest, Image source, MathTransformMethod method, + float rangeMin, float rangeMax, float power, Image mask) { + + _imaqMathTransform(dest.getAddress(), source.getAddress(), method.getValue(), rangeMin, + rangeMax, power, mask == null ? 0 : mask.getAddress()); + + } + + private static native void _imaqMathTransform(long dest, long source, int method, float rangeMin, + float rangeMax, float power, long mask); + + public static int imaqWatershedTransform(Image dest, Image source, int connectivity8) { + ByteBuffer rv_buf = ByteBuffer.allocateDirect(8).order(ByteOrder.nativeOrder()); + long rv_addr = getByteBufferAddress(rv_buf); + _imaqWatershedTransform(dest.getAddress(), source.getAddress(), connectivity8, rv_addr + 0); + int zoneCount; + zoneCount = rv_buf.getInt(0); + return zoneCount; + } + + private static native void _imaqWatershedTransform(long dest, long source, int connectivity8, + long zoneCount); + + /** + * Window Management functions + */ + + /** + * Utilities functions + */ + + public static int imaqMulticoreOptions(MulticoreOperation operation) { + ByteBuffer rv_buf = ByteBuffer.allocateDirect(8).order(ByteOrder.nativeOrder()); + long rv_addr = getByteBufferAddress(rv_buf); + _imaqMulticoreOptions(operation.getValue(), rv_addr + 0); + int customNumCores; + customNumCores = rv_buf.getInt(0); + return customNumCores; + } + + private static native void _imaqMulticoreOptions(int operation, long customNumCores); + + /** + * Tool Window functions + */ + + /** + * Meter functions + */ + + public static MeterArc imaqGetMeterArc(int lightNeedle, MeterArcMode mode, ROI roi, + PointFloat base, PointFloat start, PointFloat end) { + + long jn_rv = + _imaqGetMeterArc(lightNeedle, mode.getValue(), roi.getAddress(), base.getAddress(), + start.getAddress(), end.getAddress()); + + return new MeterArc(jn_rv, true); + } + + private static native long _imaqGetMeterArc(int lightNeedle, int mode, long roi, long base, + long start, long end); + + public static class ReadMeterResult { + public double percentage; + public PointFloat endOfNeedle; + + private ReadMeterResult(ByteBuffer rv_buf) { + percentage = rv_buf.getDouble(0); + endOfNeedle = new PointFloat(rv_buf, 8); + endOfNeedle.read(); + } + } + + public static ReadMeterResult imaqReadMeter(Image image, MeterArc arcInfo) { + ByteBuffer rv_buf = ByteBuffer.allocateDirect(8 + 8).order(ByteOrder.nativeOrder()); + long rv_addr = getByteBufferAddress(rv_buf); + _imaqReadMeter(image.getAddress(), arcInfo.getAddress(), rv_addr + 0, rv_addr + 8); + ReadMeterResult rv = new ReadMeterResult(rv_buf); + return rv; + } + + private static native void _imaqReadMeter(long image, long arcInfo, long percentage, + long endOfNeedle); + + /** + * Calibration functions + */ + + public static void imaqCopyCalibrationInfo2(Image dest, Image source, Point offset) { + + _imaqCopyCalibrationInfo2(dest.getAddress(), source.getAddress(), offset.getAddress()); + + } + + private static native void _imaqCopyCalibrationInfo2(long dest, long source, long offset); + + public static CalibrationInfo imaqGetCalibrationInfo2(Image image) { + + long jn_rv = _imaqGetCalibrationInfo2(image.getAddress()); + + return new CalibrationInfo(jn_rv, true); + } + + private static native long _imaqGetCalibrationInfo2(long image); + + public static CalibrationInfo imaqGetCalibrationInfo3(Image image, int isGetErrorMap) { + + long jn_rv = _imaqGetCalibrationInfo3(image.getAddress(), isGetErrorMap); + + return new CalibrationInfo(jn_rv, true); + } + + private static native long _imaqGetCalibrationInfo3(long image, int isGetErrorMap); + + public static float imaqLearnCalibrationGrid(Image image, ROI roi, + LearnCalibrationOptions options, GridDescriptor grid, CoordinateSystem system, + RangeFloat range) { + ByteBuffer rv_buf = ByteBuffer.allocateDirect(8).order(ByteOrder.nativeOrder()); + long rv_addr = getByteBufferAddress(rv_buf); + _imaqLearnCalibrationGrid(image.getAddress(), roi.getAddress(), options.getAddress(), + grid.getAddress(), system.getAddress(), range.getAddress(), rv_addr + 0); + float quality; + quality = rv_buf.getFloat(0); + return quality; + } + + private static native void _imaqLearnCalibrationGrid(long image, long roi, long options, + long grid, long system, long range, long quality); + + public static float imaqLearnCalibrationPoints(Image image, CalibrationPoints points, ROI roi, + LearnCalibrationOptions options, GridDescriptor grid, CoordinateSystem system) { + ByteBuffer rv_buf = ByteBuffer.allocateDirect(8).order(ByteOrder.nativeOrder()); + long rv_addr = getByteBufferAddress(rv_buf); + _imaqLearnCalibrationPoints(image.getAddress(), points.getAddress(), roi.getAddress(), + options.getAddress(), grid.getAddress(), system.getAddress(), rv_addr + 0); + float quality; + quality = rv_buf.getFloat(0); + return quality; + } + + private static native void _imaqLearnCalibrationPoints(long image, long points, long roi, + long options, long grid, long system, long quality); + + public static void imaqSetCoordinateSystem(Image image, CoordinateSystem system) { + + _imaqSetCoordinateSystem(image.getAddress(), system.getAddress()); + + } + + private static native void _imaqSetCoordinateSystem(long image, long system); + + public static void imaqSetSimpleCalibration(Image image, ScalingMethod method, int learnTable, + GridDescriptor grid, CoordinateSystem system) { + + _imaqSetSimpleCalibration(image.getAddress(), method.getValue(), learnTable, grid.getAddress(), + system.getAddress()); + + } + + private static native void _imaqSetSimpleCalibration(long image, int method, int learnTable, + long grid, long system); + + public static TransformReport imaqTransformPixelToRealWorld(Image image, + PointFloat[] pixelCoordinates) { + int numCoordinates = pixelCoordinates.length; + ByteBuffer pixelCoordinates_buf = null; + pixelCoordinates_buf = + ByteBuffer.allocateDirect(pixelCoordinates.length * 8).order(ByteOrder.nativeOrder()); + for (int i = 0, off = 0; i < pixelCoordinates.length; i++, off += 8) { + pixelCoordinates[i].setBuffer(pixelCoordinates_buf, off); + pixelCoordinates[i].write(); + } + long jn_rv = + _imaqTransformPixelToRealWorld(image.getAddress(), + getByteBufferAddress(pixelCoordinates_buf), numCoordinates); + + return new TransformReport(jn_rv, true); + } + + private static native long _imaqTransformPixelToRealWorld(long image, long pixelCoordinates, + int numCoordinates); + + public static TransformReport imaqTransformRealWorldToPixel(Image image, + PointFloat[] realWorldCoordinates) { + int numCoordinates = realWorldCoordinates.length; + ByteBuffer realWorldCoordinates_buf = null; + realWorldCoordinates_buf = + ByteBuffer.allocateDirect(realWorldCoordinates.length * 8).order(ByteOrder.nativeOrder()); + for (int i = 0, off = 0; i < realWorldCoordinates.length; i++, off += 8) { + realWorldCoordinates[i].setBuffer(realWorldCoordinates_buf, off); + realWorldCoordinates[i].write(); + } + long jn_rv = + _imaqTransformRealWorldToPixel(image.getAddress(), + getByteBufferAddress(realWorldCoordinates_buf), numCoordinates); + + return new TransformReport(jn_rv, true); + } + + private static native long _imaqTransformRealWorldToPixel(long image, long realWorldCoordinates, + int numCoordinates); + + public static void imaqSetSimpleCalibration2(Image image, GridDescriptor gridDescriptor) { + + _imaqSetSimpleCalibration2(image.getAddress(), gridDescriptor.getAddress()); + + } + + private static native void _imaqSetSimpleCalibration2(long image, long gridDescriptor); + + public static CoordinateSystem imaqCalibrationSetAxisInfo(Image image) { + ByteBuffer rv_buf = ByteBuffer.allocateDirect(8).order(ByteOrder.nativeOrder()); + long rv_addr = getByteBufferAddress(rv_buf); + _imaqCalibrationSetAxisInfo(image.getAddress(), rv_addr + 0); + CoordinateSystem axisInfo; + axisInfo = new CoordinateSystem(rv_buf, 0); + axisInfo.read(); + return axisInfo; + } + + private static native void _imaqCalibrationSetAxisInfo(long image, long axisInfo); + + public static void imaqCalibrationGetThumbnailImage(Image templateImage, Image image, + CalibrationThumbnailType type, int index) { + + _imaqCalibrationGetThumbnailImage(templateImage.getAddress(), image.getAddress(), + type.getValue(), index); + + } + + private static native void _imaqCalibrationGetThumbnailImage(long templateImage, long image, + int type, int index); + + public static GetCalibrationInfoReport imaqCalibrationGetCalibrationInfo(Image image, + int isGetErrorMap) { + + long jn_rv = _imaqCalibrationGetCalibrationInfo(image.getAddress(), isGetErrorMap); + + return new GetCalibrationInfoReport(jn_rv, true); + } + + private static native long _imaqCalibrationGetCalibrationInfo(long image, int isGetErrorMap); + + public static GetCameraParametersReport imaqCalibrationGetCameraParameters(Image templateImage) { + + long jn_rv = _imaqCalibrationGetCameraParameters(templateImage.getAddress()); + + return new GetCameraParametersReport(jn_rv, true); + } + + private static native long _imaqCalibrationGetCameraParameters(long templateImage); + + public static void imaqCalibrationCompactInformation(Image image) { + + _imaqCalibrationCompactInformation(image.getAddress()); + + } + + private static native void _imaqCalibrationCompactInformation(long image); + + /** + * Pixel Manipulation functions + */ + + public static void imaqExtractColorPlanes(Image image, ColorMode mode, Image plane1, + Image plane2, Image plane3) { + + _imaqExtractColorPlanes(image.getAddress(), mode.getValue(), + plane1 == null ? 0 : plane1.getAddress(), plane2 == null ? 0 : plane2.getAddress(), + plane3 == null ? 0 : plane3.getAddress()); + + } + + private static native void _imaqExtractColorPlanes(long image, int mode, long plane1, + long plane2, long plane3); + + public static void imaqExtractComplexPlane(Image dest, Image source, ComplexPlane plane) { + + _imaqExtractComplexPlane(dest.getAddress(), source.getAddress(), plane.getValue()); + + } + + private static native void _imaqExtractComplexPlane(long dest, long source, int plane); + + public static void imaqReplaceColorPlanes(Image dest, Image source, ColorMode mode, Image plane1, + Image plane2, Image plane3) { + + _imaqReplaceColorPlanes(dest.getAddress(), source.getAddress(), mode.getValue(), + plane1 == null ? 0 : plane1.getAddress(), plane2 == null ? 0 : plane2.getAddress(), + plane3 == null ? 0 : plane3.getAddress()); + + } + + private static native void _imaqReplaceColorPlanes(long dest, long source, int mode, long plane1, + long plane2, long plane3); + + public static void imaqReplaceComplexPlane(Image dest, Image source, Image newValues, + ComplexPlane plane) { + + _imaqReplaceComplexPlane(dest.getAddress(), source.getAddress(), newValues.getAddress(), + plane.getValue()); + + } + + private static native void _imaqReplaceComplexPlane(long dest, long source, long newValues, + int plane); + + /** + * Color Matching functions + */ + + public static ColorInformation imaqLearnColor(Image image, ROI roi, ColorSensitivity sensitivity, + int saturation) { + + long jn_rv = + _imaqLearnColor(image.getAddress(), roi == null ? 0 : roi.getAddress(), + sensitivity.getValue(), saturation); + + return new ColorInformation(jn_rv, true); + } + + private static native long _imaqLearnColor(long image, long roi, int sensitivity, int saturation); + + public static class MatchColorResult { + public int[] array; + private long array_addr; + + private MatchColorResult(ByteBuffer rv_buf, long jn_rv) { + array_addr = jn_rv; + int array_numScores; + array_numScores = rv_buf.getInt(0); + array = new int[array_numScores]; + if (array_numScores > 0 && array_addr != 0) { + newDirectByteBuffer(array_addr, array_numScores * 4).asIntBuffer().get(array); + } + } + + @Override + protected void finalize() throws Throwable { + imaqDispose(array_addr); + super.finalize(); + } + } + + public static MatchColorResult imaqMatchColor(Image image, ColorInformation info, ROI roi) { + ByteBuffer rv_buf = ByteBuffer.allocateDirect(8).order(ByteOrder.nativeOrder()); + long rv_addr = getByteBufferAddress(rv_buf); + long jn_rv = + _imaqMatchColor(image.getAddress(), info.getAddress(), roi == null ? 0 : roi.getAddress(), + rv_addr + 0); + MatchColorResult rv = new MatchColorResult(rv_buf, jn_rv); + return rv; + } + + private static native long _imaqMatchColor(long image, long info, long roi, long numScores); + + /** + * Frequency Domain Analysis functions + */ + + public static void imaqAttenuate(Image dest, Image source, AttenuateMode highlow) { + + _imaqAttenuate(dest.getAddress(), source.getAddress(), highlow.getValue()); + + } + + private static native void _imaqAttenuate(long dest, long source, int highlow); + + public static void imaqConjugate(Image dest, Image source) { + + _imaqConjugate(dest.getAddress(), source.getAddress()); + + } + + private static native void _imaqConjugate(long dest, long source); + + public static void imaqFFT(Image dest, Image source) { + + _imaqFFT(dest.getAddress(), source.getAddress()); + + } + + private static native void _imaqFFT(long dest, long source); + + public static void imaqFlipFrequencies(Image dest, Image source) { + + _imaqFlipFrequencies(dest.getAddress(), source.getAddress()); + + } + + private static native void _imaqFlipFrequencies(long dest, long source); + + public static void imaqInverseFFT(Image dest, Image source) { + + _imaqInverseFFT(dest.getAddress(), source.getAddress()); + + } + + private static native void _imaqInverseFFT(long dest, long source); + + public static void imaqTruncate(Image dest, Image source, TruncateMode highlow, float ratioToKeep) { + + _imaqTruncate(dest.getAddress(), source.getAddress(), highlow.getValue(), ratioToKeep); + + } + + private static native void _imaqTruncate(long dest, long source, int highlow, float ratioToKeep); + + /** + * Barcode I/O functions + */ + + public static AIMGradeReport imaqGradeDataMatrixBarcodeAIM(Image image) { + ByteBuffer rv_buf = ByteBuffer.allocateDirect(8).order(ByteOrder.nativeOrder()); + long rv_addr = getByteBufferAddress(rv_buf); + _imaqGradeDataMatrixBarcodeAIM(image.getAddress(), rv_addr + 0); + AIMGradeReport report; + report = new AIMGradeReport(rv_buf, 0); + report.read(); + return report; + } + + private static native void _imaqGradeDataMatrixBarcodeAIM(long image, long report); + + public static BarcodeInfo imaqReadBarcode(Image image, BarcodeType type, ROI roi, int validate) { + + long jn_rv = + _imaqReadBarcode(image.getAddress(), type.getValue(), roi == null ? 0 : roi.getAddress(), + validate); + + return new BarcodeInfo(jn_rv, true); + } + + private static native long _imaqReadBarcode(long image, int type, long roi, int validate); + + public static DataMatrixReport imaqReadDataMatrixBarcode2(Image image, ROI roi, + DataMatrixGradingMode prepareForGrading, DataMatrixDescriptionOptions descriptionOptions, + DataMatrixSizeOptions sizeOptions, DataMatrixSearchOptions searchOptions) { + + long jn_rv = + _imaqReadDataMatrixBarcode2(image.getAddress(), roi.getAddress(), + prepareForGrading.getValue(), descriptionOptions.getAddress(), + sizeOptions.getAddress(), searchOptions.getAddress()); + + return new DataMatrixReport(jn_rv, true); + } + + private static native long _imaqReadDataMatrixBarcode2(long image, long roi, + int prepareForGrading, long descriptionOptions, long sizeOptions, long searchOptions); + + public static class ReadPDF417BarcodeResult { + public Barcode2DInfo[] array; + private long array_addr; + + private ReadPDF417BarcodeResult(ByteBuffer rv_buf, long jn_rv) { + array_addr = jn_rv; + int array_numBarcodes; + array_numBarcodes = rv_buf.getInt(0); + array = new Barcode2DInfo[array_numBarcodes]; + if (array_numBarcodes > 0 && array_addr != 0) { + ByteBuffer bb = newDirectByteBuffer(array_addr, array_numBarcodes * 64); + for (int i = 0, off = 0; i < array_numBarcodes; i++, off += 64) { + array[i] = new Barcode2DInfo(bb, off); + array[i].read(); + } + } + } + + @Override + protected void finalize() throws Throwable { + imaqDispose(array_addr); + super.finalize(); + } + } + + public static ReadPDF417BarcodeResult imaqReadPDF417Barcode(Image image, ROI roi, + Barcode2DSearchMode searchMode) { + ByteBuffer rv_buf = ByteBuffer.allocateDirect(8).order(ByteOrder.nativeOrder()); + long rv_addr = getByteBufferAddress(rv_buf); + long jn_rv = + _imaqReadPDF417Barcode(image.getAddress(), roi.getAddress(), searchMode.getValue(), + rv_addr + 0); + ReadPDF417BarcodeResult rv = new ReadPDF417BarcodeResult(rv_buf, jn_rv); + return rv; + } + + private static native long _imaqReadPDF417Barcode(long image, long roi, int searchMode, + long numBarcodes); + + public static QRCodeReport imaqReadQRCode(Image image, ROI roi, QRGradingMode reserved, + QRCodeDescriptionOptions descriptionOptions, QRCodeSizeOptions sizeOptions, + QRCodeSearchOptions searchOptions) { + + long jn_rv = + _imaqReadQRCode(image.getAddress(), roi.getAddress(), reserved.getValue(), + descriptionOptions.getAddress(), sizeOptions.getAddress(), searchOptions.getAddress()); + + return new QRCodeReport(jn_rv, true); + } + + private static native long _imaqReadQRCode(long image, long roi, int reserved, + long descriptionOptions, long sizeOptions, long searchOptions); + + /** + * LCD functions + */ + + public static void imaqFindLCDSegments(ROI roi, Image image, LCDOptions options) { + + _imaqFindLCDSegments(roi.getAddress(), image.getAddress(), + options == null ? 0 : options.getAddress()); + + } + + private static native void _imaqFindLCDSegments(long roi, long image, long options); + + public static LCDReport imaqReadLCD(Image image, ROI roi, LCDOptions options) { + + long jn_rv = + _imaqReadLCD(image.getAddress(), roi.getAddress(), + options == null ? 0 : options.getAddress()); + + return new LCDReport(jn_rv, true); + } + + private static native long _imaqReadLCD(long image, long roi, long options); + + /** + * Shape Matching functions + */ + + public static class MatchShapeResult { + public ShapeReport[] array; + private long array_addr; + + private MatchShapeResult(ByteBuffer rv_buf, long jn_rv) { + array_addr = jn_rv; + int array_numMatches; + array_numMatches = rv_buf.getInt(0); + array = new ShapeReport[array_numMatches]; + if (array_numMatches > 0 && array_addr != 0) { + ByteBuffer bb = newDirectByteBuffer(array_addr, array_numMatches * 40); + for (int i = 0, off = 0; i < array_numMatches; i++, off += 40) { + array[i] = new ShapeReport(bb, off); + array[i].read(); + } + } + } + + @Override + protected void finalize() throws Throwable { + imaqDispose(array_addr); + super.finalize(); + } + } + + public static MatchShapeResult imaqMatchShape(Image dest, Image source, Image templateImage, + int scaleInvariant, int connectivity8, double tolerance) { + ByteBuffer rv_buf = ByteBuffer.allocateDirect(8).order(ByteOrder.nativeOrder()); + long rv_addr = getByteBufferAddress(rv_buf); + long jn_rv = + _imaqMatchShape(dest.getAddress(), source.getAddress(), templateImage.getAddress(), + scaleInvariant, connectivity8, tolerance, rv_addr + 0); + MatchShapeResult rv = new MatchShapeResult(rv_buf, jn_rv); + return rv; + } + + private static native long _imaqMatchShape(long dest, long source, long templateImage, + int scaleInvariant, int connectivity8, double tolerance, long numMatches); + + /** + * Contours functions + */ + + public static int imaqAddAnnulusContour(ROI roi, Annulus annulus) { + + int jn_rv = _imaqAddAnnulusContour(roi.getAddress(), annulus.getAddress()); + + return jn_rv; + } + + private static native int _imaqAddAnnulusContour(long roi, long annulus); + + public static int imaqAddClosedContour(ROI roi, Point[] points) { + int numPoints = points.length; + ByteBuffer points_buf = null; + points_buf = ByteBuffer.allocateDirect(points.length * 8).order(ByteOrder.nativeOrder()); + for (int i = 0, off = 0; i < points.length; i++, off += 8) { + points[i].setBuffer(points_buf, off); + points[i].write(); + } + int jn_rv = + _imaqAddClosedContour(roi.getAddress(), getByteBufferAddress(points_buf), numPoints); + + return jn_rv; + } + + private static native int _imaqAddClosedContour(long roi, long points, int numPoints); + + public static int imaqAddLineContour(ROI roi, Point start, Point end) { + + int jn_rv = _imaqAddLineContour(roi.getAddress(), start.getAddress(), end.getAddress()); + + return jn_rv; + } + + private static native int _imaqAddLineContour(long roi, long start, long end); + + public static int imaqAddOpenContour(ROI roi, Point[] points) { + int numPoints = points.length; + ByteBuffer points_buf = null; + points_buf = ByteBuffer.allocateDirect(points.length * 8).order(ByteOrder.nativeOrder()); + for (int i = 0, off = 0; i < points.length; i++, off += 8) { + points[i].setBuffer(points_buf, off); + points[i].write(); + } + int jn_rv = _imaqAddOpenContour(roi.getAddress(), getByteBufferAddress(points_buf), numPoints); + + return jn_rv; + } + + private static native int _imaqAddOpenContour(long roi, long points, int numPoints); + + public static int imaqAddOvalContour(ROI roi, Rect boundingBox) { + + int jn_rv = _imaqAddOvalContour(roi.getAddress(), boundingBox.getAddress()); + + return jn_rv; + } + + private static native int _imaqAddOvalContour(long roi, long boundingBox); + + public static int imaqAddPointContour(ROI roi, Point point) { + + int jn_rv = _imaqAddPointContour(roi.getAddress(), point.getAddress()); + + return jn_rv; + } + + private static native int _imaqAddPointContour(long roi, long point); + + public static int imaqAddRectContour(ROI roi, Rect rect) { + + int jn_rv = _imaqAddRectContour(roi.getAddress(), rect.getAddress()); + + return jn_rv; + } + + private static native int _imaqAddRectContour(long roi, long rect); + + public static int imaqAddRotatedRectContour2(ROI roi, RotatedRect rect) { + + int jn_rv = _imaqAddRotatedRectContour2(roi.getAddress(), rect.getAddress()); + + return jn_rv; + } + + private static native int _imaqAddRotatedRectContour2(long roi, long rect); + + public static int imaqCopyContour(ROI destRoi, ROI sourceRoi, int id) { + + int jn_rv = _imaqCopyContour(destRoi.getAddress(), sourceRoi.getAddress(), id); + + return jn_rv; + } + + private static native int _imaqCopyContour(long destRoi, long sourceRoi, int id); + + public static int imaqGetContour(ROI roi, int index) { + + int jn_rv = _imaqGetContour(roi.getAddress(), index); + + return jn_rv; + } + + private static native int _imaqGetContour(long roi, int index); + + public static RGBValue imaqGetContourColor(ROI roi, int id) { + ByteBuffer rv_buf = ByteBuffer.allocateDirect(8).order(ByteOrder.nativeOrder()); + long rv_addr = getByteBufferAddress(rv_buf); + _imaqGetContourColor(roi.getAddress(), id, rv_addr + 0); + RGBValue contourColor; + contourColor = new RGBValue(rv_buf, 0); + contourColor.read(); + return contourColor; + } + + private static native void _imaqGetContourColor(long roi, int id, long contourColor); + + public static void imaqGetContourCount(ROI roi) { + + _imaqGetContourCount(roi.getAddress()); + + } + + private static native void _imaqGetContourCount(long roi); + + public static ContourInfo2 imaqGetContourInfo2(ROI roi, int id) { + + long jn_rv = _imaqGetContourInfo2(roi.getAddress(), id); + + return new ContourInfo2(jn_rv, true); + } + + private static native long _imaqGetContourInfo2(long roi, int id); + + public static void imaqMoveContour(ROI roi, int id, int deltaX, int deltaY) { + + _imaqMoveContour(roi.getAddress(), id, deltaX, deltaY); + + } + + private static native void _imaqMoveContour(long roi, int id, int deltaX, int deltaY); + + public static void imaqRemoveContour(ROI roi, int id) { + + _imaqRemoveContour(roi.getAddress(), id); + + } + + private static native void _imaqRemoveContour(long roi, int id); + + public static void imaqSetContourColor(ROI roi, int id, RGBValue color) { + + _imaqSetContourColor(roi.getAddress(), id, color.getAddress()); + + } + + private static native void _imaqSetContourColor(long roi, int id, long color); + + /** + * Regions of Interest functions + */ + + public static ROI imaqCreateROI() { + + long jn_rv = _imaqCreateROI(); + + return new ROI(jn_rv, true); + } + + private static native long _imaqCreateROI(); + + public static Rect imaqGetROIBoundingBox(ROI roi) { + ByteBuffer rv_buf = ByteBuffer.allocateDirect(8).order(ByteOrder.nativeOrder()); + long rv_addr = getByteBufferAddress(rv_buf); + _imaqGetROIBoundingBox(roi.getAddress(), rv_addr + 0); + Rect boundingBox; + boundingBox = new Rect(rv_buf, 0); + boundingBox.read(); + return boundingBox; + } + + private static native void _imaqGetROIBoundingBox(long roi, long boundingBox); + + public static RGBValue imaqGetROIColor(ROI roi) { + ByteBuffer rv_buf = ByteBuffer.allocateDirect(8).order(ByteOrder.nativeOrder()); + long rv_addr = getByteBufferAddress(rv_buf); + _imaqGetROIColor(roi.getAddress(), rv_addr + 0); + RGBValue roiColor; + roiColor = new RGBValue(rv_buf, 0); + roiColor.read(); + return roiColor; + } + + private static native void _imaqGetROIColor(long roi, long roiColor); + + public static void imaqSetROIColor(ROI roi, RGBValue color) { + + _imaqSetROIColor(roi.getAddress(), color.getAddress()); + + } + + private static native void _imaqSetROIColor(long roi, long color); + + /** + * Image Analysis functions + */ + + public static PointFloat imaqCentroid(Image image, Image mask) { + ByteBuffer rv_buf = ByteBuffer.allocateDirect(8).order(ByteOrder.nativeOrder()); + long rv_addr = getByteBufferAddress(rv_buf); + _imaqCentroid(image.getAddress(), rv_addr + 0, mask.getAddress()); + PointFloat centroid; + centroid = new PointFloat(rv_buf, 0); + centroid.read(); + return centroid; + } + + private static native void _imaqCentroid(long image, long centroid, long mask); + + public static class ExtractCurvesResult { + public Curve[] array; + private long array_addr; + + private ExtractCurvesResult(ByteBuffer rv_buf, long jn_rv) { + array_addr = jn_rv; + int array_numCurves; + array_numCurves = rv_buf.getInt(0); + array = new Curve[array_numCurves]; + if (array_numCurves > 0 && array_addr != 0) { + ByteBuffer bb = newDirectByteBuffer(array_addr, array_numCurves * 48); + for (int i = 0, off = 0; i < array_numCurves; i++, off += 48) { + array[i] = new Curve(bb, off); + array[i].read(); + } + } + } + + @Override + protected void finalize() throws Throwable { + imaqDispose(array_addr); + super.finalize(); + } + } + + public static ExtractCurvesResult imaqExtractCurves(Image image, ROI roi, + CurveOptions curveOptions) { + ByteBuffer rv_buf = ByteBuffer.allocateDirect(8).order(ByteOrder.nativeOrder()); + long rv_addr = getByteBufferAddress(rv_buf); + long jn_rv = + _imaqExtractCurves(image.getAddress(), roi.getAddress(), curveOptions.getAddress(), + rv_addr + 0); + ExtractCurvesResult rv = new ExtractCurvesResult(rv_buf, jn_rv); + return rv; + } + + private static native long _imaqExtractCurves(long image, long roi, long curveOptions, + long numCurves); + + public static HistogramReport imaqHistogram(Image image, int numClasses, float min, float max, + Image mask) { + + long jn_rv = + _imaqHistogram(image.getAddress(), numClasses, min, max, + mask == null ? 0 : mask.getAddress()); + + return new HistogramReport(jn_rv, true); + } + + private static native long _imaqHistogram(long image, int numClasses, float min, float max, + long mask); + + public static LinearAverages imaqLinearAverages2(Image image, LinearAveragesMode mode, Rect rect) { + + long jn_rv = _imaqLinearAverages2(image.getAddress(), mode.getValue(), rect.getAddress()); + + return new LinearAverages(jn_rv, true); + } + + private static native long _imaqLinearAverages2(long image, int mode, long rect); + + public static LineProfile imaqLineProfile(Image image, Point start, Point end) { + + long jn_rv = _imaqLineProfile(image.getAddress(), start.getAddress(), end.getAddress()); + + return new LineProfile(jn_rv, true); + } + + private static native long _imaqLineProfile(long image, long start, long end); + + public static QuantifyReport imaqQuantify(Image image, Image mask) { + + long jn_rv = _imaqQuantify(image.getAddress(), mask == null ? 0 : mask.getAddress()); + + return new QuantifyReport(jn_rv, true); + } + + private static native long _imaqQuantify(long image, long mask); + + /** + * Threshold functions + */ + + public static ThresholdData imaqAutoThreshold2(Image dest, Image source, int numClasses, + ThresholdMethod method, Image mask) { + + long jn_rv = + _imaqAutoThreshold2(dest.getAddress(), source.getAddress(), numClasses, method.getValue(), + mask.getAddress()); + + return new ThresholdData(jn_rv, true); + } + + private static native long _imaqAutoThreshold2(long dest, long source, int numClasses, + int method, long mask); + + public static void imaqLocalThreshold(Image dest, Image source, int windowWidth, + int windowHeight, LocalThresholdMethod method, double deviationWeight, ObjectType type, + float replaceValue) { + + _imaqLocalThreshold(dest.getAddress(), source.getAddress(), windowWidth, windowHeight, + method.getValue(), deviationWeight, type.getValue(), replaceValue); + + } + + private static native void _imaqLocalThreshold(long dest, long source, int windowWidth, + int windowHeight, int method, double deviationWeight, int type, float replaceValue); + + public static void imaqMagicWand(Image dest, Image source, Point coord, float tolerance, + int connectivity8, float replaceValue) { + + _imaqMagicWand(dest.getAddress(), source.getAddress(), coord.getAddress(), tolerance, + connectivity8, replaceValue); + + } + + private static native void _imaqMagicWand(long dest, long source, long coord, float tolerance, + int connectivity8, float replaceValue); + + public static void imaqMultithreshold(Image dest, Image source, ThresholdData[] ranges) { + int numRanges = ranges.length; + ByteBuffer ranges_buf = null; + ranges_buf = ByteBuffer.allocateDirect(ranges.length * 16).order(ByteOrder.nativeOrder()); + for (int i = 0, off = 0; i < ranges.length; i++, off += 16) { + ranges[i].setBuffer(ranges_buf, off); + ranges[i].write(); + } + _imaqMultithreshold(dest.getAddress(), source.getAddress(), getByteBufferAddress(ranges_buf), + numRanges); + + } + + private static native void _imaqMultithreshold(long dest, long source, long ranges, int numRanges); + + public static void imaqThreshold(Image dest, Image source, float rangeMin, float rangeMax, + int useNewValue, float newValue) { + + _imaqThreshold(dest.getAddress(), source.getAddress(), rangeMin, rangeMax, useNewValue, + newValue); + + } + + private static native void _imaqThreshold(long dest, long source, float rangeMin, float rangeMax, + int useNewValue, float newValue); + + /** + * Memory Management functions + */ + + /** + * Pattern Matching functions + */ + + public static class DetectCirclesResult { + public CircleMatch[] array; + private long array_addr; + + private DetectCirclesResult(ByteBuffer rv_buf, long jn_rv) { + array_addr = jn_rv; + int array_numMatchesReturned; + array_numMatchesReturned = rv_buf.getInt(0); + array = new CircleMatch[array_numMatchesReturned]; + if (array_numMatchesReturned > 0 && array_addr != 0) { + ByteBuffer bb = newDirectByteBuffer(array_addr, array_numMatchesReturned * 24); + for (int i = 0, off = 0; i < array_numMatchesReturned; i++, off += 24) { + array[i] = new CircleMatch(bb, off); + array[i].read(); + } + } + } + + @Override + protected void finalize() throws Throwable { + imaqDispose(array_addr); + super.finalize(); + } + } + + public static DetectCirclesResult imaqDetectCircles(Image image, + CircleDescriptor circleDescriptor, CurveOptions curveOptions, + ShapeDetectionOptions shapeDetectionOptions, ROI roi) { + ByteBuffer rv_buf = ByteBuffer.allocateDirect(8).order(ByteOrder.nativeOrder()); + long rv_addr = getByteBufferAddress(rv_buf); + long jn_rv = + _imaqDetectCircles(image.getAddress(), circleDescriptor.getAddress(), + curveOptions.getAddress(), shapeDetectionOptions.getAddress(), roi.getAddress(), + rv_addr + 0); + DetectCirclesResult rv = new DetectCirclesResult(rv_buf, jn_rv); + return rv; + } + + private static native long _imaqDetectCircles(long image, long circleDescriptor, + long curveOptions, long shapeDetectionOptions, long roi, long numMatchesReturned); + + public static class DetectEllipsesResult { + public EllipseMatch[] array; + private long array_addr; + + private DetectEllipsesResult(ByteBuffer rv_buf, long jn_rv) { + array_addr = jn_rv; + int array_numMatchesReturned; + array_numMatchesReturned = rv_buf.getInt(0); + array = new EllipseMatch[array_numMatchesReturned]; + if (array_numMatchesReturned > 0 && array_addr != 0) { + ByteBuffer bb = newDirectByteBuffer(array_addr, array_numMatchesReturned * 40); + for (int i = 0, off = 0; i < array_numMatchesReturned; i++, off += 40) { + array[i] = new EllipseMatch(bb, off); + array[i].read(); + } + } + } + + @Override + protected void finalize() throws Throwable { + imaqDispose(array_addr); + super.finalize(); + } + } + + public static DetectEllipsesResult imaqDetectEllipses(Image image, + EllipseDescriptor ellipseDescriptor, CurveOptions curveOptions, + ShapeDetectionOptions shapeDetectionOptions, ROI roi) { + ByteBuffer rv_buf = ByteBuffer.allocateDirect(8).order(ByteOrder.nativeOrder()); + long rv_addr = getByteBufferAddress(rv_buf); + long jn_rv = + _imaqDetectEllipses(image.getAddress(), ellipseDescriptor.getAddress(), + curveOptions.getAddress(), shapeDetectionOptions.getAddress(), roi.getAddress(), + rv_addr + 0); + DetectEllipsesResult rv = new DetectEllipsesResult(rv_buf, jn_rv); + return rv; + } + + private static native long _imaqDetectEllipses(long image, long ellipseDescriptor, + long curveOptions, long shapeDetectionOptions, long roi, long numMatchesReturned); + + public static class DetectLinesResult { + public LineMatch[] array; + private long array_addr; + + private DetectLinesResult(ByteBuffer rv_buf, long jn_rv) { + array_addr = jn_rv; + int array_numMatchesReturned; + array_numMatchesReturned = rv_buf.getInt(0); + array = new LineMatch[array_numMatchesReturned]; + if (array_numMatchesReturned > 0 && array_addr != 0) { + ByteBuffer bb = newDirectByteBuffer(array_addr, array_numMatchesReturned * 40); + for (int i = 0, off = 0; i < array_numMatchesReturned; i++, off += 40) { + array[i] = new LineMatch(bb, off); + array[i].read(); + } + } + } + + @Override + protected void finalize() throws Throwable { + imaqDispose(array_addr); + super.finalize(); + } + } + + public static DetectLinesResult imaqDetectLines(Image image, LineDescriptor lineDescriptor, + CurveOptions curveOptions, ShapeDetectionOptions shapeDetectionOptions, ROI roi) { + ByteBuffer rv_buf = ByteBuffer.allocateDirect(8).order(ByteOrder.nativeOrder()); + long rv_addr = getByteBufferAddress(rv_buf); + long jn_rv = + _imaqDetectLines(image.getAddress(), lineDescriptor.getAddress(), + curveOptions.getAddress(), shapeDetectionOptions.getAddress(), roi.getAddress(), + rv_addr + 0); + DetectLinesResult rv = new DetectLinesResult(rv_buf, jn_rv); + return rv; + } + + private static native long _imaqDetectLines(long image, long lineDescriptor, long curveOptions, + long shapeDetectionOptions, long roi, long numMatchesReturned); + + public static class DetectRectanglesResult { + public RectangleMatch[] array; + private long array_addr; + + private DetectRectanglesResult(ByteBuffer rv_buf, long jn_rv) { + array_addr = jn_rv; + int array_numMatchesReturned; + array_numMatchesReturned = rv_buf.getInt(0); + array = new RectangleMatch[array_numMatchesReturned]; + if (array_numMatchesReturned > 0 && array_addr != 0) { + ByteBuffer bb = newDirectByteBuffer(array_addr, array_numMatchesReturned * 64); + for (int i = 0, off = 0; i < array_numMatchesReturned; i++, off += 64) { + array[i] = new RectangleMatch(bb, off); + array[i].read(); + } + } + } + + @Override + protected void finalize() throws Throwable { + imaqDispose(array_addr); + super.finalize(); + } + } + + public static DetectRectanglesResult imaqDetectRectangles(Image image, + RectangleDescriptor rectangleDescriptor, CurveOptions curveOptions, + ShapeDetectionOptions shapeDetectionOptions, ROI roi) { + ByteBuffer rv_buf = ByteBuffer.allocateDirect(8).order(ByteOrder.nativeOrder()); + long rv_addr = getByteBufferAddress(rv_buf); + long jn_rv = + _imaqDetectRectangles(image.getAddress(), rectangleDescriptor.getAddress(), + curveOptions.getAddress(), shapeDetectionOptions.getAddress(), roi.getAddress(), + rv_addr + 0); + DetectRectanglesResult rv = new DetectRectanglesResult(rv_buf, jn_rv); + return rv; + } + + private static native long _imaqDetectRectangles(long image, long rectangleDescriptor, + long curveOptions, long shapeDetectionOptions, long roi, long numMatchesReturned); + + public static class GetGeometricFeaturesFromCurvesResult { + public FeatureData[] array; + private long array_addr; + + private GetGeometricFeaturesFromCurvesResult(ByteBuffer rv_buf, long jn_rv) { + array_addr = jn_rv; + int array_numFeatures; + array_numFeatures = rv_buf.getInt(0); + array = new FeatureData[array_numFeatures]; + if (array_numFeatures > 0 && array_addr != 0) { + ByteBuffer bb = newDirectByteBuffer(array_addr, array_numFeatures * 16); + for (int i = 0, off = 0; i < array_numFeatures; i++, off += 16) { + array[i] = new FeatureData(bb, off); + array[i].read(); + } + } + } + + @Override + protected void finalize() throws Throwable { + imaqDispose(array_addr); + super.finalize(); + } + } + + public static GetGeometricFeaturesFromCurvesResult imaqGetGeometricFeaturesFromCurves( + Curve[] curves, FeatureType[] featureTypes) { + int numCurves = curves.length; + ByteBuffer curves_buf = null; + curves_buf = ByteBuffer.allocateDirect(curves.length * 48).order(ByteOrder.nativeOrder()); + for (int i = 0, off = 0; i < curves.length; i++, off += 48) { + curves[i].setBuffer(curves_buf, off); + curves[i].write(); + } + int numFeatureTypes = featureTypes.length; + ByteBuffer featureTypes_buf = null; + featureTypes_buf = + ByteBuffer.allocateDirect(featureTypes.length * 4).order(ByteOrder.nativeOrder()); + for (int i = 0, off = 0; i < featureTypes.length; i++, off += 4) { + if (featureTypes != null) + featureTypes_buf.putInt(off, featureTypes[i].getValue()); + } + ByteBuffer rv_buf = ByteBuffer.allocateDirect(8).order(ByteOrder.nativeOrder()); + long rv_addr = getByteBufferAddress(rv_buf); + long jn_rv = + _imaqGetGeometricFeaturesFromCurves(getByteBufferAddress(curves_buf), numCurves, + getByteBufferAddress(featureTypes_buf), numFeatureTypes, rv_addr + 0); + GetGeometricFeaturesFromCurvesResult rv = + new GetGeometricFeaturesFromCurvesResult(rv_buf, jn_rv); + return rv; + } + + private static native long _imaqGetGeometricFeaturesFromCurves(long curves, int numCurves, + long featureTypes, int numFeatureTypes, long numFeatures); + + public static class GetGeometricTemplateFeatureInfoResult { + public FeatureData[] array; + private long array_addr; + + private GetGeometricTemplateFeatureInfoResult(ByteBuffer rv_buf, long jn_rv) { + array_addr = jn_rv; + int array_numFeatures; + array_numFeatures = rv_buf.getInt(0); + array = new FeatureData[array_numFeatures]; + if (array_numFeatures > 0 && array_addr != 0) { + ByteBuffer bb = newDirectByteBuffer(array_addr, array_numFeatures * 16); + for (int i = 0, off = 0; i < array_numFeatures; i++, off += 16) { + array[i] = new FeatureData(bb, off); + array[i].read(); + } + } + } + + @Override + protected void finalize() throws Throwable { + imaqDispose(array_addr); + super.finalize(); + } + } + + public static GetGeometricTemplateFeatureInfoResult imaqGetGeometricTemplateFeatureInfo( + Image pattern) { + ByteBuffer rv_buf = ByteBuffer.allocateDirect(8).order(ByteOrder.nativeOrder()); + long rv_addr = getByteBufferAddress(rv_buf); + long jn_rv = _imaqGetGeometricTemplateFeatureInfo(pattern.getAddress(), rv_addr + 0); + GetGeometricTemplateFeatureInfoResult rv = + new GetGeometricTemplateFeatureInfoResult(rv_buf, jn_rv); + return rv; + } + + private static native long _imaqGetGeometricTemplateFeatureInfo(long pattern, long numFeatures); + + public static void imaqLearnColorPattern(Image image, LearnColorPatternOptions options) { + + _imaqLearnColorPattern(image.getAddress(), options.getAddress()); + + } + + private static native void _imaqLearnColorPattern(long image, long options); + + public static void imaqLearnGeometricPattern(Image image, PointFloat originOffset, + CurveOptions curveOptions, LearnGeometricPatternAdvancedOptions advancedLearnOptions, + Image mask) { + + _imaqLearnGeometricPattern(image.getAddress(), originOffset.getAddress(), + curveOptions.getAddress(), advancedLearnOptions.getAddress(), mask.getAddress()); + + } + + private static native void _imaqLearnGeometricPattern(long image, long originOffset, + long curveOptions, long advancedLearnOptions, long mask); + + public static LearnPatternAdvancedOptions imaqLearnPattern3(Image image, + LearningMode learningMode, Image mask) { + ByteBuffer rv_buf = ByteBuffer.allocateDirect(8).order(ByteOrder.nativeOrder()); + long rv_addr = getByteBufferAddress(rv_buf); + _imaqLearnPattern3(image.getAddress(), learningMode.getValue(), rv_addr + 0, mask.getAddress()); + LearnPatternAdvancedOptions advancedOptions; + advancedOptions = new LearnPatternAdvancedOptions(rv_buf, 0); + advancedOptions.read(); + return advancedOptions; + } + + private static native void _imaqLearnPattern3(long image, int learningMode, long advancedOptions, + long mask); + + public static class MatchColorPatternResult { + public PatternMatch[] array; + private long array_addr; + + private MatchColorPatternResult(ByteBuffer rv_buf, long jn_rv) { + array_addr = jn_rv; + int array_numMatches; + array_numMatches = rv_buf.getInt(0); + array = new PatternMatch[array_numMatches]; + if (array_numMatches > 0 && array_addr != 0) { + ByteBuffer bb = newDirectByteBuffer(array_addr, array_numMatches * 52); + for (int i = 0, off = 0; i < array_numMatches; i++, off += 52) { + array[i] = new PatternMatch(bb, off); + array[i].read(); + } + } + } + + @Override + protected void finalize() throws Throwable { + imaqDispose(array_addr); + super.finalize(); + } + } + + public static MatchColorPatternResult imaqMatchColorPattern(Image image, Image pattern, + MatchColorPatternOptions options, Rect searchRect) { + ByteBuffer rv_buf = ByteBuffer.allocateDirect(8).order(ByteOrder.nativeOrder()); + long rv_addr = getByteBufferAddress(rv_buf); + long jn_rv = + _imaqMatchColorPattern(image.getAddress(), pattern.getAddress(), options.getAddress(), + searchRect.getAddress(), rv_addr + 0); + MatchColorPatternResult rv = new MatchColorPatternResult(rv_buf, jn_rv); + return rv; + } + + private static native long _imaqMatchColorPattern(long image, long pattern, long options, + long searchRect, long numMatches); + + public static class MatchGeometricPattern2Result { + public GeometricPatternMatch2[] array; + private long array_addr; + + private MatchGeometricPattern2Result(ByteBuffer rv_buf, long jn_rv) { + array_addr = jn_rv; + int array_numMatches; + array_numMatches = rv_buf.getInt(0); + array = new GeometricPatternMatch2[array_numMatches]; + if (array_numMatches > 0 && array_addr != 0) { + ByteBuffer bb = newDirectByteBuffer(array_addr, array_numMatches * 380); + for (int i = 0, off = 0; i < array_numMatches; i++, off += 380) { + array[i] = new GeometricPatternMatch2(bb, off); + array[i].read(); + } + } + } + + @Override + protected void finalize() throws Throwable { + imaqDispose(array_addr); + super.finalize(); + } + } + + public static MatchGeometricPattern2Result imaqMatchGeometricPattern2(Image image, Image pattern, + CurveOptions curveOptions, MatchGeometricPatternOptions matchOptions, + MatchGeometricPatternAdvancedOptions2 advancedMatchOptions, ROI roi) { + ByteBuffer rv_buf = ByteBuffer.allocateDirect(8).order(ByteOrder.nativeOrder()); + long rv_addr = getByteBufferAddress(rv_buf); + long jn_rv = + _imaqMatchGeometricPattern2(image.getAddress(), pattern.getAddress(), + curveOptions.getAddress(), matchOptions.getAddress(), + advancedMatchOptions.getAddress(), roi.getAddress(), rv_addr + 0); + MatchGeometricPattern2Result rv = new MatchGeometricPattern2Result(rv_buf, jn_rv); + return rv; + } + + private static native long _imaqMatchGeometricPattern2(long image, long pattern, + long curveOptions, long matchOptions, long advancedMatchOptions, long roi, long numMatches); + + public static class MatchMultipleGeometricPatternsResult { + public GeometricPatternMatch2[] array; + private long array_addr; + + private MatchMultipleGeometricPatternsResult(ByteBuffer rv_buf, long jn_rv) { + array_addr = jn_rv; + int array_numMatches; + array_numMatches = rv_buf.getInt(0); + array = new GeometricPatternMatch2[array_numMatches]; + if (array_numMatches > 0 && array_addr != 0) { + ByteBuffer bb = newDirectByteBuffer(array_addr, array_numMatches * 380); + for (int i = 0, off = 0; i < array_numMatches; i++, off += 380) { + array[i] = new GeometricPatternMatch2(bb, off); + array[i].read(); + } + } + } + + @Override + protected void finalize() throws Throwable { + imaqDispose(array_addr); + super.finalize(); + } + } + + public static MatchMultipleGeometricPatternsResult imaqMatchMultipleGeometricPatterns( + Image image, MultipleGeometricPattern multiplePattern, ROI roi) { + ByteBuffer rv_buf = ByteBuffer.allocateDirect(8).order(ByteOrder.nativeOrder()); + long rv_addr = getByteBufferAddress(rv_buf); + long jn_rv = + _imaqMatchMultipleGeometricPatterns(image.getAddress(), multiplePattern.getAddress(), + roi.getAddress(), rv_addr + 0); + MatchMultipleGeometricPatternsResult rv = + new MatchMultipleGeometricPatternsResult(rv_buf, jn_rv); + return rv; + } + + private static native long _imaqMatchMultipleGeometricPatterns(long image, long multiplePattern, + long roi, long numMatches); + + public static MultipleGeometricPattern imaqReadMultipleGeometricPatternFile(String fileName, + String description) { + ByteBuffer fileName_buf = null; + if (fileName != null) { + byte[] fileName_bytes; + try { + fileName_bytes = fileName.getBytes("UTF-8"); + } catch (UnsupportedEncodingException e) { + fileName_bytes = new byte[0]; + } + fileName_buf = ByteBuffer.allocateDirect(fileName_bytes.length + 1); + putBytes(fileName_buf, fileName_bytes, 0, fileName_bytes.length).put(fileName_bytes.length, + (byte) 0); + } + ByteBuffer description_buf = ByteBuffer.allocateDirect(256).order(ByteOrder.nativeOrder()); + if (description != null) { + byte[] bytes; + try { + bytes = description.getBytes("UTF-8"); + } catch (UnsupportedEncodingException e) { + bytes = new byte[0]; + } + putBytes(description_buf, bytes, 0, bytes.length); + for (int i = bytes.length; i < 256; i++) + description_buf.put(i, (byte) 0); // fill with zero + } + long jn_rv = + _imaqReadMultipleGeometricPatternFile(fileName == null ? 0 + : getByteBufferAddress(fileName_buf), description == null ? 0 + : getByteBufferAddress(description_buf)); + + return new MultipleGeometricPattern(jn_rv, true); + } + + private static native long _imaqReadMultipleGeometricPatternFile(long fileName, long description); + + public static class RefineMatchesResult { + public MatchPatternOptions options; + public MatchPatternAdvancedOptions advancedOptions; + public PatternMatch[] array; + private long array_addr; + + private RefineMatchesResult(ByteBuffer rv_buf, long jn_rv) { + array_addr = jn_rv; + options = new MatchPatternOptions(rv_buf, 0); + options.read(); + advancedOptions = new MatchPatternAdvancedOptions(rv_buf, 8); + advancedOptions.read(); + int array_numCandidatesOut; + array_numCandidatesOut = rv_buf.getInt(16); + array = new PatternMatch[array_numCandidatesOut]; + if (array_numCandidatesOut > 0 && array_addr != 0) { + ByteBuffer bb = newDirectByteBuffer(array_addr, array_numCandidatesOut * 52); + for (int i = 0, off = 0; i < array_numCandidatesOut; i++, off += 52) { + array[i] = new PatternMatch(bb, off); + array[i].read(); + } + } + } + + @Override + protected void finalize() throws Throwable { + imaqDispose(array_addr); + super.finalize(); + } + } + + public static RefineMatchesResult imaqRefineMatches(Image image, Image pattern, + PatternMatch[] candidatesIn) { + int numCandidatesIn = candidatesIn.length; + ByteBuffer candidatesIn_buf = null; + candidatesIn_buf = + ByteBuffer.allocateDirect(candidatesIn.length * 52).order(ByteOrder.nativeOrder()); + for (int i = 0, off = 0; i < candidatesIn.length; i++, off += 52) { + candidatesIn[i].setBuffer(candidatesIn_buf, off); + candidatesIn[i].write(); + } + ByteBuffer rv_buf = ByteBuffer.allocateDirect(8 + 8 + 8).order(ByteOrder.nativeOrder()); + long rv_addr = getByteBufferAddress(rv_buf); + long jn_rv = + _imaqRefineMatches(image.getAddress(), pattern.getAddress(), + getByteBufferAddress(candidatesIn_buf), numCandidatesIn, rv_addr + 0, rv_addr + 8, + rv_addr + 16); + RefineMatchesResult rv = new RefineMatchesResult(rv_buf, jn_rv); + return rv; + } + + private static native long _imaqRefineMatches(long image, long pattern, long candidatesIn, + int numCandidatesIn, long options, long advancedOptions, long numCandidatesOut); + + public static void imaqSetMultipleGeometricPatternsOptions( + MultipleGeometricPattern multiplePattern, String label, CurveOptions curveOptions, + MatchGeometricPatternOptions matchOptions, + MatchGeometricPatternAdvancedOptions2 advancedMatchOptions) { + ByteBuffer label_buf = null; + if (label != null) { + byte[] label_bytes; + try { + label_bytes = label.getBytes("UTF-8"); + } catch (UnsupportedEncodingException e) { + label_bytes = new byte[0]; + } + label_buf = ByteBuffer.allocateDirect(label_bytes.length + 1); + putBytes(label_buf, label_bytes, 0, label_bytes.length).put(label_bytes.length, (byte) 0); + } + _imaqSetMultipleGeometricPatternsOptions(multiplePattern.getAddress(), label == null ? 0 + : getByteBufferAddress(label_buf), curveOptions.getAddress(), matchOptions.getAddress(), + advancedMatchOptions.getAddress()); + + } + + private static native void _imaqSetMultipleGeometricPatternsOptions(long multiplePattern, + long label, long curveOptions, long matchOptions, long advancedMatchOptions); + + public static void imaqWriteMultipleGeometricPatternFile( + MultipleGeometricPattern multiplePattern, String fileName, String description) { + ByteBuffer fileName_buf = null; + if (fileName != null) { + byte[] fileName_bytes; + try { + fileName_bytes = fileName.getBytes("UTF-8"); + } catch (UnsupportedEncodingException e) { + fileName_bytes = new byte[0]; + } + fileName_buf = ByteBuffer.allocateDirect(fileName_bytes.length + 1); + putBytes(fileName_buf, fileName_bytes, 0, fileName_bytes.length).put(fileName_bytes.length, + (byte) 0); + } + ByteBuffer description_buf = null; + if (description != null) { + byte[] description_bytes; + try { + description_bytes = description.getBytes("UTF-8"); + } catch (UnsupportedEncodingException e) { + description_bytes = new byte[0]; + } + description_buf = ByteBuffer.allocateDirect(description_bytes.length + 1); + putBytes(description_buf, description_bytes, 0, description_bytes.length).put( + description_bytes.length, (byte) 0); + } + _imaqWriteMultipleGeometricPatternFile(multiplePattern.getAddress(), fileName == null ? 0 + : getByteBufferAddress(fileName_buf), description == null ? 0 + : getByteBufferAddress(description_buf)); + + } + + private static native void _imaqWriteMultipleGeometricPatternFile(long multiplePattern, + long fileName, long description); + + public static class MatchGeometricPattern3Result { + public GeometricPatternMatch3[] array; + private long array_addr; + + private MatchGeometricPattern3Result(ByteBuffer rv_buf, long jn_rv) { + array_addr = jn_rv; + int array_numMatches; + array_numMatches = rv_buf.getInt(0); + array = new GeometricPatternMatch3[array_numMatches]; + if (array_numMatches > 0 && array_addr != 0) { + ByteBuffer bb = newDirectByteBuffer(array_addr, array_numMatches * 116); + for (int i = 0, off = 0; i < array_numMatches; i++, off += 116) { + array[i] = new GeometricPatternMatch3(bb, off); + array[i].read(); + } + } + } + + @Override + protected void finalize() throws Throwable { + imaqDispose(array_addr); + super.finalize(); + } + } + + public static MatchGeometricPattern3Result imaqMatchGeometricPattern3(Image image, Image pattern, + CurveOptions curveOptions, MatchGeometricPatternOptions matchOptions, + MatchGeometricPatternAdvancedOptions3 advancedMatchOptions, ROI roi) { + ByteBuffer rv_buf = ByteBuffer.allocateDirect(8).order(ByteOrder.nativeOrder()); + long rv_addr = getByteBufferAddress(rv_buf); + long jn_rv = + _imaqMatchGeometricPattern3(image.getAddress(), pattern.getAddress(), + curveOptions.getAddress(), matchOptions.getAddress(), + advancedMatchOptions.getAddress(), roi.getAddress(), rv_addr + 0); + MatchGeometricPattern3Result rv = new MatchGeometricPattern3Result(rv_buf, jn_rv); + return rv; + } + + private static native long _imaqMatchGeometricPattern3(long image, long pattern, + long curveOptions, long matchOptions, long advancedMatchOptions, long roi, long numMatches); + + public static void imaqLearnGeometricPattern2(Image image, PointFloat originOffset, + double angleOffset, CurveOptions curveOptions, + LearnGeometricPatternAdvancedOptions2 advancedLearnOptions, Image mask) { + + _imaqLearnGeometricPattern2(image.getAddress(), originOffset.getAddress(), angleOffset, + curveOptions.getAddress(), advancedLearnOptions.getAddress(), mask.getAddress()); + + } + + private static native void _imaqLearnGeometricPattern2(long image, long originOffset, + double angleOffset, long curveOptions, long advancedLearnOptions, long mask); + + public static class MatchPattern3Result { + public PatternMatch[] array; + private long array_addr; + + private MatchPattern3Result(ByteBuffer rv_buf, long jn_rv) { + array_addr = jn_rv; + int array_numMatches; + array_numMatches = rv_buf.getInt(0); + array = new PatternMatch[array_numMatches]; + if (array_numMatches > 0 && array_addr != 0) { + ByteBuffer bb = newDirectByteBuffer(array_addr, array_numMatches * 52); + for (int i = 0, off = 0; i < array_numMatches; i++, off += 52) { + array[i] = new PatternMatch(bb, off); + array[i].read(); + } + } + } + + @Override + protected void finalize() throws Throwable { + imaqDispose(array_addr); + super.finalize(); + } + } + + public static MatchPattern3Result imaqMatchPattern3(Image image, Image pattern, + MatchPatternOptions options, MatchPatternAdvancedOptions advancedOptions, ROI roi) { + ByteBuffer rv_buf = ByteBuffer.allocateDirect(8).order(ByteOrder.nativeOrder()); + long rv_addr = getByteBufferAddress(rv_buf); + long jn_rv = + _imaqMatchPattern3(image.getAddress(), pattern.getAddress(), + options == null ? 0 : options.getAddress(), advancedOptions.getAddress(), + roi.getAddress(), rv_addr + 0); + MatchPattern3Result rv = new MatchPattern3Result(rv_buf, jn_rv); + return rv; + } + + private static native long _imaqMatchPattern3(long image, long pattern, long options, + long advancedOptions, long roi, long numMatches); + + /** + * Overlay functions + */ + + public static void imaqClearOverlay(Image image, String group) { + ByteBuffer group_buf = null; + if (group != null) { + byte[] group_bytes; + try { + group_bytes = group.getBytes("UTF-8"); + } catch (UnsupportedEncodingException e) { + group_bytes = new byte[0]; + } + group_buf = ByteBuffer.allocateDirect(group_bytes.length + 1); + putBytes(group_buf, group_bytes, 0, group_bytes.length).put(group_bytes.length, (byte) 0); + } + _imaqClearOverlay(image.getAddress(), group == null ? 0 : getByteBufferAddress(group_buf)); + + } + + private static native void _imaqClearOverlay(long image, long group); + + public static void imaqCopyOverlay(Image dest, Image source, String group) { + ByteBuffer group_buf = null; + if (group != null) { + byte[] group_bytes; + try { + group_bytes = group.getBytes("UTF-8"); + } catch (UnsupportedEncodingException e) { + group_bytes = new byte[0]; + } + group_buf = ByteBuffer.allocateDirect(group_bytes.length + 1); + putBytes(group_buf, group_bytes, 0, group_bytes.length).put(group_bytes.length, (byte) 0); + } + _imaqCopyOverlay(dest.getAddress(), source.getAddress(), group == null ? 0 + : getByteBufferAddress(group_buf)); + + } + + private static native void _imaqCopyOverlay(long dest, long source, long group); + + public static TransformBehaviors imaqGetOverlayProperties(Image image, String group) { + ByteBuffer group_buf = null; + if (group != null) { + byte[] group_bytes; + try { + group_bytes = group.getBytes("UTF-8"); + } catch (UnsupportedEncodingException e) { + group_bytes = new byte[0]; + } + group_buf = ByteBuffer.allocateDirect(group_bytes.length + 1); + putBytes(group_buf, group_bytes, 0, group_bytes.length).put(group_bytes.length, (byte) 0); + } + ByteBuffer rv_buf = ByteBuffer.allocateDirect(8).order(ByteOrder.nativeOrder()); + long rv_addr = getByteBufferAddress(rv_buf); + _imaqGetOverlayProperties(image.getAddress(), group == null ? 0 + : getByteBufferAddress(group_buf), rv_addr + 0); + TransformBehaviors transformBehaviors; + transformBehaviors = new TransformBehaviors(rv_buf, 0); + transformBehaviors.read(); + return transformBehaviors; + } + + private static native void _imaqGetOverlayProperties(long image, long group, + long transformBehaviors); + + public static void imaqMergeOverlay(Image dest, Image source, RGBValue[] palette, String group) { + int numColors = palette.length; + ByteBuffer palette_buf = null; + palette_buf = ByteBuffer.allocateDirect(palette.length * 4).order(ByteOrder.nativeOrder()); + for (int i = 0, off = 0; i < palette.length; i++, off += 4) { + palette[i].setBuffer(palette_buf, off); + palette[i].write(); + } + ByteBuffer group_buf = null; + if (group != null) { + byte[] group_bytes; + try { + group_bytes = group.getBytes("UTF-8"); + } catch (UnsupportedEncodingException e) { + group_bytes = new byte[0]; + } + group_buf = ByteBuffer.allocateDirect(group_bytes.length + 1); + putBytes(group_buf, group_bytes, 0, group_bytes.length).put(group_bytes.length, (byte) 0); + } + _imaqMergeOverlay(dest.getAddress(), source.getAddress(), getByteBufferAddress(palette_buf), + numColors, group == null ? 0 : getByteBufferAddress(group_buf)); + + } + + private static native void _imaqMergeOverlay(long dest, long source, long palette, int numColors, + long group); + + public static void imaqOverlayArc(Image image, ArcInfo arc, RGBValue color, DrawMode drawMode, + String group) { + ByteBuffer group_buf = null; + if (group != null) { + byte[] group_bytes; + try { + group_bytes = group.getBytes("UTF-8"); + } catch (UnsupportedEncodingException e) { + group_bytes = new byte[0]; + } + group_buf = ByteBuffer.allocateDirect(group_bytes.length + 1); + putBytes(group_buf, group_bytes, 0, group_bytes.length).put(group_bytes.length, (byte) 0); + } + _imaqOverlayArc(image.getAddress(), arc.getAddress(), color.getAddress(), drawMode.getValue(), + group == null ? 0 : getByteBufferAddress(group_buf)); + + } + + private static native void _imaqOverlayArc(long image, long arc, long color, int drawMode, + long group); + + public static void imaqOverlayBitmap(Image image, Point destLoc, RGBValue bitmap, int numCols, + int numRows, String group) { + ByteBuffer group_buf = null; + if (group != null) { + byte[] group_bytes; + try { + group_bytes = group.getBytes("UTF-8"); + } catch (UnsupportedEncodingException e) { + group_bytes = new byte[0]; + } + group_buf = ByteBuffer.allocateDirect(group_bytes.length + 1); + putBytes(group_buf, group_bytes, 0, group_bytes.length).put(group_bytes.length, (byte) 0); + } + _imaqOverlayBitmap(image.getAddress(), destLoc.getAddress(), bitmap.getAddress(), numCols, + numRows, group == null ? 0 : getByteBufferAddress(group_buf)); + + } + + private static native void _imaqOverlayBitmap(long image, long destLoc, long bitmap, int numCols, + int numRows, long group); + + public static void imaqOverlayClosedContour(Image image, Point[] points, RGBValue color, + DrawMode drawMode, String group) { + int numPoints = points.length; + ByteBuffer points_buf = null; + points_buf = ByteBuffer.allocateDirect(points.length * 8).order(ByteOrder.nativeOrder()); + for (int i = 0, off = 0; i < points.length; i++, off += 8) { + points[i].setBuffer(points_buf, off); + points[i].write(); + } + ByteBuffer group_buf = null; + if (group != null) { + byte[] group_bytes; + try { + group_bytes = group.getBytes("UTF-8"); + } catch (UnsupportedEncodingException e) { + group_bytes = new byte[0]; + } + group_buf = ByteBuffer.allocateDirect(group_bytes.length + 1); + putBytes(group_buf, group_bytes, 0, group_bytes.length).put(group_bytes.length, (byte) 0); + } + _imaqOverlayClosedContour(image.getAddress(), getByteBufferAddress(points_buf), numPoints, + color.getAddress(), drawMode.getValue(), group == null ? 0 + : getByteBufferAddress(group_buf)); + + } + + private static native void _imaqOverlayClosedContour(long image, long points, int numPoints, + long color, int drawMode, long group); + + public static void imaqOverlayLine(Image image, Point start, Point end, RGBValue color, + String group) { + ByteBuffer group_buf = null; + if (group != null) { + byte[] group_bytes; + try { + group_bytes = group.getBytes("UTF-8"); + } catch (UnsupportedEncodingException e) { + group_bytes = new byte[0]; + } + group_buf = ByteBuffer.allocateDirect(group_bytes.length + 1); + putBytes(group_buf, group_bytes, 0, group_bytes.length).put(group_bytes.length, (byte) 0); + } + _imaqOverlayLine(image.getAddress(), start.getAddress(), end.getAddress(), color.getAddress(), + group == null ? 0 : getByteBufferAddress(group_buf)); + + } + + private static native void _imaqOverlayLine(long image, long start, long end, long color, + long group); + + public static void imaqOverlayOpenContour(Image image, Point[] points, RGBValue color, + String group) { + int numPoints = points.length; + ByteBuffer points_buf = null; + points_buf = ByteBuffer.allocateDirect(points.length * 8).order(ByteOrder.nativeOrder()); + for (int i = 0, off = 0; i < points.length; i++, off += 8) { + points[i].setBuffer(points_buf, off); + points[i].write(); + } + ByteBuffer group_buf = null; + if (group != null) { + byte[] group_bytes; + try { + group_bytes = group.getBytes("UTF-8"); + } catch (UnsupportedEncodingException e) { + group_bytes = new byte[0]; + } + group_buf = ByteBuffer.allocateDirect(group_bytes.length + 1); + putBytes(group_buf, group_bytes, 0, group_bytes.length).put(group_bytes.length, (byte) 0); + } + _imaqOverlayOpenContour(image.getAddress(), getByteBufferAddress(points_buf), numPoints, + color.getAddress(), group == null ? 0 : getByteBufferAddress(group_buf)); + + } + + private static native void _imaqOverlayOpenContour(long image, long points, int numPoints, + long color, long group); + + public static byte imaqOverlayOval(Image image, Rect boundingBox, RGBValue color, + DrawMode drawMode) { + ByteBuffer rv_buf = ByteBuffer.allocateDirect(8).order(ByteOrder.nativeOrder()); + long rv_addr = getByteBufferAddress(rv_buf); + _imaqOverlayOval(image.getAddress(), boundingBox.getAddress(), color.getAddress(), + drawMode.getValue(), rv_addr + 0); + byte group; + group = rv_buf.get(0); + return group; + } + + private static native void _imaqOverlayOval(long image, long boundingBox, long color, + int drawMode, long group); + + public static void imaqOverlayPoints(Image image, Point[] points, RGBValue[] colors, + PointSymbol symbol, UserPointSymbol userSymbol, String group) { + int numPoints = points.length; + ByteBuffer points_buf = null; + points_buf = ByteBuffer.allocateDirect(points.length * 8).order(ByteOrder.nativeOrder()); + for (int i = 0, off = 0; i < points.length; i++, off += 8) { + points[i].setBuffer(points_buf, off); + points[i].write(); + } + int numColors = colors.length; + ByteBuffer colors_buf = null; + colors_buf = ByteBuffer.allocateDirect(colors.length * 4).order(ByteOrder.nativeOrder()); + for (int i = 0, off = 0; i < colors.length; i++, off += 4) { + colors[i].setBuffer(colors_buf, off); + colors[i].write(); + } + ByteBuffer group_buf = null; + if (group != null) { + byte[] group_bytes; + try { + group_bytes = group.getBytes("UTF-8"); + } catch (UnsupportedEncodingException e) { + group_bytes = new byte[0]; + } + group_buf = ByteBuffer.allocateDirect(group_bytes.length + 1); + putBytes(group_buf, group_bytes, 0, group_bytes.length).put(group_bytes.length, (byte) 0); + } + _imaqOverlayPoints(image.getAddress(), getByteBufferAddress(points_buf), numPoints, + getByteBufferAddress(colors_buf), numColors, symbol.getValue(), userSymbol.getAddress(), + group == null ? 0 : getByteBufferAddress(group_buf)); + + } + + private static native void _imaqOverlayPoints(long image, long points, int numPoints, + long colors, int numColors, int symbol, long userSymbol, long group); + + public static void imaqOverlayRect(Image image, Rect rect, RGBValue color, DrawMode drawMode, + String group) { + ByteBuffer group_buf = null; + if (group != null) { + byte[] group_bytes; + try { + group_bytes = group.getBytes("UTF-8"); + } catch (UnsupportedEncodingException e) { + group_bytes = new byte[0]; + } + group_buf = ByteBuffer.allocateDirect(group_bytes.length + 1); + putBytes(group_buf, group_bytes, 0, group_bytes.length).put(group_bytes.length, (byte) 0); + } + _imaqOverlayRect(image.getAddress(), rect.getAddress(), color.getAddress(), + drawMode.getValue(), group == null ? 0 : getByteBufferAddress(group_buf)); + + } + + private static native void _imaqOverlayRect(long image, long rect, long color, int drawMode, + long group); + + public static void imaqOverlayROI(Image image, ROI roi, PointSymbol symbol, + UserPointSymbol userSymbol, String group) { + ByteBuffer group_buf = null; + if (group != null) { + byte[] group_bytes; + try { + group_bytes = group.getBytes("UTF-8"); + } catch (UnsupportedEncodingException e) { + group_bytes = new byte[0]; + } + group_buf = ByteBuffer.allocateDirect(group_bytes.length + 1); + putBytes(group_buf, group_bytes, 0, group_bytes.length).put(group_bytes.length, (byte) 0); + } + _imaqOverlayROI(image.getAddress(), roi.getAddress(), symbol.getValue(), + userSymbol.getAddress(), group == null ? 0 : getByteBufferAddress(group_buf)); + + } + + private static native void _imaqOverlayROI(long image, long roi, int symbol, long userSymbol, + long group); + + public static void imaqOverlayText(Image image, Point origin, String text, RGBValue color, + OverlayTextOptions options, String group) { + ByteBuffer text_buf = null; + if (text != null) { + byte[] text_bytes; + try { + text_bytes = text.getBytes("UTF-8"); + } catch (UnsupportedEncodingException e) { + text_bytes = new byte[0]; + } + text_buf = ByteBuffer.allocateDirect(text_bytes.length + 1); + putBytes(text_buf, text_bytes, 0, text_bytes.length).put(text_bytes.length, (byte) 0); + } + ByteBuffer group_buf = null; + if (group != null) { + byte[] group_bytes; + try { + group_bytes = group.getBytes("UTF-8"); + } catch (UnsupportedEncodingException e) { + group_bytes = new byte[0]; + } + group_buf = ByteBuffer.allocateDirect(group_bytes.length + 1); + putBytes(group_buf, group_bytes, 0, group_bytes.length).put(group_bytes.length, (byte) 0); + } + _imaqOverlayText(image.getAddress(), origin.getAddress(), text == null ? 0 + : getByteBufferAddress(text_buf), color.getAddress(), options.getAddress(), + group == null ? 0 : getByteBufferAddress(group_buf)); + + } + + private static native void _imaqOverlayText(long image, long origin, long text, long color, + long options, long group); + + public static TransformBehaviors imaqSetOverlayProperties(Image image, String group) { + ByteBuffer group_buf = null; + if (group != null) { + byte[] group_bytes; + try { + group_bytes = group.getBytes("UTF-8"); + } catch (UnsupportedEncodingException e) { + group_bytes = new byte[0]; + } + group_buf = ByteBuffer.allocateDirect(group_bytes.length + 1); + putBytes(group_buf, group_bytes, 0, group_bytes.length).put(group_bytes.length, (byte) 0); + } + ByteBuffer rv_buf = ByteBuffer.allocateDirect(8).order(ByteOrder.nativeOrder()); + long rv_addr = getByteBufferAddress(rv_buf); + _imaqSetOverlayProperties(image.getAddress(), group == null ? 0 + : getByteBufferAddress(group_buf), rv_addr + 0); + TransformBehaviors transformBehaviors; + transformBehaviors = new TransformBehaviors(rv_buf, 0); + transformBehaviors.read(); + return transformBehaviors; + } + + private static native void _imaqSetOverlayProperties(long image, long group, + long transformBehaviors); + + /** + * OCR functions + */ + + public static CharSet imaqCreateCharSet() { + + long jn_rv = _imaqCreateCharSet(); + + return new CharSet(jn_rv, true); + } + + private static native long _imaqCreateCharSet(); + + public static void imaqDeleteChar(CharSet set, int index) { + + _imaqDeleteChar(set.getAddress(), index); + + } + + private static native void _imaqDeleteChar(long set, int index); + + public static void imaqGetCharCount(CharSet set) { + + _imaqGetCharCount(set.getAddress()); + + } + + private static native void _imaqGetCharCount(long set); + + public static CharInfo2 imaqGetCharInfo2(CharSet set, int index) { + + long jn_rv = _imaqGetCharInfo2(set.getAddress(), index); + + return new CharInfo2(jn_rv, true); + } + + private static native long _imaqGetCharInfo2(long set, int index); + + public static class ReadOCRFileResult { + public ReadTextOptions readOptions; + public OCRProcessingOptions processingOptions; + public OCRSpacingOptions spacingOptions; + + private ReadOCRFileResult(ByteBuffer rv_buf) { + readOptions = new ReadTextOptions(rv_buf, 0); + readOptions.read(); + processingOptions = new OCRProcessingOptions(rv_buf, 8); + processingOptions.read(); + spacingOptions = new OCRSpacingOptions(rv_buf, 16); + spacingOptions.read(); + } + } + + public static ReadOCRFileResult imaqReadOCRFile(String fileName, CharSet set, + String setDescription) { + ByteBuffer fileName_buf = null; + if (fileName != null) { + byte[] fileName_bytes; + try { + fileName_bytes = fileName.getBytes("UTF-8"); + } catch (UnsupportedEncodingException e) { + fileName_bytes = new byte[0]; + } + fileName_buf = ByteBuffer.allocateDirect(fileName_bytes.length + 1); + putBytes(fileName_buf, fileName_bytes, 0, fileName_bytes.length).put(fileName_bytes.length, + (byte) 0); + } + ByteBuffer setDescription_buf = ByteBuffer.allocateDirect(256).order(ByteOrder.nativeOrder()); + if (setDescription != null) { + byte[] bytes; + try { + bytes = setDescription.getBytes("UTF-8"); + } catch (UnsupportedEncodingException e) { + bytes = new byte[0]; + } + putBytes(setDescription_buf, bytes, 0, bytes.length); + for (int i = bytes.length; i < 256; i++) + setDescription_buf.put(i, (byte) 0); // fill with zero + } + ByteBuffer rv_buf = ByteBuffer.allocateDirect(8 + 8 + 8).order(ByteOrder.nativeOrder()); + long rv_addr = getByteBufferAddress(rv_buf); + _imaqReadOCRFile(fileName == null ? 0 : getByteBufferAddress(fileName_buf), set.getAddress(), + setDescription == null ? 0 : getByteBufferAddress(setDescription_buf), rv_addr + 0, + rv_addr + 8, rv_addr + 16); + ReadOCRFileResult rv = new ReadOCRFileResult(rv_buf); + return rv; + } + + private static native void _imaqReadOCRFile(long fileName, long set, long setDescription, + long readOptions, long processingOptions, long spacingOptions); + + public static ReadTextReport3 imaqReadText3(Image image, CharSet set, ROI roi, + ReadTextOptions readOptions, OCRProcessingOptions processingOptions, + OCRSpacingOptions spacingOptions) { + + long jn_rv = + _imaqReadText3(image.getAddress(), set.getAddress(), roi.getAddress(), + readOptions.getAddress(), processingOptions.getAddress(), spacingOptions.getAddress()); + + return new ReadTextReport3(jn_rv, true); + } + + private static native long _imaqReadText3(long image, long set, long roi, long readOptions, + long processingOptions, long spacingOptions); + + public static void imaqRenameChar(CharSet set, int index, String newCharValue) { + ByteBuffer newCharValue_buf = null; + if (newCharValue != null) { + byte[] newCharValue_bytes; + try { + newCharValue_bytes = newCharValue.getBytes("UTF-8"); + } catch (UnsupportedEncodingException e) { + newCharValue_bytes = new byte[0]; + } + newCharValue_buf = ByteBuffer.allocateDirect(newCharValue_bytes.length + 1); + putBytes(newCharValue_buf, newCharValue_bytes, 0, newCharValue_bytes.length).put( + newCharValue_bytes.length, (byte) 0); + } + _imaqRenameChar(set.getAddress(), index, newCharValue == null ? 0 + : getByteBufferAddress(newCharValue_buf)); + + } + + private static native void _imaqRenameChar(long set, int index, long newCharValue); + + public static void imaqSetReferenceChar(CharSet set, int index, int isReferenceChar) { + + _imaqSetReferenceChar(set.getAddress(), index, isReferenceChar); + + } + + private static native void _imaqSetReferenceChar(long set, int index, int isReferenceChar); + + public static void imaqTrainChars(Image image, CharSet set, int index, String charValue, ROI roi, + OCRProcessingOptions processingOptions, OCRSpacingOptions spacingOptions) { + ByteBuffer charValue_buf = null; + if (charValue != null) { + byte[] charValue_bytes; + try { + charValue_bytes = charValue.getBytes("UTF-8"); + } catch (UnsupportedEncodingException e) { + charValue_bytes = new byte[0]; + } + charValue_buf = ByteBuffer.allocateDirect(charValue_bytes.length + 1); + putBytes(charValue_buf, charValue_bytes, 0, charValue_bytes.length).put( + charValue_bytes.length, (byte) 0); + } + _imaqTrainChars(image.getAddress(), set.getAddress(), index, charValue == null ? 0 + : getByteBufferAddress(charValue_buf), roi.getAddress(), processingOptions.getAddress(), + spacingOptions.getAddress()); + + } + + private static native void _imaqTrainChars(long image, long set, int index, long charValue, + long roi, long processingOptions, long spacingOptions); + + public static class VerifyTextResult { + public int[] array; + private long array_addr; + + private VerifyTextResult(ByteBuffer rv_buf, long jn_rv) { + array_addr = jn_rv; + int array_numScores; + array_numScores = rv_buf.getInt(0); + array = new int[array_numScores]; + if (array_numScores > 0 && array_addr != 0) { + newDirectByteBuffer(array_addr, array_numScores * 4).asIntBuffer().get(array); + } + } + + @Override + protected void finalize() throws Throwable { + imaqDispose(array_addr); + super.finalize(); + } + } + + public static VerifyTextResult imaqVerifyText(Image image, CharSet set, String expectedString, + ROI roi) { + ByteBuffer expectedString_buf = null; + if (expectedString != null) { + byte[] expectedString_bytes; + try { + expectedString_bytes = expectedString.getBytes("UTF-8"); + } catch (UnsupportedEncodingException e) { + expectedString_bytes = new byte[0]; + } + expectedString_buf = ByteBuffer.allocateDirect(expectedString_bytes.length + 1); + putBytes(expectedString_buf, expectedString_bytes, 0, expectedString_bytes.length).put( + expectedString_bytes.length, (byte) 0); + } + ByteBuffer rv_buf = ByteBuffer.allocateDirect(8).order(ByteOrder.nativeOrder()); + long rv_addr = getByteBufferAddress(rv_buf); + long jn_rv = + _imaqVerifyText(image.getAddress(), set.getAddress(), expectedString == null ? 0 + : getByteBufferAddress(expectedString_buf), roi.getAddress(), rv_addr + 0); + VerifyTextResult rv = new VerifyTextResult(rv_buf, jn_rv); + return rv; + } + + private static native long _imaqVerifyText(long image, long set, long expectedString, long roi, + long numScores); + + public static void imaqWriteOCRFile(String fileName, CharSet set, String setDescription, + ReadTextOptions readOptions, OCRProcessingOptions processingOptions, + OCRSpacingOptions spacingOptions) { + ByteBuffer fileName_buf = null; + if (fileName != null) { + byte[] fileName_bytes; + try { + fileName_bytes = fileName.getBytes("UTF-8"); + } catch (UnsupportedEncodingException e) { + fileName_bytes = new byte[0]; + } + fileName_buf = ByteBuffer.allocateDirect(fileName_bytes.length + 1); + putBytes(fileName_buf, fileName_bytes, 0, fileName_bytes.length).put(fileName_bytes.length, + (byte) 0); + } + ByteBuffer setDescription_buf = null; + if (setDescription != null) { + byte[] setDescription_bytes; + try { + setDescription_bytes = setDescription.getBytes("UTF-8"); + } catch (UnsupportedEncodingException e) { + setDescription_bytes = new byte[0]; + } + setDescription_buf = ByteBuffer.allocateDirect(setDescription_bytes.length + 1); + putBytes(setDescription_buf, setDescription_bytes, 0, setDescription_bytes.length).put( + setDescription_bytes.length, (byte) 0); + } + _imaqWriteOCRFile(fileName == null ? 0 : getByteBufferAddress(fileName_buf), set.getAddress(), + setDescription == null ? 0 : getByteBufferAddress(setDescription_buf), + readOptions.getAddress(), processingOptions.getAddress(), spacingOptions.getAddress()); + + } + + private static native void _imaqWriteOCRFile(long fileName, long set, long setDescription, + long readOptions, long processingOptions, long spacingOptions); + + /** + * Geometric Matching functions + */ + + public static class ExtractContourResult { + public CurveParameters curveParams; + public ExtractContourReport val; + + private ExtractContourResult(ByteBuffer rv_buf) { + curveParams = new CurveParameters(rv_buf, 0); + curveParams.read(); + } + } + + public static ExtractContourResult imaqExtractContour(Image image, ROI roi, + ExtractContourDirection direction, ConnectionConstraint connectionConstraintParams, + int numOfConstraints, ExtractContourSelection selection, Image contourImage) { + ByteBuffer rv_buf = ByteBuffer.allocateDirect(8).order(ByteOrder.nativeOrder()); + long rv_addr = getByteBufferAddress(rv_buf); + long jn_rv = + _imaqExtractContour(image.getAddress(), roi.getAddress(), direction.getValue(), + rv_addr + 0, connectionConstraintParams.getAddress(), numOfConstraints, + selection.getValue(), contourImage.getAddress()); + ExtractContourResult rv = new ExtractContourResult(rv_buf); + rv.val = new ExtractContourReport(jn_rv, true); + return rv; + } + + private static native long _imaqExtractContour(long image, long roi, int direction, + long curveParams, long connectionConstraintParams, int numOfConstraints, int selection, + long contourImage); + + public static void imaqContourOverlay(Image image, Image contourImage, + ContourOverlaySettings pointsSettings, ContourOverlaySettings eqnSettings, String groupName) { + ByteBuffer groupName_buf = null; + if (groupName != null) { + byte[] groupName_bytes; + try { + groupName_bytes = groupName.getBytes("UTF-8"); + } catch (UnsupportedEncodingException e) { + groupName_bytes = new byte[0]; + } + groupName_buf = ByteBuffer.allocateDirect(groupName_bytes.length + 1); + putBytes(groupName_buf, groupName_bytes, 0, groupName_bytes.length).put( + groupName_bytes.length, (byte) 0); + } + _imaqContourOverlay(image.getAddress(), contourImage.getAddress(), pointsSettings.getAddress(), + eqnSettings.getAddress(), groupName == null ? 0 : getByteBufferAddress(groupName_buf)); + + } + + private static native void _imaqContourOverlay(long image, long contourImage, + long pointsSettings, long eqnSettings, long groupName); + + public static ContourComputeCurvatureReport imaqContourComputeCurvature(Image contourImage, + int kernel) { + + long jn_rv = _imaqContourComputeCurvature(contourImage.getAddress(), kernel); + + return new ContourComputeCurvatureReport(jn_rv, true); + } + + private static native long _imaqContourComputeCurvature(long contourImage, int kernel); + + public static CurvatureAnalysisReport imaqContourClassifyCurvature(Image contourImage, + int kernel, RangeLabel[] curvatureClasses) { + int numCurvatureClasses = curvatureClasses.length; + ByteBuffer curvatureClasses_buf = null; + curvatureClasses_buf = + ByteBuffer.allocateDirect(curvatureClasses.length * 24).order(ByteOrder.nativeOrder()); + for (int i = 0, off = 0; i < curvatureClasses.length; i++, off += 24) { + curvatureClasses[i].setBuffer(curvatureClasses_buf, off); + curvatureClasses[i].write(); + } + long jn_rv = + _imaqContourClassifyCurvature(contourImage.getAddress(), kernel, + getByteBufferAddress(curvatureClasses_buf), numCurvatureClasses); + + return new CurvatureAnalysisReport(jn_rv, true); + } + + private static native long _imaqContourClassifyCurvature(long contourImage, int kernel, + long curvatureClasses, int numCurvatureClasses); + + public static ComputeDistancesReport imaqContourComputeDistances(Image targetImage, + Image templateImage, SetupMatchPatternData matchSetupData, int smoothingKernel) { + + long jn_rv = + _imaqContourComputeDistances(targetImage.getAddress(), templateImage.getAddress(), + matchSetupData.getAddress(), smoothingKernel); + + return new ComputeDistancesReport(jn_rv, true); + } + + private static native long _imaqContourComputeDistances(long targetImage, long templateImage, + long matchSetupData, int smoothingKernel); + + public static ClassifyDistancesReport imaqContourClassifyDistances(Image targetImage, + Image templateImage, SetupMatchPatternData matchSetupData, int smoothingKernel, + RangeLabel[] distanceRanges) { + int numDistanceRanges = distanceRanges.length; + ByteBuffer distanceRanges_buf = null; + distanceRanges_buf = + ByteBuffer.allocateDirect(distanceRanges.length * 24).order(ByteOrder.nativeOrder()); + for (int i = 0, off = 0; i < distanceRanges.length; i++, off += 24) { + distanceRanges[i].setBuffer(distanceRanges_buf, off); + distanceRanges[i].write(); + } + long jn_rv = + _imaqContourClassifyDistances(targetImage.getAddress(), templateImage.getAddress(), + matchSetupData.getAddress(), smoothingKernel, getByteBufferAddress(distanceRanges_buf), + numDistanceRanges); + + return new ClassifyDistancesReport(jn_rv, true); + } + + private static native long _imaqContourClassifyDistances(long targetImage, long templateImage, + long matchSetupData, int smoothingKernel, long distanceRanges, int numDistanceRanges); + + public static ContourInfoReport imaqContourInfo(Image contourImage) { + + long jn_rv = _imaqContourInfo(contourImage.getAddress()); + + return new ContourInfoReport(jn_rv, true); + } + + private static native long _imaqContourInfo(long contourImage); + + public static class ContourSetupMatchPatternResult { + public MatchMode matchMode; + public CurveParameters curveParams; + public SetupMatchPatternData val; + + private ContourSetupMatchPatternResult(ByteBuffer rv_buf) { + matchMode = new MatchMode(rv_buf, 0); + matchMode.read(); + curveParams = new CurveParameters(rv_buf, 8); + curveParams.read(); + } + } + + public static ContourSetupMatchPatternResult imaqContourSetupMatchPattern( + int enableSubPixelAccuracy, int useLearnCurveParameters, RangeSettingDouble[] rangeSettings) { + int numRangeSettings = rangeSettings.length; + ByteBuffer rangeSettings_buf = null; + rangeSettings_buf = + ByteBuffer.allocateDirect(rangeSettings.length * 24).order(ByteOrder.nativeOrder()); + for (int i = 0, off = 0; i < rangeSettings.length; i++, off += 24) { + rangeSettings[i].setBuffer(rangeSettings_buf, off); + rangeSettings[i].write(); + } + ByteBuffer rv_buf = ByteBuffer.allocateDirect(8 + 8).order(ByteOrder.nativeOrder()); + long rv_addr = getByteBufferAddress(rv_buf); + long jn_rv = + _imaqContourSetupMatchPattern(rv_addr + 0, enableSubPixelAccuracy, rv_addr + 8, + useLearnCurveParameters, getByteBufferAddress(rangeSettings_buf), numRangeSettings); + ContourSetupMatchPatternResult rv = new ContourSetupMatchPatternResult(rv_buf); + rv.val = new SetupMatchPatternData(jn_rv, true); + return rv; + } + + private static native long _imaqContourSetupMatchPattern(long matchMode, + int enableSubPixelAccuracy, long curveParams, int useLearnCurveParameters, + long rangeSettings, int numRangeSettings); + + public static SetupMatchPatternData imaqContourAdvancedSetupMatchPattern( + GeometricAdvancedSetupDataOption[] geometricOptions) { + int numGeometricOptions = geometricOptions.length; + ByteBuffer geometricOptions_buf = null; + geometricOptions_buf = + ByteBuffer.allocateDirect(geometricOptions.length * 16).order(ByteOrder.nativeOrder()); + for (int i = 0, off = 0; i < geometricOptions.length; i++, off += 16) { + geometricOptions[i].setBuffer(geometricOptions_buf, off); + geometricOptions[i].write(); + } + ByteBuffer rv_buf = ByteBuffer.allocateDirect(8).order(ByteOrder.nativeOrder()); + long rv_addr = getByteBufferAddress(rv_buf); + _imaqContourAdvancedSetupMatchPattern(rv_addr + 0, getByteBufferAddress(geometricOptions_buf), + numGeometricOptions); + SetupMatchPatternData matchSetupData; + matchSetupData = new SetupMatchPatternData(rv_buf, 0); + matchSetupData.read(); + return matchSetupData; + } + + private static native void _imaqContourAdvancedSetupMatchPattern(long matchSetupData, + long geometricOptions, int numGeometricOptions); + + public static ContourFitLineReport imaqContourFitLine(Image image, double pixelRadius) { + + long jn_rv = _imaqContourFitLine(image.getAddress(), pixelRadius); + + return new ContourFitLineReport(jn_rv, true); + } + + private static native long _imaqContourFitLine(long image, double pixelRadius); + + public static PartialCircle imaqContourFitCircle(Image image, double pixelRadius, + int rejectOutliers) { + + long jn_rv = _imaqContourFitCircle(image.getAddress(), pixelRadius, rejectOutliers); + + return new PartialCircle(jn_rv, true); + } + + private static native long _imaqContourFitCircle(long image, double pixelRadius, + int rejectOutliers); + + public static PartialEllipse imaqContourFitEllipse(Image image, double pixelRadius, + int rejectOutliers) { + + long jn_rv = _imaqContourFitEllipse(image.getAddress(), pixelRadius, rejectOutliers); + + return new PartialEllipse(jn_rv, true); + } + + private static native long _imaqContourFitEllipse(long image, double pixelRadius, + int rejectOutliers); + + public static ContourFitSplineReport imaqContourFitSpline(Image image, int degree, + int numberOfControlPoints) { + + long jn_rv = _imaqContourFitSpline(image.getAddress(), degree, numberOfControlPoints); + + return new ContourFitSplineReport(jn_rv, true); + } + + private static native long _imaqContourFitSpline(long image, int degree, int numberOfControlPoints); + + public static ContourFitPolynomialReport imaqContourFitPolynomial(Image image, int order) { + + long jn_rv = _imaqContourFitPolynomial(image.getAddress(), order); + + return new ContourFitPolynomialReport(jn_rv, true); + } + + private static native long _imaqContourFitPolynomial(long image, int order); + + /** + * Edge Detection functions + */ + + public static FindCircularEdgeReport imaqFindCircularEdge2(Image image, ROI roi, + CoordinateSystem baseSystem, CoordinateSystem newSystem, FindCircularEdgeOptions edgeOptions, + CircleFitOptions circleFitOptions) { + + long jn_rv = + _imaqFindCircularEdge2(image.getAddress(), roi.getAddress(), baseSystem.getAddress(), + newSystem.getAddress(), edgeOptions.getAddress(), circleFitOptions.getAddress()); + + return new FindCircularEdgeReport(jn_rv, true); + } + + private static native long _imaqFindCircularEdge2(long image, long roi, long baseSystem, + long newSystem, long edgeOptions, long circleFitOptions); + + public static FindConcentricEdgeReport imaqFindConcentricEdge2(Image image, ROI roi, + CoordinateSystem baseSystem, CoordinateSystem newSystem, + FindConcentricEdgeOptions edgeOptions, ConcentricEdgeFitOptions concentricEdgeFitOptions) { + + long jn_rv = + _imaqFindConcentricEdge2(image.getAddress(), roi.getAddress(), baseSystem.getAddress(), + newSystem.getAddress(), edgeOptions.getAddress(), concentricEdgeFitOptions.getAddress()); + + return new FindConcentricEdgeReport(jn_rv, true); + } + + private static native long _imaqFindConcentricEdge2(long image, long roi, long baseSystem, + long newSystem, long edgeOptions, long concentricEdgeFitOptions); + + /** + * Morphology Reconstruction functions + */ + + public static void imaqGrayMorphologyReconstruct(Image dstImage, Image srcImage, + Image markerImage, PointFloat[] points, MorphologyReconstructOperation operation, + StructuringElement structuringElement, ROI roi) { + int numOfPoints = points.length; + ByteBuffer points_buf = null; + points_buf = ByteBuffer.allocateDirect(points.length * 8).order(ByteOrder.nativeOrder()); + for (int i = 0, off = 0; i < points.length; i++, off += 8) { + points[i].setBuffer(points_buf, off); + points[i].write(); + } + _imaqGrayMorphologyReconstruct(dstImage.getAddress(), srcImage.getAddress(), + markerImage.getAddress(), getByteBufferAddress(points_buf), numOfPoints, + operation.getValue(), structuringElement.getAddress(), roi.getAddress()); + + } + + private static native void _imaqGrayMorphologyReconstruct(long dstImage, long srcImage, + long markerImage, long points, int numOfPoints, int operation, long structuringElement, + long roi); + + public static void imaqMorphologyReconstruct(Image dstImage, Image srcImage, Image markerImage, + PointFloat[] points, MorphologyReconstructOperation operation, Connectivity connectivity, + ROI roi) { + int numOfPoints = points.length; + ByteBuffer points_buf = null; + points_buf = ByteBuffer.allocateDirect(points.length * 8).order(ByteOrder.nativeOrder()); + for (int i = 0, off = 0; i < points.length; i++, off += 8) { + points[i].setBuffer(points_buf, off); + points[i].write(); + } + _imaqMorphologyReconstruct(dstImage.getAddress(), srcImage.getAddress(), + markerImage.getAddress(), getByteBufferAddress(points_buf), numOfPoints, + operation.getValue(), connectivity.getValue(), roi.getAddress()); + + } + + private static native void _imaqMorphologyReconstruct(long dstImage, long srcImage, + long markerImage, long points, int numOfPoints, int operation, int connectivity, long roi); + + /** + * Texture functions + */ + + public static void imaqDetectTextureDefect(ClassifierSession session, Image destImage, + Image srcImage, ROI roi, int initialStepSize, int finalStepSize, short defectPixelValue, + double minClassificationScore) { + + _imaqDetectTextureDefect(session.getAddress(), destImage.getAddress(), srcImage.getAddress(), + roi.getAddress(), initialStepSize, finalStepSize, defectPixelValue, minClassificationScore); + + } + + private static native void _imaqDetectTextureDefect(long session, long destImage, long srcImage, + long roi, int initialStepSize, int finalStepSize, short defectPixelValue, + double minClassificationScore); + + /** + * Regions of Interest Manipulation functions + */ + + public static class MaskToROIResult { + public int withinLimit; + public ROI val; + + private MaskToROIResult(ByteBuffer rv_buf) { + withinLimit = rv_buf.getInt(0); + } + } + + public static MaskToROIResult imaqMaskToROI(Image mask) { + ByteBuffer rv_buf = ByteBuffer.allocateDirect(8).order(ByteOrder.nativeOrder()); + long rv_addr = getByteBufferAddress(rv_buf); + long jn_rv = _imaqMaskToROI(mask.getAddress(), rv_addr + 0); + MaskToROIResult rv = new MaskToROIResult(rv_buf); + rv.val = new ROI(jn_rv, true); + return rv; + } + + private static native long _imaqMaskToROI(long mask, long withinLimit); + + public static ROIProfile imaqROIProfile(Image image, ROI roi) { + + long jn_rv = _imaqROIProfile(image.getAddress(), roi.getAddress()); + + return new ROIProfile(jn_rv, true); + } + + private static native long _imaqROIProfile(long image, long roi); + + public static int imaqROIToMask(Image mask, ROI roi, int fillValue, Image imageModel) { + ByteBuffer rv_buf = ByteBuffer.allocateDirect(8).order(ByteOrder.nativeOrder()); + long rv_addr = getByteBufferAddress(rv_buf); + _imaqROIToMask(mask.getAddress(), roi.getAddress(), fillValue, imageModel == null ? 0 + : imageModel.getAddress(), rv_addr + 0); + int inSpace; + inSpace = rv_buf.getInt(0); + return inSpace; + } + + private static native void _imaqROIToMask(long mask, long roi, int fillValue, long imageModel, + long inSpace); + + public static void imaqTransformROI2(ROI roi, CoordinateSystem baseSystem, + CoordinateSystem newSystem) { + + _imaqTransformROI2(roi.getAddress(), baseSystem.getAddress(), newSystem.getAddress()); + + } + + private static native void _imaqTransformROI2(long roi, long baseSystem, long newSystem); + + public static LabelToROIReport imaqLabelToROI(Image image, int[] labelsIn, int maxNumVectors, + int isExternelEdges) { + int numLabelsIn = labelsIn.length; + ByteBuffer labelsIn_buf = null; + labelsIn_buf = ByteBuffer.allocateDirect(labelsIn.length * 4).order(ByteOrder.nativeOrder()); + labelsIn_buf.asIntBuffer().put(labelsIn).rewind(); + long jn_rv = + _imaqLabelToROI(image.getAddress(), getByteBufferAddress(labelsIn_buf), numLabelsIn, + maxNumVectors, isExternelEdges); + + return new LabelToROIReport(jn_rv, true); + } + + private static native long _imaqLabelToROI(long image, long labelsIn, int numLabelsIn, + int maxNumVectors, int isExternelEdges); + + /** + * Morphology functions + */ + + public static void imaqGrayMorphology(Image dest, Image source, MorphologyMethod method, + StructuringElement structuringElement) { + + _imaqGrayMorphology(dest.getAddress(), source.getAddress(), method.getValue(), + structuringElement == null ? 0 : structuringElement.getAddress()); + + } + + private static native void _imaqGrayMorphology(long dest, long source, int method, + long structuringElement); + + /** + * Classification functions + */ + + public static void imaqAddClassifierSample(Image image, ClassifierSession session, ROI roi, + String sampleClass, double[] featureVector) { + ByteBuffer sampleClass_buf = null; + if (sampleClass != null) { + byte[] sampleClass_bytes; + try { + sampleClass_bytes = sampleClass.getBytes("UTF-8"); + } catch (UnsupportedEncodingException e) { + sampleClass_bytes = new byte[0]; + } + sampleClass_buf = ByteBuffer.allocateDirect(sampleClass_bytes.length + 1); + putBytes(sampleClass_buf, sampleClass_bytes, 0, sampleClass_bytes.length).put( + sampleClass_bytes.length, (byte) 0); + } + int vectorSize = featureVector.length; + ByteBuffer featureVector_buf = null; + featureVector_buf = + ByteBuffer.allocateDirect(featureVector.length * 8).order(ByteOrder.nativeOrder()); + featureVector_buf.asDoubleBuffer().put(featureVector).rewind(); + _imaqAddClassifierSample(image.getAddress(), session.getAddress(), roi.getAddress(), + sampleClass == null ? 0 : getByteBufferAddress(sampleClass_buf), + getByteBufferAddress(featureVector_buf), vectorSize); + + } + + private static native void _imaqAddClassifierSample(long image, long session, long roi, + long sampleClass, long featureVector, int vectorSize); + + public static ClassifierReportAdvanced imaqAdvanceClassify(Image image, + ClassifierSession session, ROI roi, double[] featureVector) { + int vectorSize = featureVector.length; + ByteBuffer featureVector_buf = null; + featureVector_buf = + ByteBuffer.allocateDirect(featureVector.length * 8).order(ByteOrder.nativeOrder()); + featureVector_buf.asDoubleBuffer().put(featureVector).rewind(); + long jn_rv = + _imaqAdvanceClassify(image.getAddress(), session.getAddress(), roi.getAddress(), + getByteBufferAddress(featureVector_buf), vectorSize); + + return new ClassifierReportAdvanced(jn_rv, true); + } + + private static native long _imaqAdvanceClassify(long image, long session, long roi, + long featureVector, int vectorSize); + + public static ClassifierReport imaqClassify(Image image, ClassifierSession session, ROI roi, + double[] featureVector) { + int vectorSize = featureVector.length; + ByteBuffer featureVector_buf = null; + featureVector_buf = + ByteBuffer.allocateDirect(featureVector.length * 8).order(ByteOrder.nativeOrder()); + featureVector_buf.asDoubleBuffer().put(featureVector).rewind(); + long jn_rv = + _imaqClassify(image.getAddress(), session.getAddress(), roi.getAddress(), + getByteBufferAddress(featureVector_buf), vectorSize); + + return new ClassifierReport(jn_rv, true); + } + + private static native long _imaqClassify(long image, long session, long roi, long featureVector, + int vectorSize); + + public static ClassifierSession imaqCreateClassifier(ClassifierType type) { + + long jn_rv = _imaqCreateClassifier(type.getValue()); + + return new ClassifierSession(jn_rv, true); + } + + private static native long _imaqCreateClassifier(int type); + + public static void imaqDeleteClassifierSample(ClassifierSession session, int index) { + + _imaqDeleteClassifierSample(session.getAddress(), index); + + } + + private static native void _imaqDeleteClassifierSample(long session, int index); + + public static ClassifierAccuracyReport imaqGetClassifierAccuracy(ClassifierSession session) { + + long jn_rv = _imaqGetClassifierAccuracy(session.getAddress()); + + return new ClassifierAccuracyReport(jn_rv, true); + } + + private static native long _imaqGetClassifierAccuracy(long session); + + public static class GetClassifierSampleInfoResult { + public int numSamples; + public ClassifierSampleInfo val; + + private GetClassifierSampleInfoResult(ByteBuffer rv_buf) { + numSamples = rv_buf.getInt(0); + } + } + + public static GetClassifierSampleInfoResult imaqGetClassifierSampleInfo( + ClassifierSession session, int index) { + ByteBuffer rv_buf = ByteBuffer.allocateDirect(8).order(ByteOrder.nativeOrder()); + long rv_addr = getByteBufferAddress(rv_buf); + long jn_rv = _imaqGetClassifierSampleInfo(session.getAddress(), index, rv_addr + 0); + GetClassifierSampleInfoResult rv = new GetClassifierSampleInfoResult(rv_buf); + rv.val = new ClassifierSampleInfo(jn_rv, true); + return rv; + } + + private static native long _imaqGetClassifierSampleInfo(long session, int index, long numSamples); + + public static ColorOptions imaqGetColorClassifierOptions(ClassifierSession session) { + ByteBuffer rv_buf = ByteBuffer.allocateDirect(8).order(ByteOrder.nativeOrder()); + long rv_addr = getByteBufferAddress(rv_buf); + _imaqGetColorClassifierOptions(session.getAddress(), rv_addr + 0); + ColorOptions options; + options = new ColorOptions(rv_buf, 0); + options.read(); + return options; + } + + private static native void _imaqGetColorClassifierOptions(long session, long options); + + public static NearestNeighborOptions imaqGetNearestNeighborOptions(ClassifierSession session) { + ByteBuffer rv_buf = ByteBuffer.allocateDirect(8).order(ByteOrder.nativeOrder()); + long rv_addr = getByteBufferAddress(rv_buf); + _imaqGetNearestNeighborOptions(session.getAddress(), rv_addr + 0); + NearestNeighborOptions options; + options = new NearestNeighborOptions(rv_buf, 0); + options.read(); + return options; + } + + private static native void _imaqGetNearestNeighborOptions(long session, long options); + + public static class GetParticleClassifierOptions2Result { + public ParticleClassifierPreprocessingOptions2 preprocessingOptions; + public ParticleClassifierOptions options; + + private GetParticleClassifierOptions2Result(ByteBuffer rv_buf) { + preprocessingOptions = new ParticleClassifierPreprocessingOptions2(rv_buf, 0); + preprocessingOptions.read(); + options = new ParticleClassifierOptions(rv_buf, 8); + options.read(); + } + } + + public static GetParticleClassifierOptions2Result imaqGetParticleClassifierOptions2( + ClassifierSession session) { + ByteBuffer rv_buf = ByteBuffer.allocateDirect(8 + 8).order(ByteOrder.nativeOrder()); + long rv_addr = getByteBufferAddress(rv_buf); + _imaqGetParticleClassifierOptions2(session.getAddress(), rv_addr + 0, rv_addr + 8); + GetParticleClassifierOptions2Result rv = new GetParticleClassifierOptions2Result(rv_buf); + return rv; + } + + private static native void _imaqGetParticleClassifierOptions2(long session, + long preprocessingOptions, long options); + + public static class ReadClassifierFileResult { + public ClassifierType type; + public ClassifierEngineType engine; + public ClassifierSession val; + + private ReadClassifierFileResult(ByteBuffer rv_buf) { + type = ClassifierType.fromValue(rv_buf.getInt(0)); + engine = ClassifierEngineType.fromValue(rv_buf.getInt(8)); + } + } + + public static ReadClassifierFileResult imaqReadClassifierFile(ClassifierSession session, + String fileName, ReadClassifierFileMode mode, String description) { + ByteBuffer fileName_buf = null; + if (fileName != null) { + byte[] fileName_bytes; + try { + fileName_bytes = fileName.getBytes("UTF-8"); + } catch (UnsupportedEncodingException e) { + fileName_bytes = new byte[0]; + } + fileName_buf = ByteBuffer.allocateDirect(fileName_bytes.length + 1); + putBytes(fileName_buf, fileName_bytes, 0, fileName_bytes.length).put(fileName_bytes.length, + (byte) 0); + } + ByteBuffer description_buf = ByteBuffer.allocateDirect(256).order(ByteOrder.nativeOrder()); + if (description != null) { + byte[] bytes; + try { + bytes = description.getBytes("UTF-8"); + } catch (UnsupportedEncodingException e) { + bytes = new byte[0]; + } + putBytes(description_buf, bytes, 0, bytes.length); + for (int i = bytes.length; i < 256; i++) + description_buf.put(i, (byte) 0); // fill with zero + } + ByteBuffer rv_buf = ByteBuffer.allocateDirect(8 + 8).order(ByteOrder.nativeOrder()); + long rv_addr = getByteBufferAddress(rv_buf); + long jn_rv = + _imaqReadClassifierFile(session.getAddress(), fileName == null ? 0 + : getByteBufferAddress(fileName_buf), mode.getValue(), rv_addr + 0, rv_addr + 8, + description == null ? 0 : getByteBufferAddress(description_buf)); + ReadClassifierFileResult rv = new ReadClassifierFileResult(rv_buf); + rv.val = new ClassifierSession(jn_rv, true); + return rv; + } + + private static native long _imaqReadClassifierFile(long session, long fileName, int mode, + long type, long engine, long description); + + public static void imaqRelabelClassifierSample(ClassifierSession session, int index, + String newClass) { + ByteBuffer newClass_buf = null; + if (newClass != null) { + byte[] newClass_bytes; + try { + newClass_bytes = newClass.getBytes("UTF-8"); + } catch (UnsupportedEncodingException e) { + newClass_bytes = new byte[0]; + } + newClass_buf = ByteBuffer.allocateDirect(newClass_bytes.length + 1); + putBytes(newClass_buf, newClass_bytes, 0, newClass_bytes.length).put(newClass_bytes.length, + (byte) 0); + } + _imaqRelabelClassifierSample(session.getAddress(), index, newClass == null ? 0 + : getByteBufferAddress(newClass_buf)); + + } + + private static native void _imaqRelabelClassifierSample(long session, int index, long newClass); + + public static void imaqSetParticleClassifierOptions2(ClassifierSession session, + ParticleClassifierPreprocessingOptions2 preprocessingOptions, + ParticleClassifierOptions options) { + + _imaqSetParticleClassifierOptions2(session.getAddress(), preprocessingOptions.getAddress(), + options.getAddress()); + + } + + private static native void _imaqSetParticleClassifierOptions2(long session, + long preprocessingOptions, long options); + + public static void imaqSetColorClassifierOptions(ClassifierSession session, ColorOptions options) { + + _imaqSetColorClassifierOptions(session.getAddress(), options.getAddress()); + + } + + private static native void _imaqSetColorClassifierOptions(long session, long options); + + public static NearestNeighborTrainingReport imaqTrainNearestNeighborClassifier( + ClassifierSession session, NearestNeighborOptions options) { + + long jn_rv = _imaqTrainNearestNeighborClassifier(session.getAddress(), options.getAddress()); + + return new NearestNeighborTrainingReport(jn_rv, true); + } + + private static native long _imaqTrainNearestNeighborClassifier(long session, long options); + + public static void imaqWriteClassifierFile(ClassifierSession session, String fileName, + WriteClassifierFileMode mode, String description) { + ByteBuffer fileName_buf = null; + if (fileName != null) { + byte[] fileName_bytes; + try { + fileName_bytes = fileName.getBytes("UTF-8"); + } catch (UnsupportedEncodingException e) { + fileName_bytes = new byte[0]; + } + fileName_buf = ByteBuffer.allocateDirect(fileName_bytes.length + 1); + putBytes(fileName_buf, fileName_bytes, 0, fileName_bytes.length).put(fileName_bytes.length, + (byte) 0); + } + ByteBuffer description_buf = ByteBuffer.allocateDirect(256).order(ByteOrder.nativeOrder()); + if (description != null) { + byte[] bytes; + try { + bytes = description.getBytes("UTF-8"); + } catch (UnsupportedEncodingException e) { + bytes = new byte[0]; + } + putBytes(description_buf, bytes, 0, bytes.length); + for (int i = bytes.length; i < 256; i++) + description_buf.put(i, (byte) 0); // fill with zero + } + _imaqWriteClassifierFile(session.getAddress(), fileName == null ? 0 + : getByteBufferAddress(fileName_buf), mode.getValue(), description == null ? 0 + : getByteBufferAddress(description_buf)); + + } + + private static native void _imaqWriteClassifierFile(long session, long fileName, int mode, + long description); + + /** + * Measure Distances functions + */ + + public static ClampMax2Report imaqClampMax2(Image image, ROI roi, CoordinateSystem baseSystem, + CoordinateSystem newSystem, CurveOptions curveSettings, ClampSettings clampSettings, + ClampOverlaySettings clampOverlaySettings) { + + long jn_rv = + _imaqClampMax2(image.getAddress(), roi.getAddress(), baseSystem.getAddress(), + newSystem.getAddress(), curveSettings.getAddress(), clampSettings.getAddress(), + clampOverlaySettings.getAddress()); + + return new ClampMax2Report(jn_rv, true); + } + + private static native long _imaqClampMax2(long image, long roi, long baseSystem, long newSystem, + long curveSettings, long clampSettings, long clampOverlaySettings); + + /** + * Inspection functions + */ + + public static void imaqCompareGoldenTemplate(Image image, Image goldenTemplate, + Image brightDefects, Image darkDefects, InspectionAlignment alignment, + InspectionOptions options) { + + _imaqCompareGoldenTemplate(image.getAddress(), goldenTemplate.getAddress(), + brightDefects.getAddress(), darkDefects.getAddress(), alignment.getAddress(), + options.getAddress()); + + } + + private static native void _imaqCompareGoldenTemplate(long image, long goldenTemplate, + long brightDefects, long darkDefects, long alignment, long options); + + public static void imaqLearnGoldenTemplate(Image goldenTemplate, PointFloat originOffset, + Image mask) { + + _imaqLearnGoldenTemplate(goldenTemplate.getAddress(), originOffset.getAddress(), + mask.getAddress()); + + } + + private static native void _imaqLearnGoldenTemplate(long goldenTemplate, long originOffset, + long mask); + + /** + * Obsolete functions + */ + + public static class GetParticleClassifierOptionsResult { + public ParticleClassifierPreprocessingOptions preprocessingOptions; + public ParticleClassifierOptions options; + + private GetParticleClassifierOptionsResult(ByteBuffer rv_buf) { + preprocessingOptions = new ParticleClassifierPreprocessingOptions(rv_buf, 0); + preprocessingOptions.read(); + options = new ParticleClassifierOptions(rv_buf, 8); + options.read(); + } + } + + public static GetParticleClassifierOptionsResult imaqGetParticleClassifierOptions( + ClassifierSession session) { + ByteBuffer rv_buf = ByteBuffer.allocateDirect(8 + 8).order(ByteOrder.nativeOrder()); + long rv_addr = getByteBufferAddress(rv_buf); + _imaqGetParticleClassifierOptions(session.getAddress(), rv_addr + 0, rv_addr + 8); + GetParticleClassifierOptionsResult rv = new GetParticleClassifierOptionsResult(rv_buf); + return rv; + } + + private static native void _imaqGetParticleClassifierOptions(long session, + long preprocessingOptions, long options); + + public static int imaqParticleFilter3(Image dest, Image source, ParticleFilterCriteria2 criteria, + int criteriaCount, ParticleFilterOptions options, ROI roi) { + ByteBuffer rv_buf = ByteBuffer.allocateDirect(8).order(ByteOrder.nativeOrder()); + long rv_addr = getByteBufferAddress(rv_buf); + _imaqParticleFilter3(dest.getAddress(), source.getAddress(), criteria.getAddress(), + criteriaCount, options.getAddress(), roi.getAddress(), rv_addr + 0); + int numParticles; + numParticles = rv_buf.getInt(0); + return numParticles; + } + + private static native void _imaqParticleFilter3(long dest, long source, long criteria, + int criteriaCount, long options, long roi, long numParticles); + + public static LearnPatternAdvancedOptions imaqLearnPattern2(Image image, LearningMode learningMode) { + ByteBuffer rv_buf = ByteBuffer.allocateDirect(8).order(ByteOrder.nativeOrder()); + long rv_addr = getByteBufferAddress(rv_buf); + _imaqLearnPattern2(image.getAddress(), learningMode.getValue(), rv_addr + 0); + LearnPatternAdvancedOptions advancedOptions; + advancedOptions = new LearnPatternAdvancedOptions(rv_buf, 0); + advancedOptions.read(); + return advancedOptions; + } + + private static native void _imaqLearnPattern2(long image, int learningMode, long advancedOptions); + + public static void imaqDivide(Image dest, Image sourceA, Image sourceB) { + + _imaqDivide(dest.getAddress(), sourceA.getAddress(), sourceB.getAddress()); + + } + + private static native void _imaqDivide(long dest, long sourceA, long sourceB); + + public static EdgeReport2 imaqEdgeTool3(Image image, ROI roi, EdgeProcess processType, + EdgeOptions2 edgeOptions) { + + long jn_rv = + _imaqEdgeTool3(image.getAddress(), roi.getAddress(), processType.getValue(), + edgeOptions.getAddress()); + + return new EdgeReport2(jn_rv, true); + } + + private static native long _imaqEdgeTool3(long image, long roi, int processType, long edgeOptions); + + public static ConcentricRakeReport imaqConcentricRake(Image image, ROI roi, + ConcentricRakeDirection direction, EdgeProcess process, RakeOptions options) { + + long jn_rv = + _imaqConcentricRake(image.getAddress(), roi.getAddress(), direction.getValue(), + process.getValue(), options.getAddress()); + + return new ConcentricRakeReport(jn_rv, true); + } + + private static native long _imaqConcentricRake(long image, long roi, int direction, int process, + long options); + + public static SpokeReport imaqSpoke(Image image, ROI roi, SpokeDirection direction, + EdgeProcess process, SpokeOptions options) { + + long jn_rv = + _imaqSpoke(image.getAddress(), roi.getAddress(), direction.getValue(), process.getValue(), + options.getAddress()); + + return new SpokeReport(jn_rv, true); + } + + private static native long _imaqSpoke(long image, long roi, int direction, int process, + long options); + + public static class MatchPattern2Result { + public PatternMatch[] array; + private long array_addr; + + private MatchPattern2Result(ByteBuffer rv_buf, long jn_rv) { + array_addr = jn_rv; + int array_numMatches; + array_numMatches = rv_buf.getInt(0); + array = new PatternMatch[array_numMatches]; + if (array_numMatches > 0 && array_addr != 0) { + ByteBuffer bb = newDirectByteBuffer(array_addr, array_numMatches * 52); + for (int i = 0, off = 0; i < array_numMatches; i++, off += 52) { + array[i] = new PatternMatch(bb, off); + array[i].read(); + } + } + } + + @Override + protected void finalize() throws Throwable { + imaqDispose(array_addr); + super.finalize(); + } + } + + public static MatchPattern2Result imaqMatchPattern2(Image image, Image pattern, + MatchPatternOptions options, MatchPatternAdvancedOptions advancedOptions, Rect searchRect) { + ByteBuffer rv_buf = ByteBuffer.allocateDirect(8).order(ByteOrder.nativeOrder()); + long rv_addr = getByteBufferAddress(rv_buf); + long jn_rv = + _imaqMatchPattern2(image.getAddress(), pattern.getAddress(), + options == null ? 0 : options.getAddress(), advancedOptions.getAddress(), + searchRect.getAddress(), rv_addr + 0); + MatchPattern2Result rv = new MatchPattern2Result(rv_buf, jn_rv); + return rv; + } + + private static native long _imaqMatchPattern2(long image, long pattern, long options, + long advancedOptions, long searchRect, long numMatches); + + public static void imaqSetParticleClassifierOptions(ClassifierSession session, + ParticleClassifierPreprocessingOptions preprocessingOptions, ParticleClassifierOptions options) { + + _imaqSetParticleClassifierOptions(session.getAddress(), preprocessingOptions.getAddress(), + options.getAddress()); + + } + + private static native void _imaqSetParticleClassifierOptions(long session, + long preprocessingOptions, long options); + + public static RakeReport imaqRake(Image image, ROI roi, RakeDirection direction, + EdgeProcess process, RakeOptions options) { + + long jn_rv = + _imaqRake(image.getAddress(), roi.getAddress(), direction.getValue(), process.getValue(), + options.getAddress()); + + return new RakeReport(jn_rv, true); + } + + private static native long _imaqRake(long image, long roi, int direction, int process, + long options); + + public static void Priv_ReadJPEGString_C(Image image, byte[] string) { + int stringLength = string.length; + ByteBuffer string_buf = null; + string_buf = ByteBuffer.allocateDirect(string.length); + putBytes(string_buf, string, 0, string.length); + _Priv_ReadJPEGString_C(image.getAddress(), getByteBufferAddress(string_buf), stringLength); + + } + + private static native void _Priv_ReadJPEGString_C(long image, long string, int stringLength); + + /** + * Purpose : Include file for NI-IMAQdx library support. + */ + public static final int IMAQDX_MAX_API_STRING_LENGTH = 512; + + /** + * Bus Type Enumeration + */ + + public static enum IMAQdxBusType { + BusTypeFireWire(0x31333934), BusTypeEthernet(0x69707634), BusTypeSimulator(0x2073696D), BusTypeDirectShow( + 0x64736877), BusTypeIP(0x4950636D), BusTypeSmartCam2(0x53436132), BusTypeUSB3Vision( + 0x55534233), BusTypeUVC(0x55564320), BusTypeGuard(0xFFFFFFFF), ; + private final int value; + + private IMAQdxBusType(int value) { + this.value = value; + } + + public static IMAQdxBusType fromValue(int val) { + for (IMAQdxBusType v : values()) { + if (v.value == val) + return v; + } + return null; + } + + public int getValue() { + return value; + } + } + + /** + * Camera Control Mode Enumeration + */ + + public static enum IMAQdxCameraControlMode { + CameraControlModeController(0), CameraControlModeListener(1), CameraControlModeGuard(0xFFFFFFFF), ; + private final int value; + + private IMAQdxCameraControlMode(int value) { + this.value = value; + } + + public static IMAQdxCameraControlMode fromValue(int val) { + for (IMAQdxCameraControlMode v : values()) { + if (v.value == val) + return v; + } + return null; + } + + public int getValue() { + return value; + } + } + + /** + * Buffer Number Mode Enumeration + */ + + public static enum IMAQdxBufferNumberMode { + BufferNumberModeNext(0), BufferNumberModeLast(1), BufferNumberModeBufferNumber(2), BufferNumberModeGuard( + 0xFFFFFFFF), ; + private final int value; + + private IMAQdxBufferNumberMode(int value) { + this.value = value; + } + + public static IMAQdxBufferNumberMode fromValue(int val) { + for (IMAQdxBufferNumberMode v : values()) { + if (v.value == val) + return v; + } + return null; + } + + public int getValue() { + return value; + } + } + + /** + * Plug n Play Event Enumeration + */ + + public static enum IMAQdxPnpEvent { + PnpEventCameraAttached(0), PnpEventCameraDetached(1), PnpEventBusReset(2), PnpEventGuard( + 0xFFFFFFFF), ; + private final int value; + + private IMAQdxPnpEvent(int value) { + this.value = value; + } + + public static IMAQdxPnpEvent fromValue(int val) { + for (IMAQdxPnpEvent v : values()) { + if (v.value == val) + return v; + } + return null; + } + + public int getValue() { + return value; + } + } + + /** + * Bayer Pattern Enumeration + */ + + public static enum IMAQdxBayerPattern { + BayerPatternNone(0), BayerPatternGB(1), BayerPatternGR(2), BayerPatternBG(3), BayerPatternRG(4), BayerPatternHardware( + 5), BayerPatternGuard(0xFFFFFFFF), ; + private final int value; + + private IMAQdxBayerPattern(int value) { + this.value = value; + } + + public static IMAQdxBayerPattern fromValue(int val) { + for (IMAQdxBayerPattern v : values()) { + if (v.value == val) + return v; + } + return null; + } + + public int getValue() { + return value; + } + } + + /** + * Bayer Decode Algorithm Enumeration + */ + + public static enum IMAQdxBayerAlgorithm { + BayerAlgorithmBilinear(0), BayerAlgorithmVNG(1), BayerAlgorithmGuard(0xFFFFFFFF), ; + private final int value; + + private IMAQdxBayerAlgorithm(int value) { + this.value = value; + } + + public static IMAQdxBayerAlgorithm fromValue(int val) { + for (IMAQdxBayerAlgorithm v : values()) { + if (v.value == val) + return v; + } + return null; + } + + public int getValue() { + return value; + } + } + + /** + * Output Image Types -- Values match Vision Development Module image types + */ + + public static enum IMAQdxOutputImageType { + OutputImageTypeU8(0), OutputImageTypeI16(1), OutputImageTypeU16(7), OutputImageTypeRGB32(4), OutputImageTypeRGB64( + 6), OutputImageTypeAuto(0x7FFFFFFF), OutputImageTypeGuard(0xFFFFFFFF), ; + private final int value; + + private IMAQdxOutputImageType(int value) { + this.value = value; + } + + public static IMAQdxOutputImageType fromValue(int val) { + for (IMAQdxOutputImageType v : values()) { + if (v.value == val) + return v; + } + return null; + } + + public int getValue() { + return value; + } + } + + /** + * Controller Destination Mode Enumeration + */ + + public static enum IMAQdxDestinationMode { + DestinationModeUnicast(0), DestinationModeBroadcast(1), DestinationModeMulticast(2), DestinationModeGuard( + 0xFFFFFFFF), ; + private final int value; + + private IMAQdxDestinationMode(int value) { + this.value = value; + } + + public static IMAQdxDestinationMode fromValue(int val) { + for (IMAQdxDestinationMode v : values()) { + if (v.value == val) + return v; + } + return null; + } + + public int getValue() { + return value; + } + } + + /** + * Attribute Type Enumeration + */ + + public static enum IMAQdxAttributeType { + AttributeTypeU32(0), AttributeTypeI64(1), AttributeTypeF64(2), AttributeTypeString(3), AttributeTypeEnum( + 4), AttributeTypeBool(5), AttributeTypeCommand(6), AttributeTypeBlob(7), AttributeTypeGuard( + 0xFFFFFFFF), ; + private final int value; + + private IMAQdxAttributeType(int value) { + this.value = value; + } + + public static IMAQdxAttributeType fromValue(int val) { + for (IMAQdxAttributeType v : values()) { + if (v.value == val) + return v; + } + return null; + } + + public int getValue() { + return value; + } + } + + /** + * Value Type Enumeration + */ + + public static enum IMAQdxValueType { + ValueTypeU32(0), ValueTypeI64(1), ValueTypeF64(2), ValueTypeString(3), ValueTypeEnumItem(4), ValueTypeBool( + 5), ValueTypeDisposableString(6), ValueTypeGuard(0xFFFFFFFF), ; + private final int value; + + private IMAQdxValueType(int value) { + this.value = value; + } + + public static IMAQdxValueType fromValue(int val) { + for (IMAQdxValueType v : values()) { + if (v.value == val) + return v; + } + return null; + } + + public int getValue() { + return value; + } + } + + /** + * Interface File Flags Enumeration + */ + + public static enum IMAQdxInterfaceFileFlags { + InterfaceFileFlagsConnected(0x1), InterfaceFileFlagsDirty(0x2), InterfaceFileFlagsGuard( + 0xFFFFFFFF), ; + private final int value; + + private IMAQdxInterfaceFileFlags(int value) { + this.value = value; + } + + public static IMAQdxInterfaceFileFlags fromValue(int val) { + for (IMAQdxInterfaceFileFlags v : values()) { + if (v.value == val) + return v; + } + return null; + } + + public int getValue() { + return value; + } + } + + /** + * Overwrite Mode Enumeration + */ + + public static enum IMAQdxOverwriteMode { + OverwriteModeGetOldest(0x0), OverwriteModeFail(0x2), OverwriteModeGetNewest(0x3), OverwriteModeGuard( + 0xFFFFFFFF), ; + private final int value; + + private IMAQdxOverwriteMode(int value) { + this.value = value; + } + + public static IMAQdxOverwriteMode fromValue(int val) { + for (IMAQdxOverwriteMode v : values()) { + if (v.value == val) + return v; + } + return null; + } + + public int getValue() { + return value; + } + } + + /** + * Incomplete Buffer Mode Enumeration + */ + + public static enum IMAQdxIncompleteBufferMode { + IncompleteBufferModeIgnore(0), IncompleteBufferModeFail(1), IncompleteBufferModeGuard( + 0xFFFFFFFF), ; + private final int value; + + private IMAQdxIncompleteBufferMode(int value) { + this.value = value; + } + + public static IMAQdxIncompleteBufferMode fromValue(int val) { + for (IMAQdxIncompleteBufferMode v : values()) { + if (v.value == val) + return v; + } + return null; + } + + public int getValue() { + return value; + } + } + + /** + * Lost Packet Mode Enumeration + */ + + public static enum IMAQdxLostPacketMode { + LostPacketModeIgnore(0), LostPacketModeFail(1), LostPacketModeGuard(0xFFFFFFFF), ; + private final int value; + + private IMAQdxLostPacketMode(int value) { + this.value = value; + } + + public static IMAQdxLostPacketMode fromValue(int val) { + for (IMAQdxLostPacketMode v : values()) { + if (v.value == val) + return v; + } + return null; + } + + public int getValue() { + return value; + } + } + + /** + * Attribute Visibility Enumeration + */ + + public static enum IMAQdxAttributeVisibility { + AttributeVisibilitySimple(0x00001000), AttributeVisibilityIntermediate(0x00002000), AttributeVisibilityAdvanced( + 0x00004000), AttributeVisibilityGuard(0xFFFFFFFF), ; + private final int value; + + private IMAQdxAttributeVisibility(int value) { + this.value = value; + } + + public static IMAQdxAttributeVisibility fromValue(int val) { + for (IMAQdxAttributeVisibility v : values()) { + if (v.value == val) + return v; + } + return null; + } + + public int getValue() { + return value; + } + } + + /** + * Stream Channel Mode Enumeration + */ + + public static enum IMAQdxStreamChannelMode { + StreamChannelModeAutomatic(0), StreamChannelModeManual(1), StreamChannelModeGuard(0xFFFFFFFF), ; + private final int value; + + private IMAQdxStreamChannelMode(int value) { + this.value = value; + } + + public static IMAQdxStreamChannelMode fromValue(int val) { + for (IMAQdxStreamChannelMode v : values()) { + if (v.value == val) + return v; + } + return null; + } + + public int getValue() { + return value; + } + } + + /** + * Pixel Signedness Enumeration + */ + + public static enum IMAQdxPixelSignedness { + PixelSignednessUnsigned(0), PixelSignednessSigned(1), PixelSignednessHardware(2), PixelSignednessGuard( + 0xFFFFFFFF), ; + private final int value; + + private IMAQdxPixelSignedness(int value) { + this.value = value; + } + + public static IMAQdxPixelSignedness fromValue(int val) { + for (IMAQdxPixelSignedness v : values()) { + if (v.value == val) + return v; + } + return null; + } + + public int getValue() { + return value; + } + } + + /** + * USB Connection Speed Enumeration + */ + + public static enum IMAQdxUSBConnectionSpeed { + USBConnectionSpeedLow(1), USBConnectionSpeedFull(2), USBConnectionSpeedHigh(4), USBConnectionSpeedSuper( + 8), USBConnectionSpeedGuard(0xFFFFFFFF), ; + private final int value; + + private IMAQdxUSBConnectionSpeed(int value) { + this.value = value; + } + + public static IMAQdxUSBConnectionSpeed fromValue(int val) { + for (IMAQdxUSBConnectionSpeed v : values()) { + if (v.value == val) + return v; + } + return null; + } + + public int getValue() { + return value; + } + } + + /** + * CVI Structures + */ + + /** + * Camera Information Structure + */ + + public static class IMAQdxCameraInformation extends DisposedStruct { + public int Type; + public int Version; + public int Flags; + public int SerialNumberHi; + public int SerialNumberLo; + public IMAQdxBusType BusType; + public String InterfaceName; + public String VendorName; + public String ModelName; + public String CameraFileName; + public String CameraAttributeURL; + + private void init() { + + } + + public IMAQdxCameraInformation() { + super(2584); + init(); + } + + public IMAQdxCameraInformation(int Type, int Version, int Flags, int SerialNumberHi, + int SerialNumberLo, IMAQdxBusType BusType, String InterfaceName, String VendorName, + String ModelName, String CameraFileName, String CameraAttributeURL) { + super(2584); + this.Type = Type; + this.Version = Version; + this.Flags = Flags; + this.SerialNumberHi = SerialNumberHi; + this.SerialNumberLo = SerialNumberLo; + this.BusType = BusType; + this.InterfaceName = InterfaceName; + this.VendorName = VendorName; + this.ModelName = ModelName; + this.CameraFileName = CameraFileName; + this.CameraAttributeURL = CameraAttributeURL; + } + + protected IMAQdxCameraInformation(ByteBuffer backing, int offset) { + super(backing, offset, 2584); + init(); + } + + protected IMAQdxCameraInformation(long nativeObj, boolean owned) { + super(nativeObj, owned, 2584); + init(); + } + + protected void setBuffer(ByteBuffer backing, int offset) { + super.setBuffer(backing, offset, 2584); + } + + public void read() { + Type = backing.getInt(0); + Version = backing.getInt(4); + Flags = backing.getInt(8); + SerialNumberHi = backing.getInt(12); + SerialNumberLo = backing.getInt(16); + BusType = IMAQdxBusType.fromValue(backing.getInt(20)); + { + byte[] bytes = new byte[IMAQDX_MAX_API_STRING_LENGTH]; + getBytes(backing, bytes, 24, IMAQDX_MAX_API_STRING_LENGTH); + int len; + for (len = 0; len < bytes.length && bytes[len] != 0; len++) { + } + try { + InterfaceName = new String(bytes, 0, len, "UTF-8"); + } catch (UnsupportedEncodingException e) { + InterfaceName = ""; + } + } + { + byte[] bytes = new byte[IMAQDX_MAX_API_STRING_LENGTH]; + getBytes(backing, bytes, 536, IMAQDX_MAX_API_STRING_LENGTH); + int len; + for (len = 0; len < bytes.length && bytes[len] != 0; len++) { + } + try { + VendorName = new String(bytes, 0, len, "UTF-8"); + } catch (UnsupportedEncodingException e) { + VendorName = ""; + } + } + { + byte[] bytes = new byte[IMAQDX_MAX_API_STRING_LENGTH]; + getBytes(backing, bytes, 1048, IMAQDX_MAX_API_STRING_LENGTH); + int len; + for (len = 0; len < bytes.length && bytes[len] != 0; len++) { + } + try { + ModelName = new String(bytes, 0, len, "UTF-8"); + } catch (UnsupportedEncodingException e) { + ModelName = ""; + } + } + { + byte[] bytes = new byte[IMAQDX_MAX_API_STRING_LENGTH]; + getBytes(backing, bytes, 1560, IMAQDX_MAX_API_STRING_LENGTH); + int len; + for (len = 0; len < bytes.length && bytes[len] != 0; len++) { + } + try { + CameraFileName = new String(bytes, 0, len, "UTF-8"); + } catch (UnsupportedEncodingException e) { + CameraFileName = ""; + } + } + { + byte[] bytes = new byte[IMAQDX_MAX_API_STRING_LENGTH]; + getBytes(backing, bytes, 2072, IMAQDX_MAX_API_STRING_LENGTH); + int len; + for (len = 0; len < bytes.length && bytes[len] != 0; len++) { + } + try { + CameraAttributeURL = new String(bytes, 0, len, "UTF-8"); + } catch (UnsupportedEncodingException e) { + CameraAttributeURL = ""; + } + } + } + + public void write() { + backing.putInt(0, Type); + backing.putInt(4, Version); + backing.putInt(8, Flags); + backing.putInt(12, SerialNumberHi); + backing.putInt(16, SerialNumberLo); + if (BusType != null) + backing.putInt(20, BusType.getValue()); + if (InterfaceName != null) { + byte[] bytes; + try { + bytes = InterfaceName.getBytes("UTF-8"); + } catch (UnsupportedEncodingException e) { + bytes = new byte[0]; + } + putBytes(backing, bytes, 24, bytes.length); + for (int i = bytes.length; i < IMAQDX_MAX_API_STRING_LENGTH; i++) + backing.put(i, (byte) 0); // fill with zero + } + if (VendorName != null) { + byte[] bytes; + try { + bytes = VendorName.getBytes("UTF-8"); + } catch (UnsupportedEncodingException e) { + bytes = new byte[0]; + } + putBytes(backing, bytes, 536, bytes.length); + for (int i = bytes.length; i < IMAQDX_MAX_API_STRING_LENGTH; i++) + backing.put(i, (byte) 0); // fill with zero + } + if (ModelName != null) { + byte[] bytes; + try { + bytes = ModelName.getBytes("UTF-8"); + } catch (UnsupportedEncodingException e) { + bytes = new byte[0]; + } + putBytes(backing, bytes, 1048, bytes.length); + for (int i = bytes.length; i < IMAQDX_MAX_API_STRING_LENGTH; i++) + backing.put(i, (byte) 0); // fill with zero + } + if (CameraFileName != null) { + byte[] bytes; + try { + bytes = CameraFileName.getBytes("UTF-8"); + } catch (UnsupportedEncodingException e) { + bytes = new byte[0]; + } + putBytes(backing, bytes, 1560, bytes.length); + for (int i = bytes.length; i < IMAQDX_MAX_API_STRING_LENGTH; i++) + backing.put(i, (byte) 0); // fill with zero + } + if (CameraAttributeURL != null) { + byte[] bytes; + try { + bytes = CameraAttributeURL.getBytes("UTF-8"); + } catch (UnsupportedEncodingException e) { + bytes = new byte[0]; + } + putBytes(backing, bytes, 2072, bytes.length); + for (int i = bytes.length; i < IMAQDX_MAX_API_STRING_LENGTH; i++) + backing.put(i, (byte) 0); // fill with zero + } + } + + public int size() { + return 2584; + } + } + + /** + * Camera File Structure + */ + + public static class IMAQdxCameraFile extends DisposedStruct { + public int Type; + public int Version; + public String FileName; + + private void init() { + + } + + public IMAQdxCameraFile() { + super(520); + init(); + } + + public IMAQdxCameraFile(int Type, int Version, String FileName) { + super(520); + this.Type = Type; + this.Version = Version; + this.FileName = FileName; + } + + protected IMAQdxCameraFile(ByteBuffer backing, int offset) { + super(backing, offset, 520); + init(); + } + + protected IMAQdxCameraFile(long nativeObj, boolean owned) { + super(nativeObj, owned, 520); + init(); + } + + protected void setBuffer(ByteBuffer backing, int offset) { + super.setBuffer(backing, offset, 520); + } + + public void read() { + Type = backing.getInt(0); + Version = backing.getInt(4); + { + byte[] bytes = new byte[IMAQDX_MAX_API_STRING_LENGTH]; + getBytes(backing, bytes, 8, IMAQDX_MAX_API_STRING_LENGTH); + int len; + for (len = 0; len < bytes.length && bytes[len] != 0; len++) { + } + try { + FileName = new String(bytes, 0, len, "UTF-8"); + } catch (UnsupportedEncodingException e) { + FileName = ""; + } + } + } + + public void write() { + backing.putInt(0, Type); + backing.putInt(4, Version); + if (FileName != null) { + byte[] bytes; + try { + bytes = FileName.getBytes("UTF-8"); + } catch (UnsupportedEncodingException e) { + bytes = new byte[0]; + } + putBytes(backing, bytes, 8, bytes.length); + for (int i = bytes.length; i < IMAQDX_MAX_API_STRING_LENGTH; i++) + backing.put(i, (byte) 0); // fill with zero + } + } + + public int size() { + return 520; + } + } + + /** + * Attribute Information Structure + */ + + public static class IMAQdxAttributeInformation extends DisposedStruct { + public IMAQdxAttributeType Type; + public int Readable; + public int Writable; + public String Name; + + private void init() { + + } + + public IMAQdxAttributeInformation() { + super(524); + init(); + } + + public IMAQdxAttributeInformation(IMAQdxAttributeType Type, int Readable, int Writable, + String Name) { + super(524); + this.Type = Type; + this.Readable = Readable; + this.Writable = Writable; + this.Name = Name; + } + + protected IMAQdxAttributeInformation(ByteBuffer backing, int offset) { + super(backing, offset, 524); + init(); + } + + protected IMAQdxAttributeInformation(long nativeObj, boolean owned) { + super(nativeObj, owned, 524); + init(); + } + + protected void setBuffer(ByteBuffer backing, int offset) { + super.setBuffer(backing, offset, 524); + } + + public void read() { + Type = IMAQdxAttributeType.fromValue(backing.getInt(0)); + Readable = backing.getInt(4); + Writable = backing.getInt(8); + { + byte[] bytes = new byte[IMAQDX_MAX_API_STRING_LENGTH]; + getBytes(backing, bytes, 12, IMAQDX_MAX_API_STRING_LENGTH); + int len; + for (len = 0; len < bytes.length && bytes[len] != 0; len++) { + } + try { + Name = new String(bytes, 0, len, "UTF-8"); + } catch (UnsupportedEncodingException e) { + Name = ""; + } + } + } + + public void write() { + if (Type != null) + backing.putInt(0, Type.getValue()); + backing.putInt(4, Readable); + backing.putInt(8, Writable); + if (Name != null) { + byte[] bytes; + try { + bytes = Name.getBytes("UTF-8"); + } catch (UnsupportedEncodingException e) { + bytes = new byte[0]; + } + putBytes(backing, bytes, 12, bytes.length); + for (int i = bytes.length; i < IMAQDX_MAX_API_STRING_LENGTH; i++) + backing.put(i, (byte) 0); // fill with zero + } + } + + public int size() { + return 524; + } + } + + /** + * Enumeration Item Structure + */ + + public static class IMAQdxEnumItem extends DisposedStruct { + public int Value; + public int Reserved; + public String Name; + + private void init() { + + } + + public IMAQdxEnumItem() { + super(520); + init(); + } + + public IMAQdxEnumItem(int Value, int Reserved, String Name) { + super(520); + this.Value = Value; + this.Reserved = Reserved; + this.Name = Name; + } + + protected IMAQdxEnumItem(ByteBuffer backing, int offset) { + super(backing, offset, 520); + init(); + } + + protected IMAQdxEnumItem(long nativeObj, boolean owned) { + super(nativeObj, owned, 520); + init(); + } + + protected void setBuffer(ByteBuffer backing, int offset) { + super.setBuffer(backing, offset, 520); + } + + public void read() { + Value = backing.getInt(0); + Reserved = backing.getInt(4); + { + byte[] bytes = new byte[IMAQDX_MAX_API_STRING_LENGTH]; + getBytes(backing, bytes, 8, IMAQDX_MAX_API_STRING_LENGTH); + int len; + for (len = 0; len < bytes.length && bytes[len] != 0; len++) { + } + try { + Name = new String(bytes, 0, len, "UTF-8"); + } catch (UnsupportedEncodingException e) { + Name = ""; + } + } + } + + public void write() { + backing.putInt(0, Value); + backing.putInt(4, Reserved); + if (Name != null) { + byte[] bytes; + try { + bytes = Name.getBytes("UTF-8"); + } catch (UnsupportedEncodingException e) { + bytes = new byte[0]; + } + putBytes(backing, bytes, 8, bytes.length); + for (int i = bytes.length; i < IMAQDX_MAX_API_STRING_LENGTH; i++) + backing.put(i, (byte) 0); // fill with zero + } + } + + public int size() { + return 520; + } + } + + /** + * Camera Information Structure + */ + + /** + * Attributes + */ + + /** + * Functions + */ + + public static void IMAQdxSnap(int id, Image image) { + + _IMAQdxSnap(id, image.getAddress()); + + } + + private static native void _IMAQdxSnap(int id, long image); + + public static void IMAQdxConfigureGrab(int id) { + + _IMAQdxConfigureGrab(id); + + } + + private static native void _IMAQdxConfigureGrab(int id); + + public static int IMAQdxGrab(int id, Image image, int waitForNextBuffer) { + ByteBuffer rv_buf = ByteBuffer.allocateDirect(8).order(ByteOrder.nativeOrder()); + long rv_addr = getByteBufferAddress(rv_buf); + _IMAQdxGrab(id, image.getAddress(), waitForNextBuffer, rv_addr + 0); + int actualBufferNumber; + actualBufferNumber = rv_buf.getInt(0); + return actualBufferNumber; + } + + private static native void _IMAQdxGrab(int id, long image, int waitForNextBuffer, + long actualBufferNumber); + + public static void IMAQdxDiscoverEthernetCameras(String address, int timeout) { + ByteBuffer address_buf = null; + if (address != null) { + byte[] address_bytes; + try { + address_bytes = address.getBytes("UTF-8"); + } catch (UnsupportedEncodingException e) { + address_bytes = new byte[0]; + } + address_buf = ByteBuffer.allocateDirect(address_bytes.length + 1); + putBytes(address_buf, address_bytes, 0, address_bytes.length).put(address_bytes.length, + (byte) 0); + } + _IMAQdxDiscoverEthernetCameras(address == null ? 0 : getByteBufferAddress(address_buf), timeout); + + } + + private static native void _IMAQdxDiscoverEthernetCameras(long address, int timeout); + + public static void IMAQdxResetCamera(String name, int resetAll) { + ByteBuffer name_buf = null; + if (name != null) { + byte[] name_bytes; + try { + name_bytes = name.getBytes("UTF-8"); + } catch (UnsupportedEncodingException e) { + name_bytes = new byte[0]; + } + name_buf = ByteBuffer.allocateDirect(name_bytes.length + 1); + putBytes(name_buf, name_bytes, 0, name_bytes.length).put(name_bytes.length, (byte) 0); + } + _IMAQdxResetCamera(name == null ? 0 : getByteBufferAddress(name_buf), resetAll); + + } + + private static native void _IMAQdxResetCamera(long name, int resetAll); + + public static int IMAQdxOpenCamera(String name, IMAQdxCameraControlMode mode) { + ByteBuffer name_buf = null; + if (name != null) { + byte[] name_bytes; + try { + name_bytes = name.getBytes("UTF-8"); + } catch (UnsupportedEncodingException e) { + name_bytes = new byte[0]; + } + name_buf = ByteBuffer.allocateDirect(name_bytes.length + 1); + putBytes(name_buf, name_bytes, 0, name_bytes.length).put(name_bytes.length, (byte) 0); + } + ByteBuffer rv_buf = ByteBuffer.allocateDirect(8).order(ByteOrder.nativeOrder()); + long rv_addr = getByteBufferAddress(rv_buf); + _IMAQdxOpenCamera(name == null ? 0 : getByteBufferAddress(name_buf), mode.getValue(), + rv_addr + 0); + int id; + id = rv_buf.getInt(0); + return id; + } + + private static native void _IMAQdxOpenCamera(long name, int mode, long id); + + public static void IMAQdxCloseCamera(int id) { + + _IMAQdxCloseCamera(id); + + } + + private static native void _IMAQdxCloseCamera(int id); + + public static void IMAQdxConfigureAcquisition(int id, int continuous, int bufferCount) { + + _IMAQdxConfigureAcquisition(id, continuous, bufferCount); + + } + + private static native void _IMAQdxConfigureAcquisition(int id, int continuous, int bufferCount); + + public static void IMAQdxStartAcquisition(int id) { + + _IMAQdxStartAcquisition(id); + + } + + private static native void _IMAQdxStartAcquisition(int id); + + public static int IMAQdxGetImage(int id, Image image, IMAQdxBufferNumberMode mode, + int desiredBufferNumber) { + ByteBuffer rv_buf = ByteBuffer.allocateDirect(8).order(ByteOrder.nativeOrder()); + long rv_addr = getByteBufferAddress(rv_buf); + _IMAQdxGetImage(id, image.getAddress(), mode.getValue(), desiredBufferNumber, rv_addr + 0); + int actualBufferNumber; + actualBufferNumber = rv_buf.getInt(0); + return actualBufferNumber; + } + + private static native void _IMAQdxGetImage(int id, long image, int mode, int desiredBufferNumber, + long actualBufferNumber); + + public static int IMAQdxGetImageData(int id, ByteBuffer buffer, IMAQdxBufferNumberMode mode, + int desiredBufferNumber) { + long buffer_addr = getByteBufferAddress(buffer); + int buffer_size = buffer.capacity(); + return _IMAQdxGetImageData(id, buffer_addr, buffer_size, mode.getValue(), desiredBufferNumber); + } + + private static native int _IMAQdxGetImageData(int id, long buffer, int bufferSize, int mode, + int desiredBufferNumber); + + public static void IMAQdxStopAcquisition(int id) { + + _IMAQdxStopAcquisition(id); + + } + + private static native void _IMAQdxStopAcquisition(int id); + + public static void IMAQdxUnconfigureAcquisition(int id) { + + _IMAQdxUnconfigureAcquisition(id); + + } + + private static native void _IMAQdxUnconfigureAcquisition(int id); + + public static class dxEnumerateVideoModesResult { + public IMAQdxEnumItem[] videoModeArray; + public int currentMode; + private ByteBuffer videoModeArray_buf; + + private dxEnumerateVideoModesResult(ByteBuffer rv_buf, ByteBuffer videoModeArray_buf) { + this.videoModeArray_buf = videoModeArray_buf; + int count = rv_buf.getInt(0); + videoModeArray = new IMAQdxEnumItem[count]; + for (int i = 0, off = 0; i < count; i++, off += 520) { + videoModeArray[i] = new IMAQdxEnumItem(videoModeArray_buf, off); + videoModeArray[i].read(); + } + currentMode = rv_buf.getInt(8); + } + } + + public static dxEnumerateVideoModesResult IMAQdxEnumerateVideoModes(int id) { + ByteBuffer rv_buf = ByteBuffer.allocateDirect(8 + 8).order(ByteOrder.nativeOrder()); + long rv_addr = getByteBufferAddress(rv_buf); + _IMAQdxEnumerateVideoModes(id, 0, rv_addr + 0, rv_addr + 8); + int count = rv_buf.getInt(0); + ByteBuffer videoModeArray_buf = + ByteBuffer.allocateDirect(count * 520).order(ByteOrder.nativeOrder()); + _IMAQdxEnumerateVideoModes(id, getByteBufferAddress(videoModeArray_buf), rv_addr + 0, + rv_addr + 8); + dxEnumerateVideoModesResult rv = new dxEnumerateVideoModesResult(rv_buf, videoModeArray_buf); + return rv; + } + + private static native void _IMAQdxEnumerateVideoModes(int id, long videoModeArray, long count, + long currentMode); + + public static IMAQdxAttributeType IMAQdxGetAttributeType(int id, String name) { + ByteBuffer name_buf = null; + if (name != null) { + byte[] name_bytes; + try { + name_bytes = name.getBytes("UTF-8"); + } catch (UnsupportedEncodingException e) { + name_bytes = new byte[0]; + } + name_buf = ByteBuffer.allocateDirect(name_bytes.length + 1); + putBytes(name_buf, name_bytes, 0, name_bytes.length).put(name_bytes.length, (byte) 0); + } + ByteBuffer rv_buf = ByteBuffer.allocateDirect(8).order(ByteOrder.nativeOrder()); + long rv_addr = getByteBufferAddress(rv_buf); + _IMAQdxGetAttributeType(id, name == null ? 0 : getByteBufferAddress(name_buf), rv_addr + 0); + IMAQdxAttributeType type; + type = IMAQdxAttributeType.fromValue(rv_buf.getInt(0)); + return type; + } + + private static native void _IMAQdxGetAttributeType(int id, long name, long type); + + public static int IMAQdxIsAttributeReadable(int id, String name) { + ByteBuffer name_buf = null; + if (name != null) { + byte[] name_bytes; + try { + name_bytes = name.getBytes("UTF-8"); + } catch (UnsupportedEncodingException e) { + name_bytes = new byte[0]; + } + name_buf = ByteBuffer.allocateDirect(name_bytes.length + 1); + putBytes(name_buf, name_bytes, 0, name_bytes.length).put(name_bytes.length, (byte) 0); + } + ByteBuffer rv_buf = ByteBuffer.allocateDirect(8).order(ByteOrder.nativeOrder()); + long rv_addr = getByteBufferAddress(rv_buf); + _IMAQdxIsAttributeReadable(id, name == null ? 0 : getByteBufferAddress(name_buf), rv_addr + 0); + int readable; + readable = rv_buf.getInt(0); + return readable; + } + + private static native void _IMAQdxIsAttributeReadable(int id, long name, long readable); + + public static int IMAQdxIsAttributeWritable(int id, String name) { + ByteBuffer name_buf = null; + if (name != null) { + byte[] name_bytes; + try { + name_bytes = name.getBytes("UTF-8"); + } catch (UnsupportedEncodingException e) { + name_bytes = new byte[0]; + } + name_buf = ByteBuffer.allocateDirect(name_bytes.length + 1); + putBytes(name_buf, name_bytes, 0, name_bytes.length).put(name_bytes.length, (byte) 0); + } + ByteBuffer rv_buf = ByteBuffer.allocateDirect(8).order(ByteOrder.nativeOrder()); + long rv_addr = getByteBufferAddress(rv_buf); + _IMAQdxIsAttributeWritable(id, name == null ? 0 : getByteBufferAddress(name_buf), rv_addr + 0); + int writable; + writable = rv_buf.getInt(0); + return writable; + } + + private static native void _IMAQdxIsAttributeWritable(int id, long name, long writable); + + public static void IMAQdxWriteRegister(int id, int offset, int value) { + + _IMAQdxWriteRegister(id, offset, value); + + } + + private static native void _IMAQdxWriteRegister(int id, int offset, int value); + + public static int IMAQdxReadRegister(int id, int offset) { + ByteBuffer rv_buf = ByteBuffer.allocateDirect(8).order(ByteOrder.nativeOrder()); + long rv_addr = getByteBufferAddress(rv_buf); + _IMAQdxReadRegister(id, offset, rv_addr + 0); + int value; + value = rv_buf.getInt(0); + return value; + } + + private static native void _IMAQdxReadRegister(int id, int offset, long value); + + public static void IMAQdxWriteAttributes(int id, String filename) { + ByteBuffer filename_buf = null; + if (filename != null) { + byte[] filename_bytes; + try { + filename_bytes = filename.getBytes("UTF-8"); + } catch (UnsupportedEncodingException e) { + filename_bytes = new byte[0]; + } + filename_buf = ByteBuffer.allocateDirect(filename_bytes.length + 1); + putBytes(filename_buf, filename_bytes, 0, filename_bytes.length).put(filename_bytes.length, + (byte) 0); + } + _IMAQdxWriteAttributes(id, filename == null ? 0 : getByteBufferAddress(filename_buf)); + + } + + private static native void _IMAQdxWriteAttributes(int id, long filename); + + public static void IMAQdxReadAttributes(int id, String filename) { + ByteBuffer filename_buf = null; + if (filename != null) { + byte[] filename_bytes; + try { + filename_bytes = filename.getBytes("UTF-8"); + } catch (UnsupportedEncodingException e) { + filename_bytes = new byte[0]; + } + filename_buf = ByteBuffer.allocateDirect(filename_bytes.length + 1); + putBytes(filename_buf, filename_bytes, 0, filename_bytes.length).put(filename_bytes.length, + (byte) 0); + } + _IMAQdxReadAttributes(id, filename == null ? 0 : getByteBufferAddress(filename_buf)); + + } + + private static native void _IMAQdxReadAttributes(int id, long filename); + + public static void IMAQdxResetEthernetCameraAddress(String name, String address, String subnet, + String gateway, int timeout) { + ByteBuffer name_buf = null; + if (name != null) { + byte[] name_bytes; + try { + name_bytes = name.getBytes("UTF-8"); + } catch (UnsupportedEncodingException e) { + name_bytes = new byte[0]; + } + name_buf = ByteBuffer.allocateDirect(name_bytes.length + 1); + putBytes(name_buf, name_bytes, 0, name_bytes.length).put(name_bytes.length, (byte) 0); + } + ByteBuffer address_buf = null; + if (address != null) { + byte[] address_bytes; + try { + address_bytes = address.getBytes("UTF-8"); + } catch (UnsupportedEncodingException e) { + address_bytes = new byte[0]; + } + address_buf = ByteBuffer.allocateDirect(address_bytes.length + 1); + putBytes(address_buf, address_bytes, 0, address_bytes.length).put(address_bytes.length, + (byte) 0); + } + ByteBuffer subnet_buf = null; + if (subnet != null) { + byte[] subnet_bytes; + try { + subnet_bytes = subnet.getBytes("UTF-8"); + } catch (UnsupportedEncodingException e) { + subnet_bytes = new byte[0]; + } + subnet_buf = ByteBuffer.allocateDirect(subnet_bytes.length + 1); + putBytes(subnet_buf, subnet_bytes, 0, subnet_bytes.length).put(subnet_bytes.length, (byte) 0); + } + ByteBuffer gateway_buf = null; + if (gateway != null) { + byte[] gateway_bytes; + try { + gateway_bytes = gateway.getBytes("UTF-8"); + } catch (UnsupportedEncodingException e) { + gateway_bytes = new byte[0]; + } + gateway_buf = ByteBuffer.allocateDirect(gateway_bytes.length + 1); + putBytes(gateway_buf, gateway_bytes, 0, gateway_bytes.length).put(gateway_bytes.length, + (byte) 0); + } + _IMAQdxResetEthernetCameraAddress(name == null ? 0 : getByteBufferAddress(name_buf), + address == null ? 0 : getByteBufferAddress(address_buf), subnet == null ? 0 + : getByteBufferAddress(subnet_buf), gateway == null ? 0 + : getByteBufferAddress(gateway_buf), timeout); + + } + + private static native void _IMAQdxResetEthernetCameraAddress(long name, long address, + long subnet, long gateway, int timeout); + + public static IMAQdxAttributeVisibility IMAQdxGetAttributeVisibility(int id, String name) { + ByteBuffer name_buf = null; + if (name != null) { + byte[] name_bytes; + try { + name_bytes = name.getBytes("UTF-8"); + } catch (UnsupportedEncodingException e) { + name_bytes = new byte[0]; + } + name_buf = ByteBuffer.allocateDirect(name_bytes.length + 1); + putBytes(name_buf, name_bytes, 0, name_bytes.length).put(name_bytes.length, (byte) 0); + } + ByteBuffer rv_buf = ByteBuffer.allocateDirect(8).order(ByteOrder.nativeOrder()); + long rv_addr = getByteBufferAddress(rv_buf); + _IMAQdxGetAttributeVisibility(id, name == null ? 0 : getByteBufferAddress(name_buf), + rv_addr + 0); + IMAQdxAttributeVisibility visibility; + visibility = IMAQdxAttributeVisibility.fromValue(rv_buf.getInt(0)); + return visibility; + } + + private static native void _IMAQdxGetAttributeVisibility(int id, long name, long visibility); + + public static int IMAQdxGetAttributeU32(int id, String name) { + ByteBuffer name_buf = null; + if (name != null) { + byte[] name_bytes; + try { + name_bytes = name.getBytes("UTF-8"); + } catch (UnsupportedEncodingException e) { + name_bytes = new byte[0]; + } + name_buf = ByteBuffer.allocateDirect(name_bytes.length + 1); + putBytes(name_buf, name_bytes, 0, name_bytes.length).put(name_bytes.length, (byte) 0); + } + ByteBuffer rv_buf = ByteBuffer.allocateDirect(8).order(ByteOrder.nativeOrder()); + long rv_addr = getByteBufferAddress(rv_buf); + _IMAQdxGetAttributeU32(id, name == null ? 0 : getByteBufferAddress(name_buf), rv_addr + 0); + int value; + value = rv_buf.getInt(0); + return value; + } + + private static native void _IMAQdxGetAttributeU32(int id, long name, long value); + + public static long IMAQdxGetAttributeI64(int id, String name) { + ByteBuffer name_buf = null; + if (name != null) { + byte[] name_bytes; + try { + name_bytes = name.getBytes("UTF-8"); + } catch (UnsupportedEncodingException e) { + name_bytes = new byte[0]; + } + name_buf = ByteBuffer.allocateDirect(name_bytes.length + 1); + putBytes(name_buf, name_bytes, 0, name_bytes.length).put(name_bytes.length, (byte) 0); + } + ByteBuffer rv_buf = ByteBuffer.allocateDirect(8).order(ByteOrder.nativeOrder()); + long rv_addr = getByteBufferAddress(rv_buf); + _IMAQdxGetAttributeI64(id, name == null ? 0 : getByteBufferAddress(name_buf), rv_addr + 0); + long value; + value = rv_buf.getLong(0); + return value; + } + + private static native void _IMAQdxGetAttributeI64(int id, long name, long value); + + public static double IMAQdxGetAttributeF64(int id, String name) { + ByteBuffer name_buf = null; + if (name != null) { + byte[] name_bytes; + try { + name_bytes = name.getBytes("UTF-8"); + } catch (UnsupportedEncodingException e) { + name_bytes = new byte[0]; + } + name_buf = ByteBuffer.allocateDirect(name_bytes.length + 1); + putBytes(name_buf, name_bytes, 0, name_bytes.length).put(name_bytes.length, (byte) 0); + } + ByteBuffer rv_buf = ByteBuffer.allocateDirect(8).order(ByteOrder.nativeOrder()); + long rv_addr = getByteBufferAddress(rv_buf); + _IMAQdxGetAttributeF64(id, name == null ? 0 : getByteBufferAddress(name_buf), rv_addr + 0); + double value; + value = rv_buf.getDouble(0); + return value; + } + + private static native void _IMAQdxGetAttributeF64(int id, long name, long value); + + public static String IMAQdxGetAttributeString(int id, String name) { + ByteBuffer name_buf = null; + if (name != null) { + byte[] name_bytes; + try { + name_bytes = name.getBytes("UTF-8"); + } catch (UnsupportedEncodingException e) { + name_bytes = new byte[0]; + } + name_buf = ByteBuffer.allocateDirect(name_bytes.length + 1); + putBytes(name_buf, name_bytes, 0, name_bytes.length).put(name_bytes.length, (byte) 0); + } + ByteBuffer rv_buf = + ByteBuffer.allocateDirect(IMAQDX_MAX_API_STRING_LENGTH).order(ByteOrder.nativeOrder()); + long rv_addr = getByteBufferAddress(rv_buf); + _IMAQdxGetAttributeString(id, name == null ? 0 : getByteBufferAddress(name_buf), rv_addr + 0); + String value; + { + byte[] bytes = new byte[IMAQDX_MAX_API_STRING_LENGTH]; + getBytes(rv_buf, bytes, 0, IMAQDX_MAX_API_STRING_LENGTH); + int len; + for (len = 0; len < bytes.length && bytes[len] != 0; len++) { + } + try { + value = new String(bytes, 0, len, "UTF-8"); + } catch (UnsupportedEncodingException e) { + value = ""; + } + } + return value; + } + + private static native void _IMAQdxGetAttributeString(int id, long name, long value); + + public static IMAQdxEnumItem IMAQdxGetAttributeEnum(int id, String name) { + ByteBuffer name_buf = null; + if (name != null) { + byte[] name_bytes; + try { + name_bytes = name.getBytes("UTF-8"); + } catch (UnsupportedEncodingException e) { + name_bytes = new byte[0]; + } + name_buf = ByteBuffer.allocateDirect(name_bytes.length + 1); + putBytes(name_buf, name_bytes, 0, name_bytes.length).put(name_bytes.length, (byte) 0); + } + ByteBuffer rv_buf = ByteBuffer.allocateDirect(8).order(ByteOrder.nativeOrder()); + long rv_addr = getByteBufferAddress(rv_buf); + _IMAQdxGetAttributeEnum(id, name == null ? 0 : getByteBufferAddress(name_buf), rv_addr + 0); + IMAQdxEnumItem value; + value = new IMAQdxEnumItem(rv_buf, 0); + value.read(); + return value; + } + + private static native void _IMAQdxGetAttributeEnum(int id, long name, long value); + + public static int IMAQdxGetAttributeBool(int id, String name) { + ByteBuffer name_buf = null; + if (name != null) { + byte[] name_bytes; + try { + name_bytes = name.getBytes("UTF-8"); + } catch (UnsupportedEncodingException e) { + name_bytes = new byte[0]; + } + name_buf = ByteBuffer.allocateDirect(name_bytes.length + 1); + putBytes(name_buf, name_bytes, 0, name_bytes.length).put(name_bytes.length, (byte) 0); + } + ByteBuffer rv_buf = ByteBuffer.allocateDirect(8).order(ByteOrder.nativeOrder()); + long rv_addr = getByteBufferAddress(rv_buf); + _IMAQdxGetAttributeBool(id, name == null ? 0 : getByteBufferAddress(name_buf), rv_addr + 0); + int value; + value = rv_buf.getInt(0); + return value; + } + + private static native void _IMAQdxGetAttributeBool(int id, long name, long value); + + public static int IMAQdxGetAttributeMinimumU32(int id, String name) { + ByteBuffer name_buf = null; + if (name != null) { + byte[] name_bytes; + try { + name_bytes = name.getBytes("UTF-8"); + } catch (UnsupportedEncodingException e) { + name_bytes = new byte[0]; + } + name_buf = ByteBuffer.allocateDirect(name_bytes.length + 1); + putBytes(name_buf, name_bytes, 0, name_bytes.length).put(name_bytes.length, (byte) 0); + } + ByteBuffer rv_buf = ByteBuffer.allocateDirect(8).order(ByteOrder.nativeOrder()); + long rv_addr = getByteBufferAddress(rv_buf); + _IMAQdxGetAttributeMinimumU32(id, name == null ? 0 : getByteBufferAddress(name_buf), + rv_addr + 0); + int value; + value = rv_buf.getInt(0); + return value; + } + + private static native void _IMAQdxGetAttributeMinimumU32(int id, long name, long value); + + public static long IMAQdxGetAttributeMinimumI64(int id, String name) { + ByteBuffer name_buf = null; + if (name != null) { + byte[] name_bytes; + try { + name_bytes = name.getBytes("UTF-8"); + } catch (UnsupportedEncodingException e) { + name_bytes = new byte[0]; + } + name_buf = ByteBuffer.allocateDirect(name_bytes.length + 1); + putBytes(name_buf, name_bytes, 0, name_bytes.length).put(name_bytes.length, (byte) 0); + } + ByteBuffer rv_buf = ByteBuffer.allocateDirect(8).order(ByteOrder.nativeOrder()); + long rv_addr = getByteBufferAddress(rv_buf); + _IMAQdxGetAttributeMinimumI64(id, name == null ? 0 : getByteBufferAddress(name_buf), + rv_addr + 0); + long value; + value = rv_buf.getLong(0); + return value; + } + + private static native void _IMAQdxGetAttributeMinimumI64(int id, long name, long value); + + public static double IMAQdxGetAttributeMinimumF64(int id, String name) { + ByteBuffer name_buf = null; + if (name != null) { + byte[] name_bytes; + try { + name_bytes = name.getBytes("UTF-8"); + } catch (UnsupportedEncodingException e) { + name_bytes = new byte[0]; + } + name_buf = ByteBuffer.allocateDirect(name_bytes.length + 1); + putBytes(name_buf, name_bytes, 0, name_bytes.length).put(name_bytes.length, (byte) 0); + } + ByteBuffer rv_buf = ByteBuffer.allocateDirect(8).order(ByteOrder.nativeOrder()); + long rv_addr = getByteBufferAddress(rv_buf); + _IMAQdxGetAttributeMinimumF64(id, name == null ? 0 : getByteBufferAddress(name_buf), + rv_addr + 0); + double value; + value = rv_buf.getDouble(0); + return value; + } + + private static native void _IMAQdxGetAttributeMinimumF64(int id, long name, long value); + + public static int IMAQdxGetAttributeMaximumU32(int id, String name) { + ByteBuffer name_buf = null; + if (name != null) { + byte[] name_bytes; + try { + name_bytes = name.getBytes("UTF-8"); + } catch (UnsupportedEncodingException e) { + name_bytes = new byte[0]; + } + name_buf = ByteBuffer.allocateDirect(name_bytes.length + 1); + putBytes(name_buf, name_bytes, 0, name_bytes.length).put(name_bytes.length, (byte) 0); + } + ByteBuffer rv_buf = ByteBuffer.allocateDirect(8).order(ByteOrder.nativeOrder()); + long rv_addr = getByteBufferAddress(rv_buf); + _IMAQdxGetAttributeMaximumU32(id, name == null ? 0 : getByteBufferAddress(name_buf), + rv_addr + 0); + int value; + value = rv_buf.getInt(0); + return value; + } + + private static native void _IMAQdxGetAttributeMaximumU32(int id, long name, long value); + + public static long IMAQdxGetAttributeMaximumI64(int id, String name) { + ByteBuffer name_buf = null; + if (name != null) { + byte[] name_bytes; + try { + name_bytes = name.getBytes("UTF-8"); + } catch (UnsupportedEncodingException e) { + name_bytes = new byte[0]; + } + name_buf = ByteBuffer.allocateDirect(name_bytes.length + 1); + putBytes(name_buf, name_bytes, 0, name_bytes.length).put(name_bytes.length, (byte) 0); + } + ByteBuffer rv_buf = ByteBuffer.allocateDirect(8).order(ByteOrder.nativeOrder()); + long rv_addr = getByteBufferAddress(rv_buf); + _IMAQdxGetAttributeMaximumI64(id, name == null ? 0 : getByteBufferAddress(name_buf), + rv_addr + 0); + long value; + value = rv_buf.getLong(0); + return value; + } + + private static native void _IMAQdxGetAttributeMaximumI64(int id, long name, long value); + + public static double IMAQdxGetAttributeMaximumF64(int id, String name) { + ByteBuffer name_buf = null; + if (name != null) { + byte[] name_bytes; + try { + name_bytes = name.getBytes("UTF-8"); + } catch (UnsupportedEncodingException e) { + name_bytes = new byte[0]; + } + name_buf = ByteBuffer.allocateDirect(name_bytes.length + 1); + putBytes(name_buf, name_bytes, 0, name_bytes.length).put(name_bytes.length, (byte) 0); + } + ByteBuffer rv_buf = ByteBuffer.allocateDirect(8).order(ByteOrder.nativeOrder()); + long rv_addr = getByteBufferAddress(rv_buf); + _IMAQdxGetAttributeMaximumF64(id, name == null ? 0 : getByteBufferAddress(name_buf), + rv_addr + 0); + double value; + value = rv_buf.getDouble(0); + return value; + } + + private static native void _IMAQdxGetAttributeMaximumF64(int id, long name, long value); + + public static int IMAQdxGetAttributeIncrementU32(int id, String name) { + ByteBuffer name_buf = null; + if (name != null) { + byte[] name_bytes; + try { + name_bytes = name.getBytes("UTF-8"); + } catch (UnsupportedEncodingException e) { + name_bytes = new byte[0]; + } + name_buf = ByteBuffer.allocateDirect(name_bytes.length + 1); + putBytes(name_buf, name_bytes, 0, name_bytes.length).put(name_bytes.length, (byte) 0); + } + ByteBuffer rv_buf = ByteBuffer.allocateDirect(8).order(ByteOrder.nativeOrder()); + long rv_addr = getByteBufferAddress(rv_buf); + _IMAQdxGetAttributeIncrementU32(id, name == null ? 0 : getByteBufferAddress(name_buf), + rv_addr + 0); + int value; + value = rv_buf.getInt(0); + return value; + } + + private static native void _IMAQdxGetAttributeIncrementU32(int id, long name, long value); + + public static long IMAQdxGetAttributeIncrementI64(int id, String name) { + ByteBuffer name_buf = null; + if (name != null) { + byte[] name_bytes; + try { + name_bytes = name.getBytes("UTF-8"); + } catch (UnsupportedEncodingException e) { + name_bytes = new byte[0]; + } + name_buf = ByteBuffer.allocateDirect(name_bytes.length + 1); + putBytes(name_buf, name_bytes, 0, name_bytes.length).put(name_bytes.length, (byte) 0); + } + ByteBuffer rv_buf = ByteBuffer.allocateDirect(8).order(ByteOrder.nativeOrder()); + long rv_addr = getByteBufferAddress(rv_buf); + _IMAQdxGetAttributeIncrementI64(id, name == null ? 0 : getByteBufferAddress(name_buf), + rv_addr + 0); + long value; + value = rv_buf.getLong(0); + return value; + } + + private static native void _IMAQdxGetAttributeIncrementI64(int id, long name, long value); + + public static double IMAQdxGetAttributeIncrementF64(int id, String name) { + ByteBuffer name_buf = null; + if (name != null) { + byte[] name_bytes; + try { + name_bytes = name.getBytes("UTF-8"); + } catch (UnsupportedEncodingException e) { + name_bytes = new byte[0]; + } + name_buf = ByteBuffer.allocateDirect(name_bytes.length + 1); + putBytes(name_buf, name_bytes, 0, name_bytes.length).put(name_bytes.length, (byte) 0); + } + ByteBuffer rv_buf = ByteBuffer.allocateDirect(8).order(ByteOrder.nativeOrder()); + long rv_addr = getByteBufferAddress(rv_buf); + _IMAQdxGetAttributeIncrementF64(id, name == null ? 0 : getByteBufferAddress(name_buf), + rv_addr + 0); + double value; + value = rv_buf.getDouble(0); + return value; + } + + private static native void _IMAQdxGetAttributeIncrementF64(int id, long name, long value); + + public static void IMAQdxSetAttributeU32(int id, String name, int value) { + ByteBuffer name_buf = null; + if (name != null) { + byte[] name_bytes; + try { + name_bytes = name.getBytes("UTF-8"); + } catch (UnsupportedEncodingException e) { + name_bytes = new byte[0]; + } + name_buf = ByteBuffer.allocateDirect(name_bytes.length + 1); + putBytes(name_buf, name_bytes, 0, name_bytes.length).put(name_bytes.length, (byte) 0); + } + _IMAQdxSetAttributeU32(id, name == null ? 0 : getByteBufferAddress(name_buf), value); + + } + + private static native void _IMAQdxSetAttributeU32(int id, long name, int value); + + public static void IMAQdxSetAttributeI64(int id, String name, long value) { + ByteBuffer name_buf = null; + if (name != null) { + byte[] name_bytes; + try { + name_bytes = name.getBytes("UTF-8"); + } catch (UnsupportedEncodingException e) { + name_bytes = new byte[0]; + } + name_buf = ByteBuffer.allocateDirect(name_bytes.length + 1); + putBytes(name_buf, name_bytes, 0, name_bytes.length).put(name_bytes.length, (byte) 0); + } + _IMAQdxSetAttributeI64(id, name == null ? 0 : getByteBufferAddress(name_buf), value); + + } + + private static native void _IMAQdxSetAttributeI64(int id, long name, long value); + + public static void IMAQdxSetAttributeF64(int id, String name, double value) { + ByteBuffer name_buf = null; + if (name != null) { + byte[] name_bytes; + try { + name_bytes = name.getBytes("UTF-8"); + } catch (UnsupportedEncodingException e) { + name_bytes = new byte[0]; + } + name_buf = ByteBuffer.allocateDirect(name_bytes.length + 1); + putBytes(name_buf, name_bytes, 0, name_bytes.length).put(name_bytes.length, (byte) 0); + } + _IMAQdxSetAttributeF64(id, name == null ? 0 : getByteBufferAddress(name_buf), value); + + } + + private static native void _IMAQdxSetAttributeF64(int id, long name, double value); + + public static void IMAQdxSetAttributeString(int id, String name, String value) { + ByteBuffer name_buf = null; + if (name != null) { + byte[] name_bytes; + try { + name_bytes = name.getBytes("UTF-8"); + } catch (UnsupportedEncodingException e) { + name_bytes = new byte[0]; + } + name_buf = ByteBuffer.allocateDirect(name_bytes.length + 1); + putBytes(name_buf, name_bytes, 0, name_bytes.length).put(name_bytes.length, (byte) 0); + } + ByteBuffer value_buf = null; + if (value != null) { + byte[] value_bytes; + try { + value_bytes = value.getBytes("UTF-8"); + } catch (UnsupportedEncodingException e) { + value_bytes = new byte[0]; + } + value_buf = ByteBuffer.allocateDirect(value_bytes.length + 1); + putBytes(value_buf, value_bytes, 0, value_bytes.length).put(value_bytes.length, (byte) 0); + } + _IMAQdxSetAttributeString(id, name == null ? 0 : getByteBufferAddress(name_buf), + value == null ? 0 : getByteBufferAddress(value_buf)); + + } + + private static native void _IMAQdxSetAttributeString(int id, long name, long value); + + public static void IMAQdxSetAttributeEnum(int id, String name, IMAQdxEnumItem value) { + ByteBuffer name_buf = null; + if (name != null) { + byte[] name_bytes; + try { + name_bytes = name.getBytes("UTF-8"); + } catch (UnsupportedEncodingException e) { + name_bytes = new byte[0]; + } + name_buf = ByteBuffer.allocateDirect(name_bytes.length + 1); + putBytes(name_buf, name_bytes, 0, name_bytes.length).put(name_bytes.length, (byte) 0); + } + _IMAQdxSetAttributeEnum(id, name == null ? 0 : getByteBufferAddress(name_buf), + value.getAddress()); + + } + + private static native void _IMAQdxSetAttributeEnum(int id, long name, long value); + + public static void IMAQdxSetAttributeBool(int id, String name, int value) { + ByteBuffer name_buf = null; + if (name != null) { + byte[] name_bytes; + try { + name_bytes = name.getBytes("UTF-8"); + } catch (UnsupportedEncodingException e) { + name_bytes = new byte[0]; + } + name_buf = ByteBuffer.allocateDirect(name_bytes.length + 1); + putBytes(name_buf, name_bytes, 0, name_bytes.length).put(name_bytes.length, (byte) 0); + } + _IMAQdxSetAttributeBool(id, name == null ? 0 : getByteBufferAddress(name_buf), value); + + } + + private static native void _IMAQdxSetAttributeBool(int id, long name, int value); } diff --git a/wpilibj/wpilibJavaDevices/src/main/java/com/ni/vision/VisionException.java b/wpilibj/wpilibJavaDevices/src/main/java/com/ni/vision/VisionException.java index a58806251d..362a20dffe 100644 --- a/wpilibj/wpilibJavaDevices/src/main/java/com/ni/vision/VisionException.java +++ b/wpilibj/wpilibJavaDevices/src/main/java/com/ni/vision/VisionException.java @@ -7,14 +7,14 @@ package com.ni.vision; public class VisionException extends RuntimeException { - private static final long serialVersionUID = 1L; + private static final long serialVersionUID = 1L; - public VisionException(String msg) { - super(msg); - } + public VisionException(String msg) { + super(msg); + } - @Override - public String toString() { - return "VisionException [" + super.toString() + "]"; - } + @Override + public String toString() { + return "VisionException [" + super.toString() + "]"; + } } diff --git a/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/ADXL345_I2C.java b/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/ADXL345_I2C.java index cfb39e7677..e8736dae5e 100644 --- a/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/ADXL345_I2C.java +++ b/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/ADXL345_I2C.java @@ -1,8 +1,8 @@ /*----------------------------------------------------------------------------*/ -/* Copyright (c) FIRST 2008-2012. All Rights Reserved. */ -/* Open Source Software - may be modified and shared by FRC teams. The code */ +/* Copyright (c) FIRST 2008-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 the root directory of */ -/* the project. */ +/* the project. */ /*----------------------------------------------------------------------------*/ package edu.wpi.first.wpilibj; @@ -20,162 +20,168 @@ import edu.wpi.first.wpilibj.tables.ITable; */ public class ADXL345_I2C extends SensorBase implements Accelerometer, LiveWindowSendable { - private static final byte kAddress = 0x1D; - private static final byte kPowerCtlRegister = 0x2D; - private static final byte kDataFormatRegister = 0x31; - private static final byte kDataRegister = 0x32; - private static final double kGsPerLSB = 0.00390625; - private static final byte kPowerCtl_Link = 0x20, kPowerCtl_AutoSleep = 0x10, kPowerCtl_Measure = 0x08, kPowerCtl_Sleep = 0x04; - private static final byte kDataFormat_SelfTest = (byte) 0x80, kDataFormat_SPI = 0x40, kDataFormat_IntInvert = 0x20, kDataFormat_FullRes = 0x08, kDataFormat_Justify = 0x04; + private static final byte kAddress = 0x1D; + private static final byte kPowerCtlRegister = 0x2D; + private static final byte kDataFormatRegister = 0x31; + private static final byte kDataRegister = 0x32; + private static final double kGsPerLSB = 0.00390625; + private static final byte kPowerCtl_Link = 0x20, kPowerCtl_AutoSleep = 0x10, + kPowerCtl_Measure = 0x08, kPowerCtl_Sleep = 0x04; + private static final byte kDataFormat_SelfTest = (byte) 0x80, kDataFormat_SPI = 0x40, + kDataFormat_IntInvert = 0x20, kDataFormat_FullRes = 0x08, kDataFormat_Justify = 0x04; - public static class Axes { + public static class Axes { - /** - * The integer value representing this enumeration - */ - public final byte value; - static final byte kX_val = 0x00; - static final byte kY_val = 0x02; - static final byte kZ_val = 0x04; - public static final Axes kX = new Axes(kX_val); - public static final Axes kY = new Axes(kY_val); - public static final Axes kZ = new Axes(kZ_val); + /** + * The integer value representing this enumeration + */ + public final byte value; + static final byte kX_val = 0x00; + static final byte kY_val = 0x02; + static final byte kZ_val = 0x04; + public static final Axes kX = new Axes(kX_val); + public static final Axes kY = new Axes(kY_val); + public static final Axes kZ = new Axes(kZ_val); - private Axes(byte value) { - this.value = value; - } - } + private Axes(byte value) { + this.value = value; + } + } - public static class AllAxes { + public static class AllAxes { - public double XAxis; - public double YAxis; - public double ZAxis; - } - private I2C m_i2c; + public double XAxis; + public double YAxis; + public double ZAxis; + } - /** - * Constructor. - * @param port The I2C port the accelerometer is attached to - * @param range The range (+ or -) that the accelerometer will measure. - */ - public ADXL345_I2C(I2C.Port port, Range range) { - m_i2c = new I2C(port, kAddress); + private I2C m_i2c; - // Turn on the measurements - m_i2c.write(kPowerCtlRegister, kPowerCtl_Measure); + /** + * Constructor. + *$ + * @param port The I2C port the accelerometer is attached to + * @param range The range (+ or -) that the accelerometer will measure. + */ + public ADXL345_I2C(I2C.Port port, Range range) { + m_i2c = new I2C(port, kAddress); - setRange(range); + // Turn on the measurements + m_i2c.write(kPowerCtlRegister, kPowerCtl_Measure); - UsageReporting.report(tResourceType.kResourceType_ADXL345, tInstances.kADXL345_I2C); - LiveWindow.addSensor("ADXL345_I2C", port.getValue(), this); - } + setRange(range); - /** {inheritdoc} */ - @Override - public void setRange(Range range) { - byte value = 0; + UsageReporting.report(tResourceType.kResourceType_ADXL345, tInstances.kADXL345_I2C); + LiveWindow.addSensor("ADXL345_I2C", port.getValue(), this); + } - switch(range) { - case k2G: - value = 0; - break; - case k4G: - value = 1; - break; - case k8G: - value = 2; - break; - case k16G: - value = 3; - break; - } + /** {inheritdoc} */ + @Override + public void setRange(Range range) { + byte value = 0; - // Specify the data format to read - m_i2c.write(kDataFormatRegister, kDataFormat_FullRes | value); - } + switch (range) { + case k2G: + value = 0; + break; + case k4G: + value = 1; + break; + case k8G: + value = 2; + break; + case k16G: + value = 3; + break; + } - /** {@inheritDoc} */ - @Override - public double getX() { - return getAcceleration(Axes.kX); - } + // Specify the data format to read + m_i2c.write(kDataFormatRegister, kDataFormat_FullRes | value); + } - /** {@inheritDoc} */ - @Override - public double getY() { - return getAcceleration(Axes.kY); - } + /** {@inheritDoc} */ + @Override + public double getX() { + return getAcceleration(Axes.kX); + } - /** {@inheritDoc} */ - @Override - public double getZ() { - return getAcceleration(Axes.kZ); - } + /** {@inheritDoc} */ + @Override + public double getY() { + return getAcceleration(Axes.kY); + } - /** - * Get the acceleration of one axis in Gs. - * - * @param axis The axis to read from. - * @return Acceleration of the ADXL345 in Gs. - */ - public double getAcceleration(Axes axis) { - byte[] rawAccel = new byte[2]; - m_i2c.read(kDataRegister + axis.value, rawAccel.length, rawAccel); + /** {@inheritDoc} */ + @Override + public double getZ() { + return getAcceleration(Axes.kZ); + } - // Sensor is little endian... swap bytes - return accelFromBytes(rawAccel[0], rawAccel[1]); - } + /** + * Get the acceleration of one axis in Gs. + * + * @param axis The axis to read from. + * @return Acceleration of the ADXL345 in Gs. + */ + public double getAcceleration(Axes axis) { + byte[] rawAccel = new byte[2]; + m_i2c.read(kDataRegister + axis.value, rawAccel.length, rawAccel); - private double accelFromBytes(byte first, byte second) { - short tempLow = (short) (first & 0xff); - short tempHigh = (short) ((second << 8) & 0xff00); - return (tempLow | tempHigh) * kGsPerLSB; - } + // Sensor is little endian... swap bytes + return accelFromBytes(rawAccel[0], rawAccel[1]); + } - /** - * Get the acceleration of all axes in Gs. - * - * @return An object containing the acceleration measured on each axis of the ADXL345 in Gs. - */ - public AllAxes getAccelerations() { - AllAxes data = new AllAxes(); - byte[] rawData = new byte[6]; - m_i2c.read(kDataRegister, rawData.length, rawData); + private double accelFromBytes(byte first, byte second) { + short tempLow = (short) (first & 0xff); + short tempHigh = (short) ((second << 8) & 0xff00); + return (tempLow | tempHigh) * kGsPerLSB; + } - // Sensor is little endian... swap bytes - data.XAxis = accelFromBytes(rawData[0], rawData[1]); - data.YAxis = accelFromBytes(rawData[2], rawData[3]); - data.ZAxis = accelFromBytes(rawData[4], rawData[5]); - return data; - } + /** + * Get the acceleration of all axes in Gs. + * + * @return An object containing the acceleration measured on each axis of the + * ADXL345 in Gs. + */ + public AllAxes getAccelerations() { + AllAxes data = new AllAxes(); + byte[] rawData = new byte[6]; + m_i2c.read(kDataRegister, rawData.length, rawData); - public String getSmartDashboardType(){ - return "3AxisAccelerometer"; - } + // Sensor is little endian... swap bytes + data.XAxis = accelFromBytes(rawData[0], rawData[1]); + data.YAxis = accelFromBytes(rawData[2], rawData[3]); + data.ZAxis = accelFromBytes(rawData[4], rawData[5]); + return data; + } - private ITable m_table; + public String getSmartDashboardType() { + return "3AxisAccelerometer"; + } - /** {@inheritDoc} */ - public void initTable(ITable subtable) { - m_table = subtable; - updateTable(); - } + private ITable m_table; - /** {@inheritDoc} */ - public void updateTable() { - if (m_table != null) { - m_table.putNumber("X", getX()); - m_table.putNumber("Y", getY()); - m_table.putNumber("Z", getZ()); - } - } + /** {@inheritDoc} */ + public void initTable(ITable subtable) { + m_table = subtable; + updateTable(); + } - /** {@inheritDoc} */ - public ITable getTable(){ - return m_table; - } + /** {@inheritDoc} */ + public void updateTable() { + if (m_table != null) { + m_table.putNumber("X", getX()); + m_table.putNumber("Y", getY()); + m_table.putNumber("Z", getZ()); + } + } - public void startLiveWindowMode() {} - public void stopLiveWindowMode() {} + /** {@inheritDoc} */ + public ITable getTable() { + return m_table; + } + + public void startLiveWindowMode() {} + + public void stopLiveWindowMode() {} } diff --git a/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/ADXL345_SPI.java b/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/ADXL345_SPI.java index 3893317e78..2ce7053c17 100644 --- a/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/ADXL345_SPI.java +++ b/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/ADXL345_SPI.java @@ -1,8 +1,8 @@ /*----------------------------------------------------------------------------*/ -/* Copyright (c) FIRST 2008-2012. All Rights Reserved. */ -/* Open Source Software - may be modified and shared by FRC teams. The code */ +/* Copyright (c) FIRST 2008-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 the root directory of */ -/* the project. */ +/* the project. */ /*----------------------------------------------------------------------------*/ package edu.wpi.first.wpilibj; @@ -23,204 +23,202 @@ import edu.wpi.first.wpilibj.tables.ITable; * @author mwills */ public class ADXL345_SPI extends SensorBase implements Accelerometer, LiveWindowSendable { - private static final int kPowerCtlRegister = 0x2D; - private static final int kDataFormatRegister = 0x31; - private static final int kDataRegister = 0x32; - private static final double kGsPerLSB = 0.00390625; + private static final int kPowerCtlRegister = 0x2D; + private static final int kDataFormatRegister = 0x31; + private static final int kDataRegister = 0x32; + private static final double kGsPerLSB = 0.00390625; - private static final int kAddress_Read = 0x80; - private static final int kAddress_MultiByte = 0x40; + private static final int kAddress_Read = 0x80; + private static final int kAddress_MultiByte = 0x40; - private static final int kPowerCtl_Link=0x20; - private static final int kPowerCtl_AutoSleep=0x10; - private static final int kPowerCtl_Measure=0x08; - private static final int kPowerCtl_Sleep=0x04; + private static final int kPowerCtl_Link = 0x20; + private static final int kPowerCtl_AutoSleep = 0x10; + private static final int kPowerCtl_Measure = 0x08; + private static final int kPowerCtl_Sleep = 0x04; - private static final int kDataFormat_SelfTest=0x80; - private static final int kDataFormat_SPI=0x40; - private static final int kDataFormat_IntInvert=0x20; - private static final int kDataFormat_FullRes=0x08; - private static final int kDataFormat_Justify=0x04; + private static final int kDataFormat_SelfTest = 0x80; + private static final int kDataFormat_SPI = 0x40; + private static final int kDataFormat_IntInvert = 0x20; + private static final int kDataFormat_FullRes = 0x08; + private static final int kDataFormat_Justify = 0x04; - public static class Axes { + public static class Axes { - /** - * The integer value representing this enumeration - */ - public final byte value; - static final byte kX_val = 0x00; - static final byte kY_val = 0x02; - static final byte kZ_val = 0x04; - public static final ADXL345_SPI.Axes kX = new ADXL345_SPI.Axes(kX_val); - public static final ADXL345_SPI.Axes kY = new ADXL345_SPI.Axes(kY_val); - public static final ADXL345_SPI.Axes kZ = new ADXL345_SPI.Axes(kZ_val); + /** + * The integer value representing this enumeration + */ + public final byte value; + static final byte kX_val = 0x00; + static final byte kY_val = 0x02; + static final byte kZ_val = 0x04; + public static final ADXL345_SPI.Axes kX = new ADXL345_SPI.Axes(kX_val); + public static final ADXL345_SPI.Axes kY = new ADXL345_SPI.Axes(kY_val); + public static final ADXL345_SPI.Axes kZ = new ADXL345_SPI.Axes(kZ_val); - private Axes(byte value) { - this.value = value; - } - } + private Axes(byte value) { + this.value = value; + } + } - public static class AllAxes { + public static class AllAxes { - public double XAxis; - public double YAxis; - public double ZAxis; - } + public double XAxis; + public double YAxis; + public double ZAxis; + } - private SPI m_spi; + private SPI m_spi; - /** - * Constructor. - * - * @param port The SPI port that the accelerometer is connected to - * @param range The range (+ or -) that the accelerometer will measure. - */ - public ADXL345_SPI(SPI.Port port, Range range) { - m_spi = new SPI(port); - init(range); - LiveWindow.addSensor("ADXL345_SPI", port.getValue(), this); - } + /** + * Constructor. + * + * @param port The SPI port that the accelerometer is connected to + * @param range The range (+ or -) that the accelerometer will measure. + */ + public ADXL345_SPI(SPI.Port port, Range range) { + m_spi = new SPI(port); + init(range); + LiveWindow.addSensor("ADXL345_SPI", port.getValue(), this); + } - public void free(){ - m_spi.free(); - } + public void free() { + m_spi.free(); + } - /** - * Set SPI bus parameters, bring device out of sleep and set format - * - * @param range The range (+ or -) that the accelerometer will measure. - */ - private void init(Range range){ - m_spi.setClockRate(500000); - m_spi.setMSBFirst(); - m_spi.setSampleDataOnFalling(); - m_spi.setClockActiveLow(); - m_spi.setChipSelectActiveHigh(); + /** + * Set SPI bus parameters, bring device out of sleep and set format + * + * @param range The range (+ or -) that the accelerometer will measure. + */ + private void init(Range range) { + m_spi.setClockRate(500000); + m_spi.setMSBFirst(); + m_spi.setSampleDataOnFalling(); + m_spi.setClockActiveLow(); + m_spi.setChipSelectActiveHigh(); - // Turn on the measurements - byte[] commands = new byte[2]; - commands[0] = kPowerCtlRegister; - commands[1] = kPowerCtl_Measure; - m_spi.write(commands, 2); + // Turn on the measurements + byte[] commands = new byte[2]; + commands[0] = kPowerCtlRegister; + commands[1] = kPowerCtl_Measure; + m_spi.write(commands, 2); - setRange(range); + setRange(range); - UsageReporting.report(tResourceType.kResourceType_ADXL345, tInstances.kADXL345_SPI); - } + UsageReporting.report(tResourceType.kResourceType_ADXL345, tInstances.kADXL345_SPI); + } - /** {inheritdoc} */ - @Override - public void setRange(Range range) { - byte value = 0; + /** {inheritdoc} */ + @Override + public void setRange(Range range) { + byte value = 0; - switch(range) { - case k2G: - value = 0; - break; - case k4G: - value = 1; - break; - case k8G: - value = 2; - break; - case k16G: - value = 3; - break; - } + switch (range) { + case k2G: + value = 0; + break; + case k4G: + value = 1; + break; + case k8G: + value = 2; + break; + case k16G: + value = 3; + break; + } - // Specify the data format to read - byte[] commands = new byte[]{ - kDataFormatRegister, - (byte)(kDataFormat_FullRes | value) - }; - m_spi.write(commands, commands.length); - } + // Specify the data format to read + byte[] commands = new byte[] {kDataFormatRegister, (byte) (kDataFormat_FullRes | value)}; + m_spi.write(commands, commands.length); + } - /** {@inheritDoc} */ - @Override - public double getX() { - return getAcceleration(Axes.kX); - } + /** {@inheritDoc} */ + @Override + public double getX() { + return getAcceleration(Axes.kX); + } - /** {@inheritDoc} */ - @Override - public double getY() { - return getAcceleration(Axes.kY); - } + /** {@inheritDoc} */ + @Override + public double getY() { + return getAcceleration(Axes.kY); + } - /** {@inheritDoc} */ - @Override - public double getZ() { - return getAcceleration(Axes.kZ); - } + /** {@inheritDoc} */ + @Override + public double getZ() { + return getAcceleration(Axes.kZ); + } - /** - * Get the acceleration of one axis in Gs. - * - * @param axis The axis to read from. - * @return Acceleration of the ADXL345 in Gs. - */ - public double getAcceleration(ADXL345_SPI.Axes axis) { - byte[] transferBuffer = new byte[3]; - transferBuffer[0] = (byte)((kAddress_Read | kAddress_MultiByte | kDataRegister) + axis.value); - m_spi.transaction(transferBuffer, transferBuffer, 3); - ByteBuffer rawAccel = ByteBuffer.wrap(transferBuffer, 1, 2); - //Sensor is little endian - rawAccel.order(ByteOrder.LITTLE_ENDIAN); - - return rawAccel.getShort() * kGsPerLSB; - } + /** + * Get the acceleration of one axis in Gs. + * + * @param axis The axis to read from. + * @return Acceleration of the ADXL345 in Gs. + */ + public double getAcceleration(ADXL345_SPI.Axes axis) { + byte[] transferBuffer = new byte[3]; + transferBuffer[0] = (byte) ((kAddress_Read | kAddress_MultiByte | kDataRegister) + axis.value); + m_spi.transaction(transferBuffer, transferBuffer, 3); + ByteBuffer rawAccel = ByteBuffer.wrap(transferBuffer, 1, 2); + // Sensor is little endian + rawAccel.order(ByteOrder.LITTLE_ENDIAN); - /** - * Get the acceleration of all axes in Gs. - * - * @return An object containing the acceleration measured on each axis of the ADXL345 in Gs. - */ - public ADXL345_SPI.AllAxes getAccelerations() { - ADXL345_SPI.AllAxes data = new ADXL345_SPI.AllAxes(); - byte dataBuffer[] = new byte[7]; - if (m_spi != null) - { - // Select the data address. - dataBuffer[0] = (byte)(kAddress_Read | kAddress_MultiByte | kDataRegister); - m_spi.transaction(dataBuffer, dataBuffer, 7); - ByteBuffer rawData = ByteBuffer.wrap(dataBuffer, 1, 6); - //Sensor is little endian... swap bytes - rawData.order(ByteOrder.LITTLE_ENDIAN); - - data.XAxis = rawData.getShort() * kGsPerLSB; - data.YAxis = rawData.getShort() * kGsPerLSB; - data.ZAxis = rawData.getShort() * kGsPerLSB; - } - return data; - } - - public String getSmartDashboardType(){ - return "3AxisAccelerometer"; - } + return rawAccel.getShort() * kGsPerLSB; + } - private ITable m_table; + /** + * Get the acceleration of all axes in Gs. + * + * @return An object containing the acceleration measured on each axis of the + * ADXL345 in Gs. + */ + public ADXL345_SPI.AllAxes getAccelerations() { + ADXL345_SPI.AllAxes data = new ADXL345_SPI.AllAxes(); + byte dataBuffer[] = new byte[7]; + if (m_spi != null) { + // Select the data address. + dataBuffer[0] = (byte) (kAddress_Read | kAddress_MultiByte | kDataRegister); + m_spi.transaction(dataBuffer, dataBuffer, 7); + ByteBuffer rawData = ByteBuffer.wrap(dataBuffer, 1, 6); + // Sensor is little endian... swap bytes + rawData.order(ByteOrder.LITTLE_ENDIAN); - /** {@inheritDoc} */ - public void initTable(ITable subtable) { - m_table = subtable; - updateTable(); - } + data.XAxis = rawData.getShort() * kGsPerLSB; + data.YAxis = rawData.getShort() * kGsPerLSB; + data.ZAxis = rawData.getShort() * kGsPerLSB; + } + return data; + } - /** {@inheritDoc} */ - public void updateTable() { - if (m_table != null) { - m_table.putNumber("X", getX()); - m_table.putNumber("Y", getY()); - m_table.putNumber("Z", getZ()); - } - } + public String getSmartDashboardType() { + return "3AxisAccelerometer"; + } - /** {@inheritDoc} */ - public ITable getTable(){ - return m_table; - } + private ITable m_table; - public void startLiveWindowMode() {} - public void stopLiveWindowMode() {} + /** {@inheritDoc} */ + public void initTable(ITable subtable) { + m_table = subtable; + updateTable(); + } + + /** {@inheritDoc} */ + public void updateTable() { + if (m_table != null) { + m_table.putNumber("X", getX()); + m_table.putNumber("Y", getY()); + m_table.putNumber("Z", getZ()); + } + } + + /** {@inheritDoc} */ + public ITable getTable() { + return m_table; + } + + public void startLiveWindowMode() {} + + public void stopLiveWindowMode() {} } diff --git a/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/AccumulatorResult.java b/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/AccumulatorResult.java index 114a752196..054d3fccdb 100644 --- a/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/AccumulatorResult.java +++ b/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/AccumulatorResult.java @@ -1,24 +1,25 @@ /*----------------------------------------------------------------------------*/ -/* Copyright (c) FIRST 2008-2012. All Rights Reserved. */ -/* Open Source Software - may be modified and shared by FRC teams. The code */ +/* Copyright (c) FIRST 2008-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 the root directory of */ -/* the project. */ +/* the project. */ /*----------------------------------------------------------------------------*/ package edu.wpi.first.wpilibj; /** - * Structure for holding the values stored in an accumulator + * Structure for holding the values stored in an accumulator + *$ * @author brad */ public class AccumulatorResult { - /** - * The total value accumulated - */ - public long value; - /** - * The number of sample vaule was accumulated over - */ - public long count; + /** + * The total value accumulated + */ + public long value; + /** + * The number of sample vaule was accumulated over + */ + public long count; } diff --git a/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/AnalogAccelerometer.java b/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/AnalogAccelerometer.java index 653137287e..15ee7c2675 100644 --- a/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/AnalogAccelerometer.java +++ b/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/AnalogAccelerometer.java @@ -1,8 +1,8 @@ /*----------------------------------------------------------------------------*/ -/* Copyright (c) FIRST 2008-2012. All Rights Reserved. */ -/* Open Source Software - may be modified and shared by FRC teams. The code */ +/* Copyright (c) FIRST 2008-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 the root directory of */ -/* the project. */ +/* the project. */ /*----------------------------------------------------------------------------*/ package edu.wpi.first.wpilibj; @@ -15,147 +15,154 @@ import edu.wpi.first.wpilibj.tables.ITable; /** - * Handle operation of an analog accelerometer. - * The accelerometer reads acceleration directly through the sensor. Many sensors have - * multiple axis and can be treated as multiple devices. Each is calibrated by finding - * the center value over a period of time. + * Handle operation of an analog accelerometer. The accelerometer reads + * acceleration directly through the sensor. Many sensors have multiple axis and + * can be treated as multiple devices. Each is calibrated by finding the center + * value over a period of time. */ public class AnalogAccelerometer extends SensorBase implements PIDSource, LiveWindowSendable { - private AnalogInput m_analogChannel; - private double m_voltsPerG = 1.0; - private double m_zeroGVoltage = 2.5; - private boolean m_allocatedChannel; + private AnalogInput m_analogChannel; + private double m_voltsPerG = 1.0; + private double m_zeroGVoltage = 2.5; + private boolean m_allocatedChannel; - /** - * Common initialization - */ - private void initAccelerometer() { - UsageReporting.report(tResourceType.kResourceType_Accelerometer, m_analogChannel.getChannel()); - LiveWindow.addSensor("Accelerometer", m_analogChannel.getChannel(), this); + /** + * Common initialization + */ + private void initAccelerometer() { + UsageReporting.report(tResourceType.kResourceType_Accelerometer, m_analogChannel.getChannel()); + LiveWindow.addSensor("Accelerometer", m_analogChannel.getChannel(), this); + } + + /** + * Create a new instance of an accelerometer. + * + * The constructor allocates desired analog channel. + *$ + * @param channel The channel number for the analog input the accelerometer is + * connected to + */ + public AnalogAccelerometer(final int channel) { + m_allocatedChannel = true; + m_analogChannel = new AnalogInput(channel); + initAccelerometer(); + } + + /** + * Create a new instance of Accelerometer from an existing AnalogChannel. Make + * a new instance of accelerometer given an AnalogChannel. This is + * particularly useful if the port is going to be read as an analog channel as + * well as through the Accelerometer class. + *$ + * @param channel The existing AnalogInput object for the analog input the + * accelerometer is connected to + */ + public AnalogAccelerometer(AnalogInput channel) { + m_allocatedChannel = false; + if (channel == null) + throw new NullPointerException("Analog Channel given was null"); + m_analogChannel = channel; + initAccelerometer(); + } + + /** + * Delete the analog components used for the accelerometer. + */ + public void free() { + if (m_analogChannel != null && m_allocatedChannel) { + m_analogChannel.free(); } + m_analogChannel = null; + } - /** - * Create a new instance of an accelerometer. - * - * The constructor allocates desired analog channel. - * @param channel The channel number for the analog input the accelerometer is connected to - */ - public AnalogAccelerometer(final int channel) { - m_allocatedChannel = true; - m_analogChannel = new AnalogInput(channel); - initAccelerometer(); + /** + * Return the acceleration in Gs. + * + * The acceleration is returned units of Gs. + * + * @return The current acceleration of the sensor in Gs. + */ + public double getAcceleration() { + return (m_analogChannel.getAverageVoltage() - m_zeroGVoltage) / m_voltsPerG; + } + + /** + * Set the accelerometer sensitivity. + * + * This sets the sensitivity of the accelerometer used for calculating the + * acceleration. The sensitivity varies by accelerometer model. There are + * constants defined for various models. + * + * @param sensitivity The sensitivity of accelerometer in Volts per G. + */ + public void setSensitivity(double sensitivity) { + m_voltsPerG = sensitivity; + } + + /** + * Set the voltage that corresponds to 0 G. + * + * The zero G voltage varies by accelerometer model. There are constants + * defined for various models. + * + * @param zero The zero G voltage. + */ + public void setZero(double zero) { + m_zeroGVoltage = zero; + } + + /** + * Get the Acceleration for the PID Source parent. + * + * @return The current acceleration in Gs. + */ + public double pidGet() { + return getAcceleration(); + } + + public String getSmartDashboardType() { + return "Accelerometer"; + } + + /* + * Live Window code, only does anything if live window is activated. + */ + private ITable m_table; + + /** + * {@inheritDoc} + */ + public void initTable(ITable subtable) { + m_table = subtable; + updateTable(); + } + + /** + * {@inheritDoc} + */ + public ITable getTable() { + return m_table; + } + + /** + * {@inheritDoc} + */ + public void updateTable() { + if (m_table != null) { + m_table.putNumber("Value", getAcceleration()); } + } - /** - * Create a new instance of Accelerometer from an existing AnalogChannel. - * Make a new instance of accelerometer given an AnalogChannel. This is particularly - * useful if the port is going to be read as an analog channel as well as through - * the Accelerometer class. - * @param channel The existing AnalogInput object for the analog input the accelerometer is connected to - */ - public AnalogAccelerometer(AnalogInput channel) { - m_allocatedChannel = false; - if (channel == null) - throw new NullPointerException("Analog Channel given was null"); - m_analogChannel = channel; - initAccelerometer(); - } + /** + * Analog Channels don't have to do anything special when entering the + * LiveWindow. {@inheritDoc} + */ + public void startLiveWindowMode() {} - /** - * Delete the analog components used for the accelerometer. - */ - public void free() { - if (m_analogChannel != null && m_allocatedChannel) { - m_analogChannel.free(); - } - m_analogChannel = null; - } - - /** - * Return the acceleration in Gs. - * - * The acceleration is returned units of Gs. - * - * @return The current acceleration of the sensor in Gs. - */ - public double getAcceleration() { - return (m_analogChannel.getAverageVoltage() - m_zeroGVoltage) / m_voltsPerG; - } - - /** - * Set the accelerometer sensitivity. - * - * This sets the sensitivity of the accelerometer used for calculating the acceleration. - * The sensitivity varies by accelerometer model. There are constants defined for various models. - * - * @param sensitivity The sensitivity of accelerometer in Volts per G. - */ - public void setSensitivity(double sensitivity) { - m_voltsPerG = sensitivity; - } - - /** - * Set the voltage that corresponds to 0 G. - * - * The zero G voltage varies by accelerometer model. There are constants defined for various models. - * - * @param zero The zero G voltage. - */ - public void setZero(double zero) { - m_zeroGVoltage = zero; - } - - /** - * Get the Acceleration for the PID Source parent. - * - * @return The current acceleration in Gs. - */ - public double pidGet() { - return getAcceleration(); - } - - public String getSmartDashboardType() { - return "Accelerometer"; - } - /* - * Live Window code, only does anything if live window is activated. - */ - private ITable m_table; - - /** - * {@inheritDoc} - */ - public void initTable(ITable subtable) { - m_table = subtable; - updateTable(); - } - - /** - * {@inheritDoc} - */ - public ITable getTable() { - return m_table; - } - - /** - * {@inheritDoc} - */ - public void updateTable() { - if (m_table != null) { - m_table.putNumber("Value", getAcceleration()); - } - } - - /** - * Analog Channels don't have to do anything special when entering the LiveWindow. - * {@inheritDoc} - */ - public void startLiveWindowMode() {} - - /** - * Analog Channels don't have to do anything special when exiting the LiveWindow. - * {@inheritDoc} - */ - public void stopLiveWindowMode() {} + /** + * Analog Channels don't have to do anything special when exiting the + * LiveWindow. {@inheritDoc} + */ + public void stopLiveWindowMode() {} } diff --git a/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/AnalogInput.java b/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/AnalogInput.java index 5e51e230cb..3c5ccab338 100644 --- a/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/AnalogInput.java +++ b/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/AnalogInput.java @@ -1,8 +1,8 @@ /*----------------------------------------------------------------------------*/ -/* Copyright (c) FIRST 2008-2012. All Rights Reserved. */ -/* Open Source Software - may be modified and shared by FRC teams. The code */ +/* Copyright (c) FIRST 2008-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 the root directory of */ -/* the project. */ +/* the project. */ /*----------------------------------------------------------------------------*/ package edu.wpi.first.wpilibj; @@ -11,8 +11,7 @@ import java.nio.IntBuffer; import java.nio.LongBuffer; import java.nio.ByteBuffer; -//import com.sun.jna.Pointer; - +// import com.sun.jna.Pointer; import edu.wpi.first.wpilibj.communication.FRCNetworkCommunicationsLibrary.tResourceType; import edu.wpi.first.wpilibj.communication.UsageReporting; @@ -27,8 +26,8 @@ import edu.wpi.first.wpilibj.util.CheckedAllocationException; /** * Analog channel class. * - * Each analog channel is read from hardware as a 12-bit number representing - * 0V to 5V. + * Each analog channel is read from hardware as a 12-bit number representing 0V + * to 5V. * * Connected to each analog channel is an averaging and oversampling engine. * This engine accumulates the specified ( by setAverageBits() and @@ -39,488 +38,479 @@ import edu.wpi.first.wpilibj.util.CheckedAllocationException; * are divided by the number of samples to retain the resolution, but get more * stable values. */ -public class AnalogInput extends SensorBase implements PIDSource, - LiveWindowSendable { +public class AnalogInput extends SensorBase implements PIDSource, LiveWindowSendable { - private static final int kAccumulatorSlot = 1; - private static Resource channels = new Resource(kAnalogInputChannels); - private ByteBuffer m_port; - private int m_channel; - private static final int[] kAccumulatorChannels = { 0, 1 }; - private long m_accumulatorOffset; + private static final int kAccumulatorSlot = 1; + private static Resource channels = new Resource(kAnalogInputChannels); + private ByteBuffer m_port; + private int m_channel; + private static final int[] kAccumulatorChannels = {0, 1}; + private long m_accumulatorOffset; - /** - * Construct an analog channel. - * - * @param channel The channel number to represent. 0-3 are on-board 4-7 are on the MXP port. - */ - public AnalogInput(final int channel) { - m_channel = channel; + /** + * Construct an analog channel. + * + * @param channel The channel number to represent. 0-3 are on-board 4-7 are on + * the MXP port. + */ + public AnalogInput(final int channel) { + m_channel = channel; - if (AnalogJNI.checkAnalogInputChannel(channel) == 0) { - throw new AllocationException("Analog input channel " + m_channel - + " cannot be allocated. Channel is not present."); - } - try { - channels.allocate(channel); - } catch (CheckedAllocationException e) { - throw new AllocationException("Analog input channel " + m_channel - + " is already allocated"); - } + if (AnalogJNI.checkAnalogInputChannel(channel) == 0) { + throw new AllocationException("Analog input channel " + m_channel + + " cannot be allocated. Channel is not present."); + } + try { + channels.allocate(channel); + } catch (CheckedAllocationException e) { + throw new AllocationException("Analog input channel " + m_channel + " is already allocated"); + } - ByteBuffer port_pointer = AnalogJNI.getPort((byte) channel); - ByteBuffer status = ByteBuffer.allocateDirect(4); - // set the byte order - status.order(ByteOrder.LITTLE_ENDIAN); - m_port = AnalogJNI.initializeAnalogInputPort(port_pointer, status.asIntBuffer()); - HALUtil.checkStatus(status.asIntBuffer()); + ByteBuffer port_pointer = AnalogJNI.getPort((byte) channel); + ByteBuffer status = ByteBuffer.allocateDirect(4); + // set the byte order + status.order(ByteOrder.LITTLE_ENDIAN); + m_port = AnalogJNI.initializeAnalogInputPort(port_pointer, status.asIntBuffer()); + HALUtil.checkStatus(status.asIntBuffer()); - LiveWindow.addSensor("AnalogInput", channel, this); - UsageReporting.report(tResourceType.kResourceType_AnalogChannel, channel); - } + LiveWindow.addSensor("AnalogInput", channel, this); + UsageReporting.report(tResourceType.kResourceType_AnalogChannel, channel); + } - /** - * Channel destructor. - */ - public void free() { - channels.free(m_channel); - m_channel = 0; - m_accumulatorOffset = 0; - } + /** + * Channel destructor. + */ + public void free() { + channels.free(m_channel); + m_channel = 0; + m_accumulatorOffset = 0; + } - /** - * Get a sample straight from this channel. The sample is a 12-bit value - * representing the 0V to 5V range of the A/D converter. The units are in - * A/D converter codes. Use GetVoltage() to get the analog value in - * calibrated units. - * - * @return A sample straight from this channel. - */ - public int getValue() { - ByteBuffer status = ByteBuffer.allocateDirect(4); - // set the byte order - status.order(ByteOrder.LITTLE_ENDIAN); - int value = AnalogJNI.getAnalogValue(m_port, status.asIntBuffer()); - HALUtil.checkStatus(status.asIntBuffer()); - return value; - } + /** + * Get a sample straight from this channel. The sample is a 12-bit value + * representing the 0V to 5V range of the A/D converter. The units are in A/D + * converter codes. Use GetVoltage() to get the analog value in calibrated + * units. + * + * @return A sample straight from this channel. + */ + public int getValue() { + ByteBuffer status = ByteBuffer.allocateDirect(4); + // set the byte order + status.order(ByteOrder.LITTLE_ENDIAN); + int value = AnalogJNI.getAnalogValue(m_port, status.asIntBuffer()); + HALUtil.checkStatus(status.asIntBuffer()); + return value; + } - /** - * Get a sample from the output of the oversample and average engine for - * this channel. The sample is 12-bit + the bits configured in - * SetOversampleBits(). The value configured in setAverageBits() will cause - * this value to be averaged 2^bits number of samples. This is not a - * sliding window. The sample will not change until 2^(OversampleBits + - * AverageBits) samples have been acquired from this channel. Use - * getAverageVoltage() to get the analog value in calibrated units. - * - * @return A sample from the oversample and average engine for this channel. - */ - public int getAverageValue() { - ByteBuffer status = ByteBuffer.allocateDirect(4); - // set the byte order - status.order(ByteOrder.LITTLE_ENDIAN); - int value = AnalogJNI.getAnalogAverageValue(m_port, status.asIntBuffer()); - HALUtil.checkStatus(status.asIntBuffer()); - return value; - } + /** + * Get a sample from the output of the oversample and average engine for this + * channel. The sample is 12-bit + the bits configured in SetOversampleBits(). + * The value configured in setAverageBits() will cause this value to be + * averaged 2^bits number of samples. This is not a sliding window. The sample + * will not change until 2^(OversampleBits + AverageBits) samples have been + * acquired from this channel. Use getAverageVoltage() to get the analog value + * in calibrated units. + * + * @return A sample from the oversample and average engine for this channel. + */ + public int getAverageValue() { + ByteBuffer status = ByteBuffer.allocateDirect(4); + // set the byte order + status.order(ByteOrder.LITTLE_ENDIAN); + int value = AnalogJNI.getAnalogAverageValue(m_port, status.asIntBuffer()); + HALUtil.checkStatus(status.asIntBuffer()); + return value; + } - /** - * Get a scaled sample straight from this channel. The value is scaled to - * units of Volts using the calibrated scaling data from getLSBWeight() and - * getOffset(). - * - * @return A scaled sample straight from this channel. - */ - public double getVoltage() { - ByteBuffer status = ByteBuffer.allocateDirect(4); - // set the byte order - status.order(ByteOrder.LITTLE_ENDIAN); - double value = AnalogJNI.getAnalogVoltage(m_port, status.asIntBuffer()); - HALUtil.checkStatus(status.asIntBuffer()); - return value; - } + /** + * Get a scaled sample straight from this channel. The value is scaled to + * units of Volts using the calibrated scaling data from getLSBWeight() and + * getOffset(). + * + * @return A scaled sample straight from this channel. + */ + public double getVoltage() { + ByteBuffer status = ByteBuffer.allocateDirect(4); + // set the byte order + status.order(ByteOrder.LITTLE_ENDIAN); + double value = AnalogJNI.getAnalogVoltage(m_port, status.asIntBuffer()); + HALUtil.checkStatus(status.asIntBuffer()); + return value; + } - /** - * Get a scaled sample from the output of the oversample and average engine - * for this channel. The value is scaled to units of Volts using the - * calibrated scaling data from getLSBWeight() and getOffset(). Using - * oversampling will cause this value to be higher resolution, but it will - * update more slowly. Using averaging will cause this value to be more - * stable, but it will update more slowly. - * - * @return A scaled sample from the output of the oversample and average - * engine for this channel. - */ - public double getAverageVoltage() { - ByteBuffer status = ByteBuffer.allocateDirect(4); - // set the byte order - status.order(ByteOrder.LITTLE_ENDIAN); - double value = AnalogJNI.getAnalogAverageVoltage(m_port, status.asIntBuffer()); - HALUtil.checkStatus(status.asIntBuffer()); - return value; - } + /** + * Get a scaled sample from the output of the oversample and average engine + * for this channel. The value is scaled to units of Volts using the + * calibrated scaling data from getLSBWeight() and getOffset(). Using + * oversampling will cause this value to be higher resolution, but it will + * update more slowly. Using averaging will cause this value to be more + * stable, but it will update more slowly. + * + * @return A scaled sample from the output of the oversample and average + * engine for this channel. + */ + public double getAverageVoltage() { + ByteBuffer status = ByteBuffer.allocateDirect(4); + // set the byte order + status.order(ByteOrder.LITTLE_ENDIAN); + double value = AnalogJNI.getAnalogAverageVoltage(m_port, status.asIntBuffer()); + HALUtil.checkStatus(status.asIntBuffer()); + return value; + } - /** - * Get the factory scaling least significant bit weight constant. The least - * significant bit weight constant for the channel that was calibrated in - * manufacturing and stored in an eeprom. - * - * Volts = ((LSB_Weight * 1e-9) * raw) - (Offset * 1e-9) - * - * @return Least significant bit weight. - */ - public long getLSBWeight() { - ByteBuffer status = ByteBuffer.allocateDirect(4); - // set the byte order - status.order(ByteOrder.LITTLE_ENDIAN); - long value = AnalogJNI.getAnalogLSBWeight(m_port, status.asIntBuffer()); - HALUtil.checkStatus(status.asIntBuffer()); - return value; - } + /** + * Get the factory scaling least significant bit weight constant. The least + * significant bit weight constant for the channel that was calibrated in + * manufacturing and stored in an eeprom. + * + * Volts = ((LSB_Weight * 1e-9) * raw) - (Offset * 1e-9) + * + * @return Least significant bit weight. + */ + public long getLSBWeight() { + ByteBuffer status = ByteBuffer.allocateDirect(4); + // set the byte order + status.order(ByteOrder.LITTLE_ENDIAN); + long value = AnalogJNI.getAnalogLSBWeight(m_port, status.asIntBuffer()); + HALUtil.checkStatus(status.asIntBuffer()); + return value; + } - /** - * Get the factory scaling offset constant. The offset constant for the - * channel that was calibrated in manufacturing and stored in an eeprom. - * - * Volts = ((LSB_Weight * 1e-9) * raw) - (Offset * 1e-9) - * - * @return Offset constant. - */ - public int getOffset() { - ByteBuffer status = ByteBuffer.allocateDirect(4); - // set the byte order - status.order(ByteOrder.LITTLE_ENDIAN); - int value = AnalogJNI.getAnalogOffset(m_port, status.asIntBuffer()); - HALUtil.checkStatus(status.asIntBuffer()); - return value; - } + /** + * Get the factory scaling offset constant. The offset constant for the + * channel that was calibrated in manufacturing and stored in an eeprom. + * + * Volts = ((LSB_Weight * 1e-9) * raw) - (Offset * 1e-9) + * + * @return Offset constant. + */ + public int getOffset() { + ByteBuffer status = ByteBuffer.allocateDirect(4); + // set the byte order + status.order(ByteOrder.LITTLE_ENDIAN); + int value = AnalogJNI.getAnalogOffset(m_port, status.asIntBuffer()); + HALUtil.checkStatus(status.asIntBuffer()); + return value; + } - /** - * Get the channel number. - * - * @return The channel number. - */ - public int getChannel() { - return m_channel; - } + /** + * Get the channel number. + * + * @return The channel number. + */ + public int getChannel() { + return m_channel; + } - /** - * Set the number of averaging bits. This sets the number of averaging bits. - * The actual number of averaged samples is 2^bits. The averaging is done - * automatically in the FPGA. - * - * @param bits - * The number of averaging bits. - */ - public void setAverageBits(final int bits) { - ByteBuffer status = ByteBuffer.allocateDirect(4); - // set the byte order - status.order(ByteOrder.LITTLE_ENDIAN); - AnalogJNI.setAnalogAverageBits(m_port, bits, status.asIntBuffer()); - HALUtil.checkStatus(status.asIntBuffer()); - } + /** + * Set the number of averaging bits. This sets the number of averaging bits. + * The actual number of averaged samples is 2^bits. The averaging is done + * automatically in the FPGA. + * + * @param bits The number of averaging bits. + */ + public void setAverageBits(final int bits) { + ByteBuffer status = ByteBuffer.allocateDirect(4); + // set the byte order + status.order(ByteOrder.LITTLE_ENDIAN); + AnalogJNI.setAnalogAverageBits(m_port, bits, status.asIntBuffer()); + HALUtil.checkStatus(status.asIntBuffer()); + } - /** - * Get the number of averaging bits. This gets the number of averaging bits - * from the FPGA. The actual number of averaged samples is 2^bits. The - * averaging is done automatically in the FPGA. - * - * @return The number of averaging bits. - */ - public int getAverageBits() { - ByteBuffer status = ByteBuffer.allocateDirect(4); - // set the byte order - status.order(ByteOrder.LITTLE_ENDIAN); - int value = AnalogJNI.getAnalogAverageBits(m_port, status.asIntBuffer()); - HALUtil.checkStatus(status.asIntBuffer()); - return value; - } + /** + * Get the number of averaging bits. This gets the number of averaging bits + * from the FPGA. The actual number of averaged samples is 2^bits. The + * averaging is done automatically in the FPGA. + * + * @return The number of averaging bits. + */ + public int getAverageBits() { + ByteBuffer status = ByteBuffer.allocateDirect(4); + // set the byte order + status.order(ByteOrder.LITTLE_ENDIAN); + int value = AnalogJNI.getAnalogAverageBits(m_port, status.asIntBuffer()); + HALUtil.checkStatus(status.asIntBuffer()); + return value; + } - /** - * Set the number of oversample bits. This sets the number of oversample - * bits. The actual number of oversampled values is 2^bits. The - * oversampling is done automatically in the FPGA. - * - * @param bits - * The number of oversample bits. - */ - public void setOversampleBits(final int bits) { - ByteBuffer status = ByteBuffer.allocateDirect(4); - // set the byte order - status.order(ByteOrder.LITTLE_ENDIAN); - AnalogJNI.setAnalogOversampleBits(m_port, bits, status.asIntBuffer()); - HALUtil.checkStatus(status.asIntBuffer()); - } + /** + * Set the number of oversample bits. This sets the number of oversample bits. + * The actual number of oversampled values is 2^bits. The oversampling is done + * automatically in the FPGA. + * + * @param bits The number of oversample bits. + */ + public void setOversampleBits(final int bits) { + ByteBuffer status = ByteBuffer.allocateDirect(4); + // set the byte order + status.order(ByteOrder.LITTLE_ENDIAN); + AnalogJNI.setAnalogOversampleBits(m_port, bits, status.asIntBuffer()); + HALUtil.checkStatus(status.asIntBuffer()); + } - /** - * Get the number of oversample bits. This gets the number of oversample - * bits from the FPGA. The actual number of oversampled values is 2^bits. - * The oversampling is done automatically in the FPGA. - * - * @return The number of oversample bits. - */ - public int getOversampleBits() { - ByteBuffer status = ByteBuffer.allocateDirect(4); - // set the byte order - status.order(ByteOrder.LITTLE_ENDIAN); - int value = AnalogJNI.getAnalogOversampleBits(m_port, status.asIntBuffer()); - HALUtil.checkStatus(status.asIntBuffer()); - return value; - } + /** + * Get the number of oversample bits. This gets the number of oversample bits + * from the FPGA. The actual number of oversampled values is 2^bits. The + * oversampling is done automatically in the FPGA. + * + * @return The number of oversample bits. + */ + public int getOversampleBits() { + ByteBuffer status = ByteBuffer.allocateDirect(4); + // set the byte order + status.order(ByteOrder.LITTLE_ENDIAN); + int value = AnalogJNI.getAnalogOversampleBits(m_port, status.asIntBuffer()); + HALUtil.checkStatus(status.asIntBuffer()); + return value; + } - /** - * Initialize the accumulator. - */ - public void initAccumulator() { - if (!isAccumulatorChannel()) { - throw new AllocationException( - "Accumulators are only available on slot " - + kAccumulatorSlot + " on channels " - + kAccumulatorChannels[0] + "," - + kAccumulatorChannels[1]); - } - m_accumulatorOffset = 0; - ByteBuffer status = ByteBuffer.allocateDirect(4); - // set the byte order - status.order(ByteOrder.LITTLE_ENDIAN); - AnalogJNI.initAccumulator(m_port, status.asIntBuffer()); - HALUtil.checkStatus(status.asIntBuffer()); - } + /** + * Initialize the accumulator. + */ + public void initAccumulator() { + if (!isAccumulatorChannel()) { + throw new AllocationException("Accumulators are only available on slot " + kAccumulatorSlot + + " on channels " + kAccumulatorChannels[0] + "," + kAccumulatorChannels[1]); + } + m_accumulatorOffset = 0; + ByteBuffer status = ByteBuffer.allocateDirect(4); + // set the byte order + status.order(ByteOrder.LITTLE_ENDIAN); + AnalogJNI.initAccumulator(m_port, status.asIntBuffer()); + HALUtil.checkStatus(status.asIntBuffer()); + } - /** - * Set an initial value for the accumulator. - * - * This will be added to all values returned to the user. - * - * @param initialValue - * The value that the accumulator should start from when reset. - */ - public void setAccumulatorInitialValue(long initialValue) { - m_accumulatorOffset = initialValue; - } + /** + * Set an initial value for the accumulator. + * + * This will be added to all values returned to the user. + * + * @param initialValue The value that the accumulator should start from when + * reset. + */ + public void setAccumulatorInitialValue(long initialValue) { + m_accumulatorOffset = initialValue; + } - /** - * Resets the accumulator to the initial value. - */ - public void resetAccumulator() { - ByteBuffer status = ByteBuffer.allocateDirect(4); - // set the byte order - status.order(ByteOrder.LITTLE_ENDIAN); - AnalogJNI.resetAccumulator(m_port, status.asIntBuffer()); - HALUtil.checkStatus(status.asIntBuffer()); + /** + * Resets the accumulator to the initial value. + */ + public void resetAccumulator() { + ByteBuffer status = ByteBuffer.allocateDirect(4); + // set the byte order + status.order(ByteOrder.LITTLE_ENDIAN); + AnalogJNI.resetAccumulator(m_port, status.asIntBuffer()); + HALUtil.checkStatus(status.asIntBuffer()); - // Wait until the next sample, so the next call to getAccumulator*() - // won't have old values. - final double sampleTime = 1.0 / getGlobalSampleRate(); - final double overSamples = 1 << getOversampleBits(); - final double averageSamples = 1 << getAverageBits(); - Timer.delay(sampleTime * overSamples * averageSamples); + // Wait until the next sample, so the next call to getAccumulator*() + // won't have old values. + final double sampleTime = 1.0 / getGlobalSampleRate(); + final double overSamples = 1 << getOversampleBits(); + final double averageSamples = 1 << getAverageBits(); + Timer.delay(sampleTime * overSamples * averageSamples); - } + } - /** - * Set the center value of the accumulator. - * - * The center value is subtracted from each A/D value before it is added to - * the accumulator. This is used for the center value of devices like gyros - * and accelerometers to take the device offset - * into account when integrating. - * - * This center value is based on the output of the oversampled and averaged - * source the accumulator channel. Because of this, any non-zero oversample bits will - * affect the size of the value for this field. - */ - public void setAccumulatorCenter(int center) { - ByteBuffer status = ByteBuffer.allocateDirect(4); - // set the byte order - status.order(ByteOrder.LITTLE_ENDIAN); - AnalogJNI.setAccumulatorCenter(m_port, center, status.asIntBuffer()); - HALUtil.checkStatus(status.asIntBuffer()); - } + /** + * Set the center value of the accumulator. + * + * The center value is subtracted from each A/D value before it is added to + * the accumulator. This is used for the center value of devices like gyros + * and accelerometers to take the device offset into account when integrating. + * + * This center value is based on the output of the oversampled and averaged + * source the accumulator channel. Because of this, any non-zero oversample + * bits will affect the size of the value for this field. + */ + public void setAccumulatorCenter(int center) { + ByteBuffer status = ByteBuffer.allocateDirect(4); + // set the byte order + status.order(ByteOrder.LITTLE_ENDIAN); + AnalogJNI.setAccumulatorCenter(m_port, center, status.asIntBuffer()); + HALUtil.checkStatus(status.asIntBuffer()); + } - /** - * Set the accumulator's deadband. - * @param deadband The deadband size in ADC codes (12-bit value) - */ - public void setAccumulatorDeadband(int deadband) { - ByteBuffer status = ByteBuffer.allocateDirect(4); - // set the byte order - status.order(ByteOrder.LITTLE_ENDIAN); - AnalogJNI.setAccumulatorDeadband(m_port, deadband, status.asIntBuffer()); - HALUtil.checkStatus(status.asIntBuffer()); - } + /** + * Set the accumulator's deadband. + *$ + * @param deadband The deadband size in ADC codes (12-bit value) + */ + public void setAccumulatorDeadband(int deadband) { + ByteBuffer status = ByteBuffer.allocateDirect(4); + // set the byte order + status.order(ByteOrder.LITTLE_ENDIAN); + AnalogJNI.setAccumulatorDeadband(m_port, deadband, status.asIntBuffer()); + HALUtil.checkStatus(status.asIntBuffer()); + } - /** - * Read the accumulated value. - * - * Read the value that has been accumulating. The accumulator - * is attached after the oversample and average engine. - * - * @return The 64-bit value accumulated since the last Reset(). - */ - public long getAccumulatorValue() { - ByteBuffer status = ByteBuffer.allocateDirect(4); - // set the byte order - status.order(ByteOrder.LITTLE_ENDIAN); - long value = AnalogJNI.getAccumulatorValue(m_port, status.asIntBuffer()); - HALUtil.checkStatus(status.asIntBuffer()); - return value + m_accumulatorOffset; - } + /** + * Read the accumulated value. + * + * Read the value that has been accumulating. The accumulator is attached + * after the oversample and average engine. + * + * @return The 64-bit value accumulated since the last Reset(). + */ + public long getAccumulatorValue() { + ByteBuffer status = ByteBuffer.allocateDirect(4); + // set the byte order + status.order(ByteOrder.LITTLE_ENDIAN); + long value = AnalogJNI.getAccumulatorValue(m_port, status.asIntBuffer()); + HALUtil.checkStatus(status.asIntBuffer()); + return value + m_accumulatorOffset; + } - /** - * Read the number of accumulated values. - * - * Read the count of the accumulated values since the accumulator was last - * Reset(). - * - * @return The number of times samples from the channel were accumulated. - */ - public long getAccumulatorCount() { - ByteBuffer status = ByteBuffer.allocateDirect(4); - // set the byte order - status.order(ByteOrder.LITTLE_ENDIAN); - long value = AnalogJNI.getAccumulatorCount(m_port, status.asIntBuffer()); - HALUtil.checkStatus(status.asIntBuffer()); - return value; - } + /** + * Read the number of accumulated values. + * + * Read the count of the accumulated values since the accumulator was last + * Reset(). + * + * @return The number of times samples from the channel were accumulated. + */ + public long getAccumulatorCount() { + ByteBuffer status = ByteBuffer.allocateDirect(4); + // set the byte order + status.order(ByteOrder.LITTLE_ENDIAN); + long value = AnalogJNI.getAccumulatorCount(m_port, status.asIntBuffer()); + HALUtil.checkStatus(status.asIntBuffer()); + return value; + } - /** - * Read the accumulated value and the number of accumulated values - * atomically. - * - * This function reads the value and count from the FPGA atomically. This - * can be used for averaging. - * - * @param result - * AccumulatorResult object to store the results in. - */ - public void getAccumulatorOutput(AccumulatorResult result) { - if (result == null) { - throw new IllegalArgumentException("Null parameter `result'"); - } - if (!isAccumulatorChannel()) { - throw new IllegalArgumentException("Channel " + m_channel - + " is not an accumulator channel."); - } - ByteBuffer value = ByteBuffer.allocateDirect(8); - // set the byte order - value.order(ByteOrder.LITTLE_ENDIAN); - ByteBuffer count = ByteBuffer.allocateDirect(4); - // set the byte order - count.order(ByteOrder.LITTLE_ENDIAN); - ByteBuffer status = ByteBuffer.allocateDirect(4); - // set the byte order - status.order(ByteOrder.LITTLE_ENDIAN); - AnalogJNI.getAccumulatorOutput(m_port, value.asLongBuffer(), count.asIntBuffer(), status.asIntBuffer()); - result.value = value.asLongBuffer().get(0) + m_accumulatorOffset; - result.count = count.asIntBuffer().get(0); - HALUtil.checkStatus(status.asIntBuffer()); - } + /** + * Read the accumulated value and the number of accumulated values atomically. + * + * This function reads the value and count from the FPGA atomically. This can + * be used for averaging. + * + * @param result AccumulatorResult object to store the results in. + */ + public void getAccumulatorOutput(AccumulatorResult result) { + if (result == null) { + throw new IllegalArgumentException("Null parameter `result'"); + } + if (!isAccumulatorChannel()) { + throw new IllegalArgumentException("Channel " + m_channel + " is not an accumulator channel."); + } + ByteBuffer value = ByteBuffer.allocateDirect(8); + // set the byte order + value.order(ByteOrder.LITTLE_ENDIAN); + ByteBuffer count = ByteBuffer.allocateDirect(4); + // set the byte order + count.order(ByteOrder.LITTLE_ENDIAN); + ByteBuffer status = ByteBuffer.allocateDirect(4); + // set the byte order + status.order(ByteOrder.LITTLE_ENDIAN); + AnalogJNI.getAccumulatorOutput(m_port, value.asLongBuffer(), count.asIntBuffer(), + status.asIntBuffer()); + result.value = value.asLongBuffer().get(0) + m_accumulatorOffset; + result.count = count.asIntBuffer().get(0); + HALUtil.checkStatus(status.asIntBuffer()); + } - /** - * Is the channel attached to an accumulator. - * - * @return The analog channel is attached to an accumulator. - */ - public boolean isAccumulatorChannel() { - for (int i = 0; i < kAccumulatorChannels.length; i++) { - if (m_channel == kAccumulatorChannels[i]) { - return true; - } - } - return false; - } + /** + * Is the channel attached to an accumulator. + * + * @return The analog channel is attached to an accumulator. + */ + public boolean isAccumulatorChannel() { + for (int i = 0; i < kAccumulatorChannels.length; i++) { + if (m_channel == kAccumulatorChannels[i]) { + return true; + } + } + return false; + } - /** - * Set the sample rate per channel. - * - * This is a global setting for all channels. - * The maximum rate is 500kS/s divided by the number of channels in use. - * This is 62500 samples/s per channel if all 8 channels are used. - * @param samplesPerSecond The number of samples per second. - */ - public static void setGlobalSampleRate(final double samplesPerSecond) { - ByteBuffer status = ByteBuffer.allocateDirect(4); - status.order(ByteOrder.LITTLE_ENDIAN); + /** + * Set the sample rate per channel. + * + * This is a global setting for all channels. The maximum rate is 500kS/s + * divided by the number of channels in use. This is 62500 samples/s per + * channel if all 8 channels are used. + *$ + * @param samplesPerSecond The number of samples per second. + */ + public static void setGlobalSampleRate(final double samplesPerSecond) { + ByteBuffer status = ByteBuffer.allocateDirect(4); + status.order(ByteOrder.LITTLE_ENDIAN); - AnalogJNI.setAnalogSampleRate((float)samplesPerSecond, status.asIntBuffer()); + AnalogJNI.setAnalogSampleRate((float) samplesPerSecond, status.asIntBuffer()); - HALUtil.checkStatus(status.asIntBuffer()); - } + HALUtil.checkStatus(status.asIntBuffer()); + } - /** - * Get the current sample rate. - * - * This assumes one entry in the scan list. This is a global setting for - * all channels. - * - * @return Sample rate. - */ - public static double getGlobalSampleRate() { - ByteBuffer status = ByteBuffer.allocateDirect(4); - status.order(ByteOrder.LITTLE_ENDIAN); + /** + * Get the current sample rate. + * + * This assumes one entry in the scan list. This is a global setting for all + * channels. + * + * @return Sample rate. + */ + public static double getGlobalSampleRate() { + ByteBuffer status = ByteBuffer.allocateDirect(4); + status.order(ByteOrder.LITTLE_ENDIAN); - double value = AnalogJNI.getAnalogSampleRate(status.asIntBuffer()); + double value = AnalogJNI.getAnalogSampleRate(status.asIntBuffer()); - HALUtil.checkStatus(status.asIntBuffer()); + HALUtil.checkStatus(status.asIntBuffer()); - return value; - } + return value; + } - /** - * Get the average voltage for use with PIDController - * - * @return the average voltage - */ - public double pidGet() { - return getAverageVoltage(); - } + /** + * Get the average voltage for use with PIDController + * + * @return the average voltage + */ + public double pidGet() { + return getAverageVoltage(); + } - /** - * Live Window code, only does anything if live window is activated. - */ - public String getSmartDashboardType() { - return "Analog Input"; - } + /** + * Live Window code, only does anything if live window is activated. + */ + public String getSmartDashboardType() { + return "Analog Input"; + } - private ITable m_table; + private ITable m_table; - /** - * {@inheritDoc} - */ - public void initTable(ITable subtable) { - m_table = subtable; - updateTable(); - } + /** + * {@inheritDoc} + */ + public void initTable(ITable subtable) { + m_table = subtable; + updateTable(); + } - /** - * {@inheritDoc} - */ - public void updateTable() { - if (m_table != null) { - m_table.putNumber("Value", getAverageVoltage()); - } - } + /** + * {@inheritDoc} + */ + public void updateTable() { + if (m_table != null) { + m_table.putNumber("Value", getAverageVoltage()); + } + } - /** - * {@inheritDoc} - */ - public ITable getTable() { - return m_table; - } + /** + * {@inheritDoc} + */ + public ITable getTable() { + return m_table; + } - /** - * Analog Channels don't have to do anything special when entering the - * LiveWindow. {@inheritDoc} - */ - public void startLiveWindowMode() { - } + /** + * Analog Channels don't have to do anything special when entering the + * LiveWindow. {@inheritDoc} + */ + public void startLiveWindowMode() {} - /** - * Analog Channels don't have to do anything special when exiting the - * LiveWindow. {@inheritDoc} - */ - public void stopLiveWindowMode() { - } + /** + * Analog Channels don't have to do anything special when exiting the + * LiveWindow. {@inheritDoc} + */ + public void stopLiveWindowMode() {} } diff --git a/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/AnalogOutput.java b/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/AnalogOutput.java index 401aec1b38..2396ea4cb0 100644 --- a/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/AnalogOutput.java +++ b/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/AnalogOutput.java @@ -1,8 +1,8 @@ /*----------------------------------------------------------------------------*/ -/* Copyright (c) FIRST 2014. All Rights Reserved. */ -/* Open Source Software - may be modified and shared by FRC teams. The code */ +/* Copyright (c) FIRST 2014. All Rights Reserved. */ +/* Open Source Software - may be modified and shared by FRC teams. The code */ /* must be accompanied by the FIRST BSD license file in the root directory of */ -/* the project. */ +/* the project. */ /*----------------------------------------------------------------------------*/ package edu.wpi.first.wpilibj; @@ -11,8 +11,7 @@ import java.nio.IntBuffer; import java.nio.LongBuffer; import java.nio.ByteBuffer; -//import com.sun.jna.Pointer; - +// import com.sun.jna.Pointer; import edu.wpi.first.wpilibj.communication.FRCNetworkCommunicationsLibrary.tResourceType; import edu.wpi.first.wpilibj.communication.UsageReporting; @@ -28,113 +27,109 @@ import edu.wpi.first.wpilibj.util.CheckedAllocationException; * Analog output class. */ public class AnalogOutput extends SensorBase implements LiveWindowSendable { - private static Resource channels = new Resource(kAnalogOutputChannels); - private ByteBuffer m_port; - private int m_channel; + private static Resource channels = new Resource(kAnalogOutputChannels); + private ByteBuffer m_port; + private int m_channel; - /** - * Construct an analog output on a specified MXP channel. - * - * @param channel - * The channel number to represent. - */ - public AnalogOutput(final int channel) { - m_channel = channel; + /** + * Construct an analog output on a specified MXP channel. + * + * @param channel The channel number to represent. + */ + public AnalogOutput(final int channel) { + m_channel = channel; - if (AnalogJNI.checkAnalogOutputChannel(channel) == 0) { - throw new AllocationException("Analog output channel " + m_channel - + " cannot be allocated. Channel is not present."); - } - try { - channels.allocate(channel); - } catch (CheckedAllocationException e) { - throw new AllocationException("Analog output channel " + m_channel - + " is already allocated"); - } + if (AnalogJNI.checkAnalogOutputChannel(channel) == 0) { + throw new AllocationException("Analog output channel " + m_channel + + " cannot be allocated. Channel is not present."); + } + try { + channels.allocate(channel); + } catch (CheckedAllocationException e) { + throw new AllocationException("Analog output channel " + m_channel + " is already allocated"); + } - ByteBuffer port_pointer = AnalogJNI.getPort((byte)channel); - ByteBuffer status = ByteBuffer.allocateDirect(4); - // set the byte order - status.order(ByteOrder.LITTLE_ENDIAN); - m_port = AnalogJNI.initializeAnalogOutputPort(port_pointer, status.asIntBuffer()); - HALUtil.checkStatus(status.asIntBuffer()); + ByteBuffer port_pointer = AnalogJNI.getPort((byte) channel); + ByteBuffer status = ByteBuffer.allocateDirect(4); + // set the byte order + status.order(ByteOrder.LITTLE_ENDIAN); + m_port = AnalogJNI.initializeAnalogOutputPort(port_pointer, status.asIntBuffer()); + HALUtil.checkStatus(status.asIntBuffer()); - LiveWindow.addSensor("AnalogOutput", channel, this); - UsageReporting.report(tResourceType.kResourceType_AnalogOutput, channel); - } + LiveWindow.addSensor("AnalogOutput", channel, this); + UsageReporting.report(tResourceType.kResourceType_AnalogOutput, channel); + } - /** - * Channel destructor. - */ - public void free() { - channels.free(m_channel); - m_channel = 0; - } + /** + * Channel destructor. + */ + public void free() { + channels.free(m_channel); + m_channel = 0; + } - public void setVoltage(double voltage) { - ByteBuffer status = ByteBuffer.allocateDirect(4); - status.order(ByteOrder.LITTLE_ENDIAN); + public void setVoltage(double voltage) { + ByteBuffer status = ByteBuffer.allocateDirect(4); + status.order(ByteOrder.LITTLE_ENDIAN); - AnalogJNI.setAnalogOutput(m_port, voltage, status.asIntBuffer()); + AnalogJNI.setAnalogOutput(m_port, voltage, status.asIntBuffer()); - HALUtil.checkStatus(status.asIntBuffer()); - } + HALUtil.checkStatus(status.asIntBuffer()); + } - public double getVoltage() { - ByteBuffer status = ByteBuffer.allocateDirect(4); - status.order(ByteOrder.LITTLE_ENDIAN); + public double getVoltage() { + ByteBuffer status = ByteBuffer.allocateDirect(4); + status.order(ByteOrder.LITTLE_ENDIAN); - double voltage = AnalogJNI.getAnalogOutput(m_port, status.asIntBuffer()); + double voltage = AnalogJNI.getAnalogOutput(m_port, status.asIntBuffer()); - HALUtil.checkStatus(status.asIntBuffer()); + HALUtil.checkStatus(status.asIntBuffer()); - return voltage; - } + return voltage; + } - /* - * Live Window code, only does anything if live window is activated. - */ - public String getSmartDashboardType() { - return "Analog Output"; - } + /* + * Live Window code, only does anything if live window is activated. + */ + public String getSmartDashboardType() { + return "Analog Output"; + } - private ITable m_table; + private ITable m_table; - /** - * {@inheritDoc} - */ - public void initTable(ITable subtable) { - m_table = subtable; - updateTable(); - } + /** + * {@inheritDoc} + */ + public void initTable(ITable subtable) { + m_table = subtable; + updateTable(); + } - /** - * {@inheritDoc} - */ - public void updateTable() { - if (m_table != null) { - m_table.putNumber("Value", getVoltage()); - } - } + /** + * {@inheritDoc} + */ + public void updateTable() { + if (m_table != null) { + m_table.putNumber("Value", getVoltage()); + } + } - /** - * {@inheritDoc} - */ - public ITable getTable() { - return m_table; - } + /** + * {@inheritDoc} + */ + public ITable getTable() { + return m_table; + } - /** - * Analog Channels don't have to do anything special when entering the - * LiveWindow. {@inheritDoc} - */ - public void startLiveWindowMode() { - } + /** + * Analog Channels don't have to do anything special when entering the + * LiveWindow. {@inheritDoc} + */ + public void startLiveWindowMode() {} - /** - * Analog Channels don't have to do anything special when exiting the - * LiveWindow. {@inheritDoc} - */ - public void stopLiveWindowMode() { - } + /** + * Analog Channels don't have to do anything special when exiting the + * LiveWindow. {@inheritDoc} + */ + public void stopLiveWindowMode() {} } diff --git a/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/AnalogPotentiometer.java b/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/AnalogPotentiometer.java index 3da4f82284..2eeac0e91c 100644 --- a/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/AnalogPotentiometer.java +++ b/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/AnalogPotentiometer.java @@ -1,10 +1,11 @@ /*----------------------------------------------------------------------------*/ -/* Copyright (c) FIRST 2008-2014. All Rights Reserved. */ -/* Open Source Software - may be modified and shared by FRC teams. The code */ +/* Copyright (c) FIRST 2008-2014. All Rights Reserved. */ +/* Open Source Software - may be modified and shared by FRC teams. The code */ /* must be accompanied by the FIRST BSD license file in the root directory of */ -/* the project. */ +/* the project. */ /*----------------------------------------------------------------------------*/ package edu.wpi.first.wpilibj; + import java.nio.ByteBuffer; import java.nio.IntBuffer; @@ -15,192 +16,202 @@ import edu.wpi.first.wpilibj.livewindow.LiveWindowSendable; import edu.wpi.first.wpilibj.tables.ITable; /** - * Class for reading analog potentiometers. Analog potentiometers read - * in an analog voltage that corresponds to a position. The position is - * in whichever units you choose, by way of the scaling and offset - * constants passed to the constructor. + * Class for reading analog potentiometers. Analog potentiometers read in an + * analog voltage that corresponds to a position. The position is in whichever + * units you choose, by way of the scaling and offset constants passed to the + * constructor. * * @author Alex Henning * @author Colby Skeggs (rail voltage) */ public class AnalogPotentiometer implements Potentiometer, LiveWindowSendable { - private double m_fullRange, m_offset; - private AnalogInput m_analog_input; - private boolean m_init_analog_input; + private double m_fullRange, m_offset; + private AnalogInput m_analog_input; + private boolean m_init_analog_input; - /** - * Common initialization code called by all constructors. - * @param input The {@link AnalogInput} 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 - */ - private void initPot(final AnalogInput input, double fullRange, double offset) { - this.m_fullRange = fullRange; - this.m_offset = offset; - m_analog_input = input; + /** + * Common initialization code called by all constructors. + *$ + * @param input The {@link AnalogInput} 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 + */ + private void initPot(final AnalogInput input, double fullRange, double offset) { + this.m_fullRange = fullRange; + this.m_offset = offset; + m_analog_input = input; + } + + /** + * 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 fraction by to get a + * meaningful unit. + * @param offset The offset to add to the scaled value for controlling the + * zero value + */ + public AnalogPotentiometer(final int channel, double fullRange, double offset) { + AnalogInput input = new AnalogInput(channel); + m_init_analog_input = true; + initPot(input, fullRange, offset); + } + + /** + * 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 input The {@link AnalogInput} this potentiometer is plugged into. + * @param fullRange The scaling to multiply the fraction by to get a + * meaningful unit. + * @param offset The offset to add to the scaled value for controlling the + * zero value + */ + public AnalogPotentiometer(final AnalogInput input, double fullRange, double offset) { + m_init_analog_input = false; + initPot(input, fullRange, offset); + } + + /** + * 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. + * + * @param channel The analog channel this potentiometer is plugged into. + * @param scale The scaling to multiply the voltage by to get a meaningful + * unit. + */ + public AnalogPotentiometer(final int channel, double scale) { + this(channel, scale, 0); + } + + /** + * 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. + * + * @param input The {@link AnalogInput} this potentiometer is plugged into. + * @param scale The scaling to multiply the voltage by to get a meaningful + * unit. + */ + public AnalogPotentiometer(final AnalogInput input, double scale) { + this(input, scale, 0); + } + + /** + * AnalogPotentiometer constructor. + * + * @param channel The analog channel this potentiometer is plugged into. + */ + public AnalogPotentiometer(final int channel) { + this(channel, 1, 0); + } + + /** + * AnalogPotentiometer constructor. + * + * @param input The {@link AnalogInput} this potentiometer is plugged into. + */ + public AnalogPotentiometer(final AnalogInput input) { + this(input, 1, 0); + } + + /** + * Get the current reading of the potentiometer. + * + * @return The current position of the potentiometer. + */ + public double get() { + return (m_analog_input.getVoltage() / ControllerPower.getVoltage5V()) * m_fullRange + m_offset; + } + + /** + * Implement the PIDSource interface. + * + * @return The current reading. + */ + public double pidGet() { + return get(); + } + + + /** + * Live Window code, only does anything if live window is activated. + */ + public String getSmartDashboardType() { + return "Analog Input"; + } + + private ITable m_table; + + /** + * {@inheritDoc} + */ + public void initTable(ITable subtable) { + m_table = subtable; + updateTable(); + } + + /** + * {@inheritDoc} + */ + public void updateTable() { + if (m_table != null) { + m_table.putNumber("Value", get()); } + } - /** - * 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 fraction by to get a meaningful unit. - * @param offset The offset to add to the scaled value for controlling the zero value - */ - public AnalogPotentiometer(final int channel, double fullRange, double offset) { - AnalogInput input = new AnalogInput(channel); - m_init_analog_input = true; - initPot(input, fullRange, offset); + /** + * {@inheritDoc} + */ + public ITable getTable() { + return m_table; + } + + public void free() { + if (m_init_analog_input) { + m_analog_input.free(); + m_analog_input = null; + m_init_analog_input = false; } + } - /** - * 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 input The {@link AnalogInput} this potentiometer is plugged into. - * @param fullRange The scaling to multiply the fraction by to get a meaningful unit. - * @param offset The offset to add to the scaled value for controlling the zero value - */ - public AnalogPotentiometer(final AnalogInput input, double fullRange, double offset) { - m_init_analog_input = false; - initPot(input, fullRange, offset); - } + /** + * Analog Channels don't have to do anything special when entering the + * LiveWindow. {@inheritDoc} + */ + public void startLiveWindowMode() {} - /** - * 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. - * - * @param channel The analog channel this potentiometer is plugged into. - * @param scale The scaling to multiply the voltage by to get a meaningful unit. - */ - public AnalogPotentiometer(final int channel, double scale) { - this(channel, scale, 0); - } - - /** - * 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. - * - * @param input The {@link AnalogInput} this potentiometer is plugged into. - * @param scale The scaling to multiply the voltage by to get a meaningful unit. - */ - public AnalogPotentiometer(final AnalogInput input, double scale) { - this(input, scale, 0); - } - - /** - * AnalogPotentiometer constructor. - * - * @param channel The analog channel this potentiometer is plugged into. - */ - public AnalogPotentiometer(final int channel) { - this(channel, 1, 0); - } - - /** - * AnalogPotentiometer constructor. - * - * @param input The {@link AnalogInput} this potentiometer is plugged into. - */ - public AnalogPotentiometer(final AnalogInput input) { - this(input, 1, 0); - } - - /** - * Get the current reading of the potentiometer. - * - * @return The current position of the potentiometer. - */ - public double get() { - return (m_analog_input.getVoltage() / ControllerPower.getVoltage5V()) * m_fullRange + m_offset; - } - - /** - * Implement the PIDSource interface. - * - * @return The current reading. - */ - public double pidGet() { - return get(); - } - - - /** - * Live Window code, only does anything if live window is activated. - */ - public String getSmartDashboardType(){ - return "Analog Input"; - } - private ITable m_table; - - /** - * {@inheritDoc} - */ - public void initTable(ITable subtable) { - m_table = subtable; - updateTable(); - } - - /** - * {@inheritDoc} - */ - public void updateTable() { - if (m_table != null) { - m_table.putNumber("Value", get()); - } - } - - /** - * {@inheritDoc} - */ - public ITable getTable(){ - return m_table; - } - - public void free(){ - if(m_init_analog_input){ - m_analog_input.free(); - m_analog_input = null; - m_init_analog_input = false; - } - } - - /** - * Analog Channels don't have to do anything special when entering the LiveWindow. - * {@inheritDoc} - */ - public void startLiveWindowMode() {} - - /** - * Analog Channels don't have to do anything special when exiting the LiveWindow. - * {@inheritDoc} - */ - public void stopLiveWindowMode() {} + /** + * Analog Channels don't have to do anything special when exiting the + * LiveWindow. {@inheritDoc} + */ + public void stopLiveWindowMode() {} } diff --git a/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/AnalogTrigger.java b/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/AnalogTrigger.java index 347e928899..80b4031721 100644 --- a/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/AnalogTrigger.java +++ b/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/AnalogTrigger.java @@ -1,8 +1,8 @@ /*----------------------------------------------------------------------------*/ -/* Copyright (c) FIRST 2008-2012. All Rights Reserved. */ -/* Open Source Software - may be modified and shared by FRC teams. The code */ +/* Copyright (c) FIRST 2008-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 the root directory of */ -/* the project. */ +/* the project. */ /*----------------------------------------------------------------------------*/ package edu.wpi.first.wpilibj; @@ -18,7 +18,7 @@ import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.IntBuffer; -//import com.sun.jna.Pointer; +// import com.sun.jna.Pointer; /** * Class for creating and configuring Analog Triggers @@ -27,208 +27,198 @@ import java.nio.IntBuffer; */ public class AnalogTrigger { - /** - * Exceptions dealing with improper operation of the Analog trigger - */ - public class AnalogTriggerException extends RuntimeException { + /** + * Exceptions dealing with improper operation of the Analog trigger + */ + public class AnalogTriggerException extends RuntimeException { - /** - * Create a new exception with the given message - * - * @param message - * the message to pass with the exception - */ - public AnalogTriggerException(String message) { - super(message); - } + /** + * Create a new exception with the given message + * + * @param message the message to pass with the exception + */ + public AnalogTriggerException(String message) { + super(message); + } - } + } - /** - * Where the analog trigger is attached - */ - protected ByteBuffer m_port; - protected int m_index; + /** + * Where the analog trigger is attached + */ + protected ByteBuffer m_port; + protected int m_index; - /** - * Initialize an analog trigger from a channel. - * - * @param channel - * the port to use for the analog trigger - */ - protected void initTrigger(final int channel) { - ByteBuffer port_pointer = AnalogJNI.getPort((byte) channel); - ByteBuffer index = ByteBuffer.allocateDirect(4); - ByteBuffer status = ByteBuffer.allocateDirect(4); - index.order(ByteOrder.LITTLE_ENDIAN); - status.order(ByteOrder.LITTLE_ENDIAN); + /** + * Initialize an analog trigger from a channel. + * + * @param channel the port to use for the analog trigger + */ + protected void initTrigger(final int channel) { + ByteBuffer port_pointer = AnalogJNI.getPort((byte) channel); + ByteBuffer index = ByteBuffer.allocateDirect(4); + ByteBuffer status = ByteBuffer.allocateDirect(4); + index.order(ByteOrder.LITTLE_ENDIAN); + status.order(ByteOrder.LITTLE_ENDIAN); - m_port = AnalogJNI.initializeAnalogTrigger(port_pointer, index.asIntBuffer(), status.asIntBuffer()); - HALUtil.checkStatus(status.asIntBuffer()); - m_index = index.asIntBuffer().get(0); + m_port = + AnalogJNI.initializeAnalogTrigger(port_pointer, index.asIntBuffer(), status.asIntBuffer()); + HALUtil.checkStatus(status.asIntBuffer()); + m_index = index.asIntBuffer().get(0); - UsageReporting.report(tResourceType.kResourceType_AnalogTrigger, channel); - } + UsageReporting.report(tResourceType.kResourceType_AnalogTrigger, channel); + } - /** - * Constructor for an analog trigger given a channel number. - * - * @param channel - * the port to use for the analog trigger 0-3 are on-board, 4-7 are on the MXP port - */ - public AnalogTrigger(final int channel) { - initTrigger(channel); - } + /** + * Constructor for an analog trigger given a channel number. + * + * @param channel the port to use for the analog trigger 0-3 are on-board, 4-7 + * are on the MXP port + */ + public AnalogTrigger(final int channel) { + initTrigger(channel); + } - /** - * Construct an analog trigger given an analog channel. This should be used - * in the case of sharing an analog channel between the trigger and an - * analog input object. - * - * @param channel - * the AnalogInput to use for the analog trigger - */ - public AnalogTrigger(AnalogInput channel) { - if(channel == null){ - throw new NullPointerException("The Analog Input given was null"); - } - initTrigger(channel.getChannel()); - } + /** + * Construct an analog trigger given an analog channel. This should be used in + * the case of sharing an analog channel between the trigger and an analog + * input object. + * + * @param channel the AnalogInput to use for the analog trigger + */ + public AnalogTrigger(AnalogInput channel) { + if (channel == null) { + throw new NullPointerException("The Analog Input given was null"); + } + initTrigger(channel.getChannel()); + } - /** - * Release the resources used by this object - */ - public void free() { - ByteBuffer status = ByteBuffer.allocateDirect(4); - status.order(ByteOrder.LITTLE_ENDIAN); - AnalogJNI.cleanAnalogTrigger(m_port, status.asIntBuffer()); - HALUtil.checkStatus(status.asIntBuffer()); - m_port = null; - } + /** + * Release the resources used by this object + */ + public void free() { + ByteBuffer status = ByteBuffer.allocateDirect(4); + status.order(ByteOrder.LITTLE_ENDIAN); + AnalogJNI.cleanAnalogTrigger(m_port, status.asIntBuffer()); + HALUtil.checkStatus(status.asIntBuffer()); + m_port = null; + } - /** - * Set the upper and lower limits of the analog trigger. The limits are - * given in ADC codes. If oversampling is used, the units must be scaled - * appropriately. - * - * @param lower - * the lower raw limit - * @param upper - * the upper raw limit - */ - public void setLimitsRaw(final int lower, final int upper) { - if (lower > upper) { - throw new BoundaryException("Lower bound is greater than upper"); - } - ByteBuffer status = ByteBuffer.allocateDirect(4); - status.order(ByteOrder.LITTLE_ENDIAN); - AnalogJNI.setAnalogTriggerLimitsRaw(m_port, lower, upper, status.asIntBuffer()); - HALUtil.checkStatus(status.asIntBuffer()); - } + /** + * Set the upper and lower limits of the analog trigger. The limits are given + * in ADC codes. If oversampling is used, the units must be scaled + * appropriately. + * + * @param lower the lower raw limit + * @param upper the upper raw limit + */ + public void setLimitsRaw(final int lower, final int upper) { + if (lower > upper) { + throw new BoundaryException("Lower bound is greater than upper"); + } + ByteBuffer status = ByteBuffer.allocateDirect(4); + status.order(ByteOrder.LITTLE_ENDIAN); + AnalogJNI.setAnalogTriggerLimitsRaw(m_port, lower, upper, status.asIntBuffer()); + HALUtil.checkStatus(status.asIntBuffer()); + } - /** - * Set the upper and lower limits of the analog trigger. The limits are - * given as floating point voltage values. - * - * @param lower - * the lower voltage limit - * @param upper - * the upper voltage limit - */ - public void setLimitsVoltage(double lower, double upper) { - if (lower > upper) { - throw new BoundaryException( - "Lower bound is greater than upper bound"); - } - ByteBuffer status = ByteBuffer.allocateDirect(4); - status.order(ByteOrder.LITTLE_ENDIAN); - AnalogJNI.setAnalogTriggerLimitsVoltage(m_port, (float) lower, - (float) upper, status.asIntBuffer()); - HALUtil.checkStatus(status.asIntBuffer()); - } + /** + * Set the upper and lower limits of the analog trigger. The limits are given + * as floating point voltage values. + * + * @param lower the lower voltage limit + * @param upper the upper voltage limit + */ + public void setLimitsVoltage(double lower, double upper) { + if (lower > upper) { + throw new BoundaryException("Lower bound is greater than upper bound"); + } + ByteBuffer status = ByteBuffer.allocateDirect(4); + status.order(ByteOrder.LITTLE_ENDIAN); + AnalogJNI.setAnalogTriggerLimitsVoltage(m_port, (float) lower, (float) upper, + status.asIntBuffer()); + HALUtil.checkStatus(status.asIntBuffer()); + } - /** - * Configure the analog trigger to use the averaged vs. raw values. If the - * value is true, then the averaged value is selected for the analog - * trigger, otherwise the immediate value is used. - * - * @param useAveragedValue - * true to use an averaged value, false otherwise - */ - public void setAveraged(boolean useAveragedValue) { - ByteBuffer status = ByteBuffer.allocateDirect(4); - status.order(ByteOrder.LITTLE_ENDIAN); - AnalogJNI.setAnalogTriggerAveraged(m_port, - (byte) (useAveragedValue ? 1 : 0), status.asIntBuffer()); - HALUtil.checkStatus(status.asIntBuffer()); - } + /** + * Configure the analog trigger to use the averaged vs. raw values. If the + * value is true, then the averaged value is selected for the analog trigger, + * otherwise the immediate value is used. + * + * @param useAveragedValue true to use an averaged value, false otherwise + */ + public void setAveraged(boolean useAveragedValue) { + ByteBuffer status = ByteBuffer.allocateDirect(4); + status.order(ByteOrder.LITTLE_ENDIAN); + AnalogJNI.setAnalogTriggerAveraged(m_port, (byte) (useAveragedValue ? 1 : 0), + status.asIntBuffer()); + HALUtil.checkStatus(status.asIntBuffer()); + } - /** - * Configure the analog trigger to use a filtered value. The analog trigger - * will operate with a 3 point average rejection filter. This is designed to - * help with 360 degree pot applications for the period where the pot - * crosses through zero. - * - * @param useFilteredValue - * true to use a filterd value, false otherwise - */ - public void setFiltered(boolean useFilteredValue) { - ByteBuffer status = ByteBuffer.allocateDirect(4); - status.order(ByteOrder.LITTLE_ENDIAN); - AnalogJNI.setAnalogTriggerFiltered(m_port, - (byte) (useFilteredValue ? 1 : 0), status.asIntBuffer()); - HALUtil.checkStatus(status.asIntBuffer()); - } + /** + * Configure the analog trigger to use a filtered value. The analog trigger + * will operate with a 3 point average rejection filter. This is designed to + * help with 360 degree pot applications for the period where the pot crosses + * through zero. + * + * @param useFilteredValue true to use a filterd value, false otherwise + */ + public void setFiltered(boolean useFilteredValue) { + ByteBuffer status = ByteBuffer.allocateDirect(4); + status.order(ByteOrder.LITTLE_ENDIAN); + AnalogJNI.setAnalogTriggerFiltered(m_port, (byte) (useFilteredValue ? 1 : 0), + status.asIntBuffer()); + HALUtil.checkStatus(status.asIntBuffer()); + } - /** - * Return the index of the analog trigger. This is the FPGA index of this - * analog trigger instance. - * - * @return The index of the analog trigger. - */ - public int getIndex() { - return m_index; - } + /** + * Return the index of the analog trigger. This is the FPGA index of this + * analog trigger instance. + * + * @return The index of the analog trigger. + */ + public int getIndex() { + return m_index; + } - /** - * Return the InWindow output of the analog trigger. True if the analog - * input is between the upper and lower limits. - * - * @return The InWindow output of the analog trigger. - */ - public boolean getInWindow() { - ByteBuffer status = ByteBuffer.allocateDirect(4); - status.order(ByteOrder.LITTLE_ENDIAN); - byte value = AnalogJNI.getAnalogTriggerInWindow(m_port, status.asIntBuffer()); - HALUtil.checkStatus(status.asIntBuffer()); - return value != 0; - } + /** + * Return the InWindow output of the analog trigger. True if the analog input + * is between the upper and lower limits. + * + * @return The InWindow output of the analog trigger. + */ + public boolean getInWindow() { + ByteBuffer status = ByteBuffer.allocateDirect(4); + status.order(ByteOrder.LITTLE_ENDIAN); + byte value = AnalogJNI.getAnalogTriggerInWindow(m_port, status.asIntBuffer()); + HALUtil.checkStatus(status.asIntBuffer()); + return value != 0; + } - /** - * Return the TriggerState output of the analog trigger. True if above upper - * limit. False if below lower limit. If in Hysteresis, maintain previous - * state. - * - * @return The TriggerState output of the analog trigger. - */ - public boolean getTriggerState() { - ByteBuffer status = ByteBuffer.allocateDirect(4); - status.order(ByteOrder.LITTLE_ENDIAN); - byte value = AnalogJNI.getAnalogTriggerTriggerState(m_port, status.asIntBuffer()); - HALUtil.checkStatus(status.asIntBuffer()); - return value != 0; - } + /** + * Return the TriggerState output of the analog trigger. True if above upper + * limit. False if below lower limit. If in Hysteresis, maintain previous + * state. + * + * @return The TriggerState output of the analog trigger. + */ + public boolean getTriggerState() { + ByteBuffer status = ByteBuffer.allocateDirect(4); + status.order(ByteOrder.LITTLE_ENDIAN); + byte value = AnalogJNI.getAnalogTriggerTriggerState(m_port, status.asIntBuffer()); + HALUtil.checkStatus(status.asIntBuffer()); + return value != 0; + } - /** - * Creates an AnalogTriggerOutput object. Gets an output object that can be - * used for routing. Caller is responsible for deleting the - * AnalogTriggerOutput object. - * - * @param type - * An enum of the type of output object to create. - * @return A pointer to a new AnalogTriggerOutput object. - */ - public AnalogTriggerOutput createOutput(AnalogTriggerType type) { - return new AnalogTriggerOutput(this, type); - } + /** + * Creates an AnalogTriggerOutput object. Gets an output object that can be + * used for routing. Caller is responsible for deleting the + * AnalogTriggerOutput object. + * + * @param type An enum of the type of output object to create. + * @return A pointer to a new AnalogTriggerOutput object. + */ + public AnalogTriggerOutput createOutput(AnalogTriggerType type) { + return new AnalogTriggerOutput(this, type); + } } diff --git a/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/AnalogTriggerOutput.java b/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/AnalogTriggerOutput.java index 3c9a431a61..2503a31591 100644 --- a/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/AnalogTriggerOutput.java +++ b/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/AnalogTriggerOutput.java @@ -1,8 +1,8 @@ /*----------------------------------------------------------------------------*/ -/* Copyright (c) FIRST 2008-2012. All Rights Reserved. */ -/* Open Source Software - may be modified and shared by FRC teams. The code */ +/* Copyright (c) FIRST 2008-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 the root directory of */ -/* the project. */ +/* the project. */ /*----------------------------------------------------------------------------*/ package edu.wpi.first.wpilibj; @@ -46,97 +46,94 @@ import java.nio.IntBuffer; */ public class AnalogTriggerOutput extends DigitalSource { - /** - * Exceptions dealing with improper operation of the Analog trigger output - */ - public class AnalogTriggerOutputException extends RuntimeException { + /** + * Exceptions dealing with improper operation of the Analog trigger output + */ + public class AnalogTriggerOutputException extends RuntimeException { - /** - * Create a new exception with the given message - * - * @param message - * the message to pass with the exception - */ - public AnalogTriggerOutputException(String message) { - super(message); - } + /** + * Create a new exception with the given message + * + * @param message the message to pass with the exception + */ + public AnalogTriggerOutputException(String message) { + super(message); + } - } + } - private final AnalogTrigger m_trigger; - private final AnalogTriggerType m_outputType; + private final AnalogTrigger m_trigger; + private final AnalogTriggerType m_outputType; - /** - * Create an object that represents one of the four outputs from an analog - * trigger. - * - * Because this class derives from DigitalSource, it can be passed into - * routing functions for Counter, Encoder, etc. - * - * @param trigger - * The trigger for which this is an output. - * @param outputType - * An enum that specifies the output on the trigger to represent. - */ - public AnalogTriggerOutput(AnalogTrigger trigger, final AnalogTriggerType outputType) { - if (trigger == null) - throw new NullPointerException("Analog Trigger given was null"); - if (outputType == null) - throw new NullPointerException("Analog Trigger Type given was null"); - m_trigger = trigger; - m_outputType = outputType; + /** + * Create an object that represents one of the four outputs from an analog + * trigger. + * + * Because this class derives from DigitalSource, it can be passed into + * routing functions for Counter, Encoder, etc. + * + * @param trigger The trigger for which this is an output. + * @param outputType An enum that specifies the output on the trigger to + * represent. + */ + public AnalogTriggerOutput(AnalogTrigger trigger, final AnalogTriggerType outputType) { + if (trigger == null) + throw new NullPointerException("Analog Trigger given was null"); + if (outputType == null) + throw new NullPointerException("Analog Trigger Type given was null"); + m_trigger = trigger; + m_outputType = outputType; - UsageReporting.report(tResourceType.kResourceType_AnalogTriggerOutput, - trigger.getIndex(), outputType.value); - } + UsageReporting.report(tResourceType.kResourceType_AnalogTriggerOutput, trigger.getIndex(), + outputType.value); + } - @Override - public void free() { - - } + @Override + public void free() { - /** - * Get the state of the analog trigger output. - * - * @return The state of the analog trigger output. - */ - public boolean get() { - IntBuffer status = IntBuffer.allocate(1); - byte value = AnalogJNI.getAnalogTriggerOutput(m_trigger.m_port, - m_outputType.value, status); - HALUtil.checkStatus(status); - return value != 0; - } + } - @Override - public int getChannelForRouting() { - return (m_trigger.m_index << 2) + m_outputType.value; - } + /** + * Get the state of the analog trigger output. + * + * @return The state of the analog trigger output. + */ + public boolean get() { + IntBuffer status = IntBuffer.allocate(1); + byte value = AnalogJNI.getAnalogTriggerOutput(m_trigger.m_port, m_outputType.value, status); + HALUtil.checkStatus(status); + return value != 0; + } - @Override - public byte getModuleForRouting() { - return (byte) (m_trigger.m_index >> 2); - } + @Override + public int getChannelForRouting() { + return (m_trigger.m_index << 2) + m_outputType.value; + } - @Override - public boolean getAnalogTriggerForRouting() { - return true; - } + @Override + public byte getModuleForRouting() { + return (byte) (m_trigger.m_index >> 2); + } - /** - * Defines the state in which the AnalogTrigger triggers - * @author jonathanleitschuh - */ - public enum AnalogTriggerType{ - kInWindow(AnalogJNI.AnalogTriggerType.kInWindow), - kState(AnalogJNI.AnalogTriggerType.kState), - kRisingPulse(AnalogJNI.AnalogTriggerType.kRisingPulse), - kFallingPulse(AnalogJNI.AnalogTriggerType.kFallingPulse); - - private final int value; - - private AnalogTriggerType(int value){ - this.value = value; - } - } + @Override + public boolean getAnalogTriggerForRouting() { + return true; + } + + /** + * Defines the state in which the AnalogTrigger triggers + *$ + * @author jonathanleitschuh + */ + public enum AnalogTriggerType { + kInWindow(AnalogJNI.AnalogTriggerType.kInWindow), kState(AnalogJNI.AnalogTriggerType.kState), kRisingPulse( + AnalogJNI.AnalogTriggerType.kRisingPulse), kFallingPulse( + AnalogJNI.AnalogTriggerType.kFallingPulse); + + private final int value; + + private AnalogTriggerType(int value) { + this.value = value; + } + } } diff --git a/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/BuiltInAccelerometer.java b/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/BuiltInAccelerometer.java index c662ef926f..ca000eb01a 100644 --- a/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/BuiltInAccelerometer.java +++ b/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/BuiltInAccelerometer.java @@ -1,9 +1,10 @@ /*----------------------------------------------------------------------------*/ -/* Copyright (c) FIRST 2014. 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. */ +/* Copyright (c) FIRST 2014. 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. */ /*----------------------------------------------------------------------------*/ package edu.wpi.first.wpilibj; + import edu.wpi.first.wpilibj.interfaces.Accelerometer; import edu.wpi.first.wpilibj.hal.AccelerometerJNI; import edu.wpi.first.wpilibj.communication.FRCNetworkCommunicationsLibrary.tResourceType; @@ -17,98 +18,99 @@ import edu.wpi.first.wpilibj.tables.ITable; * * This class allows access to the RoboRIO's internal accelerometer. */ -public class BuiltInAccelerometer implements Accelerometer, LiveWindowSendable -{ - /** - * Constructor. - * @param range The range the accelerometer will measure - */ - public BuiltInAccelerometer(Range range) { - setRange(range); - UsageReporting.report(tResourceType.kResourceType_Accelerometer, 0, 0, "Built-in accelerometer"); - LiveWindow.addSensor("BuiltInAccel", 0, this); - } +public class BuiltInAccelerometer implements Accelerometer, LiveWindowSendable { + /** + * Constructor. + *$ + * @param range The range the accelerometer will measure + */ + public BuiltInAccelerometer(Range range) { + setRange(range); + UsageReporting + .report(tResourceType.kResourceType_Accelerometer, 0, 0, "Built-in accelerometer"); + LiveWindow.addSensor("BuiltInAccel", 0, this); + } - /** - * Constructor. - * The accelerometer will measure +/-8 g-forces - */ - public BuiltInAccelerometer() { - this(Range.k8G); - } + /** + * Constructor. The accelerometer will measure +/-8 g-forces + */ + public BuiltInAccelerometer() { + this(Range.k8G); + } - /** {inheritdoc} */ - @Override - public void setRange(Range range) { - AccelerometerJNI.setAccelerometerActive(false); + /** {inheritdoc} */ + @Override + public void setRange(Range range) { + AccelerometerJNI.setAccelerometerActive(false); - switch(range) { - case k2G: - AccelerometerJNI.setAccelerometerRange(0); - break; - case k4G: - AccelerometerJNI.setAccelerometerRange(1); - break; - case k8G: - AccelerometerJNI.setAccelerometerRange(2); - break; - case k16G: - throw new RuntimeException("16G range not supported (use k2G, k4G, or k8G)"); - } + switch (range) { + case k2G: + AccelerometerJNI.setAccelerometerRange(0); + break; + case k4G: + AccelerometerJNI.setAccelerometerRange(1); + break; + case k8G: + AccelerometerJNI.setAccelerometerRange(2); + break; + case k16G: + throw new RuntimeException("16G range not supported (use k2G, k4G, or k8G)"); + } - AccelerometerJNI.setAccelerometerActive(true); - } + AccelerometerJNI.setAccelerometerActive(true); + } - /** - * @return The acceleration of the RoboRIO along the X axis in g-forces - */ - @Override - public double getX() { - return AccelerometerJNI.getAccelerometerX(); - } + /** + * @return The acceleration of the RoboRIO along the X axis in g-forces + */ + @Override + public double getX() { + return AccelerometerJNI.getAccelerometerX(); + } - /** - * @return The acceleration of the RoboRIO along the Y axis in g-forces - */ - @Override - public double getY() { - return AccelerometerJNI.getAccelerometerY(); - } + /** + * @return The acceleration of the RoboRIO along the Y axis in g-forces + */ + @Override + public double getY() { + return AccelerometerJNI.getAccelerometerY(); + } - /** - * @return The acceleration of the RoboRIO along the Z axis in g-forces - */ - @Override - public double getZ() { - return AccelerometerJNI.getAccelerometerZ(); - } + /** + * @return The acceleration of the RoboRIO along the Z axis in g-forces + */ + @Override + public double getZ() { + return AccelerometerJNI.getAccelerometerZ(); + } - public String getSmartDashboardType(){ - return "3AxisAccelerometer"; - } + public String getSmartDashboardType() { + return "3AxisAccelerometer"; + } - private ITable m_table; + private ITable m_table; - /** {@inheritDoc} */ - public void initTable(ITable subtable) { - m_table = subtable; - updateTable(); - } + /** {@inheritDoc} */ + public void initTable(ITable subtable) { + m_table = subtable; + updateTable(); + } - /** {@inheritDoc} */ - public void updateTable() { - if (m_table != null) { - m_table.putNumber("X", getX()); - m_table.putNumber("Y", getY()); - m_table.putNumber("Z", getZ()); - } - } + /** {@inheritDoc} */ + public void updateTable() { + if (m_table != null) { + m_table.putNumber("X", getX()); + m_table.putNumber("Y", getY()); + m_table.putNumber("Z", getZ()); + } + } - /** {@inheritDoc} */ - public ITable getTable(){ - return m_table; - } + /** {@inheritDoc} */ + public ITable getTable() { + return m_table; + } - public void startLiveWindowMode() {} - public void stopLiveWindowMode() {} + public void startLiveWindowMode() {} + + public void stopLiveWindowMode() {} }; diff --git a/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/CANJaguar.java b/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/CANJaguar.java index 66a08f7443..7812e0a242 100644 --- a/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/CANJaguar.java +++ b/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/CANJaguar.java @@ -1,8 +1,8 @@ /*----------------------------------------------------------------------------*/ -/* Copyright (c) FIRST 2008-2014. All Rights Reserved. */ -/* Open Source Software - may be modified and shared by FRC teams. The code */ +/* Copyright (c) FIRST 2008-2014. All Rights Reserved. */ +/* Open Source Software - may be modified and shared by FRC teams. The code */ /* must be accompanied by the FIRST BSD license file in the root directory of */ -/* the project. */ +/* the project. */ /*----------------------------------------------------------------------------*/ package edu.wpi.first.wpilibj; @@ -21,288 +21,313 @@ import edu.wpi.first.wpilibj.util.CheckedAllocationException; /** * Texas Instruments Jaguar Speed Controller as a CAN device. + *$ * @author Thomas Clark */ -public class CANJaguar implements MotorSafety, PIDOutput, PIDInterface, CANSpeedController, LiveWindowSendable { +public class CANJaguar implements MotorSafety, PIDOutput, PIDInterface, CANSpeedController, + LiveWindowSendable { - public static final int kMaxMessageDataSize = 8; + public static final int kMaxMessageDataSize = 8; - // The internal PID control loop in the Jaguar runs at 1kHz. - public static final int kControllerRate = 1000; - public static final double kApproxBusVoltage = 12.0; + // The internal PID control loop in the Jaguar runs at 1kHz. + public static final int kControllerRate = 1000; + public static final double kApproxBusVoltage = 12.0; - private MotorSafetyHelper m_safetyHelper; - private static final Resource allocated = new Resource(63); + private MotorSafetyHelper m_safetyHelper; + private static final Resource allocated = new Resource(63); - private static final int kFullMessageIDMask = CANJNI.CAN_MSGID_API_M | CANJNI.CAN_MSGID_MFR_M | CANJNI.CAN_MSGID_DTYPE_M; - private static final int kSendMessagePeriod = 20; + private static final int kFullMessageIDMask = CANJNI.CAN_MSGID_API_M | CANJNI.CAN_MSGID_MFR_M + | CANJNI.CAN_MSGID_DTYPE_M; + private static final int kSendMessagePeriod = 20; - // Control Mode tags - private static class EncoderTag {}; - /** Sets an encoder as the speed reference only.
Passed as the "tag" when setting the control mode.*/ - public final static EncoderTag kEncoder = new EncoderTag(); + // Control Mode tags + private static class EncoderTag { + }; - private static class QuadEncoderTag {}; - /** Sets a quadrature encoder as the position and speed reference.
Passed as the "tag" when setting the control mode.*/ - public final static QuadEncoderTag kQuadEncoder = new QuadEncoderTag(); + /** + * Sets an encoder as the speed reference only.
+ * Passed as the "tag" when setting the control mode. + */ + public final static EncoderTag kEncoder = new EncoderTag(); - private static class PotentiometerTag {}; - /** Sets a potentiometer as the position reference only.
Passed as the "tag" when setting the control mode. */ - public final static PotentiometerTag kPotentiometer = new PotentiometerTag(); + private static class QuadEncoderTag { + }; - private boolean isInverted = false; - /** - * Mode determines how the Jaguar is controlled, used internally. - */ - public enum ControlMode { - PercentVbus, Current, Speed, Position, Voltage; - } + /** + * Sets a quadrature encoder as the position and speed reference.
+ * Passed as the "tag" when setting the control mode. + */ + public final static QuadEncoderTag kQuadEncoder = new QuadEncoderTag(); - public static final int kCurrentFault = 1; - public static final int kTemperatureFault = 2; - public static final int kBusVoltageFault = 4; - public static final int kGateDriverFault = 8; + private static class PotentiometerTag { + }; - /** - * Limit switch masks - */ - public static final int kForwardLimit = 1; - public static final int kReverseLimit = 2; + /** + * Sets a potentiometer as the position reference only.
+ * Passed as the "tag" when setting the control mode. + */ + public final static PotentiometerTag kPotentiometer = new PotentiometerTag(); + private boolean isInverted = false; + + /** + * Mode determines how the Jaguar is controlled, used internally. + */ + public enum ControlMode { + PercentVbus, Current, Speed, Position, Voltage; + } + + public static final int kCurrentFault = 1; + public static final int kTemperatureFault = 2; + public static final int kBusVoltageFault = 4; + public static final int kGateDriverFault = 8; + + /** + * Limit switch masks + */ + public static final int kForwardLimit = 1; + public static final int kReverseLimit = 2; + + /** + * Determines how the Jaguar behaves when sending a zero signal. + */ + public enum NeutralMode { + /** Use the NeutralMode that is set by the jumper wire on the CAN device */ + Jumper((byte) 0), + /** Stop the motor's rotation by applying a force. */ + Brake((byte) 1), /** - * Determines how the Jaguar behaves when sending a zero signal. + * Do not attempt to stop the motor. Instead allow it to coast to a stop + * without applying resistance. */ - public enum NeutralMode { - /** Use the NeutralMode that is set by the jumper wire on the CAN device */ - Jumper((byte)0), - /** Stop the motor's rotation by applying a force. */ - Brake((byte)1), - /** Do not attempt to stop the motor. Instead allow it to coast to a stop without applying resistance. */ - Coast((byte)2); + Coast((byte) 2); - public byte value; + public byte value; - public static NeutralMode valueOf(byte value) { - for(NeutralMode mode : values()) { - if(mode.value == value) { - return mode; - } - } + public static NeutralMode valueOf(byte value) { + for (NeutralMode mode : values()) { + if (mode.value == value) { + return mode; + } + } - return null; - } + return null; + } - private NeutralMode(byte value) { - this.value = value; - } - } + private NeutralMode(byte value) { + this.value = value; + } + } + /** + * Determines which sensor to use for position reference. Limit switches will + * always be used to limit the rotation. This can not be disabled. + */ + public enum LimitMode { /** - * Determines which sensor to use for position reference. - * Limit switches will always be used to limit the rotation. This can not be disabled. + * Disables the soft position limits and only uses the limit switches to + * limit rotation. + *$ + * @see CANJaguar#getForwardLimitOK() + * @see CANJaguar#getReverseLimitOK() */ - public enum LimitMode { - /** - * Disables the soft position limits and only uses the limit switches to limit rotation. - * @see CANJaguar#getForwardLimitOK() - * @see CANJaguar#getReverseLimitOK() - */ - SwitchInputsOnly((byte)0), - /** - * Enables the soft position limits on the Jaguar. - * These will be used in addition to the limit switches. This does not disable the behavior - * of the limit switch input. - * @see CANJaguar#configSoftPositionLimits(double, double) - */ - SoftPositionLimits((byte)1); + SwitchInputsOnly((byte) 0), + /** + * Enables the soft position limits on the Jaguar. These will be used in + * addition to the limit switches. This does not disable the behavior of the + * limit switch input. + *$ + * @see CANJaguar#configSoftPositionLimits(double, double) + */ + SoftPositionLimits((byte) 1); - public byte value; + public byte value; - public static LimitMode valueOf(byte value) { - for(LimitMode mode : values()) { - if(mode.value == value) { - return mode; - } - } + public static LimitMode valueOf(byte value) { + for (LimitMode mode : values()) { + if (mode.value == value) { + return mode; + } + } - return null; - } + return null; + } - private LimitMode(byte value) { - this.value = value; - } - } + private LimitMode(byte value) { + this.value = value; + } + } - /** - * Constructor for the CANJaguar device.
- * By default the device is configured in Percent mode. - * The control mode can be changed by calling one of the control modes listed below. - * - * @param deviceNumber The address of the Jaguar on the CAN bus. - * @see CANJaguar#setCurrentMode(double, double, double) - * @see CANJaguar#setCurrentMode(PotentiometerTag, double, double, double) - * @see CANJaguar#setCurrentMode(EncoderTag, int, double, double, double) - * @see CANJaguar#setCurrentMode(QuadEncoderTag, int, double, double, double) - * @see CANJaguar#setPercentMode() - * @see CANJaguar#setPercentMode(PotentiometerTag) - * @see CANJaguar#setPercentMode(EncoderTag, int) - * @see CANJaguar#setPercentMode(QuadEncoderTag, int) - * @see CANJaguar#setPositionMode(PotentiometerTag, double, double, double) - * @see CANJaguar#setPositionMode(QuadEncoderTag, int, double, double, double) - * @see CANJaguar#setSpeedMode(EncoderTag, int, double, double, double) - * @see CANJaguar#setSpeedMode(QuadEncoderTag, int, double, double, double) - * @see CANJaguar#setVoltageMode() - * @see CANJaguar#setVoltageMode(PotentiometerTag) - * @see CANJaguar#setVoltageMode(EncoderTag, int) - * @see CANJaguar#setVoltageMode(QuadEncoderTag, int) - */ - public CANJaguar(int deviceNumber) { - try { - allocated.allocate(deviceNumber-1); - } catch (CheckedAllocationException e1) { - throw new AllocationException( - "CANJaguar device " + e1.getMessage() + "(increment index by one)"); - } + /** + * Constructor for the CANJaguar device.
+ * By default the device is configured in Percent mode. The control mode can + * be changed by calling one of the control modes listed below. + * + * @param deviceNumber The address of the Jaguar on the CAN bus. + * @see CANJaguar#setCurrentMode(double, double, double) + * @see CANJaguar#setCurrentMode(PotentiometerTag, double, double, double) + * @see CANJaguar#setCurrentMode(EncoderTag, int, double, double, double) + * @see CANJaguar#setCurrentMode(QuadEncoderTag, int, double, double, double) + * @see CANJaguar#setPercentMode() + * @see CANJaguar#setPercentMode(PotentiometerTag) + * @see CANJaguar#setPercentMode(EncoderTag, int) + * @see CANJaguar#setPercentMode(QuadEncoderTag, int) + * @see CANJaguar#setPositionMode(PotentiometerTag, double, double, double) + * @see CANJaguar#setPositionMode(QuadEncoderTag, int, double, double, double) + * @see CANJaguar#setSpeedMode(EncoderTag, int, double, double, double) + * @see CANJaguar#setSpeedMode(QuadEncoderTag, int, double, double, double) + * @see CANJaguar#setVoltageMode() + * @see CANJaguar#setVoltageMode(PotentiometerTag) + * @see CANJaguar#setVoltageMode(EncoderTag, int) + * @see CANJaguar#setVoltageMode(QuadEncoderTag, int) + */ + public CANJaguar(int deviceNumber) { + try { + allocated.allocate(deviceNumber - 1); + } catch (CheckedAllocationException e1) { + throw new AllocationException("CANJaguar device " + e1.getMessage() + + "(increment index by one)"); + } - m_deviceNumber = (byte)deviceNumber; - m_controlMode = ControlMode.PercentVbus; + m_deviceNumber = (byte) deviceNumber; + m_controlMode = ControlMode.PercentVbus; - m_safetyHelper = new MotorSafetyHelper(this); + m_safetyHelper = new MotorSafetyHelper(this); - boolean receivedFirmwareVersion = false; - byte[] data = new byte[8]; + boolean receivedFirmwareVersion = false; + byte[] data = new byte[8]; - // Request firmware and hardware version only once - requestMessage(CANJNI.CAN_IS_FRAME_REMOTE | CANJNI.CAN_MSGID_API_FIRMVER); - requestMessage(CANJNI.LM_API_HWVER); + // Request firmware and hardware version only once + requestMessage(CANJNI.CAN_IS_FRAME_REMOTE | CANJNI.CAN_MSGID_API_FIRMVER); + requestMessage(CANJNI.LM_API_HWVER); - // Wait until we've gotten all of the status data at least once. - for(int i = 0; i < kReceiveStatusAttempts; i++) - { - Timer.delay(0.001); + // Wait until we've gotten all of the status data at least once. + for (int i = 0; i < kReceiveStatusAttempts; i++) { + Timer.delay(0.001); - setupPeriodicStatus(); - updatePeriodicStatus(); + setupPeriodicStatus(); + updatePeriodicStatus(); - if(!receivedFirmwareVersion) { - try { - getMessage(CANJNI.CAN_MSGID_API_FIRMVER, CANJNI.CAN_MSGID_FULL_M, data); - m_firmwareVersion = unpackINT32(data); - receivedFirmwareVersion = true; - } catch(CANMessageNotFoundException e) {} - } + if (!receivedFirmwareVersion) { + try { + getMessage(CANJNI.CAN_MSGID_API_FIRMVER, CANJNI.CAN_MSGID_FULL_M, data); + m_firmwareVersion = unpackINT32(data); + receivedFirmwareVersion = true; + } catch (CANMessageNotFoundException e) { + } + } - if(m_receivedStatusMessage0 && - m_receivedStatusMessage1 && - m_receivedStatusMessage2 && - receivedFirmwareVersion) { - break; - } - } + if (m_receivedStatusMessage0 && m_receivedStatusMessage1 && m_receivedStatusMessage2 + && receivedFirmwareVersion) { + break; + } + } - if(!m_receivedStatusMessage0 || - !m_receivedStatusMessage1 || - !m_receivedStatusMessage2 || - !receivedFirmwareVersion) { - /* Free the resource */ - free(); - throw new CANMessageNotFoundException(); - } + if (!m_receivedStatusMessage0 || !m_receivedStatusMessage1 || !m_receivedStatusMessage2 + || !receivedFirmwareVersion) { + /* Free the resource */ + free(); + throw new CANMessageNotFoundException(); + } - try { - getMessage(CANJNI.LM_API_HWVER, CANJNI.CAN_MSGID_FULL_M, data); - m_hardwareVersion = data[0]; - } catch(CANMessageNotFoundException e) { - // Not all Jaguar firmware reports a hardware version. - m_hardwareVersion = 0; - } + try { + getMessage(CANJNI.LM_API_HWVER, CANJNI.CAN_MSGID_FULL_M, data); + m_hardwareVersion = data[0]; + } catch (CANMessageNotFoundException e) { + // Not all Jaguar firmware reports a hardware version. + m_hardwareVersion = 0; + } - // 3330 was the first shipping RDK firmware version for the Jaguar - if (m_firmwareVersion >= 3330 || m_firmwareVersion < 108) - { - if (m_firmwareVersion < 3330) - { - DriverStation.reportError("Jag " + m_deviceNumber + " firmware " + m_firmwareVersion + " is too old (must be at least version 108 of the FIRST approved firmware)", false); - } - else - { - DriverStation.reportError("Jag" + m_deviceNumber + " firmware " + m_firmwareVersion + " is not FIRST approved (must be at least version 108 of the FIRST approved firmware)", false); - } - return; - } - } + // 3330 was the first shipping RDK firmware version for the Jaguar + if (m_firmwareVersion >= 3330 || m_firmwareVersion < 108) { + if (m_firmwareVersion < 3330) { + DriverStation.reportError("Jag " + m_deviceNumber + " firmware " + m_firmwareVersion + + " is too old (must be at least version 108 of the FIRST approved firmware)", false); + } else { + DriverStation + .reportError( + "Jag" + + m_deviceNumber + + " firmware " + + m_firmwareVersion + + " is not FIRST approved (must be at least version 108 of the FIRST approved firmware)", + false); + } + return; + } + } - /** - * Cancel periodic messages to the Jaguar, effectively disabling it. - * No other methods should be called after this is called. - */ - public void free() { - allocated.free(m_deviceNumber-1); - m_safetyHelper = null; + /** + * Cancel periodic messages to the Jaguar, effectively disabling it. No other + * methods should be called after this is called. + */ + public void free() { + allocated.free(m_deviceNumber - 1); + m_safetyHelper = null; - ByteBuffer status = ByteBuffer.allocateDirect(4); - status.order(ByteOrder.LITTLE_ENDIAN); - status.asIntBuffer().put(0, 0); + ByteBuffer status = ByteBuffer.allocateDirect(4); + status.order(ByteOrder.LITTLE_ENDIAN); + status.asIntBuffer().put(0, 0); - int messageID ; + int messageID; - // Disable periodic setpoints - switch(m_controlMode) { - case PercentVbus: - messageID = m_deviceNumber | CANJNI.LM_API_VOLT_T_SET; - break; + // Disable periodic setpoints + switch (m_controlMode) { + case PercentVbus: + messageID = m_deviceNumber | CANJNI.LM_API_VOLT_T_SET; + break; - case Speed: - messageID = m_deviceNumber | CANJNI.LM_API_SPD_T_SET; - break; + case Speed: + messageID = m_deviceNumber | CANJNI.LM_API_SPD_T_SET; + break; - case Position: - messageID = m_deviceNumber | CANJNI.LM_API_POS_T_SET; - break; + case Position: + messageID = m_deviceNumber | CANJNI.LM_API_POS_T_SET; + break; - case Current: - messageID = m_deviceNumber | CANJNI.LM_API_ICTRL_T_SET; - break; + case Current: + messageID = m_deviceNumber | CANJNI.LM_API_ICTRL_T_SET; + break; - case Voltage: - messageID = m_deviceNumber | CANJNI.LM_API_VCOMP_T_SET; - break; + case Voltage: + messageID = m_deviceNumber | CANJNI.LM_API_VCOMP_T_SET; + break; - default: - return; - } + default: + return; + } - CANJNI.FRCNetworkCommunicationCANSessionMuxSendMessage(messageID, null, - CANJNI.CAN_SEND_PERIOD_STOP_REPEATING, status.asIntBuffer()); + CANJNI.FRCNetworkCommunicationCANSessionMuxSendMessage(messageID, null, + CANJNI.CAN_SEND_PERIOD_STOP_REPEATING, status.asIntBuffer()); - configMaxOutputVoltage(kApproxBusVoltage); - } + configMaxOutputVoltage(kApproxBusVoltage); + } - /** - * @return The CAN ID passed in the constructor - */ - int getDeviceNumber() - { - return m_deviceNumber; - } + /** + * @return The CAN ID passed in the constructor + */ + int getDeviceNumber() { + return m_deviceNumber; + } - /** - * Get the recently set outputValue set point. - * - * The scale and the units depend on the mode the Jaguar is in.
- * In percentVbus mode, the outputValue is from -1.0 to 1.0 (same as PWM Jaguar).
- * In voltage mode, the outputValue is in volts.
- * In current mode, the outputValue is in amps.
- * In speed mode, the outputValue is in rotations/minute.
- * In position mode, the outputValue is in rotations.
- * - * @return The most recently set outputValue set point. - */ - @Override - public double get() { - return m_value; - } + /** + * Get the recently set outputValue set point. + * + * The scale and the units depend on the mode the Jaguar is in.
+ * In percentVbus mode, the outputValue is from -1.0 to 1.0 (same as PWM + * Jaguar).
+ * In voltage mode, the outputValue is in volts.
+ * In current mode, the outputValue is in amps.
+ * In speed mode, the outputValue is in rotations/minute.
+ * In position mode, the outputValue is in rotations.
+ * + * @return The most recently set outputValue set point. + */ + @Override + public double get() { + return m_value; + } /** * Equivalent to {@link #get()}. @@ -315,8 +340,8 @@ public class CANJaguar implements MotorSafety, PIDOutput, PIDInterface, CANSpeed /** * Get the difference between the setpoint and goal in closed loop modes. * - * Outside of position and velocity modes the return value of getError() - * has relatively little meaning. + * Outside of position and velocity modes the return value of getError() has + * relatively little meaning. * * @return The difference between the setpoint and the current position. */ @@ -325,88 +350,91 @@ public class CANJaguar implements MotorSafety, PIDOutput, PIDInterface, CANSpeed return get() - getPosition(); } - /** - * Sets the output set-point value. - * - * The scale and the units depend on the mode the Jaguar is in.
- * In percentVbus Mode, the outputValue is from -1.0 to 1.0 (same as PWM Jaguar).
- * In voltage Mode, the outputValue is in volts.
- * In current Mode, the outputValue is in amps.
- * In speed mode, the outputValue is in rotations/minute.
- * In position Mode, the outputValue is in rotations. - * - * @param outputValue The set-point to sent to the motor controller. - * @param syncGroup The update group to add this set() to, pending UpdateSyncGroup(). If 0, update immediately. - */ - @Override - public void set(double outputValue, byte syncGroup) { - int messageID; - byte[] data = new byte[8]; - byte dataSize; + /** + * Sets the output set-point value. + * + * The scale and the units depend on the mode the Jaguar is in.
+ * In percentVbus Mode, the outputValue is from -1.0 to 1.0 (same as PWM + * Jaguar).
+ * In voltage Mode, the outputValue is in volts.
+ * In current Mode, the outputValue is in amps.
+ * In speed mode, the outputValue is in rotations/minute.
+ * In position Mode, the outputValue is in rotations. + * + * @param outputValue The set-point to sent to the motor controller. + * @param syncGroup The update group to add this set() to, pending + * UpdateSyncGroup(). If 0, update immediately. + */ + @Override + public void set(double outputValue, byte syncGroup) { + int messageID; + byte[] data = new byte[8]; + byte dataSize; - if(m_controlEnabled) { - switch(m_controlMode) { - case PercentVbus: - messageID = CANJNI.LM_API_VOLT_T_SET; - dataSize = packPercentage(data, isInverted ? -outputValue: outputValue); - break; + if (m_controlEnabled) { + switch (m_controlMode) { + case PercentVbus: + messageID = CANJNI.LM_API_VOLT_T_SET; + dataSize = packPercentage(data, isInverted ? -outputValue : outputValue); + break; - case Speed: - messageID = CANJNI.LM_API_SPD_T_SET; - dataSize = packFXP16_16(data, isInverted ? -outputValue: outputValue); - break; + case Speed: + messageID = CANJNI.LM_API_SPD_T_SET; + dataSize = packFXP16_16(data, isInverted ? -outputValue : outputValue); + break; - case Position: - messageID = CANJNI.LM_API_POS_T_SET; - dataSize = packFXP16_16(data, outputValue); - break; + case Position: + messageID = CANJNI.LM_API_POS_T_SET; + dataSize = packFXP16_16(data, outputValue); + break; - case Current: - messageID = CANJNI.LM_API_ICTRL_T_SET; - dataSize = packFXP8_8(data, outputValue); - break; + case Current: + messageID = CANJNI.LM_API_ICTRL_T_SET; + dataSize = packFXP8_8(data, outputValue); + break; - case Voltage: - messageID = CANJNI.LM_API_VCOMP_T_SET; - dataSize = packFXP8_8(data, isInverted ? -outputValue: outputValue); - break; + case Voltage: + messageID = CANJNI.LM_API_VCOMP_T_SET; + dataSize = packFXP8_8(data, isInverted ? -outputValue : outputValue); + break; - default: - return; - } + default: + return; + } - if(syncGroup != 0) { - data[dataSize++] = syncGroup; - } + if (syncGroup != 0) { + data[dataSize++] = syncGroup; + } - sendMessage(messageID, data, dataSize, kSendMessagePeriod); + sendMessage(messageID, data, dataSize, kSendMessagePeriod); - if(m_safetyHelper != null) m_safetyHelper.feed(); - } + if (m_safetyHelper != null) + m_safetyHelper.feed(); + } - m_value = outputValue; + m_value = outputValue; - verify(); - } + verify(); + } - /** - * Sets the output set-point value. - * - * The scale and the units depend on the mode the Jaguar is in.
- * In percentVbus mode, the outputValue is from -1.0 to 1.0 (same as PWM Jaguar).
- * In voltage mode, the outputValue is in volts.
- * In current mode, the outputValue is in amps.
- * In speed mode, the outputValue is in rotations/minute.
- * In position mode, the outputValue is in rotations. - * - * @param value - * The set-point to sent to the motor controller. - */ - @Override - public void set(double value) { - set(value, (byte)0); - } + /** + * Sets the output set-point value. + * + * The scale and the units depend on the mode the Jaguar is in.
+ * In percentVbus mode, the outputValue is from -1.0 to 1.0 (same as PWM + * Jaguar).
+ * In voltage mode, the outputValue is in volts.
+ * In current mode, the outputValue is in amps.
+ * In speed mode, the outputValue is in rotations/minute.
+ * In position mode, the outputValue is in rotations. + * + * @param value The set-point to sent to the motor controller. + */ + @Override + public void set(double value) { + set(value, (byte) 0); + } /** * Equivalent to {@link #set(double)}. Implements PIDInterface. @@ -422,705 +450,705 @@ public class CANJaguar implements MotorSafety, PIDOutput, PIDInterface, CANSpeed disableControl(); } - /** - * Inverts the direction of rotation of the motor - * Only works in percentVbus, Speed, and Voltage mode - * @param isInverted The state of inversion true is inverted - */ - @Override - public void setInverted(boolean isInverted) { - this.isInverted = isInverted; + /** + * Inverts the direction of rotation of the motor Only works in percentVbus, + * Speed, and Voltage mode + *$ + * @param isInverted The state of inversion true is inverted + */ + @Override + public void setInverted(boolean isInverted) { + this.isInverted = isInverted; + } + + /** + * Common interface for the inverting direction of a speed controller. + * + * @return isInverted The state of inversion, true is inverted. + * + */ + @Override + public boolean getInverted() { + return this.isInverted; + } + + /** + * Check all unverified params and make sure they're equal to their local + * cached versions. If a value isn't available, it gets requested. If a value + * doesn't match up, it gets set again. + */ + protected void verify() { + byte[] data = new byte[8]; + + // If the Jaguar lost power, everything should be considered unverified + try { + getMessage(CANJNI.LM_API_STATUS_POWER, CANJNI.CAN_MSGID_FULL_M, data); + boolean powerCycled = data[0] != 0; + + if (powerCycled) { + // Clear the power cycled bit + data[0] = 1; + sendMessage(CANJNI.LM_API_STATUS_POWER, data, 1); + + // Mark everything as unverified + m_controlModeVerified = false; + m_speedRefVerified = false; + m_posRefVerified = false; + m_neutralModeVerified = false; + m_encoderCodesPerRevVerified = false; + m_potentiometerTurnsVerified = false; + m_forwardLimitVerified = false; + m_reverseLimitVerified = false; + m_limitModeVerified = false; + m_maxOutputVoltageVerified = false; + m_faultTimeVerified = false; + + if (m_controlMode == ControlMode.PercentVbus || m_controlMode == ControlMode.Voltage) { + m_voltageRampRateVerified = false; + } else { + m_pVerified = false; + m_iVerified = false; + m_dVerified = false; + } + + // Verify periodic status messages again + m_receivedStatusMessage0 = false; + m_receivedStatusMessage1 = false; + m_receivedStatusMessage2 = false; + + // Remove any old values from netcomms. Otherwise, parameters + // are incorrectly marked as verified based on stale messages. + int[] messages = + new int[] {CANJNI.LM_API_SPD_REF, CANJNI.LM_API_POS_REF, CANJNI.LM_API_SPD_PC, + CANJNI.LM_API_POS_PC, CANJNI.LM_API_ICTRL_PC, CANJNI.LM_API_SPD_IC, + CANJNI.LM_API_POS_IC, CANJNI.LM_API_ICTRL_IC, CANJNI.LM_API_SPD_DC, + CANJNI.LM_API_POS_DC, CANJNI.LM_API_ICTRL_DC, CANJNI.LM_API_CFG_ENC_LINES, + CANJNI.LM_API_CFG_POT_TURNS, CANJNI.LM_API_CFG_BRAKE_COAST, + CANJNI.LM_API_CFG_LIMIT_MODE, CANJNI.LM_API_CFG_LIMIT_REV, + CANJNI.LM_API_CFG_MAX_VOUT, CANJNI.LM_API_VOLT_SET_RAMP, + CANJNI.LM_API_VCOMP_COMP_RAMP, CANJNI.LM_API_CFG_FAULT_TIME, + CANJNI.LM_API_CFG_LIMIT_FWD}; + + for (int message : messages) { + try { + getMessage(message, CANJNI.CAN_MSGID_FULL_M, data); + } catch (CANMessageNotFoundException e) { + } + } + } + } catch (CANMessageNotFoundException e) { + requestMessage(CANJNI.LM_API_STATUS_POWER); } - /** - * Common interface for the inverting direction of a speed controller. - * - * @return isInverted The state of inversion, true is inverted. - * - */ - @Override - public boolean getInverted() { - return this.isInverted; + // Verify that any recently set parameters are correct + if (!m_controlModeVerified && m_controlEnabled) { + try { + getMessage(CANJNI.LM_API_STATUS_CMODE, CANJNI.CAN_MSGID_FULL_M, data); + + ControlMode mode = ControlMode.values()[data[0]]; + + if (m_controlMode == mode) { + m_controlModeVerified = true; + } else { + // Enable control again to resend the control mode + enableControl(); + } + } catch (CANMessageNotFoundException e) { + // Verification is needed but not available - request it again. + requestMessage(CANJNI.LM_API_STATUS_CMODE); + } } - - /** - * Check all unverified params and make sure they're equal to their local - * cached versions. If a value isn't available, it gets requested. If a value - * doesn't match up, it gets set again. - */ - protected void verify() { - byte[] data = new byte[8]; - - // If the Jaguar lost power, everything should be considered unverified - try { - getMessage(CANJNI.LM_API_STATUS_POWER, CANJNI.CAN_MSGID_FULL_M, data); - boolean powerCycled = data[0] != 0; - - if(powerCycled) { - // Clear the power cycled bit - data[0] = 1; - sendMessage(CANJNI.LM_API_STATUS_POWER, data, 1); - - // Mark everything as unverified - m_controlModeVerified = false; - m_speedRefVerified = false; - m_posRefVerified = false; - m_neutralModeVerified = false; - m_encoderCodesPerRevVerified = false; - m_potentiometerTurnsVerified = false; - m_forwardLimitVerified = false; - m_reverseLimitVerified = false; - m_limitModeVerified = false; - m_maxOutputVoltageVerified = false; - m_faultTimeVerified = false; - - if(m_controlMode == ControlMode.PercentVbus || m_controlMode == ControlMode.Voltage) { - m_voltageRampRateVerified = false; - } - else { - m_pVerified = false; - m_iVerified = false; - m_dVerified = false; - } - - // Verify periodic status messages again - m_receivedStatusMessage0 = false; - m_receivedStatusMessage1 = false; - m_receivedStatusMessage2 = false; - - // Remove any old values from netcomms. Otherwise, parameters - // are incorrectly marked as verified based on stale messages. - int[] messages = new int[] { - CANJNI.LM_API_SPD_REF, CANJNI.LM_API_POS_REF, - CANJNI.LM_API_SPD_PC, CANJNI.LM_API_POS_PC, - CANJNI.LM_API_ICTRL_PC, CANJNI.LM_API_SPD_IC, - CANJNI.LM_API_POS_IC, CANJNI.LM_API_ICTRL_IC, - CANJNI.LM_API_SPD_DC, CANJNI.LM_API_POS_DC, - CANJNI.LM_API_ICTRL_DC, CANJNI.LM_API_CFG_ENC_LINES, - CANJNI.LM_API_CFG_POT_TURNS, CANJNI.LM_API_CFG_BRAKE_COAST, - CANJNI.LM_API_CFG_LIMIT_MODE, CANJNI.LM_API_CFG_LIMIT_REV, - CANJNI.LM_API_CFG_MAX_VOUT, CANJNI.LM_API_VOLT_SET_RAMP, - CANJNI.LM_API_VCOMP_COMP_RAMP, CANJNI.LM_API_CFG_FAULT_TIME, - CANJNI.LM_API_CFG_LIMIT_FWD - }; - - for(int message : messages) { - try { - getMessage(message, CANJNI.CAN_MSGID_FULL_M, data); - } catch (CANMessageNotFoundException e) {} - } - } - } catch(CANMessageNotFoundException e) { - requestMessage(CANJNI.LM_API_STATUS_POWER); - } - - // Verify that any recently set parameters are correct - if(!m_controlModeVerified && m_controlEnabled) { - try { - getMessage(CANJNI.LM_API_STATUS_CMODE, CANJNI.CAN_MSGID_FULL_M, data); - - ControlMode mode = ControlMode.values()[data[0]]; - - if(m_controlMode == mode) { - m_controlModeVerified = true; - } else { - // Enable control again to resend the control mode - enableControl(); - } - } catch(CANMessageNotFoundException e) { - // Verification is needed but not available - request it again. - requestMessage(CANJNI.LM_API_STATUS_CMODE); - } - } - - if(!m_speedRefVerified) { - try { - getMessage(CANJNI.LM_API_SPD_REF, CANJNI.CAN_MSGID_FULL_M, data); - - int speedRef = data[0]; - - if(m_speedReference == speedRef) { - m_speedRefVerified = true; - } else { - // It's wrong - set it again - setSpeedReference(m_speedReference); - } - } catch(CANMessageNotFoundException e) { - // Verification is needed but not available - request it again. - requestMessage(CANJNI.LM_API_SPD_REF); - } - } - - if(!m_posRefVerified) { - try { - getMessage(CANJNI.LM_API_POS_REF, CANJNI.CAN_MSGID_FULL_M, data); - - int posRef = data[0]; - - if(m_positionReference == posRef) { - m_posRefVerified = true; - } else { - // It's wrong - set it again - setPositionReference(m_positionReference); - } - } catch(CANMessageNotFoundException e) { - // Verification is needed but not available - request it again. - requestMessage(CANJNI.LM_API_POS_REF); - } - } - - if(!m_pVerified) { - int message = 0; - - switch(m_controlMode) { - case Speed: - message = CANJNI.LM_API_SPD_PC; - break; - - case Position: - message = CANJNI.LM_API_POS_PC; - break; - - case Current: - message = CANJNI.LM_API_ICTRL_PC; - break; - - default: - break; - } - - try { - getMessage(message, CANJNI.CAN_MSGID_FULL_M, data); - - double p = unpackFXP16_16(data); - - if(FXP16_EQ(m_p, p)) { - m_pVerified = true; - } else { - // It's wrong - set it again - setP(m_p); - } - } catch(CANMessageNotFoundException e) { - // Verification is needed but not available - request it again. - requestMessage(message); - } - } - - if(!m_iVerified) { - int message = 0; - - switch(m_controlMode) { - case Speed: - message = CANJNI.LM_API_SPD_IC; - break; - - case Position: - message = CANJNI.LM_API_POS_IC; - break; - - case Current: - message = CANJNI.LM_API_ICTRL_IC; - break; - - default: - break; - } - - try { - getMessage(message, CANJNI.CAN_MSGID_FULL_M, data); - - double i = unpackFXP16_16(data); - - if(FXP16_EQ(m_i, i)) { - m_iVerified = true; - } else { - // It's wrong - set it again - setI(m_i); - } - } catch(CANMessageNotFoundException e) { - // Verification is needed but not available - request it again. - requestMessage(message); - } - } - - if(!m_dVerified) { - int message = 0; - - switch(m_controlMode) { - case Speed: - message = CANJNI.LM_API_SPD_DC; - break; - - case Position: - message = CANJNI.LM_API_POS_DC; - break; - - case Current: - message = CANJNI.LM_API_ICTRL_DC; - break; - - default: - break; - } - - try { - getMessage(message, CANJNI.CAN_MSGID_FULL_M, data); - - double d = unpackFXP16_16(data); - - if(FXP16_EQ(m_d, d)) { - m_dVerified = true; - } else { - // It's wrong - set it again - setD(m_d); - } - } catch(CANMessageNotFoundException e) { - // Verification is needed but not available - request it again. - requestMessage(message); - } - } - - if(!m_neutralModeVerified) { - try { - getMessage(CANJNI.LM_API_CFG_BRAKE_COAST, CANJNI.CAN_MSGID_FULL_M, data); - - NeutralMode mode = NeutralMode.valueOf(data[0]); - - if(mode == m_neutralMode) { - m_neutralModeVerified = true; - } else { - //It's wrong - set it again - configNeutralMode(m_neutralMode); - } - } catch(CANMessageNotFoundException e) { - // Verification is needed but not available - request it again. - requestMessage(CANJNI.LM_API_CFG_BRAKE_COAST); - } - } - - if(!m_encoderCodesPerRevVerified) { - try { - getMessage(CANJNI.LM_API_CFG_ENC_LINES, CANJNI.CAN_MSGID_FULL_M, data); - - short codes = unpackINT16(data); - - if(codes == m_encoderCodesPerRev) { - m_encoderCodesPerRevVerified = true; - } else { - //It's wrong - set it again - configEncoderCodesPerRev(m_encoderCodesPerRev); - } - } catch(CANMessageNotFoundException e) { - // Verification is needed but not available - request it again. - requestMessage(CANJNI.LM_API_CFG_ENC_LINES); - } - } - - if(!m_potentiometerTurnsVerified) { - try { - getMessage(CANJNI.LM_API_CFG_POT_TURNS, CANJNI.CAN_MSGID_FULL_M, data); - - short turns = unpackINT16(data); - - if(turns == m_potentiometerTurns) { - m_potentiometerTurnsVerified = true; - } else { - //It's wrong - set it again - configPotentiometerTurns(m_potentiometerTurns); - } - } catch(CANMessageNotFoundException e) { - // Verification is needed but not available - request it again. - requestMessage(CANJNI.LM_API_CFG_POT_TURNS); - } - } - - if(!m_limitModeVerified) { - try { - getMessage(CANJNI.LM_API_CFG_LIMIT_MODE, CANJNI.CAN_MSGID_FULL_M, data); - - LimitMode mode = LimitMode.valueOf(data[0]); - - if(mode == m_limitMode) { - m_limitModeVerified = true; - } else { - //It's wrong - set it again - configLimitMode(m_limitMode); - } - } catch(CANMessageNotFoundException e) { - // Verification is needed but not available - request it again. - requestMessage(CANJNI.LM_API_CFG_LIMIT_MODE); - } - } - - if(!m_forwardLimitVerified) { - try { - getMessage(CANJNI.LM_API_CFG_LIMIT_FWD, CANJNI.CAN_MSGID_FULL_M, data); - - double limit = unpackFXP16_16(data); - - if(FXP16_EQ(limit, m_forwardLimit)) { - m_forwardLimitVerified = true; - } else { - //It's wrong - set it again - configForwardLimit(m_forwardLimit); - } - } catch(CANMessageNotFoundException e) { - // Verification is needed but not available - request it again. - requestMessage(CANJNI.LM_API_CFG_LIMIT_FWD); - } - } - - if(!m_reverseLimitVerified) { - try { - getMessage(CANJNI.LM_API_CFG_LIMIT_REV, CANJNI.CAN_MSGID_FULL_M, data); - - double limit = unpackFXP16_16(data); - - if(FXP16_EQ(limit, m_reverseLimit)) { - m_reverseLimitVerified = true; - } else { - //It's wrong - set it again - configReverseLimit(m_reverseLimit); - } - } catch(CANMessageNotFoundException e) { - // Verification is needed but not available - request it again. - requestMessage(CANJNI.LM_API_CFG_LIMIT_REV); - } - } - - if(!m_maxOutputVoltageVerified) { - try { - getMessage(CANJNI.LM_API_CFG_MAX_VOUT, CANJNI.CAN_MSGID_FULL_M, data); - - double voltage = unpackFXP8_8(data); - - // The returned max output voltage is sometimes slightly higher - // or lower than what was sent. This should not trigger - // resending the message. - if(Math.abs(voltage - m_maxOutputVoltage) < 0.1) { - m_maxOutputVoltageVerified = true; - } else { - // It's wrong - set it again - configMaxOutputVoltage(m_maxOutputVoltage); - } - - } catch(CANMessageNotFoundException e) { - // Verification is needed but not available - request it again. - requestMessage(CANJNI.LM_API_CFG_MAX_VOUT); - } - } - - if(!m_voltageRampRateVerified) { - if(m_controlMode == ControlMode.PercentVbus) { - try { - getMessage(CANJNI.LM_API_VOLT_SET_RAMP, CANJNI.CAN_MSGID_FULL_M, data); - - double rate = unpackPercentage(data); - - if(FXP16_EQ(rate, m_voltageRampRate)) { - m_voltageRampRateVerified = true; - } else { - // It's wrong - set it again - setVoltageRampRate(m_voltageRampRate); - } - - } catch(CANMessageNotFoundException e) { - // Verification is needed but not available - request it again. - requestMessage(CANJNI.LM_API_VOLT_SET_RAMP); - } - } - } else if(m_controlMode == ControlMode.Voltage) { - try { - getMessage(CANJNI.LM_API_VCOMP_COMP_RAMP, CANJNI.CAN_MSGID_FULL_M, data); - - double rate = unpackFXP8_8(data); - - if(FXP8_EQ(rate, m_voltageRampRate)) { - m_voltageRampRateVerified = true; - } else { - // It's wrong - set it again - setVoltageRampRate(m_voltageRampRate); - } - - } catch(CANMessageNotFoundException e) { - // Verification is needed but not available - request it again. - requestMessage(CANJNI.LM_API_VCOMP_COMP_RAMP); - } - } - - if(!m_faultTimeVerified) { - try { - getMessage(CANJNI.LM_API_CFG_FAULT_TIME, CANJNI.CAN_MSGID_FULL_M, data); - - int faultTime = unpackINT16(data); - - if((int)(m_faultTime * 1000.0) == faultTime) { - m_faultTimeVerified = true; - } else { - //It's wrong - set it again - configFaultTime(m_faultTime); - } - } catch(CANMessageNotFoundException e) { - // Verification is needed but not available - request it again. - requestMessage(CANJNI.LM_API_CFG_FAULT_TIME); - } - } - - if(!m_receivedStatusMessage0 || - !m_receivedStatusMessage1 || - !m_receivedStatusMessage2) { - // If the periodic status messages haven't been verified as received, - // request periodic status messages again and attempt to unpack any - // available ones. - setupPeriodicStatus(); - getTemperature(); - getPosition(); - getFaults(); - } - } - - /** - * Common interface for disabling a motor. - * - * @deprecated Call {@link #disableControl()} instead. - */ - @Deprecated - @Override - public void disable() { - disableControl(); - } + + if (!m_speedRefVerified) { + try { + getMessage(CANJNI.LM_API_SPD_REF, CANJNI.CAN_MSGID_FULL_M, data); + + int speedRef = data[0]; + + if (m_speedReference == speedRef) { + m_speedRefVerified = true; + } else { + // It's wrong - set it again + setSpeedReference(m_speedReference); + } + } catch (CANMessageNotFoundException e) { + // Verification is needed but not available - request it again. + requestMessage(CANJNI.LM_API_SPD_REF); + } + } + + if (!m_posRefVerified) { + try { + getMessage(CANJNI.LM_API_POS_REF, CANJNI.CAN_MSGID_FULL_M, data); + + int posRef = data[0]; + + if (m_positionReference == posRef) { + m_posRefVerified = true; + } else { + // It's wrong - set it again + setPositionReference(m_positionReference); + } + } catch (CANMessageNotFoundException e) { + // Verification is needed but not available - request it again. + requestMessage(CANJNI.LM_API_POS_REF); + } + } + + if (!m_pVerified) { + int message = 0; + + switch (m_controlMode) { + case Speed: + message = CANJNI.LM_API_SPD_PC; + break; + + case Position: + message = CANJNI.LM_API_POS_PC; + break; + + case Current: + message = CANJNI.LM_API_ICTRL_PC; + break; + + default: + break; + } + + try { + getMessage(message, CANJNI.CAN_MSGID_FULL_M, data); + + double p = unpackFXP16_16(data); + + if (FXP16_EQ(m_p, p)) { + m_pVerified = true; + } else { + // It's wrong - set it again + setP(m_p); + } + } catch (CANMessageNotFoundException e) { + // Verification is needed but not available - request it again. + requestMessage(message); + } + } + + if (!m_iVerified) { + int message = 0; + + switch (m_controlMode) { + case Speed: + message = CANJNI.LM_API_SPD_IC; + break; + + case Position: + message = CANJNI.LM_API_POS_IC; + break; + + case Current: + message = CANJNI.LM_API_ICTRL_IC; + break; + + default: + break; + } + + try { + getMessage(message, CANJNI.CAN_MSGID_FULL_M, data); + + double i = unpackFXP16_16(data); + + if (FXP16_EQ(m_i, i)) { + m_iVerified = true; + } else { + // It's wrong - set it again + setI(m_i); + } + } catch (CANMessageNotFoundException e) { + // Verification is needed but not available - request it again. + requestMessage(message); + } + } + + if (!m_dVerified) { + int message = 0; + + switch (m_controlMode) { + case Speed: + message = CANJNI.LM_API_SPD_DC; + break; + + case Position: + message = CANJNI.LM_API_POS_DC; + break; + + case Current: + message = CANJNI.LM_API_ICTRL_DC; + break; + + default: + break; + } + + try { + getMessage(message, CANJNI.CAN_MSGID_FULL_M, data); + + double d = unpackFXP16_16(data); + + if (FXP16_EQ(m_d, d)) { + m_dVerified = true; + } else { + // It's wrong - set it again + setD(m_d); + } + } catch (CANMessageNotFoundException e) { + // Verification is needed but not available - request it again. + requestMessage(message); + } + } + + if (!m_neutralModeVerified) { + try { + getMessage(CANJNI.LM_API_CFG_BRAKE_COAST, CANJNI.CAN_MSGID_FULL_M, data); + + NeutralMode mode = NeutralMode.valueOf(data[0]); + + if (mode == m_neutralMode) { + m_neutralModeVerified = true; + } else { + // It's wrong - set it again + configNeutralMode(m_neutralMode); + } + } catch (CANMessageNotFoundException e) { + // Verification is needed but not available - request it again. + requestMessage(CANJNI.LM_API_CFG_BRAKE_COAST); + } + } + + if (!m_encoderCodesPerRevVerified) { + try { + getMessage(CANJNI.LM_API_CFG_ENC_LINES, CANJNI.CAN_MSGID_FULL_M, data); + + short codes = unpackINT16(data); + + if (codes == m_encoderCodesPerRev) { + m_encoderCodesPerRevVerified = true; + } else { + // It's wrong - set it again + configEncoderCodesPerRev(m_encoderCodesPerRev); + } + } catch (CANMessageNotFoundException e) { + // Verification is needed but not available - request it again. + requestMessage(CANJNI.LM_API_CFG_ENC_LINES); + } + } + + if (!m_potentiometerTurnsVerified) { + try { + getMessage(CANJNI.LM_API_CFG_POT_TURNS, CANJNI.CAN_MSGID_FULL_M, data); + + short turns = unpackINT16(data); + + if (turns == m_potentiometerTurns) { + m_potentiometerTurnsVerified = true; + } else { + // It's wrong - set it again + configPotentiometerTurns(m_potentiometerTurns); + } + } catch (CANMessageNotFoundException e) { + // Verification is needed but not available - request it again. + requestMessage(CANJNI.LM_API_CFG_POT_TURNS); + } + } + + if (!m_limitModeVerified) { + try { + getMessage(CANJNI.LM_API_CFG_LIMIT_MODE, CANJNI.CAN_MSGID_FULL_M, data); + + LimitMode mode = LimitMode.valueOf(data[0]); + + if (mode == m_limitMode) { + m_limitModeVerified = true; + } else { + // It's wrong - set it again + configLimitMode(m_limitMode); + } + } catch (CANMessageNotFoundException e) { + // Verification is needed but not available - request it again. + requestMessage(CANJNI.LM_API_CFG_LIMIT_MODE); + } + } + + if (!m_forwardLimitVerified) { + try { + getMessage(CANJNI.LM_API_CFG_LIMIT_FWD, CANJNI.CAN_MSGID_FULL_M, data); + + double limit = unpackFXP16_16(data); + + if (FXP16_EQ(limit, m_forwardLimit)) { + m_forwardLimitVerified = true; + } else { + // It's wrong - set it again + configForwardLimit(m_forwardLimit); + } + } catch (CANMessageNotFoundException e) { + // Verification is needed but not available - request it again. + requestMessage(CANJNI.LM_API_CFG_LIMIT_FWD); + } + } + + if (!m_reverseLimitVerified) { + try { + getMessage(CANJNI.LM_API_CFG_LIMIT_REV, CANJNI.CAN_MSGID_FULL_M, data); + + double limit = unpackFXP16_16(data); + + if (FXP16_EQ(limit, m_reverseLimit)) { + m_reverseLimitVerified = true; + } else { + // It's wrong - set it again + configReverseLimit(m_reverseLimit); + } + } catch (CANMessageNotFoundException e) { + // Verification is needed but not available - request it again. + requestMessage(CANJNI.LM_API_CFG_LIMIT_REV); + } + } + + if (!m_maxOutputVoltageVerified) { + try { + getMessage(CANJNI.LM_API_CFG_MAX_VOUT, CANJNI.CAN_MSGID_FULL_M, data); + + double voltage = unpackFXP8_8(data); + + // The returned max output voltage is sometimes slightly higher + // or lower than what was sent. This should not trigger + // resending the message. + if (Math.abs(voltage - m_maxOutputVoltage) < 0.1) { + m_maxOutputVoltageVerified = true; + } else { + // It's wrong - set it again + configMaxOutputVoltage(m_maxOutputVoltage); + } + + } catch (CANMessageNotFoundException e) { + // Verification is needed but not available - request it again. + requestMessage(CANJNI.LM_API_CFG_MAX_VOUT); + } + } + + if (!m_voltageRampRateVerified) { + if (m_controlMode == ControlMode.PercentVbus) { + try { + getMessage(CANJNI.LM_API_VOLT_SET_RAMP, CANJNI.CAN_MSGID_FULL_M, data); + + double rate = unpackPercentage(data); + + if (FXP16_EQ(rate, m_voltageRampRate)) { + m_voltageRampRateVerified = true; + } else { + // It's wrong - set it again + setVoltageRampRate(m_voltageRampRate); + } + + } catch (CANMessageNotFoundException e) { + // Verification is needed but not available - request it again. + requestMessage(CANJNI.LM_API_VOLT_SET_RAMP); + } + } + } else if (m_controlMode == ControlMode.Voltage) { + try { + getMessage(CANJNI.LM_API_VCOMP_COMP_RAMP, CANJNI.CAN_MSGID_FULL_M, data); + + double rate = unpackFXP8_8(data); + + if (FXP8_EQ(rate, m_voltageRampRate)) { + m_voltageRampRateVerified = true; + } else { + // It's wrong - set it again + setVoltageRampRate(m_voltageRampRate); + } + + } catch (CANMessageNotFoundException e) { + // Verification is needed but not available - request it again. + requestMessage(CANJNI.LM_API_VCOMP_COMP_RAMP); + } + } + + if (!m_faultTimeVerified) { + try { + getMessage(CANJNI.LM_API_CFG_FAULT_TIME, CANJNI.CAN_MSGID_FULL_M, data); + + int faultTime = unpackINT16(data); + + if ((int) (m_faultTime * 1000.0) == faultTime) { + m_faultTimeVerified = true; + } else { + // It's wrong - set it again + configFaultTime(m_faultTime); + } + } catch (CANMessageNotFoundException e) { + // Verification is needed but not available - request it again. + requestMessage(CANJNI.LM_API_CFG_FAULT_TIME); + } + } + + if (!m_receivedStatusMessage0 || !m_receivedStatusMessage1 || !m_receivedStatusMessage2) { + // If the periodic status messages haven't been verified as received, + // request periodic status messages again and attempt to unpack any + // available ones. + setupPeriodicStatus(); + getTemperature(); + getPosition(); + getFaults(); + } + } + + /** + * Common interface for disabling a motor. + * + * @deprecated Call {@link #disableControl()} instead. + */ + @Deprecated + @Override + public void disable() { + disableControl(); + } // PIDInterface interface public void enable() { enableControl(); } - // PIDOutput interface - @Override - public void pidWrite(double output) { - if (m_controlMode == ControlMode.PercentVbus) { - set(output); - } else { - throw new IllegalStateException("PID only supported in PercentVbus mode"); - } - } + // PIDOutput interface + @Override + public void pidWrite(double output) { + if (m_controlMode == ControlMode.PercentVbus) { + set(output); + } else { + throw new IllegalStateException("PID only supported in PercentVbus mode"); + } + } - /** - * Set the reference source device for speed controller mode. - * - * Choose encoder as the source of speed feedback when in speed control mode. - * - * @param reference Specify a speed reference. - */ - private void setSpeedReference(int reference) { - sendMessage(CANJNI.LM_API_SPD_REF, new byte[] { (byte)reference }, 1); + /** + * Set the reference source device for speed controller mode. + * + * Choose encoder as the source of speed feedback when in speed control mode. + * + * @param reference Specify a speed reference. + */ + private void setSpeedReference(int reference) { + sendMessage(CANJNI.LM_API_SPD_REF, new byte[] {(byte) reference}, 1); - m_speedReference = reference; - m_speedRefVerified = false; - } + m_speedReference = reference; + m_speedRefVerified = false; + } - /** - * Set the reference source device for position controller mode. - * - * Choose between using and encoder and using a potentiometer - * as the source of position feedback when in position control mode. - * - * @param reference Specify a position reference. - */ - private void setPositionReference(int reference) { - sendMessage(CANJNI.LM_API_POS_REF, new byte[] { (byte)reference }, 1); + /** + * Set the reference source device for position controller mode. + * + * Choose between using and encoder and using a potentiometer as the source of + * position feedback when in position control mode. + * + * @param reference Specify a position reference. + */ + private void setPositionReference(int reference) { + sendMessage(CANJNI.LM_API_POS_REF, new byte[] {(byte) reference}, 1); - m_positionReference = reference; - m_posRefVerified = false; - } + m_positionReference = reference; + m_posRefVerified = false; + } - /** - * Set the P constant for the closed loop modes. - * - * @param p The proportional gain of the Jaguar's PID controller. - */ - public void setP(double p) { - byte[] data = new byte[8]; - byte dataSize = packFXP16_16(data, p); + /** + * Set the P constant for the closed loop modes. + * + * @param p The proportional gain of the Jaguar's PID controller. + */ + public void setP(double p) { + byte[] data = new byte[8]; + byte dataSize = packFXP16_16(data, p); - switch(m_controlMode) { - case Speed: - sendMessage(CANJNI.LM_API_SPD_PC, data, dataSize); - break; + switch (m_controlMode) { + case Speed: + sendMessage(CANJNI.LM_API_SPD_PC, data, dataSize); + break; - case Position: - sendMessage(CANJNI.LM_API_POS_PC, data, dataSize); - break; + case Position: + sendMessage(CANJNI.LM_API_POS_PC, data, dataSize); + break; - case Current: - sendMessage(CANJNI.LM_API_ICTRL_PC, data, dataSize); - break; + case Current: + sendMessage(CANJNI.LM_API_ICTRL_PC, data, dataSize); + break; - default: - throw new IllegalStateException("PID constants only apply in Speed, Position, and Current mode"); - } + default: + throw new IllegalStateException( + "PID constants only apply in Speed, Position, and Current mode"); + } - m_p = p; - m_pVerified = false; - } + m_p = p; + m_pVerified = false; + } - /** - * Set the I constant for the closed loop modes. - * - * @param i The integral gain of the Jaguar's PID controller. - */ - public void setI(double i) { - byte[] data = new byte[8]; - byte dataSize = packFXP16_16(data, i); + /** + * Set the I constant for the closed loop modes. + * + * @param i The integral gain of the Jaguar's PID controller. + */ + public void setI(double i) { + byte[] data = new byte[8]; + byte dataSize = packFXP16_16(data, i); - switch(m_controlMode) { - case Speed: - sendMessage(CANJNI.LM_API_SPD_IC, data, dataSize); - break; + switch (m_controlMode) { + case Speed: + sendMessage(CANJNI.LM_API_SPD_IC, data, dataSize); + break; - case Position: - sendMessage(CANJNI.LM_API_POS_IC, data, dataSize); - break; + case Position: + sendMessage(CANJNI.LM_API_POS_IC, data, dataSize); + break; - case Current: - sendMessage(CANJNI.LM_API_ICTRL_IC, data, dataSize); - break; + case Current: + sendMessage(CANJNI.LM_API_ICTRL_IC, data, dataSize); + break; - default: - throw new IllegalStateException("PID constants only apply in Speed, Position, and Current mode"); - } + default: + throw new IllegalStateException( + "PID constants only apply in Speed, Position, and Current mode"); + } - m_i = i; - m_iVerified = false; - } + m_i = i; + m_iVerified = false; + } - /** - * Set the D constant for the closed loop modes. - * - * @param d The derivative gain of the Jaguar's PID controller. - */ - public void setD(double d) { - byte[] data = new byte[8]; - byte dataSize = packFXP16_16(data, d); + /** + * Set the D constant for the closed loop modes. + * + * @param d The derivative gain of the Jaguar's PID controller. + */ + public void setD(double d) { + byte[] data = new byte[8]; + byte dataSize = packFXP16_16(data, d); - switch(m_controlMode) { - case Speed: - sendMessage(CANJNI.LM_API_SPD_DC, data, dataSize); - break; + switch (m_controlMode) { + case Speed: + sendMessage(CANJNI.LM_API_SPD_DC, data, dataSize); + break; - case Position: - sendMessage(CANJNI.LM_API_POS_DC, data, dataSize); - break; + case Position: + sendMessage(CANJNI.LM_API_POS_DC, data, dataSize); + break; - case Current: - sendMessage(CANJNI.LM_API_ICTRL_DC, data, dataSize); - break; + case Current: + sendMessage(CANJNI.LM_API_ICTRL_DC, data, dataSize); + break; - default: - throw new IllegalStateException("PID constants only apply in Speed, Position, and Current mode"); - } + default: + throw new IllegalStateException( + "PID constants only apply in Speed, Position, and Current mode"); + } - m_d = d; - m_dVerified = false; - } + m_d = d; + m_dVerified = false; + } - /** - * Set the P, I, and D constants for the closed loop modes. - * - * @param p The proportional gain of the Jaguar's PID controller. - * @param i The integral gain of the Jaguar's PID controller. - * @param d The differential gain of the Jaguar's PID controller. - */ - public void setPID(double p, double i, double d) { - setP(p); - setI(i); - setD(d); - } + /** + * Set the P, I, and D constants for the closed loop modes. + * + * @param p The proportional gain of the Jaguar's PID controller. + * @param i The integral gain of the Jaguar's PID controller. + * @param d The differential gain of the Jaguar's PID controller. + */ + public void setPID(double p, double i, double d) { + setP(p); + setI(i); + setD(d); + } - /** - * Get the Proportional gain of the controller. - * - * @return The proportional gain. - */ - public double getP() { - if(m_controlMode.equals(ControlMode.PercentVbus) || m_controlMode.equals(ControlMode.Voltage)){ - throw new IllegalStateException("PID does not apply in Percent or Voltage control modes"); - } - return m_p; - } + /** + * Get the Proportional gain of the controller. + * + * @return The proportional gain. + */ + public double getP() { + if (m_controlMode.equals(ControlMode.PercentVbus) || m_controlMode.equals(ControlMode.Voltage)) { + throw new IllegalStateException("PID does not apply in Percent or Voltage control modes"); + } + return m_p; + } - /** - * Get the Integral gain of the controller. - * - * @return The integral gain. - */ - public double getI() { - if(m_controlMode.equals(ControlMode.PercentVbus) || m_controlMode.equals(ControlMode.Voltage)){ - throw new IllegalStateException("PID does not apply in Percent or Voltage control modes"); - } - return m_i; - } + /** + * Get the Integral gain of the controller. + * + * @return The integral gain. + */ + public double getI() { + if (m_controlMode.equals(ControlMode.PercentVbus) || m_controlMode.equals(ControlMode.Voltage)) { + throw new IllegalStateException("PID does not apply in Percent or Voltage control modes"); + } + return m_i; + } - /** - * Get the Derivative gain of the controller. - * - * @return The derivative gain. - */ - public double getD() { - if(m_controlMode.equals(ControlMode.PercentVbus) || m_controlMode.equals(ControlMode.Voltage)){ - throw new IllegalStateException("PID does not apply in Percent or Voltage control modes"); - } - return m_d; - } + /** + * Get the Derivative gain of the controller. + * + * @return The derivative gain. + */ + public double getD() { + if (m_controlMode.equals(ControlMode.PercentVbus) || m_controlMode.equals(ControlMode.Voltage)) { + throw new IllegalStateException("PID does not apply in Percent or Voltage control modes"); + } + return m_d; + } - /** - * Enable the closed loop controller. - * - * Start actually controlling the output based on the feedback. - * If starting a position controller with an encoder reference, - * use the encoderInitialPosition parameter to initialize the - * encoder state. - * - * @param encoderInitialPosition Encoder position to set if position with encoder reference. Ignored otherwise. - */ - public void enableControl(double encoderInitialPosition) { - switch(m_controlMode) { - case PercentVbus: - sendMessage(CANJNI.LM_API_VOLT_T_EN, new byte[0], 0); - break; + /** + * Enable the closed loop controller. + * + * Start actually controlling the output based on the feedback. If starting a + * position controller with an encoder reference, use the + * encoderInitialPosition parameter to initialize the encoder state. + * + * @param encoderInitialPosition Encoder position to set if position with + * encoder reference. Ignored otherwise. + */ + public void enableControl(double encoderInitialPosition) { + switch (m_controlMode) { + case PercentVbus: + sendMessage(CANJNI.LM_API_VOLT_T_EN, new byte[0], 0); + break; - case Speed: - sendMessage(CANJNI.LM_API_SPD_T_EN, new byte[0], 0); - break; + case Speed: + sendMessage(CANJNI.LM_API_SPD_T_EN, new byte[0], 0); + break; - case Position: - byte[] data = new byte[8]; - int dataSize = packFXP16_16(data, encoderInitialPosition); - sendMessage(CANJNI.LM_API_POS_T_EN, data, dataSize); - break; + case Position: + byte[] data = new byte[8]; + int dataSize = packFXP16_16(data, encoderInitialPosition); + sendMessage(CANJNI.LM_API_POS_T_EN, data, dataSize); + break; - case Current: - sendMessage(CANJNI.LM_API_ICTRL_T_EN, new byte[0], 0); - break; + case Current: + sendMessage(CANJNI.LM_API_ICTRL_T_EN, new byte[0], 0); + break; - case Voltage: - sendMessage(CANJNI.LM_API_VCOMP_T_EN, new byte[0], 0); - break; - } + case Voltage: + sendMessage(CANJNI.LM_API_VCOMP_T_EN, new byte[0], 0); + break; + } - m_controlEnabled = true; - } + m_controlEnabled = true; + } - /** - * Enable the closed loop controller. - * - * Start actually controlling the output based on the feedback. - * This is the same as calling CANJaguar.enableControl(double encoderInitialPosition) - * with encoderInitialPosition set to 0.0 - */ - public void enableControl() { - enableControl(0.0); - } + /** + * Enable the closed loop controller. + * + * Start actually controlling the output based on the feedback. This is the + * same as calling + * CANJaguar.enableControl(double encoderInitialPosition) with + * encoderInitialPosition set to 0.0 + */ + public void enableControl() { + enableControl(0.0); + } /** * Return whether the controller is enabled. @@ -1131,1149 +1159,1172 @@ public class CANJaguar implements MotorSafety, PIDOutput, PIDInterface, CANSpeed return m_controlEnabled; } - /** - * Disable the closed loop controller. - * - * Stop driving the output based on the feedback. - */ - public void disableControl() { - // Disable all control modes. - sendMessage(CANJNI.LM_API_VOLT_DIS, new byte[0], 0); - sendMessage(CANJNI.LM_API_SPD_DIS, new byte[0], 0); - sendMessage(CANJNI.LM_API_POS_DIS, new byte[0], 0); - sendMessage(CANJNI.LM_API_ICTRL_DIS, new byte[0], 0); - sendMessage(CANJNI.LM_API_VCOMP_DIS, new byte[0], 0); - - // Stop all periodic setpoints - sendMessage(CANJNI.LM_API_VOLT_T_SET, new byte[0], 0, CANJNI.CAN_SEND_PERIOD_STOP_REPEATING); - sendMessage(CANJNI.LM_API_SPD_T_SET, new byte[0], 0, CANJNI.CAN_SEND_PERIOD_STOP_REPEATING); - sendMessage(CANJNI.LM_API_POS_T_SET, new byte[0], 0, CANJNI.CAN_SEND_PERIOD_STOP_REPEATING); - sendMessage(CANJNI.LM_API_ICTRL_T_SET, new byte[0], 0, CANJNI.CAN_SEND_PERIOD_STOP_REPEATING); - sendMessage(CANJNI.LM_API_VCOMP_T_SET, new byte[0], 0, CANJNI.CAN_SEND_PERIOD_STOP_REPEATING); - - m_controlEnabled = false; - } - - /** - * Enable controlling the motor voltage as a percentage of the bus voltage - * without any position or speed feedback.
- * After calling this you must call {@link CANJaguar#enableControl()} or {@link CANJaguar#enableControl(double)} to enable the device. - */ - public void setPercentMode() - { - changeControlMode(ControlMode.PercentVbus); - setPositionReference(CANJNI.LM_REF_NONE); - setSpeedReference(CANJNI.LM_REF_NONE); - } - - /** - * Enable controlling the motor voltage as a percentage of the bus voltage, - * and enable speed sensing from a non-quadrature encoder.
- * After calling this you must call {@link CANJaguar#enableControl()} or {@link CANJaguar#enableControl(double)} to enable the device. - * - * @param tag The constant {@link CANJaguar#kEncoder} - * @param codesPerRev The counts per revolution on the encoder - */ - public void setPercentMode(EncoderTag tag, int codesPerRev) - { - changeControlMode(ControlMode.PercentVbus); - setPositionReference(CANJNI.LM_REF_NONE); - setSpeedReference(CANJNI.LM_REF_ENCODER); - configEncoderCodesPerRev(codesPerRev); - } - - /** - * Enable controlling the motor voltage as a percentage of the bus voltage, - * and enable position and speed sensing from a quadrature encoder.
- * After calling this you must call {@link CANJaguar#enableControl()} or {@link CANJaguar#enableControl(double)} to enable the device. - * - * @param tag The constant {@link CANJaguar#kQuadEncoder} - * @param codesPerRev The counts per revolution on the encoder - */ - public void setPercentMode(QuadEncoderTag tag, int codesPerRev) - { - changeControlMode(ControlMode.PercentVbus); - setPositionReference(CANJNI.LM_REF_ENCODER); - setSpeedReference(CANJNI.LM_REF_QUAD_ENCODER); - configEncoderCodesPerRev(codesPerRev); - } - - /** - * Enable controlling the motor voltage as a percentage of the bus voltage, - * and enable position sensing from a potentiometer and no speed feedback.
- * After calling this you must call {@link CANJaguar#enableControl()} or {@link CANJaguar#enableControl(double)} to enable the device. - * - * @param tag The constant {@link CANJaguar#kPotentiometer} - */ - public void setPercentMode(PotentiometerTag tag) - { - changeControlMode(ControlMode.PercentVbus); - setPositionReference(CANJNI.LM_REF_POT); - setSpeedReference(CANJNI.LM_REF_NONE); - configPotentiometerTurns(1); - } - - /** - * Enable controlling the motor current with a PID loop.
- * After calling this you must call {@link CANJaguar#enableControl()} or {@link CANJaguar#enableControl(double)} to enable the device. - * - * @param p The proportional gain of the Jaguar's PID controller. - * @param i The integral gain of the Jaguar's PID controller. - * @param d The differential gain of the Jaguar's PID controller. - */ - public void setCurrentMode(double p, double i, double d) - { - changeControlMode(ControlMode.Current); - setPositionReference(CANJNI.LM_REF_NONE); - setSpeedReference(CANJNI.LM_REF_NONE); - setPID(p, i, d); - } - - /** - * Enable controlling the motor current with a PID loop, and enable speed - * sensing from a non-quadrature encoder.
- * After calling this you must call {@link CANJaguar#enableControl()} or {@link CANJaguar#enableControl(double)} to enable the device. - * - * @param tag The constant {@link CANJaguar#kEncoder} - * @param p The proportional gain of the Jaguar's PID controller. - * @param i The integral gain of the Jaguar's PID controller. - * @param d The differential gain of the Jaguar's PID controller. - */ - public void setCurrentMode(EncoderTag tag, int codesPerRev, double p, double i, double d) - { - changeControlMode(ControlMode.Current); - setPositionReference(CANJNI.LM_REF_NONE); - setSpeedReference(CANJNI.LM_REF_NONE); - configEncoderCodesPerRev(codesPerRev); - setPID(p, i, d); - } - - /** - * Enable controlling the motor current with a PID loop, and enable speed and - * position sensing from a quadrature encoder.
- * After calling this you must call {@link CANJaguar#enableControl()} or {@link CANJaguar#enableControl(double)} to enable the device. - * - * @param tag The constant {@link CANJaguar#kQuadEncoder} - * @param p The proportional gain of the Jaguar's PID controller. - * @param i The integral gain of the Jaguar's PID controller. - * @param d The differential gain of the Jaguar's PID controller. - */ - public void setCurrentMode(QuadEncoderTag tag, int codesPerRev, double p, double i, double d) - { - changeControlMode(ControlMode.Current); - setPositionReference(CANJNI.LM_REF_ENCODER); - setSpeedReference(CANJNI.LM_REF_QUAD_ENCODER); - configEncoderCodesPerRev(codesPerRev); - setPID(p, i, d); - } - - /** - * Enable controlling the motor current with a PID loop, and enable position - * sensing from a potentiometer.
- * After calling this you must call {@link CANJaguar#enableControl()} or {@link CANJaguar#enableControl(double)} to enable the device. - * - * @param tag The constant {@link CANJaguar#kPotentiometer} - * @param p The proportional gain of the Jaguar's PID controller. - * @param i The integral gain of the Jaguar's PID controller. - * @param d The differential gain of the Jaguar's PID controller. - */ - public void setCurrentMode(PotentiometerTag tag, double p, double i, double d) - { - changeControlMode(ControlMode.Current); - setPositionReference(CANJNI.LM_REF_POT); - setSpeedReference(CANJNI.LM_REF_NONE); - configPotentiometerTurns(1); - setPID(p, i, d); - } - - /** - * Enable controlling the speed with a feedback loop from a non-quadrature - * encoder.
- * After calling this you must call {@link CANJaguar#enableControl()} or {@link CANJaguar#enableControl(double)} to enable the device. - * - * @param tag The constant {@link CANJaguar#kEncoder} - * @param codesPerRev The counts per revolution on the encoder - * @param p The proportional gain of the Jaguar's PID controller. - * @param i The integral gain of the Jaguar's PID controller. - * @param d The differential gain of the Jaguar's PID controller. - */ - public void setSpeedMode(EncoderTag tag, int codesPerRev, double p, double i, double d) - { - changeControlMode(ControlMode.Speed); - setPositionReference(CANJNI.LM_REF_NONE); - setSpeedReference(CANJNI.LM_REF_ENCODER); - configEncoderCodesPerRev(codesPerRev); - setPID(p, i, d); - } - - /** - * Enable controlling the speed with a feedback loop from a quadrature encoder.
- * After calling this you must call {@link CANJaguar#enableControl()} or {@link CANJaguar#enableControl(double)} to enable the device. - * - * @param tag The constant {@link CANJaguar#kQuadEncoder} - * @param codesPerRev The counts per revolution on the encoder - * @param p The proportional gain of the Jaguar's PID controller. - * @param i The integral gain of the Jaguar's PID controller. - * @param d The differential gain of the Jaguar's PID controller. - */ - public void setSpeedMode(QuadEncoderTag tag, int codesPerRev, double p, double i, double d) - { - changeControlMode(ControlMode.Speed); - setPositionReference(CANJNI.LM_REF_ENCODER); - setSpeedReference(CANJNI.LM_REF_QUAD_ENCODER); - configEncoderCodesPerRev(codesPerRev); - setPID(p, i, d); - } - - /** - * Enable controlling the position with a feedback loop using an encoder.
- * After calling this you must call {@link CANJaguar#enableControl()} or {@link CANJaguar#enableControl(double)} to enable the device. - * - * @param tag The constant {@link CANJaguar#kQuadEncoder} - * @param codesPerRev The counts per revolution on the encoder - * @param p The proportional gain of the Jaguar's PID controller. - * @param i The integral gain of the Jaguar's PID controller. - * @param d The differential gain of the Jaguar's PID controller. - * - */ - public void setPositionMode(QuadEncoderTag tag, int codesPerRev, double p, double i, double d) - { - changeControlMode(ControlMode.Position); - setPositionReference(CANJNI.LM_REF_ENCODER); - configEncoderCodesPerRev(codesPerRev); - setPID(p, i, d); - } - - /** - * Enable controlling the position with a feedback loop using a potentiometer.
- * After calling this you must call {@link CANJaguar#enableControl()} or {@link CANJaguar#enableControl(double)} to enable the device. - * - * @param tag The constant {@link CANJaguar#kPotentiometer} - * @param p The proportional gain of the Jaguar's PID controller. - * @param i The integral gain of the Jaguar's PID controller. - * @param d The differential gain of the Jaguar's PID controller. - */ - public void setPositionMode(PotentiometerTag tag, double p, double i, double d) - { - changeControlMode(ControlMode.Position); - setPositionReference(CANJNI.LM_REF_POT); - configPotentiometerTurns(1); - setPID(p, i, d); - } - - /** - * Enable controlling the motor voltage without any position or speed feedback.
- * After calling this you must call {@link CANJaguar#enableControl()} or {@link CANJaguar#enableControl(double)} to enable the device. - */ - public void setVoltageMode() - { - changeControlMode(ControlMode.Voltage); - setPositionReference(CANJNI.LM_REF_NONE); - setSpeedReference(CANJNI.LM_REF_NONE); - } - - /** - * Enable controlling the motor voltage with speed feedback from a - * non-quadrature encoder and no position feedback.
- * After calling this you must call {@link CANJaguar#enableControl()} or {@link CANJaguar#enableControl(double)} to enable the device. - * - * @param tag The constant {@link CANJaguar#kEncoder} - * @param codesPerRev The counts per revolution on the encoder - */ - public void setVoltageMode(EncoderTag tag, int codesPerRev) - { - changeControlMode(ControlMode.Voltage); - setPositionReference(CANJNI.LM_REF_NONE); - setSpeedReference(CANJNI.LM_REF_ENCODER); - configEncoderCodesPerRev(codesPerRev); - } - - /** - * Enable controlling the motor voltage with position and speed feedback from a - * quadrature encoder.
- * After calling this you must call {@link CANJaguar#enableControl()} or {@link CANJaguar#enableControl(double)} to enable the device. - * - * @param tag The constant {@link CANJaguar#kQuadEncoder} - * @param codesPerRev The counts per revolution on the encoder - */ - public void setVoltageMode(QuadEncoderTag tag, int codesPerRev) - { - changeControlMode(ControlMode.Voltage); - setPositionReference(CANJNI.LM_REF_ENCODER); - setSpeedReference(CANJNI.LM_REF_QUAD_ENCODER); - configEncoderCodesPerRev(codesPerRev); - } - - /** - * Enable controlling the motor voltage with position feedback from a - * potentiometer and no speed feedback. - * - * @param tag The constant {@link CANJaguar#kPotentiometer} - */ - public void setVoltageMode(PotentiometerTag tag) - { - changeControlMode(ControlMode.Voltage); - setPositionReference(CANJNI.LM_REF_POT); - setSpeedReference(CANJNI.LM_REF_NONE); - configPotentiometerTurns(1); - } - - /** - * Used internally. In order to set the control mode see the methods listed below. - * - * Change the control mode of this Jaguar object. - * - * After changing modes, configure any PID constants or other settings needed - * and then EnableControl() to actually change the mode on the Jaguar. - * - * @param controlMode The new mode. - * - * @see CANJaguar#setCurrentMode(double, double, double) - * @see CANJaguar#setCurrentMode(PotentiometerTag, double, double, double) - * @see CANJaguar#setCurrentMode(EncoderTag, int, double, double, double) - * @see CANJaguar#setCurrentMode(QuadEncoderTag, int, double, double, double) - * @see CANJaguar#setPercentMode() - * @see CANJaguar#setPercentMode(PotentiometerTag) - * @see CANJaguar#setPercentMode(EncoderTag, int) - * @see CANJaguar#setPercentMode(QuadEncoderTag, int) - * @see CANJaguar#setPositionMode(PotentiometerTag, double, double, double) - * @see CANJaguar#setPositionMode(QuadEncoderTag, int, double, double, double) - * @see CANJaguar#setSpeedMode(EncoderTag, int, double, double, double) - * @see CANJaguar#setSpeedMode(QuadEncoderTag, int, double, double, double) - * @see CANJaguar#setVoltageMode() - * @see CANJaguar#setVoltageMode(PotentiometerTag) - * @see CANJaguar#setVoltageMode(EncoderTag, int) - * @see CANJaguar#setVoltageMode(QuadEncoderTag, int) - */ - private void changeControlMode(ControlMode controlMode) { - // Disable the previous mode - disableControl(); - - // Update the local mode - m_controlMode = controlMode; - m_controlModeVerified = false; - } - - /** - * Get the active control mode from the Jaguar. - * - * Ask the Jagaur what mode it is in. - * - * @return ControlMode that the Jag is in. - */ - public ControlMode getControlMode() { - return m_controlMode; - } - - /** - * Get the voltage at the battery input terminals of the Jaguar. - * - * @return The bus voltage in Volts. - */ - public double getBusVoltage() { - updatePeriodicStatus(); - - return m_busVoltage; - } - - /** - * Get the voltage being output from the motor terminals of the Jaguar. - * - * @return The output voltage in Volts. - */ - public double getOutputVoltage() { - updatePeriodicStatus(); - - return m_outputVoltage; - } - - /** - * Get the current through the motor terminals of the Jaguar. - * - * @return The output current in Amps. - */ - public double getOutputCurrent() { - updatePeriodicStatus(); - - return m_outputCurrent; - } - - /** - * Get the internal temperature of the Jaguar. - * - * @return The temperature of the Jaguar in degrees Celsius. - */ - public double getTemperature() { - updatePeriodicStatus(); - - return m_temperature; - } - - /** - * Get the position of the encoder or potentiometer. - * - * @return The position of the motor in rotations based on the configured feedback. - * @see CANJaguar#configPotentiometerTurns(int) - * @see CANJaguar#configEncoderCodesPerRev(int) - */ - public double getPosition() { - updatePeriodicStatus(); - - return m_position; - } - - /** - * Get the speed of the encoder. - * - * @return The speed of the motor in RPM based on the configured feedback. - */ - public double getSpeed() { - updatePeriodicStatus(); - - return m_speed; - } - - /** - * Get the status of the forward limit switch. - * - * @return true if the motor is allowed to turn in the forward direction. - */ - public boolean getForwardLimitOK() { - updatePeriodicStatus(); - - return (m_limits & kForwardLimit) != 0; - } - - /** - * Get the status of the reverse limit switch. - * - * @return true if the motor is allowed to turn in the reverse direction. - */ - public boolean getReverseLimitOK() { - updatePeriodicStatus(); - - return (m_limits & kReverseLimit) != 0; - } - - /** - * Get the status of any faults the Jaguar has detected. - * - * @return A bit-mask of faults defined by the "Faults" constants. - * @see #kCurrentFault - * @see #kBusVoltageFault - * @see #kTemperatureFault - * @see #kGateDriverFault - */ - public short getFaults() { - updatePeriodicStatus(); - - return m_faults; - } - - /** - * set the maximum voltage change rate. - * - * When in PercentVbus or Voltage output mode, the rate at which the voltage changes can - * be limited to reduce current spikes. set this to 0.0 to disable rate limiting. - * - * @param rampRate The maximum rate of voltage change in Percent Voltage mode in V/s. - */ - public void setVoltageRampRate(double rampRate) { - byte[] data = new byte[8]; - int dataSize; - int message; - - switch(m_controlMode) { - case PercentVbus: - dataSize = packPercentage(data, rampRate / (m_maxOutputVoltage * kControllerRate)); - message = CANJNI.LM_API_VOLT_SET_RAMP; - break; - case Voltage: - dataSize = packFXP8_8(data, rampRate / kControllerRate); - message = CANJNI.LM_API_VCOMP_COMP_RAMP; - break; - default: - throw new IllegalStateException("Voltage ramp rate only applies in Percentage and Voltage modes"); - } - - sendMessage(message, data, dataSize); - } - - /** - * Get the version of the firmware running on the Jaguar. - * - * @return The firmware version. 0 if the device did not respond. - */ - public int getFirmwareVersion() { - return m_firmwareVersion; - } - - /** - * Get the version of the Jaguar hardware. - * - * @return The hardware version. 1: Jaguar, 2: Black Jaguar - */ - public byte getHardwareVersion() { - return m_hardwareVersion; - } - - /** - * Configure what the controller does to the H-Bridge when neutral (not driving the output). - * - * This allows you to override the jumper configuration for brake or coast. - * - * @param mode Select to use the jumper setting or to override it to coast or brake. - */ - public void configNeutralMode(NeutralMode mode) { - sendMessage(CANJNI.LM_API_CFG_BRAKE_COAST, new byte[] { mode.value }, 1); - - m_neutralMode = mode; - m_neutralModeVerified = false; - } - - /** - * Configure how many codes per revolution are generated by your encoder. - * - * @param codesPerRev The number of counts per revolution in 1X mode. - */ - public void configEncoderCodesPerRev(int codesPerRev) { - byte[] data = new byte[8]; - - int dataSize = packINT16(data, (short)codesPerRev); - sendMessage(CANJNI.LM_API_CFG_ENC_LINES, data, dataSize); - - m_encoderCodesPerRev = (short)codesPerRev; - m_encoderCodesPerRevVerified = false; - } - - /** - * Configure the number of turns on the potentiometer. - * - * There is no special support for continuous turn potentiometers. - * Only integer numbers of turns are supported. - * - * @param turns The number of turns of the potentiometer - */ - public void configPotentiometerTurns(int turns) { - byte[] data = new byte[8]; - - int dataSize = packINT16(data, (short)turns); - sendMessage(CANJNI.LM_API_CFG_POT_TURNS, data, dataSize); - - m_potentiometerTurns = (short)turns; - m_potentiometerTurnsVerified = false; - } - - /** - * Configure Soft Position Limits when in Position Controller mode.
- * - * When controlling position, you can add additional limits on top of the limit switch inputs - * that are based on the position feedback. If the position limit is reached or the - * switch is opened, that direction will be disabled. - * - * @param forwardLimitPosition The position that, if exceeded, will disable the forward direction. - * @param reverseLimitPosition The position that, if exceeded, will disable the reverse direction. - */ - public void configSoftPositionLimits(double forwardLimitPosition, double reverseLimitPosition) { - configLimitMode(LimitMode.SoftPositionLimits); - configForwardLimit(forwardLimitPosition); - configReverseLimit(reverseLimitPosition); - } - - /** - * Disable Soft Position Limits if previously enabled.
- * - * Soft Position Limits are disabled by default. - */ - public void disableSoftPositionLimits() { - configLimitMode(LimitMode.SwitchInputsOnly); - } - - /** - * Set the limit mode for position control mode.
- * - * Use {@link #configSoftPositionLimits(double, double)} or {@link #disableSoftPositionLimits()} to set this - * automatically. - * @param mode The {@link LimitMode} to use to limit the rotation of the device. - * @see LimitMode#SwitchInputsOnly - * @see LimitMode#SoftPositionLimits - */ - public void configLimitMode(LimitMode mode) { - sendMessage(CANJNI.LM_API_CFG_LIMIT_MODE, new byte[] { mode.value }, 1); - } - - /** - * Set the position that, if exceeded, will disable the forward direction. - * - * Use {@link #configSoftPositionLimits(double, double)} to set this and the {@link LimitMode} automatically. - * @param forwardLimitPosition The position that, if exceeded, will disable the forward direction. - */ - public void configForwardLimit(double forwardLimitPosition) { - byte[] data = new byte[8]; - - int dataSize = packFXP16_16(data, forwardLimitPosition); - data[dataSize++] = 1; - sendMessage(CANJNI.LM_API_CFG_LIMIT_FWD, data, dataSize); - - m_forwardLimit = forwardLimitPosition; - m_forwardLimitVerified = false; - } - - /** - * Set the position that, if exceeded, will disable the reverse direction. - * - * Use {@link #configSoftPositionLimits(double, double)} to set this and the {@link LimitMode} automatically. - * @param reverseLimitPosition The position that, if exceeded, will disable the reverse direction. - */ - public void configReverseLimit(double reverseLimitPosition) { - byte[] data = new byte[8]; - - int dataSize = packFXP16_16(data, reverseLimitPosition); - data[dataSize++] = 1; - sendMessage(CANJNI.LM_API_CFG_LIMIT_REV, data, dataSize); - - m_reverseLimit = reverseLimitPosition; - m_reverseLimitVerified = false; - } - - /** - * Configure the maximum voltage that the Jaguar will ever output. - * - * This can be used to limit the maximum output voltage in all modes so that - * motors which cannot withstand full bus voltage can be used safely. - * - * @param voltage The maximum voltage output by the Jaguar. - */ - public void configMaxOutputVoltage(double voltage) { - byte[] data = new byte[8]; - - int dataSize = packFXP8_8(data, voltage); - sendMessage(CANJNI.LM_API_CFG_MAX_VOUT, data, dataSize); - - m_maxOutputVoltage = voltage; - m_maxOutputVoltageVerified = false; - } - - /** - * Configure how long the Jaguar waits in the case of a fault before resuming operation. - * - * Faults include over temerature, over current, and bus under voltage. - * The default is 3.0 seconds, but can be reduced to as low as 0.5 seconds. - * - * @param faultTime The time to wait before resuming operation, in seconds. - */ - public void configFaultTime(float faultTime) { - byte[] data = new byte[8]; - - if(faultTime < 0.5f) faultTime = 0.5f; - else if(faultTime > 3.0f) faultTime = 3.0f; - - int dataSize = packINT16(data, (short)(faultTime * 1000.0)); - sendMessage(CANJNI.LM_API_CFG_FAULT_TIME, data, dataSize); - - m_faultTime = faultTime; - m_faultTimeVerified = false; - } - - byte m_deviceNumber; - double m_value = 0.0f; - - // Parameters/configuration - ControlMode m_controlMode; - int m_speedReference = CANJNI.LM_REF_NONE; - int m_positionReference = CANJNI.LM_REF_NONE; - double m_p = 0.0; - double m_i = 0.0; - double m_d = 0.0; - NeutralMode m_neutralMode = NeutralMode.Jumper; - short m_encoderCodesPerRev = 0; - short m_potentiometerTurns = 0; - LimitMode m_limitMode = LimitMode.SwitchInputsOnly; - double m_forwardLimit = 0.0; - double m_reverseLimit = 0.0; - double m_maxOutputVoltage = kApproxBusVoltage; - double m_voltageRampRate = 0.0; - float m_faultTime = 0.0f; - - // Which parameters have been verified since they were last set? - boolean m_controlModeVerified = true; - boolean m_speedRefVerified = true; - boolean m_posRefVerified = true; - boolean m_pVerified = true; - boolean m_iVerified = true; - boolean m_dVerified = true; - boolean m_neutralModeVerified = true; - boolean m_encoderCodesPerRevVerified = true; - boolean m_potentiometerTurnsVerified = true; - boolean m_forwardLimitVerified = true; - boolean m_reverseLimitVerified = true; - boolean m_limitModeVerified = true; - boolean m_maxOutputVoltageVerified = true; - boolean m_voltageRampRateVerified = true; - boolean m_faultTimeVerified = true; - - // Status data - double m_busVoltage = 0.0f; - double m_outputVoltage = 0.0f; - double m_outputCurrent = 0.0f; - double m_temperature = 0.0f; - double m_position = 0.0; - double m_speed = 0.0; - byte m_limits = (byte)0; - short m_faults = (short)0; - int m_firmwareVersion = 0; - byte m_hardwareVersion = (byte)0; - - // Which periodic status messages have we received at least once? - boolean m_receivedStatusMessage0 = false; - boolean m_receivedStatusMessage1 = false; - boolean m_receivedStatusMessage2 = false; - - static final int kReceiveStatusAttempts = 50; - - boolean m_controlEnabled = true; - - static void sendMessageHelper(int messageID, byte[] data, int dataSize, int period) throws CANMessageNotFoundException { - final int[] kTrustedMessages = { - CANJNI.LM_API_VOLT_T_EN, CANJNI.LM_API_VOLT_T_SET, CANJNI.LM_API_SPD_T_EN, CANJNI.LM_API_SPD_T_SET, - CANJNI.LM_API_VCOMP_T_EN, CANJNI.LM_API_VCOMP_T_SET, CANJNI.LM_API_POS_T_EN, CANJNI.LM_API_POS_T_SET, - CANJNI.LM_API_ICTRL_T_EN, CANJNI.LM_API_ICTRL_T_SET - }; - - ByteBuffer status = ByteBuffer.allocateDirect(4); - status.order(ByteOrder.LITTLE_ENDIAN); - status.asIntBuffer().put(0, 0); - - for(byte i = 0; i < kTrustedMessages.length; i++) { - if((kFullMessageIDMask & messageID) == kTrustedMessages[i]) - { - // Make sure the data will still fit after adjusting for the token. - if (dataSize > kMaxMessageDataSize - 2) { - throw new RuntimeException("CAN message has too much data."); - } - - ByteBuffer trustedBuffer = ByteBuffer.allocateDirect(dataSize+2); - trustedBuffer.put(0, (byte)0); - trustedBuffer.put(1, (byte)0); - - for(byte j = 0; j < dataSize; j++) { - trustedBuffer.put(j+2, data[j]); - } - - CANJNI.FRCNetworkCommunicationCANSessionMuxSendMessage(messageID, trustedBuffer, period, status.asIntBuffer()); - int statusCode = status.asIntBuffer().get(0); - if(statusCode < 0) { - CANExceptionFactory.checkStatus(statusCode, messageID); - } - - return; - } - } - - // Use a null pointer for the data buffer if the given array is null - ByteBuffer buffer; - if(data != null) { - buffer = ByteBuffer.allocateDirect(dataSize); - for(byte i = 0; i < dataSize; i++) { - buffer.put(i, data[i]); - } - } else { - buffer = null; - } - - CANJNI.FRCNetworkCommunicationCANSessionMuxSendMessage(messageID, buffer, period, status.asIntBuffer()); - - int statusCode = status.asIntBuffer().get(0); - if(statusCode < 0) { - CANExceptionFactory.checkStatus(statusCode, messageID); - } - } - - /** - * Send a message to the Jaguar. - * - * @param messageID The messageID to be used on the CAN bus (device number - * is added internally) - * @param data The up to 8 bytes of data to be sent with the message - * @param dataSize Specify how much of the data in "data" to send - * @param period If positive, tell Network Communications to send the - * message every "period" milliseconds. - */ - protected void sendMessage(int messageID, byte[] data, int dataSize, int period) { - sendMessageHelper(messageID | m_deviceNumber, data, dataSize, period); - } - - /** - * Send a message to the Jaguar, non-periodically - * - * @param messageID The messageID to be used on the CAN bus (device number - * is added internally) - * @param data The up to 8 bytes of data to be sent with the message - * @param dataSize Specify how much of the data in "data" to send - */ - protected void sendMessage(int messageID, byte[] data, int dataSize) { - sendMessage(messageID, data, dataSize, CANJNI.CAN_SEND_PERIOD_NO_REPEAT); - } - - /** - * Request a message from the Jaguar, but don't wait for it to arrive. - * - * @param messageID The message to request - * @param period If positive, tell Network Communications to request the - * message every "period" milliseconds. - */ - protected void requestMessage(int messageID, int period) { - sendMessageHelper(messageID | m_deviceNumber, null, 0, period); - } - - /** - * Request a message from the Jaguar, but don't wait for it to arrive. - * - * @param messageID The message to request - */ - protected void requestMessage(int messageID) { - requestMessage(messageID, CANJNI.CAN_SEND_PERIOD_NO_REPEAT); - } - - /** - * Get a previously requested message. - * - * Jaguar always generates a message with the same message ID when replying. - * - * @param messageID The messageID to read from the CAN bus (device number is added internally) - * @param data The up to 8 bytes of data that was received with the message - * - * @throws CANMessageNotFoundException if there's not new message available - */ - protected void getMessage(int messageID, int messageMask, byte[] data) throws CANMessageNotFoundException { - messageID |= m_deviceNumber; - messageID &= CANJNI.CAN_MSGID_FULL_M; - - ByteBuffer targetedMessageID = ByteBuffer.allocateDirect(4); - targetedMessageID.order(ByteOrder.LITTLE_ENDIAN); - targetedMessageID.asIntBuffer().put(0, messageID); - - ByteBuffer timeStamp = ByteBuffer.allocateDirect(4); - - ByteBuffer status = ByteBuffer.allocateDirect(4); - status.order(ByteOrder.LITTLE_ENDIAN); - status.asIntBuffer().put(0, 0); - - // Get the data. - ByteBuffer dataBuffer = CANJNI.FRCNetworkCommunicationCANSessionMuxReceiveMessage( - targetedMessageID.asIntBuffer(), - messageMask, - timeStamp, - status.asIntBuffer()); - - if(data != null) { - for(int i = 0; i < dataBuffer.capacity(); i++) { - data[i] = dataBuffer.get(i); - } - } - - int statusCode = status.asIntBuffer().get(0); - if(statusCode < 0) { - CANExceptionFactory.checkStatus(statusCode, messageID); - } - } - - /** - * Enables periodic status updates from the Jaguar - */ - protected void setupPeriodicStatus() { - byte[] data = new byte[8]; - int dataSize; - - // Message 0 returns bus voltage, output voltage, output current, and - // temperature. - final byte[] kMessage0Data = new byte[] { - CANJNI.LM_PSTAT_VOLTBUS_B0, CANJNI.LM_PSTAT_VOLTBUS_B1, - CANJNI.LM_PSTAT_VOLTOUT_B0, CANJNI.LM_PSTAT_VOLTOUT_B1, - CANJNI.LM_PSTAT_CURRENT_B0, CANJNI.LM_PSTAT_CURRENT_B1, - CANJNI.LM_PSTAT_TEMP_B0, CANJNI.LM_PSTAT_TEMP_B1 - }; - - // Message 1 returns position and speed - final byte[] kMessage1Data = new byte[] { - CANJNI.LM_PSTAT_POS_B0, CANJNI.LM_PSTAT_POS_B1, CANJNI.LM_PSTAT_POS_B2, CANJNI.LM_PSTAT_POS_B3, - CANJNI.LM_PSTAT_SPD_B0, CANJNI.LM_PSTAT_SPD_B1, CANJNI.LM_PSTAT_SPD_B2, CANJNI.LM_PSTAT_SPD_B3 - }; - - // Message 2 returns limits and faults - final byte[] kMessage2Data = new byte[] { - CANJNI.LM_PSTAT_LIMIT_CLR, - CANJNI.LM_PSTAT_FAULT, - CANJNI.LM_PSTAT_END, - (byte)0, - (byte)0, - (byte)0, - (byte)0, - (byte)0, - }; - - dataSize = packINT16(data, (short)(kSendMessagePeriod)); - sendMessage(CANJNI.LM_API_PSTAT_PER_EN_S0, data, dataSize); - sendMessage(CANJNI.LM_API_PSTAT_PER_EN_S1, data, dataSize); - sendMessage(CANJNI.LM_API_PSTAT_PER_EN_S2, data, dataSize); - - dataSize = 8; - sendMessage(CANJNI.LM_API_PSTAT_CFG_S0, kMessage0Data, dataSize); - sendMessage(CANJNI.LM_API_PSTAT_CFG_S1, kMessage1Data, dataSize); - sendMessage(CANJNI.LM_API_PSTAT_CFG_S2, kMessage2Data, dataSize); - } - - /** - * Check for new periodic status updates and unpack them into local variables. - */ - protected void updatePeriodicStatus() { - byte[] data = new byte[8]; - int dataSize; - - // Check if a new bus voltage/output voltage/current/temperature message - // has arrived and unpack the values into the cached member variables - try { - getMessage(CANJNI.LM_API_PSTAT_DATA_S0, CANJNI.CAN_MSGID_FULL_M, data); - - m_busVoltage = unpackFXP8_8(new byte[] { data[0], data[1] }); - m_outputVoltage = unpackPercentage(new byte[] { data[2], data[3] }) * m_busVoltage; - m_outputCurrent = unpackFXP8_8(new byte[] { data[4], data[5] }); - m_temperature = unpackFXP8_8(new byte[] { data[6], data[7] }); - - m_receivedStatusMessage0 = true; - } catch(CANMessageNotFoundException e) {} - - // Check if a new position/speed message has arrived and do the same - try { - getMessage(CANJNI.LM_API_PSTAT_DATA_S1, CANJNI.CAN_MSGID_FULL_M, data); - - m_position = unpackFXP16_16(new byte[] { data[0], data[1], data[2], data[3] }); - m_speed = unpackFXP16_16(new byte[] { data[4], data[5], data[6], data[7] }); - - m_receivedStatusMessage1 = true; - } catch(CANMessageNotFoundException e) {} - - // Check if a new limits/faults message has arrived and do the same - try { - getMessage(CANJNI.LM_API_PSTAT_DATA_S2, CANJNI.CAN_MSGID_FULL_M, data); - m_limits = data[0]; - m_faults = data[1]; - - m_receivedStatusMessage2 = true; - } catch(CANMessageNotFoundException e) {} - } - - /** - * Update all the motors that have pending sets in the syncGroup. - * - * @param syncGroup A bitmask of groups to generate synchronous output. - */ - public static void updateSyncGroup(byte syncGroup) { - byte[] data = new byte[8]; - - data[0] = syncGroup; - - sendMessageHelper(CANJNI.CAN_MSGID_API_SYNC, data, 1, CANJNI.CAN_SEND_PERIOD_NO_REPEAT); - } - - /* we are on ARM-LE now, not Freescale so no need to swap */ - private final static void swap16(int x, byte[] buffer) { - buffer[0] = (byte)(x & 0xff); - buffer[1] = (byte)((x>>8) & 0xff); - } - - private final static void swap32(int x, byte[] buffer) { - buffer[0] = (byte)(x & 0xff); - buffer[1] = (byte)((x>>8) & 0xff); - buffer[2] = (byte)((x>>16) & 0xff); - buffer[3] = (byte)((x>>24) & 0xff); - } - - private static final byte packPercentage(byte[] buffer, double value) { - if(value < -1.0) value = -1.0; - if(value > 1.0) value = 1.0; - short intValue = (short) (value * 32767.0); - swap16(intValue, buffer); - return 2; - } - - private static final byte packFXP8_8(byte[] buffer, double value) { - short intValue = (short) (value * 256.0); - swap16(intValue, buffer); - return 2; - } - - private static final byte packFXP16_16(byte[] buffer, double value) { - int intValue = (int) (value * 65536.0); - swap32(intValue, buffer); - return 4; - } - - private static final byte packINT16(byte[] buffer, short value) { - swap16(value, buffer); - return 2; - } - - private static final byte packINT32(byte[] buffer, int value) { - swap32(value, buffer); - return 4; - } - - /** - * Unpack 16-bit data from a buffer in little-endian byte order - * @param buffer The buffer to unpack from - * @param offset The offset into he buffer to unpack - * @return The data that was unpacked - */ - private static final short unpack16(byte[] buffer, int offset) { - return (short) ((buffer[offset] & 0xFF) | (short) ((buffer[offset + 1] << 8)) & 0xFF00); - } - - /** - * Unpack 32-bit data from a buffer in little-endian byte order - * @param buffer The buffer to unpack from - * @param offset The offset into he buffer to unpack - * @return The data that was unpacked - */ - private static final int unpack32(byte[] buffer, int offset) { - return (buffer[offset] & 0xFF) | ((buffer[offset + 1] << 8) & 0xFF00) | - ((buffer[offset + 2] << 16) & 0xFF0000) | ((buffer[offset + 3] << 24) & 0xFF000000); - } - - private static final double unpackPercentage(byte[] buffer) { - return unpack16(buffer,0) / 32767.0; - } - - private static final double unpackFXP8_8(byte[] buffer) { - return unpack16(buffer,0) / 256.0; - } - - private static final double unpackFXP16_16(byte[] buffer) { - return unpack32(buffer,0) / 65536.0; - } - - private static final short unpackINT16(byte[] buffer) { - return unpack16(buffer,0); - } - - private static final int unpackINT32(byte[] buffer) { - return unpack32(buffer,0); - } - - /* Compare floats for equality as fixed point numbers */ - public boolean FXP8_EQ(double a, double b) { - return (int)(a * 256.0) == (int)(b * 256.0); - } - - /* Compare floats for equality as fixed point numbers */ - public boolean FXP16_EQ(double a, double b) { - return (int)(a * 65536.0) == (int)(b * 65536.0); - } - - @Override - public void setExpiration(double timeout) { - m_safetyHelper.setExpiration(timeout); - } - - @Override - public double getExpiration() { - return m_safetyHelper.getExpiration(); - } - - @Override - public boolean isAlive() { - return m_safetyHelper.isAlive(); - } - - @Override - public boolean isSafetyEnabled() { - return m_safetyHelper.isSafetyEnabled(); - } - - @Override - public void setSafetyEnabled(boolean enabled) { - m_safetyHelper.setSafetyEnabled(enabled); - } - - @Override - public String getDescription() { - return "CANJaguar ID "+m_deviceNumber; - } - - public int getDeviceID() { - return (int)m_deviceNumber; - } - - /** - * Common interface for stopping a motor. - * - * @deprecated Use disableControl instead. - */ - @Override - @Deprecated - public void stopMotor() { - disableControl(); - } - - /* - * Live Window code, only does anything if live window is activated. - */ - @Override - public String getSmartDashboardType() { - return "Speed Controller"; - } - private ITable m_table = null; - private ITableListener m_table_listener = null; - - /** - * {@inheritDoc} - */ - @Override - public void initTable(ITable subtable) { - m_table = subtable; - updateTable(); - } - - /** - * {@inheritDoc} - */ - @Override - public void updateTable() { - if (m_table != null) { - m_table.putNumber("Value", get()); - } - } - - /** - * {@inheritDoc} - */ - @Override - public ITable getTable() { - return m_table; - } - - /** - * {@inheritDoc} - */ - @Override - public void startLiveWindowMode() { - set(0); // Stop for safety - m_table_listener = new ITableListener() { - @Override - public void valueChanged(ITable itable, String key, Object value, boolean bln) { - set(((Double) value).doubleValue()); - } - }; - m_table.addTableListener("Value", m_table_listener, true); - } - - /** - * {@inheritDoc} - */ - @Override - public void stopLiveWindowMode() { - set(0); // Stop for safety - // TODO: Broken, should only remove the listener from "Value" only. - m_table.removeTableListener(m_table_listener); - } + /** + * Disable the closed loop controller. + * + * Stop driving the output based on the feedback. + */ + public void disableControl() { + // Disable all control modes. + sendMessage(CANJNI.LM_API_VOLT_DIS, new byte[0], 0); + sendMessage(CANJNI.LM_API_SPD_DIS, new byte[0], 0); + sendMessage(CANJNI.LM_API_POS_DIS, new byte[0], 0); + sendMessage(CANJNI.LM_API_ICTRL_DIS, new byte[0], 0); + sendMessage(CANJNI.LM_API_VCOMP_DIS, new byte[0], 0); + + // Stop all periodic setpoints + sendMessage(CANJNI.LM_API_VOLT_T_SET, new byte[0], 0, CANJNI.CAN_SEND_PERIOD_STOP_REPEATING); + sendMessage(CANJNI.LM_API_SPD_T_SET, new byte[0], 0, CANJNI.CAN_SEND_PERIOD_STOP_REPEATING); + sendMessage(CANJNI.LM_API_POS_T_SET, new byte[0], 0, CANJNI.CAN_SEND_PERIOD_STOP_REPEATING); + sendMessage(CANJNI.LM_API_ICTRL_T_SET, new byte[0], 0, CANJNI.CAN_SEND_PERIOD_STOP_REPEATING); + sendMessage(CANJNI.LM_API_VCOMP_T_SET, new byte[0], 0, CANJNI.CAN_SEND_PERIOD_STOP_REPEATING); + + m_controlEnabled = false; + } + + /** + * Enable controlling the motor voltage as a percentage of the bus voltage + * without any position or speed feedback.
+ * After calling this you must call {@link CANJaguar#enableControl()} or + * {@link CANJaguar#enableControl(double)} to enable the device. + */ + public void setPercentMode() { + changeControlMode(ControlMode.PercentVbus); + setPositionReference(CANJNI.LM_REF_NONE); + setSpeedReference(CANJNI.LM_REF_NONE); + } + + /** + * Enable controlling the motor voltage as a percentage of the bus voltage, + * and enable speed sensing from a non-quadrature encoder.
+ * After calling this you must call {@link CANJaguar#enableControl()} or + * {@link CANJaguar#enableControl(double)} to enable the device. + * + * @param tag The constant {@link CANJaguar#kEncoder} + * @param codesPerRev The counts per revolution on the encoder + */ + public void setPercentMode(EncoderTag tag, int codesPerRev) { + changeControlMode(ControlMode.PercentVbus); + setPositionReference(CANJNI.LM_REF_NONE); + setSpeedReference(CANJNI.LM_REF_ENCODER); + configEncoderCodesPerRev(codesPerRev); + } + + /** + * Enable controlling the motor voltage as a percentage of the bus voltage, + * and enable position and speed sensing from a quadrature encoder.
+ * After calling this you must call {@link CANJaguar#enableControl()} or + * {@link CANJaguar#enableControl(double)} to enable the device. + * + * @param tag The constant {@link CANJaguar#kQuadEncoder} + * @param codesPerRev The counts per revolution on the encoder + */ + public void setPercentMode(QuadEncoderTag tag, int codesPerRev) { + changeControlMode(ControlMode.PercentVbus); + setPositionReference(CANJNI.LM_REF_ENCODER); + setSpeedReference(CANJNI.LM_REF_QUAD_ENCODER); + configEncoderCodesPerRev(codesPerRev); + } + + /** + * Enable controlling the motor voltage as a percentage of the bus voltage, + * and enable position sensing from a potentiometer and no speed feedback.
+ * After calling this you must call {@link CANJaguar#enableControl()} or + * {@link CANJaguar#enableControl(double)} to enable the device. + * + * @param tag The constant {@link CANJaguar#kPotentiometer} + */ + public void setPercentMode(PotentiometerTag tag) { + changeControlMode(ControlMode.PercentVbus); + setPositionReference(CANJNI.LM_REF_POT); + setSpeedReference(CANJNI.LM_REF_NONE); + configPotentiometerTurns(1); + } + + /** + * Enable controlling the motor current with a PID loop.
+ * After calling this you must call {@link CANJaguar#enableControl()} or + * {@link CANJaguar#enableControl(double)} to enable the device. + * + * @param p The proportional gain of the Jaguar's PID controller. + * @param i The integral gain of the Jaguar's PID controller. + * @param d The differential gain of the Jaguar's PID controller. + */ + public void setCurrentMode(double p, double i, double d) { + changeControlMode(ControlMode.Current); + setPositionReference(CANJNI.LM_REF_NONE); + setSpeedReference(CANJNI.LM_REF_NONE); + setPID(p, i, d); + } + + /** + * Enable controlling the motor current with a PID loop, and enable speed + * sensing from a non-quadrature encoder.
+ * After calling this you must call {@link CANJaguar#enableControl()} or + * {@link CANJaguar#enableControl(double)} to enable the device. + * + * @param tag The constant {@link CANJaguar#kEncoder} + * @param p The proportional gain of the Jaguar's PID controller. + * @param i The integral gain of the Jaguar's PID controller. + * @param d The differential gain of the Jaguar's PID controller. + */ + public void setCurrentMode(EncoderTag tag, int codesPerRev, double p, double i, double d) { + changeControlMode(ControlMode.Current); + setPositionReference(CANJNI.LM_REF_NONE); + setSpeedReference(CANJNI.LM_REF_NONE); + configEncoderCodesPerRev(codesPerRev); + setPID(p, i, d); + } + + /** + * Enable controlling the motor current with a PID loop, and enable speed and + * position sensing from a quadrature encoder.
+ * After calling this you must call {@link CANJaguar#enableControl()} or + * {@link CANJaguar#enableControl(double)} to enable the device. + * + * @param tag The constant {@link CANJaguar#kQuadEncoder} + * @param p The proportional gain of the Jaguar's PID controller. + * @param i The integral gain of the Jaguar's PID controller. + * @param d The differential gain of the Jaguar's PID controller. + */ + public void setCurrentMode(QuadEncoderTag tag, int codesPerRev, double p, double i, double d) { + changeControlMode(ControlMode.Current); + setPositionReference(CANJNI.LM_REF_ENCODER); + setSpeedReference(CANJNI.LM_REF_QUAD_ENCODER); + configEncoderCodesPerRev(codesPerRev); + setPID(p, i, d); + } + + /** + * Enable controlling the motor current with a PID loop, and enable position + * sensing from a potentiometer.
+ * After calling this you must call {@link CANJaguar#enableControl()} or + * {@link CANJaguar#enableControl(double)} to enable the device. + * + * @param tag The constant {@link CANJaguar#kPotentiometer} + * @param p The proportional gain of the Jaguar's PID controller. + * @param i The integral gain of the Jaguar's PID controller. + * @param d The differential gain of the Jaguar's PID controller. + */ + public void setCurrentMode(PotentiometerTag tag, double p, double i, double d) { + changeControlMode(ControlMode.Current); + setPositionReference(CANJNI.LM_REF_POT); + setSpeedReference(CANJNI.LM_REF_NONE); + configPotentiometerTurns(1); + setPID(p, i, d); + } + + /** + * Enable controlling the speed with a feedback loop from a non-quadrature + * encoder.
+ * After calling this you must call {@link CANJaguar#enableControl()} or + * {@link CANJaguar#enableControl(double)} to enable the device. + * + * @param tag The constant {@link CANJaguar#kEncoder} + * @param codesPerRev The counts per revolution on the encoder + * @param p The proportional gain of the Jaguar's PID controller. + * @param i The integral gain of the Jaguar's PID controller. + * @param d The differential gain of the Jaguar's PID controller. + */ + public void setSpeedMode(EncoderTag tag, int codesPerRev, double p, double i, double d) { + changeControlMode(ControlMode.Speed); + setPositionReference(CANJNI.LM_REF_NONE); + setSpeedReference(CANJNI.LM_REF_ENCODER); + configEncoderCodesPerRev(codesPerRev); + setPID(p, i, d); + } + + /** + * Enable controlling the speed with a feedback loop from a quadrature + * encoder.
+ * After calling this you must call {@link CANJaguar#enableControl()} or + * {@link CANJaguar#enableControl(double)} to enable the device. + * + * @param tag The constant {@link CANJaguar#kQuadEncoder} + * @param codesPerRev The counts per revolution on the encoder + * @param p The proportional gain of the Jaguar's PID controller. + * @param i The integral gain of the Jaguar's PID controller. + * @param d The differential gain of the Jaguar's PID controller. + */ + public void setSpeedMode(QuadEncoderTag tag, int codesPerRev, double p, double i, double d) { + changeControlMode(ControlMode.Speed); + setPositionReference(CANJNI.LM_REF_ENCODER); + setSpeedReference(CANJNI.LM_REF_QUAD_ENCODER); + configEncoderCodesPerRev(codesPerRev); + setPID(p, i, d); + } + + /** + * Enable controlling the position with a feedback loop using an encoder.
+ * After calling this you must call {@link CANJaguar#enableControl()} or + * {@link CANJaguar#enableControl(double)} to enable the device. + * + * @param tag The constant {@link CANJaguar#kQuadEncoder} + * @param codesPerRev The counts per revolution on the encoder + * @param p The proportional gain of the Jaguar's PID controller. + * @param i The integral gain of the Jaguar's PID controller. + * @param d The differential gain of the Jaguar's PID controller. + * + */ + public void setPositionMode(QuadEncoderTag tag, int codesPerRev, double p, double i, double d) { + changeControlMode(ControlMode.Position); + setPositionReference(CANJNI.LM_REF_ENCODER); + configEncoderCodesPerRev(codesPerRev); + setPID(p, i, d); + } + + /** + * Enable controlling the position with a feedback loop using a potentiometer.
+ * After calling this you must call {@link CANJaguar#enableControl()} or + * {@link CANJaguar#enableControl(double)} to enable the device. + * + * @param tag The constant {@link CANJaguar#kPotentiometer} + * @param p The proportional gain of the Jaguar's PID controller. + * @param i The integral gain of the Jaguar's PID controller. + * @param d The differential gain of the Jaguar's PID controller. + */ + public void setPositionMode(PotentiometerTag tag, double p, double i, double d) { + changeControlMode(ControlMode.Position); + setPositionReference(CANJNI.LM_REF_POT); + configPotentiometerTurns(1); + setPID(p, i, d); + } + + /** + * Enable controlling the motor voltage without any position or speed + * feedback.
+ * After calling this you must call {@link CANJaguar#enableControl()} or + * {@link CANJaguar#enableControl(double)} to enable the device. + */ + public void setVoltageMode() { + changeControlMode(ControlMode.Voltage); + setPositionReference(CANJNI.LM_REF_NONE); + setSpeedReference(CANJNI.LM_REF_NONE); + } + + /** + * Enable controlling the motor voltage with speed feedback from a + * non-quadrature encoder and no position feedback.
+ * After calling this you must call {@link CANJaguar#enableControl()} or + * {@link CANJaguar#enableControl(double)} to enable the device. + * + * @param tag The constant {@link CANJaguar#kEncoder} + * @param codesPerRev The counts per revolution on the encoder + */ + public void setVoltageMode(EncoderTag tag, int codesPerRev) { + changeControlMode(ControlMode.Voltage); + setPositionReference(CANJNI.LM_REF_NONE); + setSpeedReference(CANJNI.LM_REF_ENCODER); + configEncoderCodesPerRev(codesPerRev); + } + + /** + * Enable controlling the motor voltage with position and speed feedback from + * a quadrature encoder.
+ * After calling this you must call {@link CANJaguar#enableControl()} or + * {@link CANJaguar#enableControl(double)} to enable the device. + * + * @param tag The constant {@link CANJaguar#kQuadEncoder} + * @param codesPerRev The counts per revolution on the encoder + */ + public void setVoltageMode(QuadEncoderTag tag, int codesPerRev) { + changeControlMode(ControlMode.Voltage); + setPositionReference(CANJNI.LM_REF_ENCODER); + setSpeedReference(CANJNI.LM_REF_QUAD_ENCODER); + configEncoderCodesPerRev(codesPerRev); + } + + /** + * Enable controlling the motor voltage with position feedback from a + * potentiometer and no speed feedback. + * + * @param tag The constant {@link CANJaguar#kPotentiometer} + */ + public void setVoltageMode(PotentiometerTag tag) { + changeControlMode(ControlMode.Voltage); + setPositionReference(CANJNI.LM_REF_POT); + setSpeedReference(CANJNI.LM_REF_NONE); + configPotentiometerTurns(1); + } + + /** + * Used internally. In order to set the control mode see the methods listed + * below. + * + * Change the control mode of this Jaguar object. + * + * After changing modes, configure any PID constants or other settings needed + * and then EnableControl() to actually change the mode on the Jaguar. + * + * @param controlMode The new mode. + * + * @see CANJaguar#setCurrentMode(double, double, double) + * @see CANJaguar#setCurrentMode(PotentiometerTag, double, double, double) + * @see CANJaguar#setCurrentMode(EncoderTag, int, double, double, double) + * @see CANJaguar#setCurrentMode(QuadEncoderTag, int, double, double, double) + * @see CANJaguar#setPercentMode() + * @see CANJaguar#setPercentMode(PotentiometerTag) + * @see CANJaguar#setPercentMode(EncoderTag, int) + * @see CANJaguar#setPercentMode(QuadEncoderTag, int) + * @see CANJaguar#setPositionMode(PotentiometerTag, double, double, double) + * @see CANJaguar#setPositionMode(QuadEncoderTag, int, double, double, double) + * @see CANJaguar#setSpeedMode(EncoderTag, int, double, double, double) + * @see CANJaguar#setSpeedMode(QuadEncoderTag, int, double, double, double) + * @see CANJaguar#setVoltageMode() + * @see CANJaguar#setVoltageMode(PotentiometerTag) + * @see CANJaguar#setVoltageMode(EncoderTag, int) + * @see CANJaguar#setVoltageMode(QuadEncoderTag, int) + */ + private void changeControlMode(ControlMode controlMode) { + // Disable the previous mode + disableControl(); + + // Update the local mode + m_controlMode = controlMode; + m_controlModeVerified = false; + } + + /** + * Get the active control mode from the Jaguar. + * + * Ask the Jagaur what mode it is in. + * + * @return ControlMode that the Jag is in. + */ + public ControlMode getControlMode() { + return m_controlMode; + } + + /** + * Get the voltage at the battery input terminals of the Jaguar. + * + * @return The bus voltage in Volts. + */ + public double getBusVoltage() { + updatePeriodicStatus(); + + return m_busVoltage; + } + + /** + * Get the voltage being output from the motor terminals of the Jaguar. + * + * @return The output voltage in Volts. + */ + public double getOutputVoltage() { + updatePeriodicStatus(); + + return m_outputVoltage; + } + + /** + * Get the current through the motor terminals of the Jaguar. + * + * @return The output current in Amps. + */ + public double getOutputCurrent() { + updatePeriodicStatus(); + + return m_outputCurrent; + } + + /** + * Get the internal temperature of the Jaguar. + * + * @return The temperature of the Jaguar in degrees Celsius. + */ + public double getTemperature() { + updatePeriodicStatus(); + + return m_temperature; + } + + /** + * Get the position of the encoder or potentiometer. + * + * @return The position of the motor in rotations based on the configured + * feedback. + * @see CANJaguar#configPotentiometerTurns(int) + * @see CANJaguar#configEncoderCodesPerRev(int) + */ + public double getPosition() { + updatePeriodicStatus(); + + return m_position; + } + + /** + * Get the speed of the encoder. + * + * @return The speed of the motor in RPM based on the configured feedback. + */ + public double getSpeed() { + updatePeriodicStatus(); + + return m_speed; + } + + /** + * Get the status of the forward limit switch. + * + * @return true if the motor is allowed to turn in the forward direction. + */ + public boolean getForwardLimitOK() { + updatePeriodicStatus(); + + return (m_limits & kForwardLimit) != 0; + } + + /** + * Get the status of the reverse limit switch. + * + * @return true if the motor is allowed to turn in the reverse direction. + */ + public boolean getReverseLimitOK() { + updatePeriodicStatus(); + + return (m_limits & kReverseLimit) != 0; + } + + /** + * Get the status of any faults the Jaguar has detected. + * + * @return A bit-mask of faults defined by the "Faults" constants. + * @see #kCurrentFault + * @see #kBusVoltageFault + * @see #kTemperatureFault + * @see #kGateDriverFault + */ + public short getFaults() { + updatePeriodicStatus(); + + return m_faults; + } + + /** + * set the maximum voltage change rate. + * + * When in PercentVbus or Voltage output mode, the rate at which the voltage + * changes can be limited to reduce current spikes. set this to 0.0 to disable + * rate limiting. + * + * @param rampRate The maximum rate of voltage change in Percent Voltage mode + * in V/s. + */ + public void setVoltageRampRate(double rampRate) { + byte[] data = new byte[8]; + int dataSize; + int message; + + switch (m_controlMode) { + case PercentVbus: + dataSize = packPercentage(data, rampRate / (m_maxOutputVoltage * kControllerRate)); + message = CANJNI.LM_API_VOLT_SET_RAMP; + break; + case Voltage: + dataSize = packFXP8_8(data, rampRate / kControllerRate); + message = CANJNI.LM_API_VCOMP_COMP_RAMP; + break; + default: + throw new IllegalStateException( + "Voltage ramp rate only applies in Percentage and Voltage modes"); + } + + sendMessage(message, data, dataSize); + } + + /** + * Get the version of the firmware running on the Jaguar. + * + * @return The firmware version. 0 if the device did not respond. + */ + public int getFirmwareVersion() { + return m_firmwareVersion; + } + + /** + * Get the version of the Jaguar hardware. + * + * @return The hardware version. 1: Jaguar, 2: Black Jaguar + */ + public byte getHardwareVersion() { + return m_hardwareVersion; + } + + /** + * Configure what the controller does to the H-Bridge when neutral (not + * driving the output). + * + * This allows you to override the jumper configuration for brake or coast. + * + * @param mode Select to use the jumper setting or to override it to coast or + * brake. + */ + public void configNeutralMode(NeutralMode mode) { + sendMessage(CANJNI.LM_API_CFG_BRAKE_COAST, new byte[] {mode.value}, 1); + + m_neutralMode = mode; + m_neutralModeVerified = false; + } + + /** + * Configure how many codes per revolution are generated by your encoder. + * + * @param codesPerRev The number of counts per revolution in 1X mode. + */ + public void configEncoderCodesPerRev(int codesPerRev) { + byte[] data = new byte[8]; + + int dataSize = packINT16(data, (short) codesPerRev); + sendMessage(CANJNI.LM_API_CFG_ENC_LINES, data, dataSize); + + m_encoderCodesPerRev = (short) codesPerRev; + m_encoderCodesPerRevVerified = false; + } + + /** + * Configure the number of turns on the potentiometer. + * + * There is no special support for continuous turn potentiometers. Only + * integer numbers of turns are supported. + * + * @param turns The number of turns of the potentiometer + */ + public void configPotentiometerTurns(int turns) { + byte[] data = new byte[8]; + + int dataSize = packINT16(data, (short) turns); + sendMessage(CANJNI.LM_API_CFG_POT_TURNS, data, dataSize); + + m_potentiometerTurns = (short) turns; + m_potentiometerTurnsVerified = false; + } + + /** + * Configure Soft Position Limits when in Position Controller mode.
+ * + * When controlling position, you can add additional limits on top of the + * limit switch inputs that are based on the position feedback. If the + * position limit is reached or the switch is opened, that direction will be + * disabled. + * + * @param forwardLimitPosition The position that, if exceeded, will disable + * the forward direction. + * @param reverseLimitPosition The position that, if exceeded, will disable + * the reverse direction. + */ + public void configSoftPositionLimits(double forwardLimitPosition, double reverseLimitPosition) { + configLimitMode(LimitMode.SoftPositionLimits); + configForwardLimit(forwardLimitPosition); + configReverseLimit(reverseLimitPosition); + } + + /** + * Disable Soft Position Limits if previously enabled.
+ * + * Soft Position Limits are disabled by default. + */ + public void disableSoftPositionLimits() { + configLimitMode(LimitMode.SwitchInputsOnly); + } + + /** + * Set the limit mode for position control mode.
+ * + * Use {@link #configSoftPositionLimits(double, double)} or + * {@link #disableSoftPositionLimits()} to set this automatically. + *$ + * @param mode The {@link LimitMode} to use to limit the rotation of the + * device. + * @see LimitMode#SwitchInputsOnly + * @see LimitMode#SoftPositionLimits + */ + public void configLimitMode(LimitMode mode) { + sendMessage(CANJNI.LM_API_CFG_LIMIT_MODE, new byte[] {mode.value}, 1); + } + + /** + * Set the position that, if exceeded, will disable the forward direction. + * + * Use {@link #configSoftPositionLimits(double, double)} to set this and the + * {@link LimitMode} automatically. + *$ + * @param forwardLimitPosition The position that, if exceeded, will disable + * the forward direction. + */ + public void configForwardLimit(double forwardLimitPosition) { + byte[] data = new byte[8]; + + int dataSize = packFXP16_16(data, forwardLimitPosition); + data[dataSize++] = 1; + sendMessage(CANJNI.LM_API_CFG_LIMIT_FWD, data, dataSize); + + m_forwardLimit = forwardLimitPosition; + m_forwardLimitVerified = false; + } + + /** + * Set the position that, if exceeded, will disable the reverse direction. + * + * Use {@link #configSoftPositionLimits(double, double)} to set this and the + * {@link LimitMode} automatically. + *$ + * @param reverseLimitPosition The position that, if exceeded, will disable + * the reverse direction. + */ + public void configReverseLimit(double reverseLimitPosition) { + byte[] data = new byte[8]; + + int dataSize = packFXP16_16(data, reverseLimitPosition); + data[dataSize++] = 1; + sendMessage(CANJNI.LM_API_CFG_LIMIT_REV, data, dataSize); + + m_reverseLimit = reverseLimitPosition; + m_reverseLimitVerified = false; + } + + /** + * Configure the maximum voltage that the Jaguar will ever output. + * + * This can be used to limit the maximum output voltage in all modes so that + * motors which cannot withstand full bus voltage can be used safely. + * + * @param voltage The maximum voltage output by the Jaguar. + */ + public void configMaxOutputVoltage(double voltage) { + byte[] data = new byte[8]; + + int dataSize = packFXP8_8(data, voltage); + sendMessage(CANJNI.LM_API_CFG_MAX_VOUT, data, dataSize); + + m_maxOutputVoltage = voltage; + m_maxOutputVoltageVerified = false; + } + + /** + * Configure how long the Jaguar waits in the case of a fault before resuming + * operation. + * + * Faults include over temerature, over current, and bus under voltage. The + * default is 3.0 seconds, but can be reduced to as low as 0.5 seconds. + * + * @param faultTime The time to wait before resuming operation, in seconds. + */ + public void configFaultTime(float faultTime) { + byte[] data = new byte[8]; + + if (faultTime < 0.5f) + faultTime = 0.5f; + else if (faultTime > 3.0f) + faultTime = 3.0f; + + int dataSize = packINT16(data, (short) (faultTime * 1000.0)); + sendMessage(CANJNI.LM_API_CFG_FAULT_TIME, data, dataSize); + + m_faultTime = faultTime; + m_faultTimeVerified = false; + } + + byte m_deviceNumber; + double m_value = 0.0f; + + // Parameters/configuration + ControlMode m_controlMode; + int m_speedReference = CANJNI.LM_REF_NONE; + int m_positionReference = CANJNI.LM_REF_NONE; + double m_p = 0.0; + double m_i = 0.0; + double m_d = 0.0; + NeutralMode m_neutralMode = NeutralMode.Jumper; + short m_encoderCodesPerRev = 0; + short m_potentiometerTurns = 0; + LimitMode m_limitMode = LimitMode.SwitchInputsOnly; + double m_forwardLimit = 0.0; + double m_reverseLimit = 0.0; + double m_maxOutputVoltage = kApproxBusVoltage; + double m_voltageRampRate = 0.0; + float m_faultTime = 0.0f; + + // Which parameters have been verified since they were last set? + boolean m_controlModeVerified = true; + boolean m_speedRefVerified = true; + boolean m_posRefVerified = true; + boolean m_pVerified = true; + boolean m_iVerified = true; + boolean m_dVerified = true; + boolean m_neutralModeVerified = true; + boolean m_encoderCodesPerRevVerified = true; + boolean m_potentiometerTurnsVerified = true; + boolean m_forwardLimitVerified = true; + boolean m_reverseLimitVerified = true; + boolean m_limitModeVerified = true; + boolean m_maxOutputVoltageVerified = true; + boolean m_voltageRampRateVerified = true; + boolean m_faultTimeVerified = true; + + // Status data + double m_busVoltage = 0.0f; + double m_outputVoltage = 0.0f; + double m_outputCurrent = 0.0f; + double m_temperature = 0.0f; + double m_position = 0.0; + double m_speed = 0.0; + byte m_limits = (byte) 0; + short m_faults = (short) 0; + int m_firmwareVersion = 0; + byte m_hardwareVersion = (byte) 0; + + // Which periodic status messages have we received at least once? + boolean m_receivedStatusMessage0 = false; + boolean m_receivedStatusMessage1 = false; + boolean m_receivedStatusMessage2 = false; + + static final int kReceiveStatusAttempts = 50; + + boolean m_controlEnabled = true; + + static void sendMessageHelper(int messageID, byte[] data, int dataSize, int period) + throws CANMessageNotFoundException { + final int[] kTrustedMessages = + {CANJNI.LM_API_VOLT_T_EN, CANJNI.LM_API_VOLT_T_SET, CANJNI.LM_API_SPD_T_EN, + CANJNI.LM_API_SPD_T_SET, CANJNI.LM_API_VCOMP_T_EN, CANJNI.LM_API_VCOMP_T_SET, + CANJNI.LM_API_POS_T_EN, CANJNI.LM_API_POS_T_SET, CANJNI.LM_API_ICTRL_T_EN, + CANJNI.LM_API_ICTRL_T_SET}; + + ByteBuffer status = ByteBuffer.allocateDirect(4); + status.order(ByteOrder.LITTLE_ENDIAN); + status.asIntBuffer().put(0, 0); + + for (byte i = 0; i < kTrustedMessages.length; i++) { + if ((kFullMessageIDMask & messageID) == kTrustedMessages[i]) { + // Make sure the data will still fit after adjusting for the token. + if (dataSize > kMaxMessageDataSize - 2) { + throw new RuntimeException("CAN message has too much data."); + } + + ByteBuffer trustedBuffer = ByteBuffer.allocateDirect(dataSize + 2); + trustedBuffer.put(0, (byte) 0); + trustedBuffer.put(1, (byte) 0); + + for (byte j = 0; j < dataSize; j++) { + trustedBuffer.put(j + 2, data[j]); + } + + CANJNI.FRCNetworkCommunicationCANSessionMuxSendMessage(messageID, trustedBuffer, period, + status.asIntBuffer()); + int statusCode = status.asIntBuffer().get(0); + if (statusCode < 0) { + CANExceptionFactory.checkStatus(statusCode, messageID); + } + + return; + } + } + + // Use a null pointer for the data buffer if the given array is null + ByteBuffer buffer; + if (data != null) { + buffer = ByteBuffer.allocateDirect(dataSize); + for (byte i = 0; i < dataSize; i++) { + buffer.put(i, data[i]); + } + } else { + buffer = null; + } + + CANJNI.FRCNetworkCommunicationCANSessionMuxSendMessage(messageID, buffer, period, + status.asIntBuffer()); + + int statusCode = status.asIntBuffer().get(0); + if (statusCode < 0) { + CANExceptionFactory.checkStatus(statusCode, messageID); + } + } + + /** + * Send a message to the Jaguar. + * + * @param messageID The messageID to be used on the CAN bus (device number is + * added internally) + * @param data The up to 8 bytes of data to be sent with the message + * @param dataSize Specify how much of the data in "data" to send + * @param period If positive, tell Network Communications to send the message + * every "period" milliseconds. + */ + protected void sendMessage(int messageID, byte[] data, int dataSize, int period) { + sendMessageHelper(messageID | m_deviceNumber, data, dataSize, period); + } + + /** + * Send a message to the Jaguar, non-periodically + * + * @param messageID The messageID to be used on the CAN bus (device number is + * added internally) + * @param data The up to 8 bytes of data to be sent with the message + * @param dataSize Specify how much of the data in "data" to send + */ + protected void sendMessage(int messageID, byte[] data, int dataSize) { + sendMessage(messageID, data, dataSize, CANJNI.CAN_SEND_PERIOD_NO_REPEAT); + } + + /** + * Request a message from the Jaguar, but don't wait for it to arrive. + * + * @param messageID The message to request + * @param period If positive, tell Network Communications to request the + * message every "period" milliseconds. + */ + protected void requestMessage(int messageID, int period) { + sendMessageHelper(messageID | m_deviceNumber, null, 0, period); + } + + /** + * Request a message from the Jaguar, but don't wait for it to arrive. + * + * @param messageID The message to request + */ + protected void requestMessage(int messageID) { + requestMessage(messageID, CANJNI.CAN_SEND_PERIOD_NO_REPEAT); + } + + /** + * Get a previously requested message. + * + * Jaguar always generates a message with the same message ID when replying. + * + * @param messageID The messageID to read from the CAN bus (device number is + * added internally) + * @param data The up to 8 bytes of data that was received with the message + * + * @throws CANMessageNotFoundException if there's not new message available + */ + protected void getMessage(int messageID, int messageMask, byte[] data) + throws CANMessageNotFoundException { + messageID |= m_deviceNumber; + messageID &= CANJNI.CAN_MSGID_FULL_M; + + ByteBuffer targetedMessageID = ByteBuffer.allocateDirect(4); + targetedMessageID.order(ByteOrder.LITTLE_ENDIAN); + targetedMessageID.asIntBuffer().put(0, messageID); + + ByteBuffer timeStamp = ByteBuffer.allocateDirect(4); + + ByteBuffer status = ByteBuffer.allocateDirect(4); + status.order(ByteOrder.LITTLE_ENDIAN); + status.asIntBuffer().put(0, 0); + + // Get the data. + ByteBuffer dataBuffer = + CANJNI.FRCNetworkCommunicationCANSessionMuxReceiveMessage(targetedMessageID.asIntBuffer(), + messageMask, timeStamp, status.asIntBuffer()); + + if (data != null) { + for (int i = 0; i < dataBuffer.capacity(); i++) { + data[i] = dataBuffer.get(i); + } + } + + int statusCode = status.asIntBuffer().get(0); + if (statusCode < 0) { + CANExceptionFactory.checkStatus(statusCode, messageID); + } + } + + /** + * Enables periodic status updates from the Jaguar + */ + protected void setupPeriodicStatus() { + byte[] data = new byte[8]; + int dataSize; + + // Message 0 returns bus voltage, output voltage, output current, and + // temperature. + final byte[] kMessage0Data = + new byte[] {CANJNI.LM_PSTAT_VOLTBUS_B0, CANJNI.LM_PSTAT_VOLTBUS_B1, + CANJNI.LM_PSTAT_VOLTOUT_B0, CANJNI.LM_PSTAT_VOLTOUT_B1, CANJNI.LM_PSTAT_CURRENT_B0, + CANJNI.LM_PSTAT_CURRENT_B1, CANJNI.LM_PSTAT_TEMP_B0, CANJNI.LM_PSTAT_TEMP_B1}; + + // Message 1 returns position and speed + final byte[] kMessage1Data = + new byte[] {CANJNI.LM_PSTAT_POS_B0, CANJNI.LM_PSTAT_POS_B1, CANJNI.LM_PSTAT_POS_B2, + CANJNI.LM_PSTAT_POS_B3, CANJNI.LM_PSTAT_SPD_B0, CANJNI.LM_PSTAT_SPD_B1, + CANJNI.LM_PSTAT_SPD_B2, CANJNI.LM_PSTAT_SPD_B3}; + + // Message 2 returns limits and faults + final byte[] kMessage2Data = + new byte[] {CANJNI.LM_PSTAT_LIMIT_CLR, CANJNI.LM_PSTAT_FAULT, CANJNI.LM_PSTAT_END, + (byte) 0, (byte) 0, (byte) 0, (byte) 0, (byte) 0,}; + + dataSize = packINT16(data, (short) (kSendMessagePeriod)); + sendMessage(CANJNI.LM_API_PSTAT_PER_EN_S0, data, dataSize); + sendMessage(CANJNI.LM_API_PSTAT_PER_EN_S1, data, dataSize); + sendMessage(CANJNI.LM_API_PSTAT_PER_EN_S2, data, dataSize); + + dataSize = 8; + sendMessage(CANJNI.LM_API_PSTAT_CFG_S0, kMessage0Data, dataSize); + sendMessage(CANJNI.LM_API_PSTAT_CFG_S1, kMessage1Data, dataSize); + sendMessage(CANJNI.LM_API_PSTAT_CFG_S2, kMessage2Data, dataSize); + } + + /** + * Check for new periodic status updates and unpack them into local variables. + */ + protected void updatePeriodicStatus() { + byte[] data = new byte[8]; + int dataSize; + + // Check if a new bus voltage/output voltage/current/temperature message + // has arrived and unpack the values into the cached member variables + try { + getMessage(CANJNI.LM_API_PSTAT_DATA_S0, CANJNI.CAN_MSGID_FULL_M, data); + + m_busVoltage = unpackFXP8_8(new byte[] {data[0], data[1]}); + m_outputVoltage = unpackPercentage(new byte[] {data[2], data[3]}) * m_busVoltage; + m_outputCurrent = unpackFXP8_8(new byte[] {data[4], data[5]}); + m_temperature = unpackFXP8_8(new byte[] {data[6], data[7]}); + + m_receivedStatusMessage0 = true; + } catch (CANMessageNotFoundException e) { + } + + // Check if a new position/speed message has arrived and do the same + try { + getMessage(CANJNI.LM_API_PSTAT_DATA_S1, CANJNI.CAN_MSGID_FULL_M, data); + + m_position = unpackFXP16_16(new byte[] {data[0], data[1], data[2], data[3]}); + m_speed = unpackFXP16_16(new byte[] {data[4], data[5], data[6], data[7]}); + + m_receivedStatusMessage1 = true; + } catch (CANMessageNotFoundException e) { + } + + // Check if a new limits/faults message has arrived and do the same + try { + getMessage(CANJNI.LM_API_PSTAT_DATA_S2, CANJNI.CAN_MSGID_FULL_M, data); + m_limits = data[0]; + m_faults = data[1]; + + m_receivedStatusMessage2 = true; + } catch (CANMessageNotFoundException e) { + } + } + + /** + * Update all the motors that have pending sets in the syncGroup. + * + * @param syncGroup A bitmask of groups to generate synchronous output. + */ + public static void updateSyncGroup(byte syncGroup) { + byte[] data = new byte[8]; + + data[0] = syncGroup; + + sendMessageHelper(CANJNI.CAN_MSGID_API_SYNC, data, 1, CANJNI.CAN_SEND_PERIOD_NO_REPEAT); + } + + /* we are on ARM-LE now, not Freescale so no need to swap */ + private final static void swap16(int x, byte[] buffer) { + buffer[0] = (byte) (x & 0xff); + buffer[1] = (byte) ((x >> 8) & 0xff); + } + + private final static void swap32(int x, byte[] buffer) { + buffer[0] = (byte) (x & 0xff); + buffer[1] = (byte) ((x >> 8) & 0xff); + buffer[2] = (byte) ((x >> 16) & 0xff); + buffer[3] = (byte) ((x >> 24) & 0xff); + } + + private static final byte packPercentage(byte[] buffer, double value) { + if (value < -1.0) + value = -1.0; + if (value > 1.0) + value = 1.0; + short intValue = (short) (value * 32767.0); + swap16(intValue, buffer); + return 2; + } + + private static final byte packFXP8_8(byte[] buffer, double value) { + short intValue = (short) (value * 256.0); + swap16(intValue, buffer); + return 2; + } + + private static final byte packFXP16_16(byte[] buffer, double value) { + int intValue = (int) (value * 65536.0); + swap32(intValue, buffer); + return 4; + } + + private static final byte packINT16(byte[] buffer, short value) { + swap16(value, buffer); + return 2; + } + + private static final byte packINT32(byte[] buffer, int value) { + swap32(value, buffer); + return 4; + } + + /** + * Unpack 16-bit data from a buffer in little-endian byte order + *$ + * @param buffer The buffer to unpack from + * @param offset The offset into he buffer to unpack + * @return The data that was unpacked + */ + private static final short unpack16(byte[] buffer, int offset) { + return (short) ((buffer[offset] & 0xFF) | (short) ((buffer[offset + 1] << 8)) & 0xFF00); + } + + /** + * Unpack 32-bit data from a buffer in little-endian byte order + *$ + * @param buffer The buffer to unpack from + * @param offset The offset into he buffer to unpack + * @return The data that was unpacked + */ + private static final int unpack32(byte[] buffer, int offset) { + return (buffer[offset] & 0xFF) | ((buffer[offset + 1] << 8) & 0xFF00) + | ((buffer[offset + 2] << 16) & 0xFF0000) | ((buffer[offset + 3] << 24) & 0xFF000000); + } + + private static final double unpackPercentage(byte[] buffer) { + return unpack16(buffer, 0) / 32767.0; + } + + private static final double unpackFXP8_8(byte[] buffer) { + return unpack16(buffer, 0) / 256.0; + } + + private static final double unpackFXP16_16(byte[] buffer) { + return unpack32(buffer, 0) / 65536.0; + } + + private static final short unpackINT16(byte[] buffer) { + return unpack16(buffer, 0); + } + + private static final int unpackINT32(byte[] buffer) { + return unpack32(buffer, 0); + } + + /* Compare floats for equality as fixed point numbers */ + public boolean FXP8_EQ(double a, double b) { + return (int) (a * 256.0) == (int) (b * 256.0); + } + + /* Compare floats for equality as fixed point numbers */ + public boolean FXP16_EQ(double a, double b) { + return (int) (a * 65536.0) == (int) (b * 65536.0); + } + + @Override + public void setExpiration(double timeout) { + m_safetyHelper.setExpiration(timeout); + } + + @Override + public double getExpiration() { + return m_safetyHelper.getExpiration(); + } + + @Override + public boolean isAlive() { + return m_safetyHelper.isAlive(); + } + + @Override + public boolean isSafetyEnabled() { + return m_safetyHelper.isSafetyEnabled(); + } + + @Override + public void setSafetyEnabled(boolean enabled) { + m_safetyHelper.setSafetyEnabled(enabled); + } + + @Override + public String getDescription() { + return "CANJaguar ID " + m_deviceNumber; + } + + public int getDeviceID() { + return (int) m_deviceNumber; + } + + /** + * Common interface for stopping a motor. + * + * @deprecated Use disableControl instead. + */ + @Override + @Deprecated + public void stopMotor() { + disableControl(); + } + + /* + * Live Window code, only does anything if live window is activated. + */ + @Override + public String getSmartDashboardType() { + return "Speed Controller"; + } + + private ITable m_table = null; + private ITableListener m_table_listener = null; + + /** + * {@inheritDoc} + */ + @Override + public void initTable(ITable subtable) { + m_table = subtable; + updateTable(); + } + + /** + * {@inheritDoc} + */ + @Override + public void updateTable() { + if (m_table != null) { + m_table.putNumber("Value", get()); + } + } + + /** + * {@inheritDoc} + */ + @Override + public ITable getTable() { + return m_table; + } + + /** + * {@inheritDoc} + */ + @Override + public void startLiveWindowMode() { + set(0); // Stop for safety + m_table_listener = new ITableListener() { + @Override + public void valueChanged(ITable itable, String key, Object value, boolean bln) { + set(((Double) value).doubleValue()); + } + }; + m_table.addTableListener("Value", m_table_listener, true); + } + + /** + * {@inheritDoc} + */ + @Override + public void stopLiveWindowMode() { + set(0); // Stop for safety + // TODO: Broken, should only remove the listener from "Value" only. + m_table.removeTableListener(m_table_listener); + } } diff --git a/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/CANSpeedController.java b/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/CANSpeedController.java index 09ecca4a65..2b6856738e 100644 --- a/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/CANSpeedController.java +++ b/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/CANSpeedController.java @@ -1,35 +1,31 @@ package edu.wpi.first.wpilibj; public interface CANSpeedController extends SpeedController { - /** - * Mode determines how the motor is controlled, used internally. - * - * Note that the Jaguar does not support follower mode. - */ - public enum ControlMode { - PercentVbus((byte)0), - Current((byte)1), - Speed((byte)2), - Position((byte)3), - Voltage((byte)4), - Follower((byte)5); // Not supported by Jaguar. + /** + * Mode determines how the motor is controlled, used internally. + * + * Note that the Jaguar does not support follower mode. + */ + public enum ControlMode { + PercentVbus((byte) 0), Current((byte) 1), Speed((byte) 2), Position((byte) 3), Voltage((byte) 4), Follower( + (byte) 5); // Not supported by Jaguar. - public byte value; + public byte value; - public static ControlMode valueOf(byte value) { - for(ControlMode mode : values()) { - if(mode.value == value) { - return mode; - } - } + public static ControlMode valueOf(byte value) { + for (ControlMode mode : values()) { + if (mode.value == value) { + return mode; + } + } - return null; - } + return null; + } - private ControlMode(byte value) { - this.value = value; - } - } + private ControlMode(byte value) { + this.value = value; + } + } /** * Return the current setpoint. @@ -97,7 +93,7 @@ public interface CANSpeedController extends SpeedController { * Return the current position of whatever the current selected sensor is. * * See specific implementations for more information on selecting feedback - * sensors. + * sensors. * * @return the current sensor position. */ @@ -107,7 +103,7 @@ public interface CANSpeedController extends SpeedController { * Return the current velocity of whatever the current selected sensor is. * * See specific implementations for more information on selecting feedback - * sensors. + * sensors. * * @return the current sensor velocity. */ diff --git a/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/CANTalon.java b/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/CANTalon.java index 0806e1eb7a..aa5bd56c59 100644 --- a/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/CANTalon.java +++ b/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/CANTalon.java @@ -12,59 +12,64 @@ import edu.wpi.first.wpilibj.livewindow.LiveWindowSendable; import edu.wpi.first.wpilibj.tables.ITable; import edu.wpi.first.wpilibj.tables.ITableListener; -public class CANTalon implements MotorSafety, PIDOutput, PIDSource, PIDInterface, CANSpeedController, LiveWindowSendable { - private MotorSafetyHelper m_safetyHelper; +public class CANTalon implements MotorSafety, PIDOutput, PIDSource, PIDInterface, + CANSpeedController, LiveWindowSendable { + private MotorSafetyHelper m_safetyHelper; private boolean isInverted = false; - public enum TalonControlMode { - PercentVbus(0), Follower(5), Voltage(4), Position(1), Speed(2), Current(3), Disabled(15); + + public enum TalonControlMode { + PercentVbus(0), Follower(5), Voltage(4), Position(1), Speed(2), Current(3), Disabled(15); public int value; - public static TalonControlMode valueOf(int value) { - for(TalonControlMode mode : values()) { - if(mode.value == value) { - return mode; - } - } - return null; + public static TalonControlMode valueOf(int value) { + for (TalonControlMode mode : values()) { + if (mode.value == value) { + return mode; + } + } + + return null; } private TalonControlMode(int value) { this.value = value; } - } + } public enum FeedbackDevice { - QuadEncoder(0), AnalogPot(2), AnalogEncoder(3), EncRising(4), EncFalling(5); + QuadEncoder(0), AnalogPot(2), AnalogEncoder(3), EncRising(4), EncFalling(5); public int value; public static FeedbackDevice valueOf(int value) { - for(FeedbackDevice mode : values()) { - if(mode.value == value) { - return mode; - } - } + for (FeedbackDevice mode : values()) { + if (mode.value == value) { + return mode; + } + } - return null; + return null; } private FeedbackDevice(int value) { this.value = value; } - } + } /** enumerated types for frame rate ms */ public enum StatusFrameRate { - General(0), Feedback(1), QuadEncoder(2), AnalogTempVbat(3); + General(0), Feedback(1), QuadEncoder(2), AnalogTempVbat(3); public int value; + public static StatusFrameRate valueOf(int value) { - for(StatusFrameRate mode : values()) { - if(mode.value == value) { - return mode; - } - } - return null; + for (StatusFrameRate mode : values()) { + if (mode.value == value) { + return mode; + } + } + return null; } + private StatusFrameRate(int value) { this.value = value; } @@ -94,9 +99,13 @@ public class CANTalon implements MotorSafety, PIDOutput, PIDSource, PIDInterface applyControlMode(TalonControlMode.PercentVbus); } - public CANTalon(int deviceNumber,int controlPeriodMs) { + public CANTalon(int deviceNumber, int controlPeriodMs) { m_deviceNumber = deviceNumber; - m_impl = new CanTalonSRX(deviceNumber,controlPeriodMs); /* bound period to be within [1 ms,95 ms] */ + m_impl = new CanTalonSRX(deviceNumber, controlPeriodMs); /* + * bound period to + * be within [1 + * ms,95 ms] + */ m_safetyHelper = new MotorSafetyHelper(this); m_controlEnabled = true; m_profile = 0; @@ -106,13 +115,11 @@ public class CANTalon implements MotorSafety, PIDOutput, PIDSource, PIDInterface } @Override - public void pidWrite(double output) - { + public void pidWrite(double output) { if (getControlMode() == TalonControlMode.PercentVbus) { set(output); - } - else { - throw new IllegalStateException("PID only supported in PercentVbus mode"); + } else { + throw new IllegalStateException("PID only supported in PercentVbus mode"); } } @@ -128,13 +135,12 @@ public class CANTalon implements MotorSafety, PIDOutput, PIDSource, PIDInterface /** * Sets the appropriate output on the talon, depending on the mode. * - * In PercentVbus, the output is between -1.0 and 1.0, with 0.0 as stopped. - * In Follower mode, the output is the integer device ID of the talon to duplicate. - * In Voltage mode, outputValue is in volts. - * In Current mode, outputValue is in amperes. - * In Speed mode, outputValue is in position change / 10ms. - * In Position mode, outputValue is in encoder ticks or an analog value, - * depending on the sensor. + * In PercentVbus, the output is between -1.0 and 1.0, with 0.0 as stopped. In + * Follower mode, the output is the integer device ID of the talon to + * duplicate. In Voltage mode, outputValue is in volts. In Current mode, + * outputValue is in amperes. In Speed mode, outputValue is in position change + * / 10ms. In Position mode, outputValue is in encoder ticks or an analog + * value, depending on the sensor. * * @param outputValue The setpoint value, as described above. */ @@ -145,21 +151,21 @@ public class CANTalon implements MotorSafety, PIDOutput, PIDSource, PIDInterface m_setPoint = outputValue; switch (m_controlMode) { case PercentVbus: - m_impl.Set(isInverted ? -outputValue: outputValue); + m_impl.Set(isInverted ? -outputValue : outputValue); break; case Follower: - m_impl.SetDemand((int)outputValue); + m_impl.SetDemand((int) outputValue); break; case Voltage: // Voltage is an 8.8 fixed point number. - int volts = (int)((isInverted ? -outputValue: outputValue) * 256); + int volts = (int) ((isInverted ? -outputValue : outputValue) * 256); m_impl.SetDemand(volts); break; case Speed: - m_impl.SetDemand((int)(isInverted ? -outputValue: outputValue)); + m_impl.SetDemand((int) (isInverted ? -outputValue : outputValue)); break; case Position: - m_impl.SetDemand((int)outputValue); + m_impl.SetDemand((int) outputValue); break; default: break; @@ -168,33 +174,34 @@ public class CANTalon implements MotorSafety, PIDOutput, PIDSource, PIDInterface } } - /** - * Inverts the direction of the motor's rotation. - * Only works in PercentVbus mode. - * - * @param isInverted The state of inversion, true is inverted. - */ - @Override - public void setInverted(boolean isInverted) { - this.isInverted = isInverted; - } - - /** - * Common interface for the inverting direction of a speed controller. - * - * @return isInverted The state of inversion, true is inverted. - * - */ - @Override - public boolean getInverted() { - return this.isInverted; - } + /** + * Inverts the direction of the motor's rotation. Only works in PercentVbus + * mode. + * + * @param isInverted The state of inversion, true is inverted. + */ + @Override + public void setInverted(boolean isInverted) { + this.isInverted = isInverted; + } - /** + /** + * Common interface for the inverting direction of a speed controller. + * + * @return isInverted The state of inversion, true is inverted. + * + */ + @Override + public boolean getInverted() { + return this.isInverted; + } + + /** * Sets the output of the Talon. * * @param outputValue See set(). - * @param thisValueDoesNotDoAnything corresponds to syncGroup from Jaguar; not relevant here. + * @param thisValueDoesNotDoAnything corresponds to syncGroup from Jaguar; not + * relevant here. */ @Override public void set(double outputValue, byte thisValueDoesNotDoAnything) { @@ -228,20 +235,24 @@ public class CANTalon implements MotorSafety, PIDOutput, PIDSource, PIDInterface * @return The error in units corresponding to whichever mode we are in. * @see #set(double) set() for a detailed description of the various units. */ - public double getError() {return getClosedLoopError();} + public double getError() { + return getClosedLoopError(); + } /** * Calls {@link #set(double)}. */ - public void setSetpoint(double setpoint) { set(setpoint); } + public void setSetpoint(double setpoint) { + set(setpoint); + } /** * Flips the sign (multiplies by negative one) the sensor values going into - *the talon. + * the talon. * * This only affects position and velocity closed loop control. Allows for - * situations where you may have a sensor flipped and going in the wrong - * direction. + * situations where you may have a sensor flipped and going in the wrong + * direction. * * @param flip True if sensor input should be flipped; False if not. */ @@ -249,12 +260,12 @@ public class CANTalon implements MotorSafety, PIDOutput, PIDSource, PIDInterface m_impl.SetRevFeedbackSensor(flip ? 1 : 0); } - /** - * Flips the sign (multiplies by negative one) the throttle values going into - * the motor on the talon in closed loop modes. - * - * @param flip True if motor output should be flipped; False if not. - */ + /** + * Flips the sign (multiplies by negative one) the throttle values going into + * the motor on the talon in closed loop modes. + * + * @param flip True if motor output should be flipped; False if not. + */ public void reverseOutput(boolean flip) { m_impl.SetRevMotDuringCloseLoopEn(flip ? 1 : 0); } @@ -262,10 +273,9 @@ public class CANTalon implements MotorSafety, PIDOutput, PIDSource, PIDInterface /** * Gets the current status of the Talon (usually a sensor value). * - * In Current mode: returns output current. - * In Speed mode: returns current speed. - * In Position mode: returns current sensor position. - * In PercentVbus and Follower modes: returns current applied throttle. + * In Current mode: returns output current. In Speed mode: returns current + * speed. In Position mode: returns current sensor position. In PercentVbus + * and Follower modes: returns current applied throttle. * * @return The current sensor value of the Talon. */ @@ -279,19 +289,20 @@ public class CANTalon implements MotorSafety, PIDOutput, PIDSource, PIDInterface return getOutputCurrent(); case Speed: m_impl.GetSensorVelocity(swigp); - return (double)CanTalonJNI.intp_value(valuep); + return (double) CanTalonJNI.intp_value(valuep); case Position: m_impl.GetSensorPosition(swigp); - return (double)CanTalonJNI.intp_value(valuep); + return (double) CanTalonJNI.intp_value(valuep); case PercentVbus: default: m_impl.GetAppliedThrottle(swigp); - return (double)CanTalonJNI.intp_value(valuep) / 1023.0; + return (double) CanTalonJNI.intp_value(valuep) / 1023.0; } } /** - * Get the current encoder position, regardless of whether it is the current feedback device. + * Get the current encoder position, regardless of whether it is the current + * feedback device. * * @return The current position of the encoder. */ @@ -303,7 +314,8 @@ public class CANTalon implements MotorSafety, PIDOutput, PIDSource, PIDInterface } /** - * Get the current encoder velocity, regardless of whether it is the current feedback device. + * Get the current encoder velocity, regardless of whether it is the current + * feedback device. * * @return The current speed of the encoder. */ @@ -325,15 +337,17 @@ public class CANTalon implements MotorSafety, PIDOutput, PIDSource, PIDInterface m_impl.GetEncIndexRiseEvents(swigp); return CanTalonJNI.intp_value(valuep); } + /** * @return IO level of QUADA pin. */ - public int getPinStateQuadA(){ + public int getPinStateQuadA() { long valuep = CanTalonJNI.new_intp(); SWIGTYPE_p_int swigp = new SWIGTYPE_p_int(valuep, true); m_impl.GetQuadApin(swigp); return CanTalonJNI.intp_value(valuep); } + /** * @return IO level of QUADB pin. */ @@ -343,10 +357,11 @@ public class CANTalon implements MotorSafety, PIDOutput, PIDSource, PIDInterface m_impl.GetQuadBpin(swigp); return CanTalonJNI.intp_value(valuep); } + /** * @return IO level of QUAD Index pin. */ - public int getPinStateQuadIdx(){ + public int getPinStateQuadIdx() { long valuep = CanTalonJNI.new_intp(); SWIGTYPE_p_int swigp = new SWIGTYPE_p_int(valuep, true); m_impl.GetQuadIdxpin(swigp); @@ -357,9 +372,9 @@ public class CANTalon implements MotorSafety, PIDOutput, PIDSource, PIDInterface * Get the current analog in position, regardless of whether it is the current * feedback device. * - * @return The 24bit analog position. The bottom ten bits is the ADC (0 - 1023) on - * the analog pin of the Talon. The upper 14 bits - * tracks the overflows and underflows (continuous sensor). + * @return The 24bit analog position. The bottom ten bits is the ADC (0 - + * 1023) on the analog pin of the Talon. The upper 14 bits tracks the + * overflows and underflows (continuous sensor). */ public int getAnalogInPosition() { long valuep = CanTalonJNI.new_intp(); @@ -367,14 +382,17 @@ public class CANTalon implements MotorSafety, PIDOutput, PIDSource, PIDInterface m_impl.GetAnalogInWithOv(swigp); return CanTalonJNI.intp_value(valuep); } + /** * Get the current analog in position, regardless of whether it is the current * feedback device. + *$ * @return The ADC (0 - 1023) on analog pin of the Talon. */ public int getAnalogInRaw() { return getAnalogInPosition() & 0x3FF; } + /** * Get the current encoder velocity, regardless of whether it is the current * feedback device. @@ -399,29 +417,33 @@ public class CANTalon implements MotorSafety, PIDOutput, PIDSource, PIDInterface m_impl.GetCloseLoopErr(swigp); return CanTalonJNI.intp_value(valuep); } + // Returns true if limit switch is closed. false if open. public boolean isFwdLimitSwitchClosed() { long valuep = CanTalonJNI.new_intp(); SWIGTYPE_p_int swigp = new SWIGTYPE_p_int(valuep, true); m_impl.GetLimitSwitchClosedFor(swigp); - return (CanTalonJNI.intp_value(valuep)==0) ? true : false; + return (CanTalonJNI.intp_value(valuep) == 0) ? true : false; } + // Returns true if limit switch is closed. false if open. public boolean isRevLimitSwitchClosed() { long valuep = CanTalonJNI.new_intp(); SWIGTYPE_p_int swigp = new SWIGTYPE_p_int(valuep, true); m_impl.GetLimitSwitchClosedRev(swigp); - return (CanTalonJNI.intp_value(valuep)==0) ? true : false; + return (CanTalonJNI.intp_value(valuep) == 0) ? true : false; } + // Returns true if break is enabled during neutral. false if coast. public boolean getBrakeEnableDuringNeutral() { long valuep = CanTalonJNI.new_intp(); SWIGTYPE_p_int swigp = new SWIGTYPE_p_int(valuep, true); m_impl.GetBrakeIsEnabled(swigp); - return (CanTalonJNI.intp_value(valuep)==0) ? false : true; + return (CanTalonJNI.intp_value(valuep) == 0) ? false : true; } + /** - * Returns temperature of Talon, in degrees Celsius. + * Returns temperature of Talon, in degrees Celsius. */ public double getTemperature() { long tempp = CanTalonJNI.new_doublep(); // Create a new swig pointer. @@ -430,7 +452,7 @@ public class CANTalon implements MotorSafety, PIDOutput, PIDSource, PIDInterface } /** - * Returns the current going through the Talon, in Amperes. + * Returns the current going through the Talon, in Amperes. */ public double getOutputCurrent() { long curp = CanTalonJNI.new_doublep(); // Create a new swig pointer. @@ -444,7 +466,7 @@ public class CANTalon implements MotorSafety, PIDOutput, PIDSource, PIDInterface public double getOutputVoltage() { long throttlep = CanTalonJNI.new_intp(); m_impl.GetAppliedThrottle(new SWIGTYPE_p_int(throttlep, true)); - double voltage = getBusVoltage() * (double)CanTalonJNI.intp_value(throttlep) / 1023.0; + double voltage = getBusVoltage() * (double) CanTalonJNI.intp_value(throttlep) / 1023.0; return voltage; } @@ -454,24 +476,25 @@ public class CANTalon implements MotorSafety, PIDOutput, PIDSource, PIDInterface public double getBusVoltage() { long voltagep = CanTalonJNI.new_doublep(); SWIGTYPE_p_CTR_Code status = m_impl.GetBatteryV(new SWIGTYPE_p_double(voltagep, true)); - /* Note: This section needs the JNI bindings regenerated with - pointer_functions for CTR_Code included in order to be able to catch notice - and throw errors. - if (CanTalonJNI.CTR_Codep_value(status) != 0) { - // TODO throw an error. - }*/ + /* + * Note: This section needs the JNI bindings regenerated with + * pointer_functions for CTR_Code included in order to be able to catch + * notice and throw errors. if (CanTalonJNI.CTR_Codep_value(status) != 0) { + * // TODO throw an error. } + */ return CanTalonJNI.doublep_value(voltagep); } /** - * TODO documentation (see CANJaguar.java) - * - * @return The position of the sensor currently providing feedback. - * When using analog sensors, 0 units corresponds to 0V, 1023 units corresponds to 3.3V - * When using an analog encoder (wrapping around 1023 to 0 is possible) the units are still 3.3V per 1023 units. - * When using quadrature, each unit is a quadrature edge (4X) mode. - */ + * TODO documentation (see CANJaguar.java) + * + * @return The position of the sensor currently providing feedback. When using + * analog sensors, 0 units corresponds to 0V, 1023 units corresponds + * to 3.3V When using an analog encoder (wrapping around 1023 to 0 is + * possible) the units are still 3.3V per 1023 units. When using + * quadrature, each unit is a quadrature edge (4X) mode. + */ public double getPosition() { long positionp = CanTalonJNI.new_intp(); m_impl.GetSensorPosition(new SWIGTYPE_p_int(positionp, true)); @@ -479,24 +502,24 @@ public class CANTalon implements MotorSafety, PIDOutput, PIDSource, PIDInterface } public void setPosition(double pos) { - m_impl.SetSensorPosition((int)pos); + m_impl.SetSensorPosition((int) pos); } -/** - * TODO documentation (see CANJaguar.java) - * - * @return The speed of the sensor currently providing feedback. - * - * The speed units will be in the sensor's native ticks per 100ms. - * - * For analog sensors, 3.3V corresponds to 1023 units. - * So a speed of 200 equates to ~0.645 dV per 100ms or 6.451 dV per second. - * If this is an analog encoder, that likely means 1.9548 rotations per sec. - * For quadrature encoders, each unit corresponds a quadrature edge (4X). - * So a 250 count encoder will produce 1000 edge events per rotation. - * An example speed of 200 would then equate to 20% of a rotation per 100ms, - * or 10 rotations per second. - */ + /** + * TODO documentation (see CANJaguar.java) + * + * @return The speed of the sensor currently providing feedback. + * + * The speed units will be in the sensor's native ticks per 100ms. + * + * For analog sensors, 3.3V corresponds to 1023 units. So a speed of + * 200 equates to ~0.645 dV per 100ms or 6.451 dV per second. If this + * is an analog encoder, that likely means 1.9548 rotations per sec. + * For quadrature encoders, each unit corresponds a quadrature edge + * (4X). So a 250 count encoder will produce 1000 edge events per + * rotation. An example speed of 200 would then equate to 20% of a + * rotation per 100ms, or 10 rotations per second. + */ public double getSpeed() { long speedp = CanTalonJNI.new_intp(); m_impl.GetSensorVelocity(new SWIGTYPE_p_int(speedp, true)); @@ -506,9 +529,11 @@ public class CANTalon implements MotorSafety, PIDOutput, PIDSource, PIDInterface public TalonControlMode getControlMode() { return m_controlMode; } + /** - * Fixup the m_controlMode so set() serializes the correct demand value. - * Also fills the modeSelecet in the control frame to disabled. + * Fixup the m_controlMode so set() serializes the correct demand value. Also + * fills the modeSelecet in the control frame to disabled. + *$ * @param controlMode Control mode to ultimately enter once user calls set(). * @see #set */ @@ -519,12 +544,14 @@ public class CANTalon implements MotorSafety, PIDOutput, PIDSource, PIDInterface // Disable until set() is called. m_impl.SetModeSelect(TalonControlMode.Disabled.value); - UsageReporting.report(tResourceType.kResourceType_CANTalonSRX, m_deviceNumber + 1, controlMode.value); + UsageReporting.report(tResourceType.kResourceType_CANTalonSRX, m_deviceNumber + 1, + controlMode.value); } + public void changeControlMode(TalonControlMode controlMode) { - if(m_controlMode == controlMode){ + if (m_controlMode == controlMode) { /* we already are in this mode, don't perform disable workaround */ - }else{ + } else { applyControlMode(controlMode); } } @@ -532,20 +559,23 @@ public class CANTalon implements MotorSafety, PIDOutput, PIDSource, PIDInterface public void setFeedbackDevice(FeedbackDevice device) { m_impl.SetFeedbackDeviceSelect(device.value); } - public void setStatusFrameRateMs(StatusFrameRate stateFrame, int periodMs){ - m_impl.SetStatusFrameRate(stateFrame.value,periodMs); + + public void setStatusFrameRateMs(StatusFrameRate stateFrame, int periodMs) { + m_impl.SetStatusFrameRate(stateFrame.value, periodMs); } + public void enableControl() { changeControlMode(m_controlMode); - m_controlEnabled = true; + m_controlEnabled = true; } + public void enable() { enableControl(); } public void disableControl() { m_impl.SetModeSelect(TalonControlMode.Disabled.value); - m_controlEnabled = false; + m_controlEnabled = false; } public boolean isControlEnabled() { @@ -558,9 +588,11 @@ public class CANTalon implements MotorSafety, PIDOutput, PIDSource, PIDInterface * @return double proportional constant for current profile. */ public double getP() { - //if(!(m_controlMode.equals(ControlMode.Position) || m_controlMode.equals(ControlMode.Speed))) { - // throw new IllegalStateException("PID mode only applies in Position and Speed modes."); - //} + // if(!(m_controlMode.equals(ControlMode.Position) || + // m_controlMode.equals(ControlMode.Speed))) { + // throw new + // IllegalStateException("PID mode only applies in Position and Speed modes."); + // } // Update the information that we have. if (m_profile == 0) @@ -577,9 +609,11 @@ public class CANTalon implements MotorSafety, PIDOutput, PIDSource, PIDInterface } public double getI() { - //if(!(m_controlMode.equals(ControlMode.Position) || m_controlMode.equals(ControlMode.Speed))) { - // throw new IllegalStateException("PID mode only applies in Position and Speed modes."); - //} + // if(!(m_controlMode.equals(ControlMode.Position) || + // m_controlMode.equals(ControlMode.Speed))) { + // throw new + // IllegalStateException("PID mode only applies in Position and Speed modes."); + // } // Update the information that we have. if (m_profile == 0) @@ -596,9 +630,11 @@ public class CANTalon implements MotorSafety, PIDOutput, PIDSource, PIDInterface } public double getD() { - //if(!(m_controlMode.equals(ControlMode.Position) || m_controlMode.equals(ControlMode.Speed))) { - // throw new IllegalStateException("PID mode only applies in Position and Speed modes."); - //} + // if(!(m_controlMode.equals(ControlMode.Position) || + // m_controlMode.equals(ControlMode.Speed))) { + // throw new + // IllegalStateException("PID mode only applies in Position and Speed modes."); + // } // Update the information that we have. if (m_profile == 0) @@ -615,9 +651,11 @@ public class CANTalon implements MotorSafety, PIDOutput, PIDSource, PIDInterface } public double getF() { - //if(!(m_controlMode.equals(ControlMode.Position) || m_controlMode.equals(ControlMode.Speed))) { - // throw new IllegalStateException("PID mode only applies in Position and Speed modes."); - //} + // if(!(m_controlMode.equals(ControlMode.Position) || + // m_controlMode.equals(ControlMode.Speed))) { + // throw new + // IllegalStateException("PID mode only applies in Position and Speed modes."); + // } // Update the information that we have. if (m_profile == 0) @@ -634,9 +672,11 @@ public class CANTalon implements MotorSafety, PIDOutput, PIDSource, PIDInterface } public double getIZone() { - //if(!(m_controlMode.equals(ControlMode.Position) || m_controlMode.equals(ControlMode.Speed))) { - // throw new IllegalStateException("PID mode only applies in Position and Speed modes."); - //} + // if(!(m_controlMode.equals(ControlMode.Position) || + // m_controlMode.equals(ControlMode.Speed))) { + // throw new + // IllegalStateException("PID mode only applies in Position and Speed modes."); + // } // Update the information that we have. if (m_profile == 0) @@ -651,19 +691,22 @@ public class CANTalon implements MotorSafety, PIDOutput, PIDSource, PIDInterface m_impl.GetIzone(m_profile, new SWIGTYPE_p_int(fp, true)); return CanTalonJNI.intp_value(fp); } + /** * Get the closed loop ramp rate for the current profile. * - * Limits the rate at which the throttle will change. - * Only affects position and speed closed loop modes. + * Limits the rate at which the throttle will change. Only affects position + * and speed closed loop modes. * * @return rampRate Maximum change in voltage, in volts / sec. * @see #setProfile For selecting a certain profile. */ public double getCloseLoopRampRate() { - // if(!(m_controlMode.equals(ControlMode.Position) || m_controlMode.equals(ControlMode.Speed))) { - // throw new IllegalStateException("PID mode only applies in Position and Speed modes."); - // } + // if(!(m_controlMode.equals(ControlMode.Position) || + // m_controlMode.equals(ControlMode.Speed))) { + // throw new + // IllegalStateException("PID mode only applies in Position and Speed modes."); + // } // Update the information that we have. if (m_profile == 0) @@ -677,11 +720,12 @@ public class CANTalon implements MotorSafety, PIDOutput, PIDSource, PIDInterface long fp = CanTalonJNI.new_intp(); m_impl.GetCloseLoopRampRate(m_profile, new SWIGTYPE_p_int(fp, true)); double throttlePerMs = CanTalonJNI.intp_value(fp); - return throttlePerMs / 1023.0 * 12.0 * 1000.0; + return throttlePerMs / 1023.0 * 12.0 * 1000.0; } + /** - * @return The version of the firmware running on the Talon - */ + * @return The version of the firmware running on the Talon + */ public long GetFirmwareVersion() { // Update the information that we have. @@ -694,6 +738,7 @@ public class CANTalon implements MotorSafety, PIDOutput, PIDSource, PIDInterface m_impl.GetParamResponseInt32(CanTalonSRX.param_t.eFirmVers, new SWIGTYPE_p_int(fp, true)); return CanTalonJNI.intp_value(fp); } + public long GetIaccum() { // Update the information that we have. @@ -747,17 +792,17 @@ public class CANTalon implements MotorSafety, PIDOutput, PIDSource, PIDInterface m_impl.SetFgain(m_profile, f); } - /** - * Set the integration zone of the current Closed Loop profile. - * - * Whenever the error is larger than the izone value, the accumulated - * integration error is cleared so that high errors aren't racked up when at - * high errors. - * An izone value of 0 means no difference from a standard PIDF loop. - * - * @param izone Width of the integration zone. - * @see #setProfile For selecting a certain profile. - */ + /** + * Set the integration zone of the current Closed Loop profile. + * + * Whenever the error is larger than the izone value, the accumulated + * integration error is cleared so that high errors aren't racked up when at + * high errors. An izone value of 0 means no difference from a standard PIDF + * loop. + * + * @param izone Width of the integration zone. + * @see #setProfile For selecting a certain profile. + */ public void setIZone(int izone) { m_impl.SetIzone(m_profile, izone); } @@ -765,8 +810,8 @@ public class CANTalon implements MotorSafety, PIDOutput, PIDSource, PIDInterface /** * Set the closed loop ramp rate for the current profile. * - * Limits the rate at which the throttle will change. - * Only affects position and speed closed loop modes. + * Limits the rate at which the throttle will change. Only affects position + * and speed closed loop modes. * * @param rampRate Maximum change in voltage, in volts / sec. * @see #setProfile For selecting a certain profile. @@ -780,24 +825,22 @@ public class CANTalon implements MotorSafety, PIDOutput, PIDSource, PIDInterface /** * Set the voltage ramp rate for the current profile. * - * Limits the rate at which the throttle will change. - * Affects all modes. + * Limits the rate at which the throttle will change. Affects all modes. * * @param rampRate Maximum change in voltage, in volts / sec. */ public void setVoltageRampRate(double rampRate) { // CanTalonSRX takes units of Throttle (0 - 1023) / 10ms. - int rate = (int) (rampRate * 1023.0 / 12.0 /100.0); + int rate = (int) (rampRate * 1023.0 / 12.0 / 100.0); m_impl.SetRampThrottle(rate); } - /** - * Clear the accumulator for I gain. - */ - public void ClearIaccum() - { - SWIGTYPE_p_CTR_Code status = m_impl.SetParam(CanTalonSRX.param_t.ePidIaccum, 0); - } + /** + * Clear the accumulator for I gain. + */ + public void ClearIaccum() { + SWIGTYPE_p_CTR_Code status = m_impl.SetParam(CanTalonSRX.param_t.ePidIaccum, 0); + } /** * Sets control values for closed loop control. @@ -807,15 +850,16 @@ public class CANTalon implements MotorSafety, PIDOutput, PIDSource, PIDInterface * @param d Differential constant. * @param f Feedforward constant. * @param izone Integration zone -- prevents accumulation of integration error - * with large errors. Setting this to zero will ignore any izone stuff. - * @param closeLoopRampRate Closed loop ramp rate. Maximum change in voltage, in volts / sec. + * with large errors. Setting this to zero will ignore any izone stuff. + * @param closeLoopRampRate Closed loop ramp rate. Maximum change in voltage, + * in volts / sec. * @param profile which profile to set the pid constants for. You can have two - * profiles, with values of 0 or 1, allowing you to keep a second set of values - * on hand in the talon. In order to switch profiles without recalling setPID, - * you must call setProfile(). + * profiles, with values of 0 or 1, allowing you to keep a second set + * of values on hand in the talon. In order to switch profiles without + * recalling setPID, you must call setProfile(). */ - public void setPID(double p, double i, double d, double f, int izone, double closeLoopRampRate, int profile) - { + public void setPID(double p, double i, double d, double f, int izone, double closeLoopRampRate, + int profile) { if (profile != 0 && profile != 1) throw new IllegalArgumentException("Talon PID profile must be 0 or 1."); m_profile = profile; @@ -843,38 +887,38 @@ public class CANTalon implements MotorSafety, PIDOutput, PIDSource, PIDInterface * Select which closed loop profile to use, and uses whatever PIDF gains and * the such that are already there. */ - public void setProfile(int profile) - { + public void setProfile(int profile) { if (profile != 0 && profile != 1) throw new IllegalArgumentException("Talon PID profile must be 0 or 1."); m_profile = profile; m_impl.SetProfileSlotSelect(m_profile); } - /** - * Common interface for stopping a motor. - * - * @deprecated Use disableControl instead. - */ - @Override - @Deprecated - public void stopMotor() { - disableControl(); - } + /** + * Common interface for stopping a motor. + * + * @deprecated Use disableControl instead. + */ + @Override + @Deprecated + public void stopMotor() { + disableControl(); + } @Override public void disable() { disableControl(); } - public int getDeviceID() { - return m_deviceNumber; - } + public int getDeviceID() { + return m_deviceNumber; + } // TODO: Documentation for all these accessors/setters for misc. stuff. public void clearIAccum() { - SWIGTYPE_p_CTR_Code status = m_impl.SetParam(CanTalonSRX.param_t.ePidIaccum, 0); + SWIGTYPE_p_CTR_Code status = m_impl.SetParam(CanTalonSRX.param_t.ePidIaccum, 0); } + public void setForwardSoftLimit(int forwardLimit) { m_impl.SetForwardSoftLimit(forwardLimit); } @@ -892,7 +936,7 @@ public class CANTalon implements MotorSafety, PIDOutput, PIDSource, PIDInterface public boolean isForwardSoftLimitEnabled() { long valuep = CanTalonJNI.new_intp(); m_impl.GetForwardSoftEnable(new SWIGTYPE_p_int(valuep, true)); - return (CanTalonJNI.intp_value(valuep)==0) ? false : true; + return (CanTalonJNI.intp_value(valuep) == 0) ? false : true; } public void setReverseSoftLimit(int reverseLimit) { @@ -912,7 +956,7 @@ public class CANTalon implements MotorSafety, PIDOutput, PIDSource, PIDInterface public boolean isReverseSoftLimitEnabled() { long valuep = CanTalonJNI.new_intp(); m_impl.GetReverseSoftEnable(new SWIGTYPE_p_int(valuep, true)); - return (CanTalonJNI.intp_value(valuep)==0) ? false : true; + return (CanTalonJNI.intp_value(valuep) == 0) ? false : true; } public void clearStickyFaults() { @@ -923,33 +967,37 @@ public class CANTalon implements MotorSafety, PIDOutput, PIDSource, PIDInterface int mask = 4 + (forward ? 1 : 0) * 2 + (reverse ? 1 : 0); m_impl.SetOverrideLimitSwitchEn(mask); } + /** * Configure the fwd limit switch to be normally open or normally closed. - * Talon will disable momentarilly if the Talon's current setting - * is dissimilar to the caller's requested setting. + * 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. + * 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. + * @param normallyOpen true for normally open. false for normally closed. */ - public void ConfigFwdLimitSwitchNormallyOpen(boolean normallyOpen) - { - SWIGTYPE_p_CTR_Code status = m_impl.SetParam(CanTalonSRX.param_t.eOnBoot_LimitSwitch_Forward_NormallyClosed,normallyOpen ? 0 : 1); + public void ConfigFwdLimitSwitchNormallyOpen(boolean normallyOpen) { + SWIGTYPE_p_CTR_Code status = + m_impl.SetParam(CanTalonSRX.param_t.eOnBoot_LimitSwitch_Forward_NormallyClosed, + normallyOpen ? 0 : 1); } + /** * Configure the rev limit switch to be normally open or normally closed. - * Talon will disable momentarilly if the Talon's current setting - * is dissimilar to the caller's requested setting. + * 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. + * 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. + * @param normallyOpen true for normally open. false for normally closed. */ - public void ConfigRevLimitSwitchNormallyOpen(boolean normallyOpen) - { - SWIGTYPE_p_CTR_Code status = m_impl.SetParam(CanTalonSRX.param_t.eOnBoot_LimitSwitch_Reverse_NormallyClosed,normallyOpen ? 0 : 1); + public void ConfigRevLimitSwitchNormallyOpen(boolean normallyOpen) { + SWIGTYPE_p_CTR_Code status = + m_impl.SetParam(CanTalonSRX.param_t.eOnBoot_LimitSwitch_Reverse_NormallyClosed, + normallyOpen ? 0 : 1); } public void enableBrakeMode(boolean brake) { @@ -1035,96 +1083,97 @@ public class CANTalon implements MotorSafety, PIDOutput, PIDSource, PIDInterface } - @Override - public void setExpiration(double timeout) { - m_safetyHelper.setExpiration(timeout); - } + @Override + public void setExpiration(double timeout) { + m_safetyHelper.setExpiration(timeout); + } - @Override - public double getExpiration() { - return m_safetyHelper.getExpiration(); - } + @Override + public double getExpiration() { + return m_safetyHelper.getExpiration(); + } - @Override - public boolean isAlive() { - return m_safetyHelper.isAlive(); - } + @Override + public boolean isAlive() { + return m_safetyHelper.isAlive(); + } - @Override - public boolean isSafetyEnabled() { - return m_safetyHelper.isSafetyEnabled(); - } + @Override + public boolean isSafetyEnabled() { + return m_safetyHelper.isSafetyEnabled(); + } - @Override - public void setSafetyEnabled(boolean enabled) { - m_safetyHelper.setSafetyEnabled(enabled); - } + @Override + public void setSafetyEnabled(boolean enabled) { + m_safetyHelper.setSafetyEnabled(enabled); + } - @Override - public String getDescription() { - return "CANTalon ID "+m_deviceNumber; - } + @Override + public String getDescription() { + return "CANTalon ID " + m_deviceNumber; + } - /* - * Live Window code, only does anything if live window is activated. - */ - @Override - public String getSmartDashboardType() { - return "Speed Controller"; - } - private ITable m_table = null; - private ITableListener m_table_listener = null; + /* + * Live Window code, only does anything if live window is activated. + */ + @Override + public String getSmartDashboardType() { + return "Speed Controller"; + } - /** - * {@inheritDoc} - */ - @Override - public void initTable(ITable subtable) { - m_table = subtable; - updateTable(); - } + private ITable m_table = null; + private ITableListener m_table_listener = null; - /** - * {@inheritDoc} - */ - @Override - public void updateTable() { - if (m_table != null) { - m_table.putNumber("Value", get()); - } - } + /** + * {@inheritDoc} + */ + @Override + public void initTable(ITable subtable) { + m_table = subtable; + updateTable(); + } - /** - * {@inheritDoc} - */ - @Override - public ITable getTable() { - return m_table; - } + /** + * {@inheritDoc} + */ + @Override + public void updateTable() { + if (m_table != null) { + m_table.putNumber("Value", get()); + } + } - /** - * {@inheritDoc} - */ - @Override - public void startLiveWindowMode() { - set(0); // Stop for safety - m_table_listener = new ITableListener() { - @Override - public void valueChanged(ITable itable, String key, Object value, boolean bln) { - set(((Double) value).doubleValue()); - } - }; - m_table.addTableListener("Value", m_table_listener, true); - } + /** + * {@inheritDoc} + */ + @Override + public ITable getTable() { + return m_table; + } - /** - * {@inheritDoc} - */ - @Override - public void stopLiveWindowMode() { - set(0); // Stop for safety - // TODO: Broken, should only remove the listener from "Value" only. - m_table.removeTableListener(m_table_listener); - } + /** + * {@inheritDoc} + */ + @Override + public void startLiveWindowMode() { + set(0); // Stop for safety + m_table_listener = new ITableListener() { + @Override + public void valueChanged(ITable itable, String key, Object value, boolean bln) { + set(((Double) value).doubleValue()); + } + }; + m_table.addTableListener("Value", m_table_listener, true); + } + + /** + * {@inheritDoc} + */ + @Override + public void stopLiveWindowMode() { + set(0); // Stop for safety + // TODO: Broken, should only remove the listener from "Value" only. + m_table.removeTableListener(m_table_listener); + } } diff --git a/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/CameraServer.java b/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/CameraServer.java index b38385f7d2..8df27a6460 100644 --- a/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/CameraServer.java +++ b/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/CameraServer.java @@ -25,344 +25,348 @@ import edu.wpi.first.wpilibj.DriverStation; import edu.wpi.first.wpilibj.Timer; import edu.wpi.first.wpilibj.vision.USBCamera; -//replicates CameraServer.cpp in java lib +// replicates CameraServer.cpp in java lib public class CameraServer { - private static final int kPort = 1180; - private static final byte[] kMagicNumber = { 0x01, 0x00, 0x00, 0x00 }; - private static final int kSize640x480 = 0; - private static final int kSize320x240 = 1; - private static final int kSize160x120 = 2; - private static final int kHardwareCompression = -1; - private static final String kDefaultCameraName = "cam1"; - private static final int kMaxImageSize = 200000; - private static CameraServer server; + private static final int kPort = 1180; + private static final byte[] kMagicNumber = {0x01, 0x00, 0x00, 0x00}; + private static final int kSize640x480 = 0; + private static final int kSize320x240 = 1; + private static final int kSize160x120 = 2; + private static final int kHardwareCompression = -1; + private static final String kDefaultCameraName = "cam1"; + private static final int kMaxImageSize = 200000; + private static CameraServer server; - public static CameraServer getInstance() { - if (server == null) { - server = new CameraServer(); - } - return server; + public static CameraServer getInstance() { + if (server == null) { + server = new CameraServer(); } + return server; + } - private Thread serverThread; - private int m_quality; - private boolean m_autoCaptureStarted; - private boolean m_hwClient = true; - private USBCamera m_camera; - private CameraData m_imageData; - private Deque m_imageDataPool; + private Thread serverThread; + private int m_quality; + private boolean m_autoCaptureStarted; + private boolean m_hwClient = true; + private USBCamera m_camera; + private CameraData m_imageData; + private Deque m_imageDataPool; - private class CameraData { - RawData data; - int start; - public CameraData(RawData d, int s) { - data = d; - start = s; - } + private class CameraData { + RawData data; + int start; + + public CameraData(RawData d, int s) { + data = d; + start = s; } + } - private CameraServer() { - m_quality = 50; - m_camera = null; - m_imageData = null; - m_imageDataPool = new ArrayDeque<>(3); - for (int i = 0; i < 3; i++) { - m_imageDataPool.addLast(ByteBuffer.allocateDirect(kMaxImageSize)); - } - serverThread = new Thread(new Runnable() { - public void run() { - try { - serve(); - } catch (IOException e) { - // do stuff here - } catch (InterruptedException e) { - // do stuff here - } - } - }); - serverThread.setName("CameraServer Send Thread"); - serverThread.start(); + private CameraServer() { + m_quality = 50; + m_camera = null; + m_imageData = null; + m_imageDataPool = new ArrayDeque<>(3); + for (int i = 0; i < 3; i++) { + m_imageDataPool.addLast(ByteBuffer.allocateDirect(kMaxImageSize)); } - - private synchronized void setImageData(RawData data, int start) { - if (m_imageData != null && m_imageData.data != null) { - m_imageData.data.free(); - if (m_imageData.data.getBuffer() != null) - m_imageDataPool.addLast(m_imageData.data.getBuffer()); - m_imageData = null; - } - m_imageData = new CameraData(data, start); - notifyAll(); - } - - /** - * Manually change the image that is served by the MJPEG stream. This can be - * called to pass custom annotated images to the dashboard. Note that, for - * 640x480 video, this method could take between 40 and 50 milliseconds to - * complete. - * - * This shouldn't be called if {@link #startAutomaticCapture} is called. - * - * @param image - * The IMAQ image to show on the dashboard - */ - public void setImage(Image image) { - // handle multi-threadedness - - /* Flatten the IMAQ image to a JPEG */ - - RawData data = NIVision.imaqFlatten(image, - NIVision.FlattenType.FLATTEN_IMAGE, - NIVision.CompressionType.COMPRESSION_JPEG, 10 * m_quality); - ByteBuffer buffer = data.getBuffer(); - boolean hwClient; - - synchronized (this) { - hwClient = m_hwClient; - } - - /* Find the start of the JPEG data */ - int index = 0; - if (hwClient) { - while (index < buffer.limit() - 1) { - if ((buffer.get(index) & 0xff) == 0xFF - && (buffer.get(index + 1) & 0xff) == 0xD8) - break; - index++; - } - } - - if (buffer.limit() - index - 1 <= 2) { - throw new VisionException("data size of flattened image is less than 2. Try another camera! "); - } - - setImageData(data, index); - } - - /** - * Start automatically capturing images to send to the dashboard. - * You should call this method to just see a camera feed on the dashboard - * without doing any vision processing on the roboRIO. {@link #setImage} - * shouldn't be called after this is called. - * This overload calles {@link #startAutomaticCapture(String)} with the - * default camera name - */ - public void startAutomaticCapture() { - startAutomaticCapture(USBCamera.kDefaultCameraName); - } - - /** - * Start automatically capturing images to send to the dashboard. - * - * You should call this method to just see a camera feed on the dashboard - * without doing any vision processing on the roboRIO. {@link #setImage} - * shouldn't be called after this is called. - * - * @param cameraName - * The name of the camera interface (e.g. "cam1") - */ - public void startAutomaticCapture(String cameraName) { + serverThread = new Thread(new Runnable() { + public void run() { try { - USBCamera camera = new USBCamera(cameraName); - camera.openCamera(); - startAutomaticCapture(camera); - } - catch (VisionException ex) { - DriverStation.reportError("Error when starting the camera: " + cameraName + " " + ex.getMessage(), true); + serve(); + } catch (IOException e) { + // do stuff here + } catch (InterruptedException e) { + // do stuff here } + } + }); + serverThread.setName("CameraServer Send Thread"); + serverThread.start(); + } + + private synchronized void setImageData(RawData data, int start) { + if (m_imageData != null && m_imageData.data != null) { + m_imageData.data.free(); + if (m_imageData.data.getBuffer() != null) + m_imageDataPool.addLast(m_imageData.data.getBuffer()); + m_imageData = null; + } + m_imageData = new CameraData(data, start); + notifyAll(); + } + + /** + * Manually change the image that is served by the MJPEG stream. This can be + * called to pass custom annotated images to the dashboard. Note that, for + * 640x480 video, this method could take between 40 and 50 milliseconds to + * complete. + * + * This shouldn't be called if {@link #startAutomaticCapture} is called. + * + * @param image The IMAQ image to show on the dashboard + */ + public void setImage(Image image) { + // handle multi-threadedness + + /* Flatten the IMAQ image to a JPEG */ + + RawData data = + NIVision.imaqFlatten(image, NIVision.FlattenType.FLATTEN_IMAGE, + NIVision.CompressionType.COMPRESSION_JPEG, 10 * m_quality); + ByteBuffer buffer = data.getBuffer(); + boolean hwClient; + + synchronized (this) { + hwClient = m_hwClient; } - public synchronized void startAutomaticCapture(USBCamera camera) { - if (m_autoCaptureStarted) return; - m_autoCaptureStarted = true; - m_camera = camera; - - m_camera.startCapture(); - - Thread captureThread = new Thread(new Runnable() { - @Override - public void run() { - capture(); - } - }); - captureThread.setName("Camera Capture Thread"); - captureThread.start(); + /* Find the start of the JPEG data */ + int index = 0; + if (hwClient) { + while (index < buffer.limit() - 1) { + if ((buffer.get(index) & 0xff) == 0xFF && (buffer.get(index + 1) & 0xff) == 0xD8) + break; + index++; + } } - protected void capture() { - Image frame = NIVision.imaqCreateImage(NIVision.ImageType.IMAGE_RGB, 0); + if (buffer.limit() - index - 1 <= 2) { + throw new VisionException("data size of flattened image is less than 2. Try another camera! "); + } + + setImageData(data, index); + } + + /** + * Start automatically capturing images to send to the dashboard. You should + * call this method to just see a camera feed on the dashboard without doing + * any vision processing on the roboRIO. {@link #setImage} shouldn't be called + * after this is called. This overload calles + * {@link #startAutomaticCapture(String)} with the default camera name + */ + public void startAutomaticCapture() { + startAutomaticCapture(USBCamera.kDefaultCameraName); + } + + /** + * Start automatically capturing images to send to the dashboard. + * + * You should call this method to just see a camera feed on the dashboard + * without doing any vision processing on the roboRIO. {@link #setImage} + * shouldn't be called after this is called. + * + * @param cameraName The name of the camera interface (e.g. "cam1") + */ + public void startAutomaticCapture(String cameraName) { + try { + USBCamera camera = new USBCamera(cameraName); + camera.openCamera(); + startAutomaticCapture(camera); + } catch (VisionException ex) { + DriverStation.reportError( + "Error when starting the camera: " + cameraName + " " + ex.getMessage(), true); + } + } + + public synchronized void startAutomaticCapture(USBCamera camera) { + if (m_autoCaptureStarted) + return; + m_autoCaptureStarted = true; + m_camera = camera; + + m_camera.startCapture(); + + Thread captureThread = new Thread(new Runnable() { + @Override + public void run() { + capture(); + } + }); + captureThread.setName("Camera Capture Thread"); + captureThread.start(); + } + + protected void capture() { + Image frame = NIVision.imaqCreateImage(NIVision.ImageType.IMAGE_RGB, 0); + while (true) { + boolean hwClient; + ByteBuffer dataBuffer = null; + synchronized (this) { + hwClient = m_hwClient; + if (hwClient) { + dataBuffer = m_imageDataPool.removeLast(); + } + } + + try { + if (hwClient && dataBuffer != null) { + // Reset the image buffer limit + dataBuffer.limit(dataBuffer.capacity() - 1); + m_camera.getImageData(dataBuffer); + setImageData(new RawData(dataBuffer), 0); + } else { + m_camera.getImage(frame); + setImage(frame); + } + } catch (VisionException ex) { + DriverStation.reportError("Error when getting image from the camera: " + ex.getMessage(), + true); + if (dataBuffer != null) { + synchronized (this) { + m_imageDataPool.addLast(dataBuffer); + Timer.delay(.1); + } + } + } + } + } + + + + /** + * check if auto capture is started + * + */ + public synchronized boolean isAutoCaptureStarted() { + return m_autoCaptureStarted; + } + + /** + * Sets the size of the image to use. Use the public kSize constants to set + * the correct mode, or set it directory on a camera and call the appropriate + * autoCapture method + *$ + * @param size The size to use + */ + public synchronized void setSize(int size) { + if (m_camera == null) + return; + switch (size) { + case kSize640x480: + m_camera.setSize(640, 480); + break; + case kSize320x240: + m_camera.setSize(320, 240); + break; + case kSize160x120: + m_camera.setSize(160, 120); + break; + } + } + + /** + * Set the quality of the compressed image sent to the dashboard + * + * @param quality The quality of the JPEG image, from 0 to 100 + */ + public synchronized void setQuality(int quality) { + m_quality = quality > 100 ? 100 : quality < 0 ? 0 : quality; + } + + /** + * Get the quality of the compressed image sent to the dashboard + * + * @return The quality, from 0 to 100 + */ + public synchronized int getQuality() { + return m_quality; + } + + /** + * Run the M-JPEG server. + * + * This function listens for a connection from the dashboard in a background + * thread, then sends back the M-JPEG stream. + * + * @throws IOException if the Socket connection fails + * @throws InterruptedException if the sleep is interrupted + */ + protected void serve() throws IOException, InterruptedException { + + ServerSocket socket = new ServerSocket(); + socket.setReuseAddress(true); + InetSocketAddress address = new InetSocketAddress(kPort); + socket.bind(address); + + while (true) { + try { + Socket s = socket.accept(); + + DataInputStream is = new DataInputStream(s.getInputStream()); + DataOutputStream os = new DataOutputStream(s.getOutputStream()); + + int fps = is.readInt(); + int compression = is.readInt(); + int size = is.readInt(); + + if (compression != kHardwareCompression) { + DriverStation.reportError("Choose \"USB Camera HW\" on the dashboard", false); + s.close(); + continue; + } + + // Wait for the camera + synchronized (this) { + System.out.println("Camera not yet ready, awaiting image"); + if (m_camera == null) + wait(); + m_hwClient = compression == kHardwareCompression; + if (!m_hwClient) + setQuality(100 - compression); + else if (m_camera != null) + m_camera.setFPS(fps); + setSize(size); + } + + long period = (long) (1000 / (1.0 * fps)); while (true) { - boolean hwClient; - ByteBuffer dataBuffer = null; - synchronized (this) { - hwClient = m_hwClient; - if (hwClient) { - dataBuffer = m_imageDataPool.removeLast(); - } + long t0 = System.currentTimeMillis(); + CameraData imageData = null; + synchronized (this) { + wait(); + imageData = m_imageData; + m_imageData = null; + } + + if (imageData == null) + continue; + // Set the buffer position to the start of the data, + // and then create a new wrapper for the data at + // exactly that position + imageData.data.getBuffer().position(imageData.start); + byte[] imageArray = new byte[imageData.data.getBuffer().remaining()]; + imageData.data.getBuffer().get(imageArray, 0, imageData.data.getBuffer().remaining()); + + // write numbers + try { + os.write(kMagicNumber); + os.writeInt(imageArray.length); + os.write(imageArray); + os.flush(); + long dt = System.currentTimeMillis() - t0; + + if (dt < period) { + Thread.sleep(period - dt); } - - try { - if (hwClient && dataBuffer != null) { - // Reset the image buffer limit - dataBuffer.limit(dataBuffer.capacity() - 1); - m_camera.getImageData(dataBuffer); - setImageData(new RawData(dataBuffer), 0); - } else { - m_camera.getImage(frame); - setImage(frame); - } - } catch (VisionException ex) { - DriverStation.reportError("Error when getting image from the camera: " + ex.getMessage(), true); - if (dataBuffer != null) { - synchronized (this) { - m_imageDataPool.addLast(dataBuffer); - Timer.delay(.1); - } - } - } - } - } - - - - /** - * check if auto capture is started - * - */ - public synchronized boolean isAutoCaptureStarted() { - return m_autoCaptureStarted; - } - - /** - * Sets the size of the image to use. Use the public kSize constants - * to set the correct mode, or set it directory on a camera and call - * the appropriate autoCapture method - * @param size The size to use - */ - public synchronized void setSize(int size) { - if (m_camera == null) return; - switch (size) { - case kSize640x480: - m_camera.setSize(640, 480); - break; - case kSize320x240: - m_camera.setSize(320, 240); - break; - case kSize160x120: - m_camera.setSize(160, 120); - break; - } - } - - /** - * Set the quality of the compressed image sent to the dashboard - * - * @param quality - * The quality of the JPEG image, from 0 to 100 - */ - public synchronized void setQuality(int quality) { - m_quality = quality > 100 ? 100 : quality < 0 ? 0 : quality; - } - - /** - * Get the quality of the compressed image sent to the dashboard - * - * @return The quality, from 0 to 100 - */ - public synchronized int getQuality() { - return m_quality; - } - - /** - * Run the M-JPEG server. - * - * This function listens for a connection from the dashboard in a background - * thread, then sends back the M-JPEG stream. - * - * @throws IOException if the Socket connection fails - * @throws InterruptedException if the sleep is interrupted - */ - protected void serve() throws IOException, InterruptedException { - - ServerSocket socket = new ServerSocket(); - socket.setReuseAddress(true); - InetSocketAddress address = new InetSocketAddress(kPort); - socket.bind(address); - - while (true) { - try { - Socket s = socket.accept(); - - DataInputStream is = new DataInputStream(s.getInputStream()); - DataOutputStream os = new DataOutputStream(s.getOutputStream()); - - int fps = is.readInt(); - int compression = is.readInt(); - int size = is.readInt(); - - if (compression != kHardwareCompression) { - DriverStation.reportError("Choose \"USB Camera HW\" on the dashboard", false); - s.close(); - continue; - } - - // Wait for the camera - synchronized (this) { - System.out.println("Camera not yet ready, awaiting image"); - if (m_camera == null) wait(); - m_hwClient = compression == kHardwareCompression; - if (!m_hwClient) setQuality(100 - compression); - else if (m_camera != null) m_camera.setFPS(fps); - setSize(size); - } - - long period = (long) (1000 / (1.0 * fps)); - while (true) { - long t0 = System.currentTimeMillis(); - CameraData imageData = null; - synchronized (this) { - wait(); - imageData = m_imageData; - m_imageData = null; - } - - if (imageData == null) continue; - // Set the buffer position to the start of the data, - // and then create a new wrapper for the data at - // exactly that position - imageData.data.getBuffer().position(imageData.start); - byte[] imageArray = new byte[imageData.data.getBuffer().remaining()]; - imageData.data.getBuffer().get(imageArray, 0, imageData.data.getBuffer().remaining()); - - // write numbers - try { - os.write(kMagicNumber); - os.writeInt(imageArray.length); - os.write(imageArray); - os.flush(); - long dt = System.currentTimeMillis() - t0; - - if (dt < period) { - Thread.sleep(period - dt); - } - } catch (IOException | UnsupportedOperationException ex) { - DriverStation.reportError(ex.getMessage(), true); - break; - } finally { - imageData.data.free(); - if (imageData.data.getBuffer() != null) { - synchronized (this) { - m_imageDataPool.addLast(imageData.data.getBuffer()); - } - } - } - } - } catch (IOException ex) { - DriverStation.reportError(ex.getMessage(), true); - continue; + } catch (IOException | UnsupportedOperationException ex) { + DriverStation.reportError(ex.getMessage(), true); + break; + } finally { + imageData.data.free(); + if (imageData.data.getBuffer() != null) { + synchronized (this) { + m_imageDataPool.addLast(imageData.data.getBuffer()); + } } + } } + } catch (IOException ex) { + DriverStation.reportError(ex.getMessage(), true); + continue; + } } + } } diff --git a/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/CanTalonSRX.java b/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/CanTalonSRX.java index 8b22403e65..9f303536cb 100644 --- a/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/CanTalonSRX.java +++ b/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/CanTalonSRX.java @@ -1,10 +1,12 @@ -/* ---------------------------------------------------------------------------- - * This file was automatically generated by SWIG (http://www.swig.org). - * Version 2.0.11 - * +/* + * ---------------------------------------------------------------------------- + * This file was automatically generated by SWIG (http://www.swig.org). Version + * 2.0.11 + *$ * Do not make changes to this file unless you know what you are doing--modify * the SWIG interface file instead. - * ----------------------------------------------------------------------------- */ + * ----------------------------------------------------------------------------- + */ package edu.wpi.first.wpilibj.hal; @@ -52,107 +54,134 @@ public class CanTalonSRX extends CtreCanNode { } public SWIGTYPE_p_CTR_Code SetParam(CanTalonSRX.param_t paramEnum, double value) { - return new SWIGTYPE_p_CTR_Code(CanTalonJNI.CanTalonSRX_SetParam(swigCPtr, this, paramEnum.swigValue(), value), true); + return new SWIGTYPE_p_CTR_Code(CanTalonJNI.CanTalonSRX_SetParam(swigCPtr, this, + paramEnum.swigValue(), value), true); } public SWIGTYPE_p_CTR_Code RequestParam(CanTalonSRX.param_t paramEnum) { - return new SWIGTYPE_p_CTR_Code(CanTalonJNI.CanTalonSRX_RequestParam(swigCPtr, this, paramEnum.swigValue()), true); + return new SWIGTYPE_p_CTR_Code(CanTalonJNI.CanTalonSRX_RequestParam(swigCPtr, this, + paramEnum.swigValue()), true); } public SWIGTYPE_p_CTR_Code GetParamResponse(CanTalonSRX.param_t paramEnum, SWIGTYPE_p_double value) { - return new SWIGTYPE_p_CTR_Code(CanTalonJNI.CanTalonSRX_GetParamResponse(swigCPtr, this, paramEnum.swigValue(), SWIGTYPE_p_double.getCPtr(value)), true); + return new SWIGTYPE_p_CTR_Code(CanTalonJNI.CanTalonSRX_GetParamResponse(swigCPtr, this, + paramEnum.swigValue(), SWIGTYPE_p_double.getCPtr(value)), true); } - public SWIGTYPE_p_CTR_Code GetParamResponseInt32(CanTalonSRX.param_t paramEnum, SWIGTYPE_p_int value) { - return new SWIGTYPE_p_CTR_Code(CanTalonJNI.CanTalonSRX_GetParamResponseInt32(swigCPtr, this, paramEnum.swigValue(), SWIGTYPE_p_int.getCPtr(value)), true); + public SWIGTYPE_p_CTR_Code GetParamResponseInt32(CanTalonSRX.param_t paramEnum, + SWIGTYPE_p_int value) { + return new SWIGTYPE_p_CTR_Code(CanTalonJNI.CanTalonSRX_GetParamResponseInt32(swigCPtr, this, + paramEnum.swigValue(), SWIGTYPE_p_int.getCPtr(value)), true); } public SWIGTYPE_p_CTR_Code SetPgain(long slotIdx, double gain) { - return new SWIGTYPE_p_CTR_Code(CanTalonJNI.CanTalonSRX_SetPgain(swigCPtr, this, slotIdx, gain), true); + return new SWIGTYPE_p_CTR_Code(CanTalonJNI.CanTalonSRX_SetPgain(swigCPtr, this, slotIdx, gain), + true); } public SWIGTYPE_p_CTR_Code SetIgain(long slotIdx, double gain) { - return new SWIGTYPE_p_CTR_Code(CanTalonJNI.CanTalonSRX_SetIgain(swigCPtr, this, slotIdx, gain), true); + return new SWIGTYPE_p_CTR_Code(CanTalonJNI.CanTalonSRX_SetIgain(swigCPtr, this, slotIdx, gain), + true); } public SWIGTYPE_p_CTR_Code SetDgain(long slotIdx, double gain) { - return new SWIGTYPE_p_CTR_Code(CanTalonJNI.CanTalonSRX_SetDgain(swigCPtr, this, slotIdx, gain), true); + return new SWIGTYPE_p_CTR_Code(CanTalonJNI.CanTalonSRX_SetDgain(swigCPtr, this, slotIdx, gain), + true); } public SWIGTYPE_p_CTR_Code SetFgain(long slotIdx, double gain) { - return new SWIGTYPE_p_CTR_Code(CanTalonJNI.CanTalonSRX_SetFgain(swigCPtr, this, slotIdx, gain), true); + return new SWIGTYPE_p_CTR_Code(CanTalonJNI.CanTalonSRX_SetFgain(swigCPtr, this, slotIdx, gain), + true); } public SWIGTYPE_p_CTR_Code SetIzone(long slotIdx, int zone) { - return new SWIGTYPE_p_CTR_Code(CanTalonJNI.CanTalonSRX_SetIzone(swigCPtr, this, slotIdx, zone), true); + return new SWIGTYPE_p_CTR_Code(CanTalonJNI.CanTalonSRX_SetIzone(swigCPtr, this, slotIdx, zone), + true); } public SWIGTYPE_p_CTR_Code SetCloseLoopRampRate(long slotIdx, int closeLoopRampRate) { - return new SWIGTYPE_p_CTR_Code(CanTalonJNI.CanTalonSRX_SetCloseLoopRampRate(swigCPtr, this, slotIdx, closeLoopRampRate), true); + return new SWIGTYPE_p_CTR_Code(CanTalonJNI.CanTalonSRX_SetCloseLoopRampRate(swigCPtr, this, + slotIdx, closeLoopRampRate), true); } public SWIGTYPE_p_CTR_Code SetSensorPosition(int pos) { - return new SWIGTYPE_p_CTR_Code(CanTalonJNI.CanTalonSRX_SetSensorPosition(swigCPtr, this, pos), true); + return new SWIGTYPE_p_CTR_Code(CanTalonJNI.CanTalonSRX_SetSensorPosition(swigCPtr, this, pos), + true); } public SWIGTYPE_p_CTR_Code SetForwardSoftLimit(int forwardLimit) { - return new SWIGTYPE_p_CTR_Code(CanTalonJNI.CanTalonSRX_SetForwardSoftLimit(swigCPtr, this, forwardLimit), true); + return new SWIGTYPE_p_CTR_Code(CanTalonJNI.CanTalonSRX_SetForwardSoftLimit(swigCPtr, this, + forwardLimit), true); } public SWIGTYPE_p_CTR_Code SetReverseSoftLimit(int reverseLimit) { - return new SWIGTYPE_p_CTR_Code(CanTalonJNI.CanTalonSRX_SetReverseSoftLimit(swigCPtr, this, reverseLimit), true); + return new SWIGTYPE_p_CTR_Code(CanTalonJNI.CanTalonSRX_SetReverseSoftLimit(swigCPtr, this, + reverseLimit), true); } public SWIGTYPE_p_CTR_Code SetForwardSoftEnable(int enable) { - return new SWIGTYPE_p_CTR_Code(CanTalonJNI.CanTalonSRX_SetForwardSoftEnable(swigCPtr, this, enable), true); + return new SWIGTYPE_p_CTR_Code(CanTalonJNI.CanTalonSRX_SetForwardSoftEnable(swigCPtr, this, + enable), true); } public SWIGTYPE_p_CTR_Code SetReverseSoftEnable(int enable) { - return new SWIGTYPE_p_CTR_Code(CanTalonJNI.CanTalonSRX_SetReverseSoftEnable(swigCPtr, this, enable), true); + return new SWIGTYPE_p_CTR_Code(CanTalonJNI.CanTalonSRX_SetReverseSoftEnable(swigCPtr, this, + enable), true); } public SWIGTYPE_p_CTR_Code GetPgain(long slotIdx, SWIGTYPE_p_double gain) { - return new SWIGTYPE_p_CTR_Code(CanTalonJNI.CanTalonSRX_GetPgain(swigCPtr, this, slotIdx, SWIGTYPE_p_double.getCPtr(gain)), true); + return new SWIGTYPE_p_CTR_Code(CanTalonJNI.CanTalonSRX_GetPgain(swigCPtr, this, slotIdx, + SWIGTYPE_p_double.getCPtr(gain)), true); } public SWIGTYPE_p_CTR_Code GetIgain(long slotIdx, SWIGTYPE_p_double gain) { - return new SWIGTYPE_p_CTR_Code(CanTalonJNI.CanTalonSRX_GetIgain(swigCPtr, this, slotIdx, SWIGTYPE_p_double.getCPtr(gain)), true); + return new SWIGTYPE_p_CTR_Code(CanTalonJNI.CanTalonSRX_GetIgain(swigCPtr, this, slotIdx, + SWIGTYPE_p_double.getCPtr(gain)), true); } public SWIGTYPE_p_CTR_Code GetDgain(long slotIdx, SWIGTYPE_p_double gain) { - return new SWIGTYPE_p_CTR_Code(CanTalonJNI.CanTalonSRX_GetDgain(swigCPtr, this, slotIdx, SWIGTYPE_p_double.getCPtr(gain)), true); + return new SWIGTYPE_p_CTR_Code(CanTalonJNI.CanTalonSRX_GetDgain(swigCPtr, this, slotIdx, + SWIGTYPE_p_double.getCPtr(gain)), true); } public SWIGTYPE_p_CTR_Code GetFgain(long slotIdx, SWIGTYPE_p_double gain) { - return new SWIGTYPE_p_CTR_Code(CanTalonJNI.CanTalonSRX_GetFgain(swigCPtr, this, slotIdx, SWIGTYPE_p_double.getCPtr(gain)), true); + return new SWIGTYPE_p_CTR_Code(CanTalonJNI.CanTalonSRX_GetFgain(swigCPtr, this, slotIdx, + SWIGTYPE_p_double.getCPtr(gain)), true); } public SWIGTYPE_p_CTR_Code GetIzone(long slotIdx, SWIGTYPE_p_int zone) { - return new SWIGTYPE_p_CTR_Code(CanTalonJNI.CanTalonSRX_GetIzone(swigCPtr, this, slotIdx, SWIGTYPE_p_int.getCPtr(zone)), true); + return new SWIGTYPE_p_CTR_Code(CanTalonJNI.CanTalonSRX_GetIzone(swigCPtr, this, slotIdx, + SWIGTYPE_p_int.getCPtr(zone)), true); } public SWIGTYPE_p_CTR_Code GetCloseLoopRampRate(long slotIdx, SWIGTYPE_p_int closeLoopRampRate) { - return new SWIGTYPE_p_CTR_Code(CanTalonJNI.CanTalonSRX_GetCloseLoopRampRate(swigCPtr, this, slotIdx, SWIGTYPE_p_int.getCPtr(closeLoopRampRate)), true); + return new SWIGTYPE_p_CTR_Code(CanTalonJNI.CanTalonSRX_GetCloseLoopRampRate(swigCPtr, this, + slotIdx, SWIGTYPE_p_int.getCPtr(closeLoopRampRate)), true); } public SWIGTYPE_p_CTR_Code GetForwardSoftLimit(SWIGTYPE_p_int forwardLimit) { - return new SWIGTYPE_p_CTR_Code(CanTalonJNI.CanTalonSRX_GetForwardSoftLimit(swigCPtr, this, SWIGTYPE_p_int.getCPtr(forwardLimit)), true); + return new SWIGTYPE_p_CTR_Code(CanTalonJNI.CanTalonSRX_GetForwardSoftLimit(swigCPtr, this, + SWIGTYPE_p_int.getCPtr(forwardLimit)), true); } public SWIGTYPE_p_CTR_Code GetReverseSoftLimit(SWIGTYPE_p_int reverseLimit) { - return new SWIGTYPE_p_CTR_Code(CanTalonJNI.CanTalonSRX_GetReverseSoftLimit(swigCPtr, this, SWIGTYPE_p_int.getCPtr(reverseLimit)), true); + return new SWIGTYPE_p_CTR_Code(CanTalonJNI.CanTalonSRX_GetReverseSoftLimit(swigCPtr, this, + SWIGTYPE_p_int.getCPtr(reverseLimit)), true); } public SWIGTYPE_p_CTR_Code GetForwardSoftEnable(SWIGTYPE_p_int enable) { - return new SWIGTYPE_p_CTR_Code(CanTalonJNI.CanTalonSRX_GetForwardSoftEnable(swigCPtr, this, SWIGTYPE_p_int.getCPtr(enable)), true); + return new SWIGTYPE_p_CTR_Code(CanTalonJNI.CanTalonSRX_GetForwardSoftEnable(swigCPtr, this, + SWIGTYPE_p_int.getCPtr(enable)), true); } public SWIGTYPE_p_CTR_Code GetReverseSoftEnable(SWIGTYPE_p_int enable) { - return new SWIGTYPE_p_CTR_Code(CanTalonJNI.CanTalonSRX_GetReverseSoftEnable(swigCPtr, this, SWIGTYPE_p_int.getCPtr(enable)), true); + return new SWIGTYPE_p_CTR_Code(CanTalonJNI.CanTalonSRX_GetReverseSoftEnable(swigCPtr, this, + SWIGTYPE_p_int.getCPtr(enable)), true); } public SWIGTYPE_p_CTR_Code SetStatusFrameRate(long frameEnum, long periodMs) { - return new SWIGTYPE_p_CTR_Code(CanTalonJNI.CanTalonSRX_SetStatusFrameRate(swigCPtr, this, frameEnum, periodMs), true); + return new SWIGTYPE_p_CTR_Code(CanTalonJNI.CanTalonSRX_SetStatusFrameRate(swigCPtr, this, + frameEnum, periodMs), true); } public SWIGTYPE_p_CTR_Code ClearStickyFaults() { @@ -160,151 +189,188 @@ public class CanTalonSRX extends CtreCanNode { } public SWIGTYPE_p_CTR_Code GetFault_OverTemp(SWIGTYPE_p_int param) { - return new SWIGTYPE_p_CTR_Code(CanTalonJNI.CanTalonSRX_GetFault_OverTemp(swigCPtr, this, SWIGTYPE_p_int.getCPtr(param)), true); + return new SWIGTYPE_p_CTR_Code(CanTalonJNI.CanTalonSRX_GetFault_OverTemp(swigCPtr, this, + SWIGTYPE_p_int.getCPtr(param)), true); } public SWIGTYPE_p_CTR_Code GetFault_UnderVoltage(SWIGTYPE_p_int param) { - return new SWIGTYPE_p_CTR_Code(CanTalonJNI.CanTalonSRX_GetFault_UnderVoltage(swigCPtr, this, SWIGTYPE_p_int.getCPtr(param)), true); + return new SWIGTYPE_p_CTR_Code(CanTalonJNI.CanTalonSRX_GetFault_UnderVoltage(swigCPtr, this, + SWIGTYPE_p_int.getCPtr(param)), true); } public SWIGTYPE_p_CTR_Code GetFault_ForLim(SWIGTYPE_p_int param) { - return new SWIGTYPE_p_CTR_Code(CanTalonJNI.CanTalonSRX_GetFault_ForLim(swigCPtr, this, SWIGTYPE_p_int.getCPtr(param)), true); + return new SWIGTYPE_p_CTR_Code(CanTalonJNI.CanTalonSRX_GetFault_ForLim(swigCPtr, this, + SWIGTYPE_p_int.getCPtr(param)), true); } public SWIGTYPE_p_CTR_Code GetFault_RevLim(SWIGTYPE_p_int param) { - return new SWIGTYPE_p_CTR_Code(CanTalonJNI.CanTalonSRX_GetFault_RevLim(swigCPtr, this, SWIGTYPE_p_int.getCPtr(param)), true); + return new SWIGTYPE_p_CTR_Code(CanTalonJNI.CanTalonSRX_GetFault_RevLim(swigCPtr, this, + SWIGTYPE_p_int.getCPtr(param)), true); } public SWIGTYPE_p_CTR_Code GetFault_HardwareFailure(SWIGTYPE_p_int param) { - return new SWIGTYPE_p_CTR_Code(CanTalonJNI.CanTalonSRX_GetFault_HardwareFailure(swigCPtr, this, SWIGTYPE_p_int.getCPtr(param)), true); + return new SWIGTYPE_p_CTR_Code(CanTalonJNI.CanTalonSRX_GetFault_HardwareFailure(swigCPtr, this, + SWIGTYPE_p_int.getCPtr(param)), true); } public SWIGTYPE_p_CTR_Code GetFault_ForSoftLim(SWIGTYPE_p_int param) { - return new SWIGTYPE_p_CTR_Code(CanTalonJNI.CanTalonSRX_GetFault_ForSoftLim(swigCPtr, this, SWIGTYPE_p_int.getCPtr(param)), true); + return new SWIGTYPE_p_CTR_Code(CanTalonJNI.CanTalonSRX_GetFault_ForSoftLim(swigCPtr, this, + SWIGTYPE_p_int.getCPtr(param)), true); } public SWIGTYPE_p_CTR_Code GetFault_RevSoftLim(SWIGTYPE_p_int param) { - return new SWIGTYPE_p_CTR_Code(CanTalonJNI.CanTalonSRX_GetFault_RevSoftLim(swigCPtr, this, SWIGTYPE_p_int.getCPtr(param)), true); + return new SWIGTYPE_p_CTR_Code(CanTalonJNI.CanTalonSRX_GetFault_RevSoftLim(swigCPtr, this, + SWIGTYPE_p_int.getCPtr(param)), true); } public SWIGTYPE_p_CTR_Code GetStckyFault_OverTemp(SWIGTYPE_p_int param) { - return new SWIGTYPE_p_CTR_Code(CanTalonJNI.CanTalonSRX_GetStckyFault_OverTemp(swigCPtr, this, SWIGTYPE_p_int.getCPtr(param)), true); + return new SWIGTYPE_p_CTR_Code(CanTalonJNI.CanTalonSRX_GetStckyFault_OverTemp(swigCPtr, this, + SWIGTYPE_p_int.getCPtr(param)), true); } public SWIGTYPE_p_CTR_Code GetStckyFault_UnderVoltage(SWIGTYPE_p_int param) { - return new SWIGTYPE_p_CTR_Code(CanTalonJNI.CanTalonSRX_GetStckyFault_UnderVoltage(swigCPtr, this, SWIGTYPE_p_int.getCPtr(param)), true); + return new SWIGTYPE_p_CTR_Code(CanTalonJNI.CanTalonSRX_GetStckyFault_UnderVoltage(swigCPtr, + this, SWIGTYPE_p_int.getCPtr(param)), true); } public SWIGTYPE_p_CTR_Code GetStckyFault_ForLim(SWIGTYPE_p_int param) { - return new SWIGTYPE_p_CTR_Code(CanTalonJNI.CanTalonSRX_GetStckyFault_ForLim(swigCPtr, this, SWIGTYPE_p_int.getCPtr(param)), true); + return new SWIGTYPE_p_CTR_Code(CanTalonJNI.CanTalonSRX_GetStckyFault_ForLim(swigCPtr, this, + SWIGTYPE_p_int.getCPtr(param)), true); } public SWIGTYPE_p_CTR_Code GetStckyFault_RevLim(SWIGTYPE_p_int param) { - return new SWIGTYPE_p_CTR_Code(CanTalonJNI.CanTalonSRX_GetStckyFault_RevLim(swigCPtr, this, SWIGTYPE_p_int.getCPtr(param)), true); + return new SWIGTYPE_p_CTR_Code(CanTalonJNI.CanTalonSRX_GetStckyFault_RevLim(swigCPtr, this, + SWIGTYPE_p_int.getCPtr(param)), true); } public SWIGTYPE_p_CTR_Code GetStckyFault_ForSoftLim(SWIGTYPE_p_int param) { - return new SWIGTYPE_p_CTR_Code(CanTalonJNI.CanTalonSRX_GetStckyFault_ForSoftLim(swigCPtr, this, SWIGTYPE_p_int.getCPtr(param)), true); + return new SWIGTYPE_p_CTR_Code(CanTalonJNI.CanTalonSRX_GetStckyFault_ForSoftLim(swigCPtr, this, + SWIGTYPE_p_int.getCPtr(param)), true); } public SWIGTYPE_p_CTR_Code GetStckyFault_RevSoftLim(SWIGTYPE_p_int param) { - return new SWIGTYPE_p_CTR_Code(CanTalonJNI.CanTalonSRX_GetStckyFault_RevSoftLim(swigCPtr, this, SWIGTYPE_p_int.getCPtr(param)), true); + return new SWIGTYPE_p_CTR_Code(CanTalonJNI.CanTalonSRX_GetStckyFault_RevSoftLim(swigCPtr, this, + SWIGTYPE_p_int.getCPtr(param)), true); } public SWIGTYPE_p_CTR_Code GetAppliedThrottle(SWIGTYPE_p_int param) { - return new SWIGTYPE_p_CTR_Code(CanTalonJNI.CanTalonSRX_GetAppliedThrottle(swigCPtr, this, SWIGTYPE_p_int.getCPtr(param)), true); + return new SWIGTYPE_p_CTR_Code(CanTalonJNI.CanTalonSRX_GetAppliedThrottle(swigCPtr, this, + SWIGTYPE_p_int.getCPtr(param)), true); } public SWIGTYPE_p_CTR_Code GetCloseLoopErr(SWIGTYPE_p_int param) { - return new SWIGTYPE_p_CTR_Code(CanTalonJNI.CanTalonSRX_GetCloseLoopErr(swigCPtr, this, SWIGTYPE_p_int.getCPtr(param)), true); + return new SWIGTYPE_p_CTR_Code(CanTalonJNI.CanTalonSRX_GetCloseLoopErr(swigCPtr, this, + SWIGTYPE_p_int.getCPtr(param)), true); } public SWIGTYPE_p_CTR_Code GetFeedbackDeviceSelect(SWIGTYPE_p_int param) { - return new SWIGTYPE_p_CTR_Code(CanTalonJNI.CanTalonSRX_GetFeedbackDeviceSelect(swigCPtr, this, SWIGTYPE_p_int.getCPtr(param)), true); + return new SWIGTYPE_p_CTR_Code(CanTalonJNI.CanTalonSRX_GetFeedbackDeviceSelect(swigCPtr, this, + SWIGTYPE_p_int.getCPtr(param)), true); } public SWIGTYPE_p_CTR_Code GetModeSelect(SWIGTYPE_p_int param) { - return new SWIGTYPE_p_CTR_Code(CanTalonJNI.CanTalonSRX_GetModeSelect(swigCPtr, this, SWIGTYPE_p_int.getCPtr(param)), true); + return new SWIGTYPE_p_CTR_Code(CanTalonJNI.CanTalonSRX_GetModeSelect(swigCPtr, this, + SWIGTYPE_p_int.getCPtr(param)), true); } public SWIGTYPE_p_CTR_Code GetLimitSwitchEn(SWIGTYPE_p_int param) { - return new SWIGTYPE_p_CTR_Code(CanTalonJNI.CanTalonSRX_GetLimitSwitchEn(swigCPtr, this, SWIGTYPE_p_int.getCPtr(param)), true); + return new SWIGTYPE_p_CTR_Code(CanTalonJNI.CanTalonSRX_GetLimitSwitchEn(swigCPtr, this, + SWIGTYPE_p_int.getCPtr(param)), true); } public SWIGTYPE_p_CTR_Code GetLimitSwitchClosedFor(SWIGTYPE_p_int param) { - return new SWIGTYPE_p_CTR_Code(CanTalonJNI.CanTalonSRX_GetLimitSwitchClosedFor(swigCPtr, this, SWIGTYPE_p_int.getCPtr(param)), true); + return new SWIGTYPE_p_CTR_Code(CanTalonJNI.CanTalonSRX_GetLimitSwitchClosedFor(swigCPtr, this, + SWIGTYPE_p_int.getCPtr(param)), true); } public SWIGTYPE_p_CTR_Code GetLimitSwitchClosedRev(SWIGTYPE_p_int param) { - return new SWIGTYPE_p_CTR_Code(CanTalonJNI.CanTalonSRX_GetLimitSwitchClosedRev(swigCPtr, this, SWIGTYPE_p_int.getCPtr(param)), true); + return new SWIGTYPE_p_CTR_Code(CanTalonJNI.CanTalonSRX_GetLimitSwitchClosedRev(swigCPtr, this, + SWIGTYPE_p_int.getCPtr(param)), true); } public SWIGTYPE_p_CTR_Code GetSensorPosition(SWIGTYPE_p_int param) { - return new SWIGTYPE_p_CTR_Code(CanTalonJNI.CanTalonSRX_GetSensorPosition(swigCPtr, this, SWIGTYPE_p_int.getCPtr(param)), true); + return new SWIGTYPE_p_CTR_Code(CanTalonJNI.CanTalonSRX_GetSensorPosition(swigCPtr, this, + SWIGTYPE_p_int.getCPtr(param)), true); } public SWIGTYPE_p_CTR_Code GetSensorVelocity(SWIGTYPE_p_int param) { - return new SWIGTYPE_p_CTR_Code(CanTalonJNI.CanTalonSRX_GetSensorVelocity(swigCPtr, this, SWIGTYPE_p_int.getCPtr(param)), true); + return new SWIGTYPE_p_CTR_Code(CanTalonJNI.CanTalonSRX_GetSensorVelocity(swigCPtr, this, + SWIGTYPE_p_int.getCPtr(param)), true); } public SWIGTYPE_p_CTR_Code GetCurrent(SWIGTYPE_p_double param) { - return new SWIGTYPE_p_CTR_Code(CanTalonJNI.CanTalonSRX_GetCurrent(swigCPtr, this, SWIGTYPE_p_double.getCPtr(param)), true); + return new SWIGTYPE_p_CTR_Code(CanTalonJNI.CanTalonSRX_GetCurrent(swigCPtr, this, + SWIGTYPE_p_double.getCPtr(param)), true); } public SWIGTYPE_p_CTR_Code GetBrakeIsEnabled(SWIGTYPE_p_int param) { - return new SWIGTYPE_p_CTR_Code(CanTalonJNI.CanTalonSRX_GetBrakeIsEnabled(swigCPtr, this, SWIGTYPE_p_int.getCPtr(param)), true); + return new SWIGTYPE_p_CTR_Code(CanTalonJNI.CanTalonSRX_GetBrakeIsEnabled(swigCPtr, this, + SWIGTYPE_p_int.getCPtr(param)), true); } public SWIGTYPE_p_CTR_Code GetEncPosition(SWIGTYPE_p_int param) { - return new SWIGTYPE_p_CTR_Code(CanTalonJNI.CanTalonSRX_GetEncPosition(swigCPtr, this, SWIGTYPE_p_int.getCPtr(param)), true); + return new SWIGTYPE_p_CTR_Code(CanTalonJNI.CanTalonSRX_GetEncPosition(swigCPtr, this, + SWIGTYPE_p_int.getCPtr(param)), true); } public SWIGTYPE_p_CTR_Code GetEncVel(SWIGTYPE_p_int param) { - return new SWIGTYPE_p_CTR_Code(CanTalonJNI.CanTalonSRX_GetEncVel(swigCPtr, this, SWIGTYPE_p_int.getCPtr(param)), true); + return new SWIGTYPE_p_CTR_Code(CanTalonJNI.CanTalonSRX_GetEncVel(swigCPtr, this, + SWIGTYPE_p_int.getCPtr(param)), true); } public SWIGTYPE_p_CTR_Code GetEncIndexRiseEvents(SWIGTYPE_p_int param) { - return new SWIGTYPE_p_CTR_Code(CanTalonJNI.CanTalonSRX_GetEncIndexRiseEvents(swigCPtr, this, SWIGTYPE_p_int.getCPtr(param)), true); + return new SWIGTYPE_p_CTR_Code(CanTalonJNI.CanTalonSRX_GetEncIndexRiseEvents(swigCPtr, this, + SWIGTYPE_p_int.getCPtr(param)), true); } public SWIGTYPE_p_CTR_Code GetQuadApin(SWIGTYPE_p_int param) { - return new SWIGTYPE_p_CTR_Code(CanTalonJNI.CanTalonSRX_GetQuadApin(swigCPtr, this, SWIGTYPE_p_int.getCPtr(param)), true); + return new SWIGTYPE_p_CTR_Code(CanTalonJNI.CanTalonSRX_GetQuadApin(swigCPtr, this, + SWIGTYPE_p_int.getCPtr(param)), true); } public SWIGTYPE_p_CTR_Code GetQuadBpin(SWIGTYPE_p_int param) { - return new SWIGTYPE_p_CTR_Code(CanTalonJNI.CanTalonSRX_GetQuadBpin(swigCPtr, this, SWIGTYPE_p_int.getCPtr(param)), true); + return new SWIGTYPE_p_CTR_Code(CanTalonJNI.CanTalonSRX_GetQuadBpin(swigCPtr, this, + SWIGTYPE_p_int.getCPtr(param)), true); } public SWIGTYPE_p_CTR_Code GetQuadIdxpin(SWIGTYPE_p_int param) { - return new SWIGTYPE_p_CTR_Code(CanTalonJNI.CanTalonSRX_GetQuadIdxpin(swigCPtr, this, SWIGTYPE_p_int.getCPtr(param)), true); + return new SWIGTYPE_p_CTR_Code(CanTalonJNI.CanTalonSRX_GetQuadIdxpin(swigCPtr, this, + SWIGTYPE_p_int.getCPtr(param)), true); } public SWIGTYPE_p_CTR_Code GetAnalogInWithOv(SWIGTYPE_p_int param) { - return new SWIGTYPE_p_CTR_Code(CanTalonJNI.CanTalonSRX_GetAnalogInWithOv(swigCPtr, this, SWIGTYPE_p_int.getCPtr(param)), true); + return new SWIGTYPE_p_CTR_Code(CanTalonJNI.CanTalonSRX_GetAnalogInWithOv(swigCPtr, this, + SWIGTYPE_p_int.getCPtr(param)), true); } public SWIGTYPE_p_CTR_Code GetAnalogInVel(SWIGTYPE_p_int param) { - return new SWIGTYPE_p_CTR_Code(CanTalonJNI.CanTalonSRX_GetAnalogInVel(swigCPtr, this, SWIGTYPE_p_int.getCPtr(param)), true); + return new SWIGTYPE_p_CTR_Code(CanTalonJNI.CanTalonSRX_GetAnalogInVel(swigCPtr, this, + SWIGTYPE_p_int.getCPtr(param)), true); } public SWIGTYPE_p_CTR_Code GetTemp(SWIGTYPE_p_double param) { - return new SWIGTYPE_p_CTR_Code(CanTalonJNI.CanTalonSRX_GetTemp(swigCPtr, this, SWIGTYPE_p_double.getCPtr(param)), true); + return new SWIGTYPE_p_CTR_Code(CanTalonJNI.CanTalonSRX_GetTemp(swigCPtr, this, + SWIGTYPE_p_double.getCPtr(param)), true); } public SWIGTYPE_p_CTR_Code GetBatteryV(SWIGTYPE_p_double param) { - return new SWIGTYPE_p_CTR_Code(CanTalonJNI.CanTalonSRX_GetBatteryV(swigCPtr, this, SWIGTYPE_p_double.getCPtr(param)), true); + return new SWIGTYPE_p_CTR_Code(CanTalonJNI.CanTalonSRX_GetBatteryV(swigCPtr, this, + SWIGTYPE_p_double.getCPtr(param)), true); } public SWIGTYPE_p_CTR_Code GetResetCount(SWIGTYPE_p_int param) { - return new SWIGTYPE_p_CTR_Code(CanTalonJNI.CanTalonSRX_GetResetCount(swigCPtr, this, SWIGTYPE_p_int.getCPtr(param)), true); + return new SWIGTYPE_p_CTR_Code(CanTalonJNI.CanTalonSRX_GetResetCount(swigCPtr, this, + SWIGTYPE_p_int.getCPtr(param)), true); } public SWIGTYPE_p_CTR_Code GetResetFlags(SWIGTYPE_p_int param) { - return new SWIGTYPE_p_CTR_Code(CanTalonJNI.CanTalonSRX_GetResetFlags(swigCPtr, this, SWIGTYPE_p_int.getCPtr(param)), true); + return new SWIGTYPE_p_CTR_Code(CanTalonJNI.CanTalonSRX_GetResetFlags(swigCPtr, this, + SWIGTYPE_p_int.getCPtr(param)), true); } public SWIGTYPE_p_CTR_Code GetFirmVers(SWIGTYPE_p_int param) { - return new SWIGTYPE_p_CTR_Code(CanTalonJNI.CanTalonSRX_GetFirmVers(swigCPtr, this, SWIGTYPE_p_int.getCPtr(param)), true); + return new SWIGTYPE_p_CTR_Code(CanTalonJNI.CanTalonSRX_GetFirmVers(swigCPtr, this, + SWIGTYPE_p_int.getCPtr(param)), true); } public SWIGTYPE_p_CTR_Code SetDemand(int param) { @@ -312,131 +378,237 @@ public class CanTalonSRX extends CtreCanNode { } public SWIGTYPE_p_CTR_Code SetOverrideLimitSwitchEn(int param) { - return new SWIGTYPE_p_CTR_Code(CanTalonJNI.CanTalonSRX_SetOverrideLimitSwitchEn(swigCPtr, this, param), true); + return new SWIGTYPE_p_CTR_Code(CanTalonJNI.CanTalonSRX_SetOverrideLimitSwitchEn(swigCPtr, this, + param), true); } public SWIGTYPE_p_CTR_Code SetFeedbackDeviceSelect(int param) { - return new SWIGTYPE_p_CTR_Code(CanTalonJNI.CanTalonSRX_SetFeedbackDeviceSelect(swigCPtr, this, param), true); + return new SWIGTYPE_p_CTR_Code(CanTalonJNI.CanTalonSRX_SetFeedbackDeviceSelect(swigCPtr, this, + param), true); } public SWIGTYPE_p_CTR_Code SetRevMotDuringCloseLoopEn(int param) { - return new SWIGTYPE_p_CTR_Code(CanTalonJNI.CanTalonSRX_SetRevMotDuringCloseLoopEn(swigCPtr, this, param), true); + return new SWIGTYPE_p_CTR_Code(CanTalonJNI.CanTalonSRX_SetRevMotDuringCloseLoopEn(swigCPtr, + this, param), true); } public SWIGTYPE_p_CTR_Code SetOverrideBrakeType(int param) { - return new SWIGTYPE_p_CTR_Code(CanTalonJNI.CanTalonSRX_SetOverrideBrakeType(swigCPtr, this, param), true); + return new SWIGTYPE_p_CTR_Code(CanTalonJNI.CanTalonSRX_SetOverrideBrakeType(swigCPtr, this, + param), true); } public SWIGTYPE_p_CTR_Code SetModeSelect(int param) { - return new SWIGTYPE_p_CTR_Code(CanTalonJNI.CanTalonSRX_SetModeSelect(swigCPtr, this, param), true); + return new SWIGTYPE_p_CTR_Code(CanTalonJNI.CanTalonSRX_SetModeSelect(swigCPtr, this, param), + true); } public SWIGTYPE_p_CTR_Code SetProfileSlotSelect(int param) { - return new SWIGTYPE_p_CTR_Code(CanTalonJNI.CanTalonSRX_SetProfileSlotSelect(swigCPtr, this, param), true); + return new SWIGTYPE_p_CTR_Code(CanTalonJNI.CanTalonSRX_SetProfileSlotSelect(swigCPtr, this, + param), true); } public SWIGTYPE_p_CTR_Code SetRampThrottle(int param) { - return new SWIGTYPE_p_CTR_Code(CanTalonJNI.CanTalonSRX_SetRampThrottle(swigCPtr, this, param), true); + return new SWIGTYPE_p_CTR_Code(CanTalonJNI.CanTalonSRX_SetRampThrottle(swigCPtr, this, param), + true); } public SWIGTYPE_p_CTR_Code SetRevFeedbackSensor(int param) { - return new SWIGTYPE_p_CTR_Code(CanTalonJNI.CanTalonSRX_SetRevFeedbackSensor(swigCPtr, this, param), true); + return new SWIGTYPE_p_CTR_Code(CanTalonJNI.CanTalonSRX_SetRevFeedbackSensor(swigCPtr, this, + param), true); } - public final static int kDefaultControlPeriodMs = CanTalonJNI.CanTalonSRX_kDefaultControlPeriodMs_get(); + public final static int kDefaultControlPeriodMs = CanTalonJNI + .CanTalonSRX_kDefaultControlPeriodMs_get(); public final static int kMode_DutyCycle = CanTalonJNI.CanTalonSRX_kMode_DutyCycle_get(); - public final static int kMode_PositionCloseLoop = CanTalonJNI.CanTalonSRX_kMode_PositionCloseLoop_get(); - public final static int kMode_VelocityCloseLoop = CanTalonJNI.CanTalonSRX_kMode_VelocityCloseLoop_get(); - public final static int kMode_CurrentCloseLoop = CanTalonJNI.CanTalonSRX_kMode_CurrentCloseLoop_get(); + public final static int kMode_PositionCloseLoop = CanTalonJNI + .CanTalonSRX_kMode_PositionCloseLoop_get(); + public final static int kMode_VelocityCloseLoop = CanTalonJNI + .CanTalonSRX_kMode_VelocityCloseLoop_get(); + public final static int kMode_CurrentCloseLoop = CanTalonJNI + .CanTalonSRX_kMode_CurrentCloseLoop_get(); public final static int kMode_VoltCompen = CanTalonJNI.CanTalonSRX_kMode_VoltCompen_get(); public final static int kMode_SlaveFollower = CanTalonJNI.CanTalonSRX_kMode_SlaveFollower_get(); public final static int kMode_NoDrive = CanTalonJNI.CanTalonSRX_kMode_NoDrive_get(); - public final static int kLimitSwitchOverride_UseDefaultsFromFlash = CanTalonJNI.CanTalonSRX_kLimitSwitchOverride_UseDefaultsFromFlash_get(); - public final static int kLimitSwitchOverride_DisableFwd_DisableRev = CanTalonJNI.CanTalonSRX_kLimitSwitchOverride_DisableFwd_DisableRev_get(); - public final static int kLimitSwitchOverride_DisableFwd_EnableRev = CanTalonJNI.CanTalonSRX_kLimitSwitchOverride_DisableFwd_EnableRev_get(); - public final static int kLimitSwitchOverride_EnableFwd_DisableRev = CanTalonJNI.CanTalonSRX_kLimitSwitchOverride_EnableFwd_DisableRev_get(); - public final static int kLimitSwitchOverride_EnableFwd_EnableRev = CanTalonJNI.CanTalonSRX_kLimitSwitchOverride_EnableFwd_EnableRev_get(); - public final static int kBrakeOverride_UseDefaultsFromFlash = CanTalonJNI.CanTalonSRX_kBrakeOverride_UseDefaultsFromFlash_get(); - public final static int kBrakeOverride_OverrideCoast = CanTalonJNI.CanTalonSRX_kBrakeOverride_OverrideCoast_get(); - public final static int kBrakeOverride_OverrideBrake = CanTalonJNI.CanTalonSRX_kBrakeOverride_OverrideBrake_get(); - public final static int kFeedbackDev_DigitalQuadEnc = CanTalonJNI.CanTalonSRX_kFeedbackDev_DigitalQuadEnc_get(); - public final static int kFeedbackDev_AnalogPot = CanTalonJNI.CanTalonSRX_kFeedbackDev_AnalogPot_get(); - public final static int kFeedbackDev_AnalogEncoder = CanTalonJNI.CanTalonSRX_kFeedbackDev_AnalogEncoder_get(); - public final static int kFeedbackDev_CountEveryRisingEdge = CanTalonJNI.CanTalonSRX_kFeedbackDev_CountEveryRisingEdge_get(); - public final static int kFeedbackDev_CountEveryFallingEdge = CanTalonJNI.CanTalonSRX_kFeedbackDev_CountEveryFallingEdge_get(); - public final static int kFeedbackDev_PosIsPulseWidth = CanTalonJNI.CanTalonSRX_kFeedbackDev_PosIsPulseWidth_get(); - public final static int kProfileSlotSelect_Slot0 = CanTalonJNI.CanTalonSRX_kProfileSlotSelect_Slot0_get(); - public final static int kProfileSlotSelect_Slot1 = CanTalonJNI.CanTalonSRX_kProfileSlotSelect_Slot1_get(); + public final static int kLimitSwitchOverride_UseDefaultsFromFlash = CanTalonJNI + .CanTalonSRX_kLimitSwitchOverride_UseDefaultsFromFlash_get(); + public final static int kLimitSwitchOverride_DisableFwd_DisableRev = CanTalonJNI + .CanTalonSRX_kLimitSwitchOverride_DisableFwd_DisableRev_get(); + public final static int kLimitSwitchOverride_DisableFwd_EnableRev = CanTalonJNI + .CanTalonSRX_kLimitSwitchOverride_DisableFwd_EnableRev_get(); + public final static int kLimitSwitchOverride_EnableFwd_DisableRev = CanTalonJNI + .CanTalonSRX_kLimitSwitchOverride_EnableFwd_DisableRev_get(); + public final static int kLimitSwitchOverride_EnableFwd_EnableRev = CanTalonJNI + .CanTalonSRX_kLimitSwitchOverride_EnableFwd_EnableRev_get(); + public final static int kBrakeOverride_UseDefaultsFromFlash = CanTalonJNI + .CanTalonSRX_kBrakeOverride_UseDefaultsFromFlash_get(); + public final static int kBrakeOverride_OverrideCoast = CanTalonJNI + .CanTalonSRX_kBrakeOverride_OverrideCoast_get(); + public final static int kBrakeOverride_OverrideBrake = CanTalonJNI + .CanTalonSRX_kBrakeOverride_OverrideBrake_get(); + public final static int kFeedbackDev_DigitalQuadEnc = CanTalonJNI + .CanTalonSRX_kFeedbackDev_DigitalQuadEnc_get(); + public final static int kFeedbackDev_AnalogPot = CanTalonJNI + .CanTalonSRX_kFeedbackDev_AnalogPot_get(); + public final static int kFeedbackDev_AnalogEncoder = CanTalonJNI + .CanTalonSRX_kFeedbackDev_AnalogEncoder_get(); + public final static int kFeedbackDev_CountEveryRisingEdge = CanTalonJNI + .CanTalonSRX_kFeedbackDev_CountEveryRisingEdge_get(); + public final static int kFeedbackDev_CountEveryFallingEdge = CanTalonJNI + .CanTalonSRX_kFeedbackDev_CountEveryFallingEdge_get(); + public final static int kFeedbackDev_PosIsPulseWidth = CanTalonJNI + .CanTalonSRX_kFeedbackDev_PosIsPulseWidth_get(); + public final static int kProfileSlotSelect_Slot0 = CanTalonJNI + .CanTalonSRX_kProfileSlotSelect_Slot0_get(); + public final static int kProfileSlotSelect_Slot1 = CanTalonJNI + .CanTalonSRX_kProfileSlotSelect_Slot1_get(); public final static int kStatusFrame_General = CanTalonJNI.CanTalonSRX_kStatusFrame_General_get(); - public final static int kStatusFrame_Feedback = CanTalonJNI.CanTalonSRX_kStatusFrame_Feedback_get(); + public final static int kStatusFrame_Feedback = CanTalonJNI + .CanTalonSRX_kStatusFrame_Feedback_get(); public final static int kStatusFrame_Encoder = CanTalonJNI.CanTalonSRX_kStatusFrame_Encoder_get(); - public final static int kStatusFrame_AnalogTempVbat = CanTalonJNI.CanTalonSRX_kStatusFrame_AnalogTempVbat_get(); + public final static int kStatusFrame_AnalogTempVbat = CanTalonJNI + .CanTalonSRX_kStatusFrame_AnalogTempVbat_get(); + public final static class param_t { - public final static CanTalonSRX.param_t eProfileParamSlot0_P = new CanTalonSRX.param_t("eProfileParamSlot0_P", CanTalonJNI.CanTalonSRX_eProfileParamSlot0_P_get()); - public final static CanTalonSRX.param_t eProfileParamSlot0_I = new CanTalonSRX.param_t("eProfileParamSlot0_I", CanTalonJNI.CanTalonSRX_eProfileParamSlot0_I_get()); - public final static CanTalonSRX.param_t eProfileParamSlot0_D = new CanTalonSRX.param_t("eProfileParamSlot0_D", CanTalonJNI.CanTalonSRX_eProfileParamSlot0_D_get()); - public final static CanTalonSRX.param_t eProfileParamSlot0_F = new CanTalonSRX.param_t("eProfileParamSlot0_F", CanTalonJNI.CanTalonSRX_eProfileParamSlot0_F_get()); - public final static CanTalonSRX.param_t eProfileParamSlot0_IZone = new CanTalonSRX.param_t("eProfileParamSlot0_IZone", CanTalonJNI.CanTalonSRX_eProfileParamSlot0_IZone_get()); - public final static CanTalonSRX.param_t eProfileParamSlot0_CloseLoopRampRate = new CanTalonSRX.param_t("eProfileParamSlot0_CloseLoopRampRate", CanTalonJNI.CanTalonSRX_eProfileParamSlot0_CloseLoopRampRate_get()); - public final static CanTalonSRX.param_t eProfileParamSlot1_P = new CanTalonSRX.param_t("eProfileParamSlot1_P", CanTalonJNI.CanTalonSRX_eProfileParamSlot1_P_get()); - public final static CanTalonSRX.param_t eProfileParamSlot1_I = new CanTalonSRX.param_t("eProfileParamSlot1_I", CanTalonJNI.CanTalonSRX_eProfileParamSlot1_I_get()); - public final static CanTalonSRX.param_t eProfileParamSlot1_D = new CanTalonSRX.param_t("eProfileParamSlot1_D", CanTalonJNI.CanTalonSRX_eProfileParamSlot1_D_get()); - public final static CanTalonSRX.param_t eProfileParamSlot1_F = new CanTalonSRX.param_t("eProfileParamSlot1_F", CanTalonJNI.CanTalonSRX_eProfileParamSlot1_F_get()); - public final static CanTalonSRX.param_t eProfileParamSlot1_IZone = new CanTalonSRX.param_t("eProfileParamSlot1_IZone", CanTalonJNI.CanTalonSRX_eProfileParamSlot1_IZone_get()); - public final static CanTalonSRX.param_t eProfileParamSlot1_CloseLoopRampRate = new CanTalonSRX.param_t("eProfileParamSlot1_CloseLoopRampRate", CanTalonJNI.CanTalonSRX_eProfileParamSlot1_CloseLoopRampRate_get()); - public final static CanTalonSRX.param_t eProfileParamSoftLimitForThreshold = new CanTalonSRX.param_t("eProfileParamSoftLimitForThreshold", CanTalonJNI.CanTalonSRX_eProfileParamSoftLimitForThreshold_get()); - public final static CanTalonSRX.param_t eProfileParamSoftLimitRevThreshold = new CanTalonSRX.param_t("eProfileParamSoftLimitRevThreshold", CanTalonJNI.CanTalonSRX_eProfileParamSoftLimitRevThreshold_get()); - public final static CanTalonSRX.param_t eProfileParamSoftLimitForEnable = new CanTalonSRX.param_t("eProfileParamSoftLimitForEnable", CanTalonJNI.CanTalonSRX_eProfileParamSoftLimitForEnable_get()); - public final static CanTalonSRX.param_t eProfileParamSoftLimitRevEnable = new CanTalonSRX.param_t("eProfileParamSoftLimitRevEnable", CanTalonJNI.CanTalonSRX_eProfileParamSoftLimitRevEnable_get()); - public final static CanTalonSRX.param_t eOnBoot_BrakeMode = new CanTalonSRX.param_t("eOnBoot_BrakeMode", CanTalonJNI.CanTalonSRX_eOnBoot_BrakeMode_get()); - public final static CanTalonSRX.param_t eOnBoot_LimitSwitch_Forward_NormallyClosed = new CanTalonSRX.param_t("eOnBoot_LimitSwitch_Forward_NormallyClosed", CanTalonJNI.CanTalonSRX_eOnBoot_LimitSwitch_Forward_NormallyClosed_get()); - public final static CanTalonSRX.param_t eOnBoot_LimitSwitch_Reverse_NormallyClosed = new CanTalonSRX.param_t("eOnBoot_LimitSwitch_Reverse_NormallyClosed", CanTalonJNI.CanTalonSRX_eOnBoot_LimitSwitch_Reverse_NormallyClosed_get()); - public final static CanTalonSRX.param_t eOnBoot_LimitSwitch_Forward_Disable = new CanTalonSRX.param_t("eOnBoot_LimitSwitch_Forward_Disable", CanTalonJNI.CanTalonSRX_eOnBoot_LimitSwitch_Forward_Disable_get()); - public final static CanTalonSRX.param_t eOnBoot_LimitSwitch_Reverse_Disable = new CanTalonSRX.param_t("eOnBoot_LimitSwitch_Reverse_Disable", CanTalonJNI.CanTalonSRX_eOnBoot_LimitSwitch_Reverse_Disable_get()); - public final static CanTalonSRX.param_t eFault_OverTemp = new CanTalonSRX.param_t("eFault_OverTemp", CanTalonJNI.CanTalonSRX_eFault_OverTemp_get()); - public final static CanTalonSRX.param_t eFault_UnderVoltage = new CanTalonSRX.param_t("eFault_UnderVoltage", CanTalonJNI.CanTalonSRX_eFault_UnderVoltage_get()); - public final static CanTalonSRX.param_t eFault_ForLim = new CanTalonSRX.param_t("eFault_ForLim", CanTalonJNI.CanTalonSRX_eFault_ForLim_get()); - public final static CanTalonSRX.param_t eFault_RevLim = new CanTalonSRX.param_t("eFault_RevLim", CanTalonJNI.CanTalonSRX_eFault_RevLim_get()); - public final static CanTalonSRX.param_t eFault_HardwareFailure = new CanTalonSRX.param_t("eFault_HardwareFailure", CanTalonJNI.CanTalonSRX_eFault_HardwareFailure_get()); - public final static CanTalonSRX.param_t eFault_ForSoftLim = new CanTalonSRX.param_t("eFault_ForSoftLim", CanTalonJNI.CanTalonSRX_eFault_ForSoftLim_get()); - public final static CanTalonSRX.param_t eFault_RevSoftLim = new CanTalonSRX.param_t("eFault_RevSoftLim", CanTalonJNI.CanTalonSRX_eFault_RevSoftLim_get()); - public final static CanTalonSRX.param_t eStckyFault_OverTemp = new CanTalonSRX.param_t("eStckyFault_OverTemp", CanTalonJNI.CanTalonSRX_eStckyFault_OverTemp_get()); - public final static CanTalonSRX.param_t eStckyFault_UnderVoltage = new CanTalonSRX.param_t("eStckyFault_UnderVoltage", CanTalonJNI.CanTalonSRX_eStckyFault_UnderVoltage_get()); - public final static CanTalonSRX.param_t eStckyFault_ForLim = new CanTalonSRX.param_t("eStckyFault_ForLim", CanTalonJNI.CanTalonSRX_eStckyFault_ForLim_get()); - public final static CanTalonSRX.param_t eStckyFault_RevLim = new CanTalonSRX.param_t("eStckyFault_RevLim", CanTalonJNI.CanTalonSRX_eStckyFault_RevLim_get()); - public final static CanTalonSRX.param_t eStckyFault_ForSoftLim = new CanTalonSRX.param_t("eStckyFault_ForSoftLim", CanTalonJNI.CanTalonSRX_eStckyFault_ForSoftLim_get()); - public final static CanTalonSRX.param_t eStckyFault_RevSoftLim = new CanTalonSRX.param_t("eStckyFault_RevSoftLim", CanTalonJNI.CanTalonSRX_eStckyFault_RevSoftLim_get()); - public final static CanTalonSRX.param_t eAppliedThrottle = new CanTalonSRX.param_t("eAppliedThrottle", CanTalonJNI.CanTalonSRX_eAppliedThrottle_get()); - public final static CanTalonSRX.param_t eCloseLoopErr = new CanTalonSRX.param_t("eCloseLoopErr", CanTalonJNI.CanTalonSRX_eCloseLoopErr_get()); - public final static CanTalonSRX.param_t eFeedbackDeviceSelect = new CanTalonSRX.param_t("eFeedbackDeviceSelect", CanTalonJNI.CanTalonSRX_eFeedbackDeviceSelect_get()); - public final static CanTalonSRX.param_t eRevMotDuringCloseLoopEn = new CanTalonSRX.param_t("eRevMotDuringCloseLoopEn", CanTalonJNI.CanTalonSRX_eRevMotDuringCloseLoopEn_get()); - public final static CanTalonSRX.param_t eModeSelect = new CanTalonSRX.param_t("eModeSelect", CanTalonJNI.CanTalonSRX_eModeSelect_get()); - public final static CanTalonSRX.param_t eProfileSlotSelect = new CanTalonSRX.param_t("eProfileSlotSelect", CanTalonJNI.CanTalonSRX_eProfileSlotSelect_get()); - public final static CanTalonSRX.param_t eRampThrottle = new CanTalonSRX.param_t("eRampThrottle", CanTalonJNI.CanTalonSRX_eRampThrottle_get()); - public final static CanTalonSRX.param_t eRevFeedbackSensor = new CanTalonSRX.param_t("eRevFeedbackSensor", CanTalonJNI.CanTalonSRX_eRevFeedbackSensor_get()); - public final static CanTalonSRX.param_t eLimitSwitchEn = new CanTalonSRX.param_t("eLimitSwitchEn", CanTalonJNI.CanTalonSRX_eLimitSwitchEn_get()); - public final static CanTalonSRX.param_t eLimitSwitchClosedFor = new CanTalonSRX.param_t("eLimitSwitchClosedFor", CanTalonJNI.CanTalonSRX_eLimitSwitchClosedFor_get()); - public final static CanTalonSRX.param_t eLimitSwitchClosedRev = new CanTalonSRX.param_t("eLimitSwitchClosedRev", CanTalonJNI.CanTalonSRX_eLimitSwitchClosedRev_get()); - public final static CanTalonSRX.param_t eSensorPosition = new CanTalonSRX.param_t("eSensorPosition", CanTalonJNI.CanTalonSRX_eSensorPosition_get()); - public final static CanTalonSRX.param_t eSensorVelocity = new CanTalonSRX.param_t("eSensorVelocity", CanTalonJNI.CanTalonSRX_eSensorVelocity_get()); - public final static CanTalonSRX.param_t eCurrent = new CanTalonSRX.param_t("eCurrent", CanTalonJNI.CanTalonSRX_eCurrent_get()); - public final static CanTalonSRX.param_t eBrakeIsEnabled = new CanTalonSRX.param_t("eBrakeIsEnabled", CanTalonJNI.CanTalonSRX_eBrakeIsEnabled_get()); - public final static CanTalonSRX.param_t eEncPosition = new CanTalonSRX.param_t("eEncPosition", CanTalonJNI.CanTalonSRX_eEncPosition_get()); - public final static CanTalonSRX.param_t eEncVel = new CanTalonSRX.param_t("eEncVel", CanTalonJNI.CanTalonSRX_eEncVel_get()); - public final static CanTalonSRX.param_t eEncIndexRiseEvents = new CanTalonSRX.param_t("eEncIndexRiseEvents", CanTalonJNI.CanTalonSRX_eEncIndexRiseEvents_get()); - public final static CanTalonSRX.param_t eQuadApin = new CanTalonSRX.param_t("eQuadApin", CanTalonJNI.CanTalonSRX_eQuadApin_get()); - public final static CanTalonSRX.param_t eQuadBpin = new CanTalonSRX.param_t("eQuadBpin", CanTalonJNI.CanTalonSRX_eQuadBpin_get()); - public final static CanTalonSRX.param_t eQuadIdxpin = new CanTalonSRX.param_t("eQuadIdxpin", CanTalonJNI.CanTalonSRX_eQuadIdxpin_get()); - public final static CanTalonSRX.param_t eAnalogInWithOv = new CanTalonSRX.param_t("eAnalogInWithOv", CanTalonJNI.CanTalonSRX_eAnalogInWithOv_get()); - public final static CanTalonSRX.param_t eAnalogInVel = new CanTalonSRX.param_t("eAnalogInVel", CanTalonJNI.CanTalonSRX_eAnalogInVel_get()); - public final static CanTalonSRX.param_t eTemp = new CanTalonSRX.param_t("eTemp", CanTalonJNI.CanTalonSRX_eTemp_get()); - public final static CanTalonSRX.param_t eBatteryV = new CanTalonSRX.param_t("eBatteryV", CanTalonJNI.CanTalonSRX_eBatteryV_get()); - public final static CanTalonSRX.param_t eResetCount = new CanTalonSRX.param_t("eResetCount", CanTalonJNI.CanTalonSRX_eResetCount_get()); - public final static CanTalonSRX.param_t eResetFlags = new CanTalonSRX.param_t("eResetFlags", CanTalonJNI.CanTalonSRX_eResetFlags_get()); - public final static CanTalonSRX.param_t eFirmVers = new CanTalonSRX.param_t("eFirmVers", CanTalonJNI.CanTalonSRX_eFirmVers_get()); - public final static CanTalonSRX.param_t eSettingsChanged = new CanTalonSRX.param_t("eSettingsChanged", CanTalonJNI.CanTalonSRX_eSettingsChanged_get()); - public final static CanTalonSRX.param_t eQuadFilterEn = new CanTalonSRX.param_t("eQuadFilterEn", CanTalonJNI.CanTalonSRX_eQuadFilterEn_get()); - public final static CanTalonSRX.param_t ePidIaccum = new CanTalonSRX.param_t("ePidIaccum", CanTalonJNI.CanTalonSRX_ePidIaccum_get()); + public final static CanTalonSRX.param_t eProfileParamSlot0_P = new CanTalonSRX.param_t( + "eProfileParamSlot0_P", CanTalonJNI.CanTalonSRX_eProfileParamSlot0_P_get()); + public final static CanTalonSRX.param_t eProfileParamSlot0_I = new CanTalonSRX.param_t( + "eProfileParamSlot0_I", CanTalonJNI.CanTalonSRX_eProfileParamSlot0_I_get()); + public final static CanTalonSRX.param_t eProfileParamSlot0_D = new CanTalonSRX.param_t( + "eProfileParamSlot0_D", CanTalonJNI.CanTalonSRX_eProfileParamSlot0_D_get()); + public final static CanTalonSRX.param_t eProfileParamSlot0_F = new CanTalonSRX.param_t( + "eProfileParamSlot0_F", CanTalonJNI.CanTalonSRX_eProfileParamSlot0_F_get()); + public final static CanTalonSRX.param_t eProfileParamSlot0_IZone = new CanTalonSRX.param_t( + "eProfileParamSlot0_IZone", CanTalonJNI.CanTalonSRX_eProfileParamSlot0_IZone_get()); + public final static CanTalonSRX.param_t eProfileParamSlot0_CloseLoopRampRate = + new CanTalonSRX.param_t("eProfileParamSlot0_CloseLoopRampRate", + CanTalonJNI.CanTalonSRX_eProfileParamSlot0_CloseLoopRampRate_get()); + public final static CanTalonSRX.param_t eProfileParamSlot1_P = new CanTalonSRX.param_t( + "eProfileParamSlot1_P", CanTalonJNI.CanTalonSRX_eProfileParamSlot1_P_get()); + public final static CanTalonSRX.param_t eProfileParamSlot1_I = new CanTalonSRX.param_t( + "eProfileParamSlot1_I", CanTalonJNI.CanTalonSRX_eProfileParamSlot1_I_get()); + public final static CanTalonSRX.param_t eProfileParamSlot1_D = new CanTalonSRX.param_t( + "eProfileParamSlot1_D", CanTalonJNI.CanTalonSRX_eProfileParamSlot1_D_get()); + public final static CanTalonSRX.param_t eProfileParamSlot1_F = new CanTalonSRX.param_t( + "eProfileParamSlot1_F", CanTalonJNI.CanTalonSRX_eProfileParamSlot1_F_get()); + public final static CanTalonSRX.param_t eProfileParamSlot1_IZone = new CanTalonSRX.param_t( + "eProfileParamSlot1_IZone", CanTalonJNI.CanTalonSRX_eProfileParamSlot1_IZone_get()); + public final static CanTalonSRX.param_t eProfileParamSlot1_CloseLoopRampRate = + new CanTalonSRX.param_t("eProfileParamSlot1_CloseLoopRampRate", + CanTalonJNI.CanTalonSRX_eProfileParamSlot1_CloseLoopRampRate_get()); + public final static CanTalonSRX.param_t eProfileParamSoftLimitForThreshold = + new CanTalonSRX.param_t("eProfileParamSoftLimitForThreshold", + CanTalonJNI.CanTalonSRX_eProfileParamSoftLimitForThreshold_get()); + public final static CanTalonSRX.param_t eProfileParamSoftLimitRevThreshold = + new CanTalonSRX.param_t("eProfileParamSoftLimitRevThreshold", + CanTalonJNI.CanTalonSRX_eProfileParamSoftLimitRevThreshold_get()); + public final static CanTalonSRX.param_t eProfileParamSoftLimitForEnable = + new CanTalonSRX.param_t("eProfileParamSoftLimitForEnable", + CanTalonJNI.CanTalonSRX_eProfileParamSoftLimitForEnable_get()); + public final static CanTalonSRX.param_t eProfileParamSoftLimitRevEnable = + new CanTalonSRX.param_t("eProfileParamSoftLimitRevEnable", + CanTalonJNI.CanTalonSRX_eProfileParamSoftLimitRevEnable_get()); + public final static CanTalonSRX.param_t eOnBoot_BrakeMode = new CanTalonSRX.param_t( + "eOnBoot_BrakeMode", CanTalonJNI.CanTalonSRX_eOnBoot_BrakeMode_get()); + public final static CanTalonSRX.param_t eOnBoot_LimitSwitch_Forward_NormallyClosed = + new CanTalonSRX.param_t("eOnBoot_LimitSwitch_Forward_NormallyClosed", + CanTalonJNI.CanTalonSRX_eOnBoot_LimitSwitch_Forward_NormallyClosed_get()); + public final static CanTalonSRX.param_t eOnBoot_LimitSwitch_Reverse_NormallyClosed = + new CanTalonSRX.param_t("eOnBoot_LimitSwitch_Reverse_NormallyClosed", + CanTalonJNI.CanTalonSRX_eOnBoot_LimitSwitch_Reverse_NormallyClosed_get()); + public final static CanTalonSRX.param_t eOnBoot_LimitSwitch_Forward_Disable = + new CanTalonSRX.param_t("eOnBoot_LimitSwitch_Forward_Disable", + CanTalonJNI.CanTalonSRX_eOnBoot_LimitSwitch_Forward_Disable_get()); + public final static CanTalonSRX.param_t eOnBoot_LimitSwitch_Reverse_Disable = + new CanTalonSRX.param_t("eOnBoot_LimitSwitch_Reverse_Disable", + CanTalonJNI.CanTalonSRX_eOnBoot_LimitSwitch_Reverse_Disable_get()); + public final static CanTalonSRX.param_t eFault_OverTemp = new CanTalonSRX.param_t( + "eFault_OverTemp", CanTalonJNI.CanTalonSRX_eFault_OverTemp_get()); + public final static CanTalonSRX.param_t eFault_UnderVoltage = new CanTalonSRX.param_t( + "eFault_UnderVoltage", CanTalonJNI.CanTalonSRX_eFault_UnderVoltage_get()); + public final static CanTalonSRX.param_t eFault_ForLim = new CanTalonSRX.param_t( + "eFault_ForLim", CanTalonJNI.CanTalonSRX_eFault_ForLim_get()); + public final static CanTalonSRX.param_t eFault_RevLim = new CanTalonSRX.param_t( + "eFault_RevLim", CanTalonJNI.CanTalonSRX_eFault_RevLim_get()); + public final static CanTalonSRX.param_t eFault_HardwareFailure = new CanTalonSRX.param_t( + "eFault_HardwareFailure", CanTalonJNI.CanTalonSRX_eFault_HardwareFailure_get()); + public final static CanTalonSRX.param_t eFault_ForSoftLim = new CanTalonSRX.param_t( + "eFault_ForSoftLim", CanTalonJNI.CanTalonSRX_eFault_ForSoftLim_get()); + public final static CanTalonSRX.param_t eFault_RevSoftLim = new CanTalonSRX.param_t( + "eFault_RevSoftLim", CanTalonJNI.CanTalonSRX_eFault_RevSoftLim_get()); + public final static CanTalonSRX.param_t eStckyFault_OverTemp = new CanTalonSRX.param_t( + "eStckyFault_OverTemp", CanTalonJNI.CanTalonSRX_eStckyFault_OverTemp_get()); + public final static CanTalonSRX.param_t eStckyFault_UnderVoltage = new CanTalonSRX.param_t( + "eStckyFault_UnderVoltage", CanTalonJNI.CanTalonSRX_eStckyFault_UnderVoltage_get()); + public final static CanTalonSRX.param_t eStckyFault_ForLim = new CanTalonSRX.param_t( + "eStckyFault_ForLim", CanTalonJNI.CanTalonSRX_eStckyFault_ForLim_get()); + public final static CanTalonSRX.param_t eStckyFault_RevLim = new CanTalonSRX.param_t( + "eStckyFault_RevLim", CanTalonJNI.CanTalonSRX_eStckyFault_RevLim_get()); + public final static CanTalonSRX.param_t eStckyFault_ForSoftLim = new CanTalonSRX.param_t( + "eStckyFault_ForSoftLim", CanTalonJNI.CanTalonSRX_eStckyFault_ForSoftLim_get()); + public final static CanTalonSRX.param_t eStckyFault_RevSoftLim = new CanTalonSRX.param_t( + "eStckyFault_RevSoftLim", CanTalonJNI.CanTalonSRX_eStckyFault_RevSoftLim_get()); + public final static CanTalonSRX.param_t eAppliedThrottle = new CanTalonSRX.param_t( + "eAppliedThrottle", CanTalonJNI.CanTalonSRX_eAppliedThrottle_get()); + public final static CanTalonSRX.param_t eCloseLoopErr = new CanTalonSRX.param_t( + "eCloseLoopErr", CanTalonJNI.CanTalonSRX_eCloseLoopErr_get()); + public final static CanTalonSRX.param_t eFeedbackDeviceSelect = new CanTalonSRX.param_t( + "eFeedbackDeviceSelect", CanTalonJNI.CanTalonSRX_eFeedbackDeviceSelect_get()); + public final static CanTalonSRX.param_t eRevMotDuringCloseLoopEn = new CanTalonSRX.param_t( + "eRevMotDuringCloseLoopEn", CanTalonJNI.CanTalonSRX_eRevMotDuringCloseLoopEn_get()); + public final static CanTalonSRX.param_t eModeSelect = new CanTalonSRX.param_t("eModeSelect", + CanTalonJNI.CanTalonSRX_eModeSelect_get()); + public final static CanTalonSRX.param_t eProfileSlotSelect = new CanTalonSRX.param_t( + "eProfileSlotSelect", CanTalonJNI.CanTalonSRX_eProfileSlotSelect_get()); + public final static CanTalonSRX.param_t eRampThrottle = new CanTalonSRX.param_t( + "eRampThrottle", CanTalonJNI.CanTalonSRX_eRampThrottle_get()); + public final static CanTalonSRX.param_t eRevFeedbackSensor = new CanTalonSRX.param_t( + "eRevFeedbackSensor", CanTalonJNI.CanTalonSRX_eRevFeedbackSensor_get()); + public final static CanTalonSRX.param_t eLimitSwitchEn = new CanTalonSRX.param_t( + "eLimitSwitchEn", CanTalonJNI.CanTalonSRX_eLimitSwitchEn_get()); + public final static CanTalonSRX.param_t eLimitSwitchClosedFor = new CanTalonSRX.param_t( + "eLimitSwitchClosedFor", CanTalonJNI.CanTalonSRX_eLimitSwitchClosedFor_get()); + public final static CanTalonSRX.param_t eLimitSwitchClosedRev = new CanTalonSRX.param_t( + "eLimitSwitchClosedRev", CanTalonJNI.CanTalonSRX_eLimitSwitchClosedRev_get()); + public final static CanTalonSRX.param_t eSensorPosition = new CanTalonSRX.param_t( + "eSensorPosition", CanTalonJNI.CanTalonSRX_eSensorPosition_get()); + public final static CanTalonSRX.param_t eSensorVelocity = new CanTalonSRX.param_t( + "eSensorVelocity", CanTalonJNI.CanTalonSRX_eSensorVelocity_get()); + public final static CanTalonSRX.param_t eCurrent = new CanTalonSRX.param_t("eCurrent", + CanTalonJNI.CanTalonSRX_eCurrent_get()); + public final static CanTalonSRX.param_t eBrakeIsEnabled = new CanTalonSRX.param_t( + "eBrakeIsEnabled", CanTalonJNI.CanTalonSRX_eBrakeIsEnabled_get()); + public final static CanTalonSRX.param_t eEncPosition = new CanTalonSRX.param_t("eEncPosition", + CanTalonJNI.CanTalonSRX_eEncPosition_get()); + public final static CanTalonSRX.param_t eEncVel = new CanTalonSRX.param_t("eEncVel", + CanTalonJNI.CanTalonSRX_eEncVel_get()); + public final static CanTalonSRX.param_t eEncIndexRiseEvents = new CanTalonSRX.param_t( + "eEncIndexRiseEvents", CanTalonJNI.CanTalonSRX_eEncIndexRiseEvents_get()); + public final static CanTalonSRX.param_t eQuadApin = new CanTalonSRX.param_t("eQuadApin", + CanTalonJNI.CanTalonSRX_eQuadApin_get()); + public final static CanTalonSRX.param_t eQuadBpin = new CanTalonSRX.param_t("eQuadBpin", + CanTalonJNI.CanTalonSRX_eQuadBpin_get()); + public final static CanTalonSRX.param_t eQuadIdxpin = new CanTalonSRX.param_t("eQuadIdxpin", + CanTalonJNI.CanTalonSRX_eQuadIdxpin_get()); + public final static CanTalonSRX.param_t eAnalogInWithOv = new CanTalonSRX.param_t( + "eAnalogInWithOv", CanTalonJNI.CanTalonSRX_eAnalogInWithOv_get()); + public final static CanTalonSRX.param_t eAnalogInVel = new CanTalonSRX.param_t("eAnalogInVel", + CanTalonJNI.CanTalonSRX_eAnalogInVel_get()); + public final static CanTalonSRX.param_t eTemp = new CanTalonSRX.param_t("eTemp", + CanTalonJNI.CanTalonSRX_eTemp_get()); + public final static CanTalonSRX.param_t eBatteryV = new CanTalonSRX.param_t("eBatteryV", + CanTalonJNI.CanTalonSRX_eBatteryV_get()); + public final static CanTalonSRX.param_t eResetCount = new CanTalonSRX.param_t("eResetCount", + CanTalonJNI.CanTalonSRX_eResetCount_get()); + public final static CanTalonSRX.param_t eResetFlags = new CanTalonSRX.param_t("eResetFlags", + CanTalonJNI.CanTalonSRX_eResetFlags_get()); + public final static CanTalonSRX.param_t eFirmVers = new CanTalonSRX.param_t("eFirmVers", + CanTalonJNI.CanTalonSRX_eFirmVers_get()); + public final static CanTalonSRX.param_t eSettingsChanged = new CanTalonSRX.param_t( + "eSettingsChanged", CanTalonJNI.CanTalonSRX_eSettingsChanged_get()); + public final static CanTalonSRX.param_t eQuadFilterEn = new CanTalonSRX.param_t( + "eQuadFilterEn", CanTalonJNI.CanTalonSRX_eQuadFilterEn_get()); + public final static CanTalonSRX.param_t ePidIaccum = new CanTalonSRX.param_t("ePidIaccum", + CanTalonJNI.CanTalonSRX_ePidIaccum_get()); public final int swigValue() { return swigValue; @@ -447,7 +619,8 @@ public class CanTalonSRX extends CtreCanNode { } public static param_t swigToEnum(int swigValue) { - if (swigValue < swigValues.length && swigValue >= 0 && swigValues[swigValue].swigValue == swigValue) + if (swigValue < swigValues.length && swigValue >= 0 + && swigValues[swigValue].swigValue == swigValue) return swigValues[swigValue]; for (int i = 0; i < swigValues.length; i++) if (swigValues[i].swigValue == swigValue) @@ -463,16 +636,33 @@ public class CanTalonSRX extends CtreCanNode { private param_t(String swigName, int swigValue) { this.swigName = swigName; this.swigValue = swigValue; - swigNext = swigValue+1; + swigNext = swigValue + 1; } private param_t(String swigName, param_t swigEnum) { this.swigName = swigName; this.swigValue = swigEnum.swigValue; - swigNext = this.swigValue+1; + swigNext = this.swigValue + 1; } - private static param_t[] swigValues = { eProfileParamSlot0_P, eProfileParamSlot0_I, eProfileParamSlot0_D, eProfileParamSlot0_F, eProfileParamSlot0_IZone, eProfileParamSlot0_CloseLoopRampRate, eProfileParamSlot1_P, eProfileParamSlot1_I, eProfileParamSlot1_D, eProfileParamSlot1_F, eProfileParamSlot1_IZone, eProfileParamSlot1_CloseLoopRampRate, eProfileParamSoftLimitForThreshold, eProfileParamSoftLimitRevThreshold, eProfileParamSoftLimitForEnable, eProfileParamSoftLimitRevEnable, eOnBoot_BrakeMode, eOnBoot_LimitSwitch_Forward_NormallyClosed, eOnBoot_LimitSwitch_Reverse_NormallyClosed, eOnBoot_LimitSwitch_Forward_Disable, eOnBoot_LimitSwitch_Reverse_Disable, eFault_OverTemp, eFault_UnderVoltage, eFault_ForLim, eFault_RevLim, eFault_HardwareFailure, eFault_ForSoftLim, eFault_RevSoftLim, eStckyFault_OverTemp, eStckyFault_UnderVoltage, eStckyFault_ForLim, eStckyFault_RevLim, eStckyFault_ForSoftLim, eStckyFault_RevSoftLim, eAppliedThrottle, eCloseLoopErr, eFeedbackDeviceSelect, eRevMotDuringCloseLoopEn, eModeSelect, eProfileSlotSelect, eRampThrottle, eRevFeedbackSensor, eLimitSwitchEn, eLimitSwitchClosedFor, eLimitSwitchClosedRev, eSensorPosition, eSensorVelocity, eCurrent, eBrakeIsEnabled, eEncPosition, eEncVel, eEncIndexRiseEvents, eQuadApin, eQuadBpin, eQuadIdxpin, eAnalogInWithOv, eAnalogInVel, eTemp, eBatteryV, eResetCount, eResetFlags, eFirmVers, eSettingsChanged, eQuadFilterEn, ePidIaccum }; + private static param_t[] swigValues = {eProfileParamSlot0_P, eProfileParamSlot0_I, + eProfileParamSlot0_D, eProfileParamSlot0_F, eProfileParamSlot0_IZone, + eProfileParamSlot0_CloseLoopRampRate, eProfileParamSlot1_P, eProfileParamSlot1_I, + eProfileParamSlot1_D, eProfileParamSlot1_F, eProfileParamSlot1_IZone, + eProfileParamSlot1_CloseLoopRampRate, eProfileParamSoftLimitForThreshold, + eProfileParamSoftLimitRevThreshold, eProfileParamSoftLimitForEnable, + eProfileParamSoftLimitRevEnable, eOnBoot_BrakeMode, + eOnBoot_LimitSwitch_Forward_NormallyClosed, eOnBoot_LimitSwitch_Reverse_NormallyClosed, + eOnBoot_LimitSwitch_Forward_Disable, eOnBoot_LimitSwitch_Reverse_Disable, eFault_OverTemp, + eFault_UnderVoltage, eFault_ForLim, eFault_RevLim, eFault_HardwareFailure, + eFault_ForSoftLim, eFault_RevSoftLim, eStckyFault_OverTemp, eStckyFault_UnderVoltage, + eStckyFault_ForLim, eStckyFault_RevLim, eStckyFault_ForSoftLim, eStckyFault_RevSoftLim, + eAppliedThrottle, eCloseLoopErr, eFeedbackDeviceSelect, eRevMotDuringCloseLoopEn, + eModeSelect, eProfileSlotSelect, eRampThrottle, eRevFeedbackSensor, eLimitSwitchEn, + eLimitSwitchClosedFor, eLimitSwitchClosedRev, eSensorPosition, eSensorVelocity, eCurrent, + eBrakeIsEnabled, eEncPosition, eEncVel, eEncIndexRiseEvents, eQuadApin, eQuadBpin, + eQuadIdxpin, eAnalogInWithOv, eAnalogInVel, eTemp, eBatteryV, eResetCount, eResetFlags, + eFirmVers, eSettingsChanged, eQuadFilterEn, ePidIaccum}; private static int swigNext = 0; private final int swigValue; private final String swigName; diff --git a/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/Compressor.java b/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/Compressor.java index 925f389626..86bbe96e73 100644 --- a/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/Compressor.java +++ b/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/Compressor.java @@ -1,272 +1,284 @@ -package edu.wpi.first.wpilibj; - -import java.nio.ByteBuffer; -import java.nio.ByteOrder; - -import edu.wpi.first.wpilibj.SensorBase; -import edu.wpi.first.wpilibj.hal.CompressorJNI; -import edu.wpi.first.wpilibj.hal.HALUtil; -import edu.wpi.first.wpilibj.livewindow.LiveWindowSendable; -import edu.wpi.first.wpilibj.tables.ITable; - -/** - * Class for operating the PCM (Pneumatics compressor module) - * The PCM automatically will run in close-loop mode by default whenever a Solenoid object is - * created. For most cases the Compressor object does not need to be - * instantiated or used in a robot program. - * - * This class is only required in cases where more detailed status or to enable/disable - * closed loop control. Note: you cannot operate the compressor directly from this class as - * doing so would circumvent the safety provided in using the pressure switch and closed - * loop control. You can only turn off closed loop control, thereby stopping the compressor - * from operating. - */ -public class Compressor extends SensorBase implements LiveWindowSendable { - private ByteBuffer m_pcm; - - /** - * Create an instance of the Compressor - * @param pcmId - * The PCM CAN device ID. Most robots that use PCM will have a single module. Use this - * for supporting a second module other than the default. - */ - public Compressor(int pcmId) { - initCompressor(pcmId); - } - - /** - * Create an instance of the Compressor - * Makes a new instance of the compressor using the default PCM ID (0). Additional modules can be - * supported by making a new instance and specifying the CAN ID - */ - public Compressor() { - initCompressor(getDefaultSolenoidModule()); - } - - private void initCompressor(int module) { - m_table = null; - - m_pcm = CompressorJNI.initializeCompressor((byte)module); - } - - /** - * Start the compressor running in closed loop control mode - * Use the method in cases where you would like to manually stop and start the compressor - * for applications such as conserving battery or making sure that the compressor motor - * doesn't start during critical operations. - */ - public void start() { - setClosedLoopControl(true); - } - - /** - * Stop the compressor from running in closed loop control mode. - * Use the method in cases where you would like to manually stop and start the compressor - * for applications such as conserving battery or making sure that the compressor motor - * doesn't start during critical operations. - */ - public void stop() { - setClosedLoopControl(false); - } - - /** - * Get the enabled status of the compressor - * @return true if the compressor is on - */ - public boolean enabled() { - ByteBuffer status = ByteBuffer.allocateDirect(4); - status.order(ByteOrder.LITTLE_ENDIAN); - - boolean on = CompressorJNI.getCompressor(m_pcm, status.asIntBuffer()); - HALUtil.checkStatus(status.asIntBuffer()); - - return on; - } - - /** - * Get the current pressure switch value - * @return true if the pressure is low by reading the pressure switch that is plugged into the PCM - */ - public boolean getPressureSwitchValue() { - ByteBuffer status = ByteBuffer.allocateDirect(4); - status.order(ByteOrder.LITTLE_ENDIAN); - - boolean on = CompressorJNI.getPressureSwitch(m_pcm, status.asIntBuffer()); - HALUtil.checkStatus(status.asIntBuffer()); - - return on; - } - - /** - * Get the current being used by the compressor - * @return current consumed in amps for the compressor motor - */ - public float getCompressorCurrent() { - ByteBuffer status = ByteBuffer.allocateDirect(4); - status.order(ByteOrder.LITTLE_ENDIAN); - - float current = CompressorJNI.getCompressorCurrent(m_pcm, status.asIntBuffer()); - HALUtil.checkStatus(status.asIntBuffer()); - - return current; - } - - /** - * Set the PCM in closed loop control mode - * @param on - * If true sets the compressor to be in closed loop control mode otherwise - * normal operation of the compressor is disabled. - */ - public void setClosedLoopControl(boolean on) { - ByteBuffer status = ByteBuffer.allocateDirect(4); - status.order(ByteOrder.LITTLE_ENDIAN); - - CompressorJNI.setClosedLoopControl(m_pcm, on, status.asIntBuffer()); - HALUtil.checkStatus(status.asIntBuffer()); - } - - /** - * Gets the current operating mode of the PCM - * @return true if compressor is operating on closed-loop mode, otherwise return false. - */ - public boolean getClosedLoopControl() { - ByteBuffer status = ByteBuffer.allocateDirect(4); - status.order(ByteOrder.LITTLE_ENDIAN); - - boolean on = CompressorJNI.getClosedLoopControl(m_pcm, status.asIntBuffer()); - HALUtil.checkStatus(status.asIntBuffer()); - - return on; - } - - /** - * @return true if PCM is in fault state : Compressor Drive is - * disabled due to compressor current being too high. - */ - public boolean getCompressorCurrentTooHighFault() { - ByteBuffer status = ByteBuffer.allocateDirect(4); - status.order(ByteOrder.LITTLE_ENDIAN); - - boolean retval = CompressorJNI.getCompressorCurrentTooHighFault(m_pcm, status.asIntBuffer()); - HALUtil.checkStatus(status.asIntBuffer()); - - return retval; - } - /** - * @return true if PCM sticky fault is set : Compressor Drive is - * disabled due to compressor current being too high. - */ - public boolean getCompressorCurrentTooHighStickyFault() { - ByteBuffer status = ByteBuffer.allocateDirect(4); - status.order(ByteOrder.LITTLE_ENDIAN); - - boolean retval = CompressorJNI.getCompressorCurrentTooHighStickyFault(m_pcm, status.asIntBuffer()); - HALUtil.checkStatus(status.asIntBuffer()); - - return retval; - } - /** - * @return true if PCM sticky fault is set : Compressor output - * appears to be shorted. - */ - public boolean getCompressorShortedStickyFault() { - ByteBuffer status = ByteBuffer.allocateDirect(4); - status.order(ByteOrder.LITTLE_ENDIAN); - - boolean retval = CompressorJNI.getCompressorShortedStickyFault(m_pcm, status.asIntBuffer()); - HALUtil.checkStatus(status.asIntBuffer()); - - return retval; - } - /** - * @return true if PCM is in fault state : Compressor output - * appears to be shorted. - */ - public boolean getCompressorShortedFault() { - ByteBuffer status = ByteBuffer.allocateDirect(4); - status.order(ByteOrder.LITTLE_ENDIAN); - - boolean retval = CompressorJNI.getCompressorShortedFault(m_pcm, status.asIntBuffer()); - HALUtil.checkStatus(status.asIntBuffer()); - - return retval; - } - /** - * @return true if PCM sticky fault is set : Compressor does not - * appear to be wired, i.e. compressor is - * not drawing enough current. - */ - public boolean getCompressorNotConnectedStickyFault() { - ByteBuffer status = ByteBuffer.allocateDirect(4); - status.order(ByteOrder.LITTLE_ENDIAN); - - boolean retval = CompressorJNI.getCompressorNotConnectedStickyFault(m_pcm, status.asIntBuffer()); - HALUtil.checkStatus(status.asIntBuffer()); - - return retval; - } - /** - * @return true if PCM is in fault state : Compressor does not - * appear to be wired, i.e. compressor is - * not drawing enough current. - */ - public boolean getCompressorNotConnectedFault() { - ByteBuffer status = ByteBuffer.allocateDirect(4); - status.order(ByteOrder.LITTLE_ENDIAN); - - boolean retval = CompressorJNI.getCompressorNotConnectedFault(m_pcm, status.asIntBuffer()); - HALUtil.checkStatus(status.asIntBuffer()); - - return retval; - } - /** - * Clear ALL sticky faults inside PCM that Compressor is wired to. - * - * If a sticky fault is set, then it will be persistently cleared. Compressor drive - * maybe momentarily disable while flags are being cleared. Care should be - * taken to not call this too frequently, otherwise normal compressor - * functionality may be prevented. - * - * If no sticky faults are set then this call will have no effect. - */ - public void clearAllPCMStickyFaults() { - ByteBuffer status = ByteBuffer.allocateDirect(4); - status.order(ByteOrder.LITTLE_ENDIAN); - - CompressorJNI.clearAllPCMStickyFaults(m_pcm, status.asIntBuffer()); - HALUtil.checkStatus(status.asIntBuffer()); - } - @Override - public void startLiveWindowMode() { - } - - @Override - public void stopLiveWindowMode() { - } - - @Override - public String getSmartDashboardType() { - return "Compressor"; - } - - private ITable m_table; - - @Override - public void initTable(ITable subtable) { - m_table = subtable; - updateTable(); - } - - @Override - public ITable getTable() { - return m_table; - } - - @Override - public void updateTable() { - if (m_table != null) { - m_table.putBoolean("Enabled", enabled()); - m_table.putBoolean("Pressure Switch", getPressureSwitchValue()); - } - } -} +package edu.wpi.first.wpilibj; + +import java.nio.ByteBuffer; +import java.nio.ByteOrder; + +import edu.wpi.first.wpilibj.SensorBase; +import edu.wpi.first.wpilibj.hal.CompressorJNI; +import edu.wpi.first.wpilibj.hal.HALUtil; +import edu.wpi.first.wpilibj.livewindow.LiveWindowSendable; +import edu.wpi.first.wpilibj.tables.ITable; + +/** + * Class for operating the PCM (Pneumatics compressor module) The PCM + * automatically will run in close-loop mode by default whenever a Solenoid + * object is created. For most cases the Compressor object does not need to be + * instantiated or used in a robot program. + *$ + * This class is only required in cases where more detailed status or to + * enable/disable closed loop control. Note: you cannot operate the compressor + * directly from this class as doing so would circumvent the safety provided in + * using the pressure switch and closed loop control. You can only turn off + * closed loop control, thereby stopping the compressor from operating. + */ +public class Compressor extends SensorBase implements LiveWindowSendable { + private ByteBuffer m_pcm; + + /** + * Create an instance of the Compressor + *$ + * @param pcmId The PCM CAN device ID. Most robots that use PCM will have a + * single module. Use this for supporting a second module other than + * the default. + */ + public Compressor(int pcmId) { + initCompressor(pcmId); + } + + /** + * Create an instance of the Compressor Makes a new instance of the compressor + * using the default PCM ID (0). Additional modules can be supported by making + * a new instance and specifying the CAN ID + */ + public Compressor() { + initCompressor(getDefaultSolenoidModule()); + } + + private void initCompressor(int module) { + m_table = null; + + m_pcm = CompressorJNI.initializeCompressor((byte) module); + } + + /** + * Start the compressor running in closed loop control mode Use the method in + * cases where you would like to manually stop and start the compressor for + * applications such as conserving battery or making sure that the compressor + * motor doesn't start during critical operations. + */ + public void start() { + setClosedLoopControl(true); + } + + /** + * Stop the compressor from running in closed loop control mode. Use the + * method in cases where you would like to manually stop and start the + * compressor for applications such as conserving battery or making sure that + * the compressor motor doesn't start during critical operations. + */ + public void stop() { + setClosedLoopControl(false); + } + + /** + * Get the enabled status of the compressor + *$ + * @return true if the compressor is on + */ + public boolean enabled() { + ByteBuffer status = ByteBuffer.allocateDirect(4); + status.order(ByteOrder.LITTLE_ENDIAN); + + boolean on = CompressorJNI.getCompressor(m_pcm, status.asIntBuffer()); + HALUtil.checkStatus(status.asIntBuffer()); + + return on; + } + + /** + * Get the current pressure switch value + *$ + * @return true if the pressure is low by reading the pressure switch that is + * plugged into the PCM + */ + public boolean getPressureSwitchValue() { + ByteBuffer status = ByteBuffer.allocateDirect(4); + status.order(ByteOrder.LITTLE_ENDIAN); + + boolean on = CompressorJNI.getPressureSwitch(m_pcm, status.asIntBuffer()); + HALUtil.checkStatus(status.asIntBuffer()); + + return on; + } + + /** + * Get the current being used by the compressor + *$ + * @return current consumed in amps for the compressor motor + */ + public float getCompressorCurrent() { + ByteBuffer status = ByteBuffer.allocateDirect(4); + status.order(ByteOrder.LITTLE_ENDIAN); + + float current = CompressorJNI.getCompressorCurrent(m_pcm, status.asIntBuffer()); + HALUtil.checkStatus(status.asIntBuffer()); + + return current; + } + + /** + * Set the PCM in closed loop control mode + *$ + * @param on If true sets the compressor to be in closed loop control mode + * otherwise normal operation of the compressor is disabled. + */ + public void setClosedLoopControl(boolean on) { + ByteBuffer status = ByteBuffer.allocateDirect(4); + status.order(ByteOrder.LITTLE_ENDIAN); + + CompressorJNI.setClosedLoopControl(m_pcm, on, status.asIntBuffer()); + HALUtil.checkStatus(status.asIntBuffer()); + } + + /** + * Gets the current operating mode of the PCM + *$ + * @return true if compressor is operating on closed-loop mode, otherwise + * return false. + */ + public boolean getClosedLoopControl() { + ByteBuffer status = ByteBuffer.allocateDirect(4); + status.order(ByteOrder.LITTLE_ENDIAN); + + boolean on = CompressorJNI.getClosedLoopControl(m_pcm, status.asIntBuffer()); + HALUtil.checkStatus(status.asIntBuffer()); + + return on; + } + + /** + * @return true if PCM is in fault state : Compressor Drive is disabled due to + * compressor current being too high. + */ + public boolean getCompressorCurrentTooHighFault() { + ByteBuffer status = ByteBuffer.allocateDirect(4); + status.order(ByteOrder.LITTLE_ENDIAN); + + boolean retval = CompressorJNI.getCompressorCurrentTooHighFault(m_pcm, status.asIntBuffer()); + HALUtil.checkStatus(status.asIntBuffer()); + + return retval; + } + + /** + * @return true if PCM sticky fault is set : Compressor Drive is disabled due + * to compressor current being too high. + */ + public boolean getCompressorCurrentTooHighStickyFault() { + ByteBuffer status = ByteBuffer.allocateDirect(4); + status.order(ByteOrder.LITTLE_ENDIAN); + + boolean retval = + CompressorJNI.getCompressorCurrentTooHighStickyFault(m_pcm, status.asIntBuffer()); + HALUtil.checkStatus(status.asIntBuffer()); + + return retval; + } + + /** + * @return true if PCM sticky fault is set : Compressor output appears to be + * shorted. + */ + public boolean getCompressorShortedStickyFault() { + ByteBuffer status = ByteBuffer.allocateDirect(4); + status.order(ByteOrder.LITTLE_ENDIAN); + + boolean retval = CompressorJNI.getCompressorShortedStickyFault(m_pcm, status.asIntBuffer()); + HALUtil.checkStatus(status.asIntBuffer()); + + return retval; + } + + /** + * @return true if PCM is in fault state : Compressor output appears to be + * shorted. + */ + public boolean getCompressorShortedFault() { + ByteBuffer status = ByteBuffer.allocateDirect(4); + status.order(ByteOrder.LITTLE_ENDIAN); + + boolean retval = CompressorJNI.getCompressorShortedFault(m_pcm, status.asIntBuffer()); + HALUtil.checkStatus(status.asIntBuffer()); + + return retval; + } + + /** + * @return true if PCM sticky fault is set : Compressor does not appear to be + * wired, i.e. compressor is not drawing enough current. + */ + public boolean getCompressorNotConnectedStickyFault() { + ByteBuffer status = ByteBuffer.allocateDirect(4); + status.order(ByteOrder.LITTLE_ENDIAN); + + boolean retval = + CompressorJNI.getCompressorNotConnectedStickyFault(m_pcm, status.asIntBuffer()); + HALUtil.checkStatus(status.asIntBuffer()); + + return retval; + } + + /** + * @return true if PCM is in fault state : Compressor does not appear to be + * wired, i.e. compressor is not drawing enough current. + */ + public boolean getCompressorNotConnectedFault() { + ByteBuffer status = ByteBuffer.allocateDirect(4); + status.order(ByteOrder.LITTLE_ENDIAN); + + boolean retval = CompressorJNI.getCompressorNotConnectedFault(m_pcm, status.asIntBuffer()); + HALUtil.checkStatus(status.asIntBuffer()); + + return retval; + } + + /** + * Clear ALL sticky faults inside PCM that Compressor is wired to. + * + * If a sticky fault is set, then it will be persistently cleared. Compressor + * drive maybe momentarily disable while flags are being cleared. Care should + * be taken to not call this too frequently, otherwise normal compressor + * functionality may be prevented. + * + * If no sticky faults are set then this call will have no effect. + */ + public void clearAllPCMStickyFaults() { + ByteBuffer status = ByteBuffer.allocateDirect(4); + status.order(ByteOrder.LITTLE_ENDIAN); + + CompressorJNI.clearAllPCMStickyFaults(m_pcm, status.asIntBuffer()); + HALUtil.checkStatus(status.asIntBuffer()); + } + + @Override + public void startLiveWindowMode() {} + + @Override + public void stopLiveWindowMode() {} + + @Override + public String getSmartDashboardType() { + return "Compressor"; + } + + private ITable m_table; + + @Override + public void initTable(ITable subtable) { + m_table = subtable; + updateTable(); + } + + @Override + public ITable getTable() { + return m_table; + } + + @Override + public void updateTable() { + if (m_table != null) { + m_table.putBoolean("Enabled", enabled()); + m_table.putBoolean("Pressure Switch", getPressureSwitchValue()); + } + } +} diff --git a/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/ControllerPower.java b/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/ControllerPower.java index a3fe44c939..b009f4bd8f 100644 --- a/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/ControllerPower.java +++ b/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/ControllerPower.java @@ -1,8 +1,8 @@ /*----------------------------------------------------------------------------*/ -/* Copyright (c) FIRST 2008-2012. All Rights Reserved. */ -/* Open Source Software - may be modified and shared by FRC teams. The code */ +/* Copyright (c) FIRST 2008-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 the root directory of */ -/* the project. */ +/* the project. */ /*----------------------------------------------------------------------------*/ package edu.wpi.first.wpilibj; @@ -14,190 +14,195 @@ import java.nio.IntBuffer; import edu.wpi.first.wpilibj.hal.HALUtil; import edu.wpi.first.wpilibj.hal.PowerJNI; -public class ControllerPower -{ - /** - * Get the input voltage to the robot controller - * @return The controller input voltage value in Volts - */ - public static double getInputVoltage() - { - ByteBuffer status = ByteBuffer.allocateDirect(4); - status.order(ByteOrder.LITTLE_ENDIAN); - double retVal = PowerJNI.getVinVoltage(status.asIntBuffer()); - HALUtil.checkStatus(status.asIntBuffer()); - return retVal; - } +public class ControllerPower { + /** + * Get the input voltage to the robot controller + *$ + * @return The controller input voltage value in Volts + */ + public static double getInputVoltage() { + ByteBuffer status = ByteBuffer.allocateDirect(4); + status.order(ByteOrder.LITTLE_ENDIAN); + double retVal = PowerJNI.getVinVoltage(status.asIntBuffer()); + HALUtil.checkStatus(status.asIntBuffer()); + return retVal; + } - /** - * Get the input current to the robot controller - * @return The controller input current value in Amps - */ - public static double getInputCurrent() - { - ByteBuffer status = ByteBuffer.allocateDirect(4); - status.order(ByteOrder.LITTLE_ENDIAN); - double retVal = PowerJNI.getVinCurrent(status.asIntBuffer()); - HALUtil.checkStatus(status.asIntBuffer()); - return retVal; - } - - /** - * Get the voltage of the 3.3V rail - * @return The controller 3.3V rail voltage value in Volts - */ - public static double getVoltage3V3() - { - ByteBuffer status = ByteBuffer.allocateDirect(4); - status.order(ByteOrder.LITTLE_ENDIAN); - double retVal = PowerJNI.getUserVoltage3V3(status.asIntBuffer()); - HALUtil.checkStatus(status.asIntBuffer()); - return retVal; - } - - /** - * Get the current output of the 3.3V rail - * @return The controller 3.3V rail output current value in Volts - */ - public static double getCurrent3V3() - { - ByteBuffer status = ByteBuffer.allocateDirect(4); - status.order(ByteOrder.LITTLE_ENDIAN); - double retVal = PowerJNI.getUserCurrent3V3(status.asIntBuffer()); - HALUtil.checkStatus(status.asIntBuffer()); - return retVal; - } - - /** - * Get the enabled state of the 3.3V rail. The rail may be disabled due to a controller - * brownout, a short circuit on the rail, or controller over-voltage - * @return The controller 3.3V rail enabled value - */ - public static boolean getEnabled3V3() - { - ByteBuffer status = ByteBuffer.allocateDirect(4); - status.order(ByteOrder.LITTLE_ENDIAN); - boolean retVal = PowerJNI.getUserActive3V3(status.asIntBuffer()); - HALUtil.checkStatus(status.asIntBuffer()); - return retVal; - } - - /** - * Get the count of the total current faults on the 3.3V rail since the controller has booted - * @return The number of faults - */ - public static int getFaultCount3V3() - { - ByteBuffer status = ByteBuffer.allocateDirect(4); - status.order(ByteOrder.LITTLE_ENDIAN); - int retVal = PowerJNI.getUserCurrentFaults3V3(status.asIntBuffer()); - HALUtil.checkStatus(status.asIntBuffer()); - return retVal; - } - - /** - * Get the voltage of the 5V rail - * @return The controller 5V rail voltage value in Volts - */ - public static double getVoltage5V() - { - ByteBuffer status = ByteBuffer.allocateDirect(4); - status.order(ByteOrder.LITTLE_ENDIAN); - double retVal = PowerJNI.getUserVoltage5V(status.asIntBuffer()); - HALUtil.checkStatus(status.asIntBuffer()); - return retVal; - } - - /** - * Get the current output of the 5V rail - * @return The controller 5V rail output current value in Amps - */ - public static double getCurrent5V() - { - ByteBuffer status = ByteBuffer.allocateDirect(4); - status.order(ByteOrder.LITTLE_ENDIAN); - double retVal = PowerJNI.getUserCurrent5V(status.asIntBuffer()); - HALUtil.checkStatus(status.asIntBuffer()); - return retVal; - } - - /** - * Get the enabled state of the 5V rail. The rail may be disabled due to a controller - * brownout, a short circuit on the rail, or controller over-voltage - * @return The controller 5V rail enabled value - */ - public static boolean getEnabled5V() - { - ByteBuffer status = ByteBuffer.allocateDirect(4); - status.order(ByteOrder.LITTLE_ENDIAN); - boolean retVal = PowerJNI.getUserActive5V(status.asIntBuffer()); - HALUtil.checkStatus(status.asIntBuffer()); - return retVal; - } - - /** - * Get the count of the total current faults on the 5V rail since the controller has booted - * @return The number of faults - */ - public static int getFaultCount5V() - { - ByteBuffer status = ByteBuffer.allocateDirect(4); - status.order(ByteOrder.LITTLE_ENDIAN); - int retVal = PowerJNI.getUserCurrentFaults5V(status.asIntBuffer()); - HALUtil.checkStatus(status.asIntBuffer()); - return retVal; - } - - /** - * Get the voltage of the 6V rail - * @return The controller 6V rail voltage value in Volts - */ - public static double getVoltage6V() - { - ByteBuffer status = ByteBuffer.allocateDirect(4); - status.order(ByteOrder.LITTLE_ENDIAN); - double retVal = PowerJNI.getUserVoltage6V(status.asIntBuffer()); - HALUtil.checkStatus(status.asIntBuffer()); - return retVal; - } - - /** - * Get the current output of the 6V rail - * @return The controller 6V rail output current value in Amps - */ - public static double getCurrent6V() - { - ByteBuffer status = ByteBuffer.allocateDirect(4); - status.order(ByteOrder.LITTLE_ENDIAN); - double retVal = PowerJNI.getUserCurrent6V(status.asIntBuffer()); - HALUtil.checkStatus(status.asIntBuffer()); - return retVal; - } - - /** - * Get the enabled state of the 6V rail. The rail may be disabled due to a controller - * brownout, a short circuit on the rail, or controller over-voltage - * @return The controller 6V rail enabled value - */ - public static boolean getEnabled6V() - { - ByteBuffer status = ByteBuffer.allocateDirect(4); - status.order(ByteOrder.LITTLE_ENDIAN); - boolean retVal = PowerJNI.getUserActive6V(status.asIntBuffer()); - HALUtil.checkStatus(status.asIntBuffer()); - return retVal; - } + /** + * Get the input current to the robot controller + *$ + * @return The controller input current value in Amps + */ + public static double getInputCurrent() { + ByteBuffer status = ByteBuffer.allocateDirect(4); + status.order(ByteOrder.LITTLE_ENDIAN); + double retVal = PowerJNI.getVinCurrent(status.asIntBuffer()); + HALUtil.checkStatus(status.asIntBuffer()); + return retVal; + } - /** - * Get the count of the total current faults on the 6V rail since the controller has booted - * @return The number of faults - */ - public static int getFaultCount6V() - { - ByteBuffer status = ByteBuffer.allocateDirect(4); - status.order(ByteOrder.LITTLE_ENDIAN); - int retVal = PowerJNI.getUserCurrentFaults6V(status.asIntBuffer()); - HALUtil.checkStatus(status.asIntBuffer()); - return retVal; - } -} \ No newline at end of file + /** + * Get the voltage of the 3.3V rail + *$ + * @return The controller 3.3V rail voltage value in Volts + */ + public static double getVoltage3V3() { + ByteBuffer status = ByteBuffer.allocateDirect(4); + status.order(ByteOrder.LITTLE_ENDIAN); + double retVal = PowerJNI.getUserVoltage3V3(status.asIntBuffer()); + HALUtil.checkStatus(status.asIntBuffer()); + return retVal; + } + + /** + * Get the current output of the 3.3V rail + *$ + * @return The controller 3.3V rail output current value in Volts + */ + public static double getCurrent3V3() { + ByteBuffer status = ByteBuffer.allocateDirect(4); + status.order(ByteOrder.LITTLE_ENDIAN); + double retVal = PowerJNI.getUserCurrent3V3(status.asIntBuffer()); + HALUtil.checkStatus(status.asIntBuffer()); + return retVal; + } + + /** + * Get the enabled state of the 3.3V rail. The rail may be disabled due to a + * controller brownout, a short circuit on the rail, or controller + * over-voltage + *$ + * @return The controller 3.3V rail enabled value + */ + public static boolean getEnabled3V3() { + ByteBuffer status = ByteBuffer.allocateDirect(4); + status.order(ByteOrder.LITTLE_ENDIAN); + boolean retVal = PowerJNI.getUserActive3V3(status.asIntBuffer()); + HALUtil.checkStatus(status.asIntBuffer()); + return retVal; + } + + /** + * Get the count of the total current faults on the 3.3V rail since the + * controller has booted + *$ + * @return The number of faults + */ + public static int getFaultCount3V3() { + ByteBuffer status = ByteBuffer.allocateDirect(4); + status.order(ByteOrder.LITTLE_ENDIAN); + int retVal = PowerJNI.getUserCurrentFaults3V3(status.asIntBuffer()); + HALUtil.checkStatus(status.asIntBuffer()); + return retVal; + } + + /** + * Get the voltage of the 5V rail + *$ + * @return The controller 5V rail voltage value in Volts + */ + public static double getVoltage5V() { + ByteBuffer status = ByteBuffer.allocateDirect(4); + status.order(ByteOrder.LITTLE_ENDIAN); + double retVal = PowerJNI.getUserVoltage5V(status.asIntBuffer()); + HALUtil.checkStatus(status.asIntBuffer()); + return retVal; + } + + /** + * Get the current output of the 5V rail + *$ + * @return The controller 5V rail output current value in Amps + */ + public static double getCurrent5V() { + ByteBuffer status = ByteBuffer.allocateDirect(4); + status.order(ByteOrder.LITTLE_ENDIAN); + double retVal = PowerJNI.getUserCurrent5V(status.asIntBuffer()); + HALUtil.checkStatus(status.asIntBuffer()); + return retVal; + } + + /** + * Get the enabled state of the 5V rail. The rail may be disabled due to a + * controller brownout, a short circuit on the rail, or controller + * over-voltage + *$ + * @return The controller 5V rail enabled value + */ + public static boolean getEnabled5V() { + ByteBuffer status = ByteBuffer.allocateDirect(4); + status.order(ByteOrder.LITTLE_ENDIAN); + boolean retVal = PowerJNI.getUserActive5V(status.asIntBuffer()); + HALUtil.checkStatus(status.asIntBuffer()); + return retVal; + } + + /** + * Get the count of the total current faults on the 5V rail since the + * controller has booted + *$ + * @return The number of faults + */ + public static int getFaultCount5V() { + ByteBuffer status = ByteBuffer.allocateDirect(4); + status.order(ByteOrder.LITTLE_ENDIAN); + int retVal = PowerJNI.getUserCurrentFaults5V(status.asIntBuffer()); + HALUtil.checkStatus(status.asIntBuffer()); + return retVal; + } + + /** + * Get the voltage of the 6V rail + *$ + * @return The controller 6V rail voltage value in Volts + */ + public static double getVoltage6V() { + ByteBuffer status = ByteBuffer.allocateDirect(4); + status.order(ByteOrder.LITTLE_ENDIAN); + double retVal = PowerJNI.getUserVoltage6V(status.asIntBuffer()); + HALUtil.checkStatus(status.asIntBuffer()); + return retVal; + } + + /** + * Get the current output of the 6V rail + *$ + * @return The controller 6V rail output current value in Amps + */ + public static double getCurrent6V() { + ByteBuffer status = ByteBuffer.allocateDirect(4); + status.order(ByteOrder.LITTLE_ENDIAN); + double retVal = PowerJNI.getUserCurrent6V(status.asIntBuffer()); + HALUtil.checkStatus(status.asIntBuffer()); + return retVal; + } + + /** + * Get the enabled state of the 6V rail. The rail may be disabled due to a + * controller brownout, a short circuit on the rail, or controller + * over-voltage + *$ + * @return The controller 6V rail enabled value + */ + public static boolean getEnabled6V() { + ByteBuffer status = ByteBuffer.allocateDirect(4); + status.order(ByteOrder.LITTLE_ENDIAN); + boolean retVal = PowerJNI.getUserActive6V(status.asIntBuffer()); + HALUtil.checkStatus(status.asIntBuffer()); + return retVal; + } + + /** + * Get the count of the total current faults on the 6V rail since the + * controller has booted + *$ + * @return The number of faults + */ + public static int getFaultCount6V() { + ByteBuffer status = ByteBuffer.allocateDirect(4); + status.order(ByteOrder.LITTLE_ENDIAN); + int retVal = PowerJNI.getUserCurrentFaults6V(status.asIntBuffer()); + HALUtil.checkStatus(status.asIntBuffer()); + return retVal; + } +} diff --git a/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/Counter.java b/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/Counter.java index 6331806e53..28c3057cba 100644 --- a/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/Counter.java +++ b/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/Counter.java @@ -1,8 +1,8 @@ /*----------------------------------------------------------------------------*/ -/* Copyright (c) FIRST 2008-2012. All Rights Reserved. */ -/* Open Source Software - may be modified and shared by FRC teams. The code */ +/* Copyright (c) FIRST 2008-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 the root directory of */ -/* the project. */ +/* the project. */ /*----------------------------------------------------------------------------*/ package edu.wpi.first.wpilibj; @@ -28,722 +28,684 @@ import edu.wpi.first.wpilibj.util.BoundaryException; * All counters will immediately start counting - reset() them if you need them * to be zeroed before use. */ -public class Counter extends SensorBase implements CounterBase, - LiveWindowSendable, PIDSource { +public class Counter extends SensorBase implements CounterBase, LiveWindowSendable, PIDSource { - /** - * Mode determines how and what the counter counts - */ - public static enum Mode { - /** - * mode: two pulse - */ - kTwoPulse(0), - /** - * mode: semi period - */ - kSemiperiod(1), - /** - * mode: pulse length - */ - kPulseLength(2), - /** - * mode: external direction - */ - kExternalDirection(3); + /** + * Mode determines how and what the counter counts + */ + public static enum Mode { + /** + * mode: two pulse + */ + kTwoPulse(0), + /** + * mode: semi period + */ + kSemiperiod(1), + /** + * mode: pulse length + */ + kPulseLength(2), + /** + * mode: external direction + */ + kExternalDirection(3); - /** - * The integer value representing this enumeration - */ - public final int value; - private Mode(int value) { - this.value = value; - } - } + /** + * The integer value representing this enumeration + */ + public final int value; - private DigitalSource m_upSource; // /< What makes the counter count up. - private DigitalSource m_downSource; // /< What makes the counter count down. - private boolean m_allocatedUpSource; - private boolean m_allocatedDownSource; - private ByteBuffer m_counter; // /< The FPGA counter object. - private int m_index; // /< The index of this counter. - private PIDSourceParameter m_pidSource; - private double m_distancePerPulse; // distance of travel for each tick + private Mode(int value) { + this.value = value; + } + } - private void initCounter(final Mode mode) { - ByteBuffer status = ByteBuffer.allocateDirect(4); - // set the byte order - status.order(ByteOrder.LITTLE_ENDIAN); - ByteBuffer index = ByteBuffer.allocateDirect(4); - // set the byte order - index.order(ByteOrder.LITTLE_ENDIAN); - m_counter = CounterJNI.initializeCounter(mode.value, index.asIntBuffer(), status.asIntBuffer()); - HALUtil.checkStatus(status.asIntBuffer()); - m_index = index.asIntBuffer().get(0); + private DigitalSource m_upSource; // /< What makes the counter count up. + private DigitalSource m_downSource; // /< What makes the counter count down. + private boolean m_allocatedUpSource; + private boolean m_allocatedDownSource; + private ByteBuffer m_counter; // /< The FPGA counter object. + private int m_index; // /< The index of this counter. + private PIDSourceParameter m_pidSource; + private double m_distancePerPulse; // distance of travel for each tick - m_allocatedUpSource = false; - m_allocatedDownSource = false; - m_upSource = null; - m_downSource = null; + private void initCounter(final Mode mode) { + ByteBuffer status = ByteBuffer.allocateDirect(4); + // set the byte order + status.order(ByteOrder.LITTLE_ENDIAN); + ByteBuffer index = ByteBuffer.allocateDirect(4); + // set the byte order + index.order(ByteOrder.LITTLE_ENDIAN); + m_counter = CounterJNI.initializeCounter(mode.value, index.asIntBuffer(), status.asIntBuffer()); + HALUtil.checkStatus(status.asIntBuffer()); + m_index = index.asIntBuffer().get(0); - setMaxPeriod(.5); + m_allocatedUpSource = false; + m_allocatedDownSource = false; + m_upSource = null; + m_downSource = null; - UsageReporting.report(tResourceType.kResourceType_Counter, m_index, - mode.value); - } + setMaxPeriod(.5); - /** - * Create an instance of a counter where no sources are selected. Then they - * all must be selected by calling functions to specify the upsource and the - * downsource independently. - * - * The counter will start counting immediately. - */ - public Counter() { - initCounter(Mode.kTwoPulse); - } + UsageReporting.report(tResourceType.kResourceType_Counter, m_index, mode.value); + } - /** - * Create an instance of a counter from a Digital Input. This is used if an - * existing digital input is to be shared by multiple other objects such as - * encoders or if the Digital Source is not a DIO channel (such as an Analog Trigger) - * - * The counter will start counting immediately. - * - * @param source - * the digital source to count - */ - public Counter(DigitalSource source) { - if (source == null) - throw new NullPointerException("Digital Source given was null"); - initCounter(Mode.kTwoPulse); - setUpSource(source); - } + /** + * Create an instance of a counter where no sources are selected. Then they + * all must be selected by calling functions to specify the upsource and the + * downsource independently. + * + * The counter will start counting immediately. + */ + public Counter() { + initCounter(Mode.kTwoPulse); + } - /** - * Create an instance of a Counter object. Create an up-Counter instance - * given a channel. - * - * The counter will start counting immediately. - * - * @param channel - * the DIO channel to use as the up source. 0-9 are on-board, 10-25 are on the MXP - */ - public Counter(int channel) { - initCounter(Mode.kTwoPulse); - setUpSource(channel); - } + /** + * Create an instance of a counter from a Digital Input. This is used if an + * existing digital input is to be shared by multiple other objects such as + * encoders or if the Digital Source is not a DIO channel (such as an Analog + * Trigger) + * + * The counter will start counting immediately. + * + * @param source the digital source to count + */ + public Counter(DigitalSource source) { + if (source == null) + throw new NullPointerException("Digital Source given was null"); + initCounter(Mode.kTwoPulse); + setUpSource(source); + } - /** - * Create an instance of a Counter object. Create an instance of a simple - * up-Counter given an analog trigger. Use the trigger state output from the - * analog trigger. - * - * The counter will start counting immediately. - * - * @param encodingType - * which edges to count - * @param upSource - * first source to count - * @param downSource - * second source for direction - * @param inverted - * true to invert the count - */ - public Counter(EncodingType encodingType, DigitalSource upSource, - DigitalSource downSource, boolean inverted) { - initCounter(Mode.kExternalDirection); - if (encodingType != EncodingType.k1X - && encodingType != EncodingType.k2X) { - throw new RuntimeException( - "Counters only support 1X and 2X quadreature decoding!"); - } - if (upSource == null) - throw new NullPointerException("Up Source given was null"); - setUpSource(upSource); - if (downSource == null) - throw new NullPointerException("Down Source given was null"); - setDownSource(downSource); + /** + * Create an instance of a Counter object. Create an up-Counter instance given + * a channel. + * + * The counter will start counting immediately. + * + * @param channel the DIO channel to use as the up source. 0-9 are on-board, + * 10-25 are on the MXP + */ + public Counter(int channel) { + initCounter(Mode.kTwoPulse); + setUpSource(channel); + } - if (encodingType == null) - throw new NullPointerException("Encoding type given was null"); + /** + * Create an instance of a Counter object. Create an instance of a simple + * up-Counter given an analog trigger. Use the trigger state output from the + * analog trigger. + * + * The counter will start counting immediately. + * + * @param encodingType which edges to count + * @param upSource first source to count + * @param downSource second source for direction + * @param inverted true to invert the count + */ + public Counter(EncodingType encodingType, DigitalSource upSource, DigitalSource downSource, + boolean inverted) { + initCounter(Mode.kExternalDirection); + if (encodingType != EncodingType.k1X && encodingType != EncodingType.k2X) { + throw new RuntimeException("Counters only support 1X and 2X quadreature decoding!"); + } + if (upSource == null) + throw new NullPointerException("Up Source given was null"); + setUpSource(upSource); + if (downSource == null) + throw new NullPointerException("Down Source given was null"); + setDownSource(downSource); - ByteBuffer status = ByteBuffer.allocateDirect(4); - if (encodingType == EncodingType.k1X) { - setUpSourceEdge(true, false); - CounterJNI.setCounterAverageSize(m_counter, 1, status.asIntBuffer()); - } else { - setUpSourceEdge(true, true); - CounterJNI.setCounterAverageSize(m_counter, 2, status.asIntBuffer()); - } + if (encodingType == null) + throw new NullPointerException("Encoding type given was null"); - HALUtil.checkStatus(status.asIntBuffer()); - setDownSourceEdge(inverted, true); - } + ByteBuffer status = ByteBuffer.allocateDirect(4); + if (encodingType == EncodingType.k1X) { + setUpSourceEdge(true, false); + CounterJNI.setCounterAverageSize(m_counter, 1, status.asIntBuffer()); + } else { + setUpSourceEdge(true, true); + CounterJNI.setCounterAverageSize(m_counter, 2, status.asIntBuffer()); + } - /** - * Create an instance of a Counter object. Create an instance of a simple - * up-Counter given an analog trigger. Use the trigger state output from the - * analog trigger. - * - * The counter will start counting immediately. - * - * @param trigger - * the analog trigger to count - */ - public Counter(AnalogTrigger trigger) { - if( trigger == null){ - throw new NullPointerException("The Analog Trigger given was null"); - } - initCounter(Mode.kTwoPulse); - setUpSource(trigger.createOutput(AnalogTriggerType.kState)); - } + HALUtil.checkStatus(status.asIntBuffer()); + setDownSourceEdge(inverted, true); + } - @Override - public void free() { - setUpdateWhenEmpty(true); + /** + * Create an instance of a Counter object. Create an instance of a simple + * up-Counter given an analog trigger. Use the trigger state output from the + * analog trigger. + * + * The counter will start counting immediately. + * + * @param trigger the analog trigger to count + */ + public Counter(AnalogTrigger trigger) { + if (trigger == null) { + throw new NullPointerException("The Analog Trigger given was null"); + } + initCounter(Mode.kTwoPulse); + setUpSource(trigger.createOutput(AnalogTriggerType.kState)); + } - clearUpSource(); - clearDownSource(); + @Override + public void free() { + setUpdateWhenEmpty(true); - ByteBuffer status = ByteBuffer.allocateDirect(4); - status.order(ByteOrder.LITTLE_ENDIAN); - CounterJNI.freeCounter(m_counter, status.asIntBuffer()); - HALUtil.checkStatus(status.asIntBuffer()); + clearUpSource(); + clearDownSource(); - m_upSource = null; - m_downSource = null; - m_counter = null; - } + ByteBuffer status = ByteBuffer.allocateDirect(4); + status.order(ByteOrder.LITTLE_ENDIAN); + CounterJNI.freeCounter(m_counter, status.asIntBuffer()); + HALUtil.checkStatus(status.asIntBuffer()); - /** - * @return the Counter's FPGA index - */ - public int getFPGAIndex() { - return m_index; - } + m_upSource = null; + m_downSource = null; + m_counter = null; + } - /** - * Set the upsource for the counter as a digital input channel. - * - * @param channel - * the DIO channel to count 0-9 are on-board, 10-25 are on the MXP - */ - public void setUpSource(int channel) { - setUpSource(new DigitalInput(channel)); - m_allocatedUpSource = true; - } + /** + * @return the Counter's FPGA index + */ + public int getFPGAIndex() { + return m_index; + } - /** - * Set the source object that causes the counter to count up. Set the up - * counting DigitalSource. - * - * @param source - * the digital source to count - */ - public void setUpSource(DigitalSource source) { - if (m_upSource != null && m_allocatedUpSource) { - m_upSource.free(); - m_allocatedUpSource = false; - } - m_upSource = source; - ByteBuffer status = ByteBuffer.allocateDirect(4); - status.order(ByteOrder.LITTLE_ENDIAN); - CounterJNI.setCounterUpSource(m_counter, - source.getChannelForRouting(), - (byte) (source.getAnalogTriggerForRouting() ? 1 : 0), status.asIntBuffer()); - HALUtil.checkStatus(status.asIntBuffer()); - } + /** + * Set the upsource for the counter as a digital input channel. + * + * @param channel the DIO channel to count 0-9 are on-board, 10-25 are on the + * MXP + */ + public void setUpSource(int channel) { + setUpSource(new DigitalInput(channel)); + m_allocatedUpSource = true; + } - /** - * Set the up counting source to be an analog trigger. - * - * @param analogTrigger - * The analog trigger object that is used for the Up Source - * @param triggerType - * The analog trigger output that will trigger the counter. - */ - public void setUpSource(AnalogTrigger analogTrigger, AnalogTriggerType triggerType) { - if (analogTrigger == null){ - throw new NullPointerException("Analog Trigger given was null"); - } - if (triggerType == null){ - throw new NullPointerException("Analog Trigger Type given was null"); - } - setUpSource(analogTrigger.createOutput(triggerType)); - m_allocatedUpSource = true; - } + /** + * Set the source object that causes the counter to count up. Set the up + * counting DigitalSource. + * + * @param source the digital source to count + */ + public void setUpSource(DigitalSource source) { + if (m_upSource != null && m_allocatedUpSource) { + m_upSource.free(); + m_allocatedUpSource = false; + } + m_upSource = source; + ByteBuffer status = ByteBuffer.allocateDirect(4); + status.order(ByteOrder.LITTLE_ENDIAN); + CounterJNI.setCounterUpSource(m_counter, source.getChannelForRouting(), + (byte) (source.getAnalogTriggerForRouting() ? 1 : 0), status.asIntBuffer()); + HALUtil.checkStatus(status.asIntBuffer()); + } - /** - * Set the edge sensitivity on an up counting source. Set the up source to - * either detect rising edges or falling edges. - * - * @param risingEdge - * true to count rising edge - * @param fallingEdge - * true to count falling edge - */ - public void setUpSourceEdge(boolean risingEdge, boolean fallingEdge) { - if (m_upSource == null) - throw new RuntimeException( - "Up Source must be set before setting the edge!"); - ByteBuffer status = ByteBuffer.allocateDirect(4); - status.order(ByteOrder.LITTLE_ENDIAN); - CounterJNI.setCounterUpSourceEdge(m_counter, - (byte) (risingEdge ? 1 : 0), (byte) (fallingEdge ? 1 : 0), - status.asIntBuffer()); - HALUtil.checkStatus(status.asIntBuffer()); - } + /** + * Set the up counting source to be an analog trigger. + * + * @param analogTrigger The analog trigger object that is used for the Up + * Source + * @param triggerType The analog trigger output that will trigger the counter. + */ + public void setUpSource(AnalogTrigger analogTrigger, AnalogTriggerType triggerType) { + if (analogTrigger == null) { + throw new NullPointerException("Analog Trigger given was null"); + } + if (triggerType == null) { + throw new NullPointerException("Analog Trigger Type given was null"); + } + setUpSource(analogTrigger.createOutput(triggerType)); + m_allocatedUpSource = true; + } - /** - * Disable the up counting source to the counter. - */ - public void clearUpSource() { - if (m_upSource != null && m_allocatedUpSource) { - m_upSource.free(); - m_allocatedUpSource = false; - } - m_upSource = null; + /** + * Set the edge sensitivity on an up counting source. Set the up source to + * either detect rising edges or falling edges. + * + * @param risingEdge true to count rising edge + * @param fallingEdge true to count falling edge + */ + public void setUpSourceEdge(boolean risingEdge, boolean fallingEdge) { + if (m_upSource == null) + throw new RuntimeException("Up Source must be set before setting the edge!"); + ByteBuffer status = ByteBuffer.allocateDirect(4); + status.order(ByteOrder.LITTLE_ENDIAN); + CounterJNI.setCounterUpSourceEdge(m_counter, (byte) (risingEdge ? 1 : 0), + (byte) (fallingEdge ? 1 : 0), status.asIntBuffer()); + HALUtil.checkStatus(status.asIntBuffer()); + } - ByteBuffer status = ByteBuffer.allocateDirect(4); - status.order(ByteOrder.LITTLE_ENDIAN); - CounterJNI.clearCounterUpSource(m_counter, status.asIntBuffer()); - HALUtil.checkStatus(status.asIntBuffer()); - } + /** + * Disable the up counting source to the counter. + */ + public void clearUpSource() { + if (m_upSource != null && m_allocatedUpSource) { + m_upSource.free(); + m_allocatedUpSource = false; + } + m_upSource = null; - /** - * Set the down counting source to be a digital input channel. - * - * @param channel - * the DIO channel to count 0-9 are on-board, 10-25 are on the MXP - */ - public void setDownSource(int channel) { - setDownSource(new DigitalInput(channel)); - m_allocatedDownSource = true; - } + ByteBuffer status = ByteBuffer.allocateDirect(4); + status.order(ByteOrder.LITTLE_ENDIAN); + CounterJNI.clearCounterUpSource(m_counter, status.asIntBuffer()); + HALUtil.checkStatus(status.asIntBuffer()); + } - /** - * Set the source object that causes the counter to count down. Set the down - * counting DigitalSource. - * - * @param source - * the digital source to count - */ - public void setDownSource(DigitalSource source) { - if(source == null){ - throw new NullPointerException("The Digital Source given was null"); - } + /** + * Set the down counting source to be a digital input channel. + * + * @param channel the DIO channel to count 0-9 are on-board, 10-25 are on the + * MXP + */ + public void setDownSource(int channel) { + setDownSource(new DigitalInput(channel)); + m_allocatedDownSource = true; + } - if (m_downSource != null && m_allocatedDownSource) { - m_downSource.free(); - m_allocatedDownSource = false; - } - ByteBuffer status = ByteBuffer.allocateDirect(4); - status.order(ByteOrder.LITTLE_ENDIAN); - CounterJNI.setCounterDownSource(m_counter, - source.getChannelForRouting(), - (byte) (source.getAnalogTriggerForRouting() ? 1 : 0), status.asIntBuffer()); - if (status.asIntBuffer().get(0) == HALUtil.PARAMETER_OUT_OF_RANGE) { - throw new IllegalArgumentException( - "Counter only supports DownSource in TwoPulse and ExternalDirection modes."); - } - HALUtil.checkStatus(status.asIntBuffer()); - m_downSource = source; - } + /** + * Set the source object that causes the counter to count down. Set the down + * counting DigitalSource. + * + * @param source the digital source to count + */ + public void setDownSource(DigitalSource source) { + if (source == null) { + throw new NullPointerException("The Digital Source given was null"); + } - /** - * Set the down counting source to be an analog trigger. - * - * @param analogTrigger - * The analog trigger object that is used for the Down Source - * @param triggerType - * The analog trigger output that will trigger the counter. - */ - public void setDownSource(AnalogTrigger analogTrigger, AnalogTriggerType triggerType) { - if (analogTrigger == null){ - throw new NullPointerException("Analog Trigger given was null"); - } - if (triggerType == null){ - throw new NullPointerException("Analog Trigger Type given was null"); - } + if (m_downSource != null && m_allocatedDownSource) { + m_downSource.free(); + m_allocatedDownSource = false; + } + ByteBuffer status = ByteBuffer.allocateDirect(4); + status.order(ByteOrder.LITTLE_ENDIAN); + CounterJNI.setCounterDownSource(m_counter, source.getChannelForRouting(), + (byte) (source.getAnalogTriggerForRouting() ? 1 : 0), status.asIntBuffer()); + if (status.asIntBuffer().get(0) == HALUtil.PARAMETER_OUT_OF_RANGE) { + throw new IllegalArgumentException( + "Counter only supports DownSource in TwoPulse and ExternalDirection modes."); + } + HALUtil.checkStatus(status.asIntBuffer()); + m_downSource = source; + } - setDownSource(analogTrigger.createOutput(triggerType)); - m_allocatedDownSource = true; - } + /** + * Set the down counting source to be an analog trigger. + * + * @param analogTrigger The analog trigger object that is used for the Down + * Source + * @param triggerType The analog trigger output that will trigger the counter. + */ + public void setDownSource(AnalogTrigger analogTrigger, AnalogTriggerType triggerType) { + if (analogTrigger == null) { + throw new NullPointerException("Analog Trigger given was null"); + } + if (triggerType == null) { + throw new NullPointerException("Analog Trigger Type given was null"); + } - /** - * Set the edge sensitivity on a down counting source. Set the down source - * to either detect rising edges or falling edges. - * - * @param risingEdge - * true to count the rising edge - * @param fallingEdge - * true to count the falling edge - */ - public void setDownSourceEdge(boolean risingEdge, boolean fallingEdge) { - if (m_downSource == null) - throw new RuntimeException( - " Down Source must be set before setting the edge!"); - ByteBuffer status = ByteBuffer.allocateDirect(4); - status.order(ByteOrder.LITTLE_ENDIAN); - CounterJNI.setCounterDownSourceEdge(m_counter, (byte) (risingEdge ? 1 - : 0), (byte) (fallingEdge ? 1 : 0), status.asIntBuffer()); - HALUtil.checkStatus(status.asIntBuffer()); - } + setDownSource(analogTrigger.createOutput(triggerType)); + m_allocatedDownSource = true; + } - /** - * Disable the down counting source to the counter. - */ - public void clearDownSource() { - if (m_downSource != null && m_allocatedDownSource) { - m_downSource.free(); - m_allocatedDownSource = false; - } - m_downSource = null; + /** + * Set the edge sensitivity on a down counting source. Set the down source to + * either detect rising edges or falling edges. + * + * @param risingEdge true to count the rising edge + * @param fallingEdge true to count the falling edge + */ + public void setDownSourceEdge(boolean risingEdge, boolean fallingEdge) { + if (m_downSource == null) + throw new RuntimeException(" Down Source must be set before setting the edge!"); + ByteBuffer status = ByteBuffer.allocateDirect(4); + status.order(ByteOrder.LITTLE_ENDIAN); + CounterJNI.setCounterDownSourceEdge(m_counter, (byte) (risingEdge ? 1 : 0), + (byte) (fallingEdge ? 1 : 0), status.asIntBuffer()); + HALUtil.checkStatus(status.asIntBuffer()); + } - ByteBuffer status = ByteBuffer.allocateDirect(4); - status.order(ByteOrder.LITTLE_ENDIAN); - CounterJNI.clearCounterDownSource(m_counter, status.asIntBuffer()); - HALUtil.checkStatus(status.asIntBuffer()); - } + /** + * Disable the down counting source to the counter. + */ + public void clearDownSource() { + if (m_downSource != null && m_allocatedDownSource) { + m_downSource.free(); + m_allocatedDownSource = false; + } + m_downSource = null; - /** - * Set standard up / down counting mode on this counter. Up and down counts - * are sourced independently from two inputs. - */ - public void setUpDownCounterMode() { - ByteBuffer status = ByteBuffer.allocateDirect(4); - status.order(ByteOrder.LITTLE_ENDIAN); - CounterJNI.setCounterUpDownMode(m_counter, status.asIntBuffer()); - HALUtil.checkStatus(status.asIntBuffer()); - } + ByteBuffer status = ByteBuffer.allocateDirect(4); + status.order(ByteOrder.LITTLE_ENDIAN); + CounterJNI.clearCounterDownSource(m_counter, status.asIntBuffer()); + HALUtil.checkStatus(status.asIntBuffer()); + } - /** - * Set external direction mode on this counter. Counts are sourced on the Up - * counter input. The Down counter input represents the direction to count. - */ - public void setExternalDirectionMode() { - ByteBuffer status = ByteBuffer.allocateDirect(4); - status.order(ByteOrder.LITTLE_ENDIAN); - CounterJNI.setCounterExternalDirectionMode(m_counter, status.asIntBuffer()); - HALUtil.checkStatus(status.asIntBuffer()); - } + /** + * Set standard up / down counting mode on this counter. Up and down counts + * are sourced independently from two inputs. + */ + public void setUpDownCounterMode() { + ByteBuffer status = ByteBuffer.allocateDirect(4); + status.order(ByteOrder.LITTLE_ENDIAN); + CounterJNI.setCounterUpDownMode(m_counter, status.asIntBuffer()); + HALUtil.checkStatus(status.asIntBuffer()); + } - /** - * Set Semi-period mode on this counter. Counts up on both rising and - * falling edges. - * - * @param highSemiPeriod - * true to count up on both rising and falling - */ - public void setSemiPeriodMode(boolean highSemiPeriod) { - ByteBuffer status = ByteBuffer.allocateDirect(4); - status.order(ByteOrder.LITTLE_ENDIAN); - CounterJNI.setCounterSemiPeriodMode(m_counter, - (byte) (highSemiPeriod ? 1 : 0), status.asIntBuffer()); - HALUtil.checkStatus(status.asIntBuffer()); - } + /** + * Set external direction mode on this counter. Counts are sourced on the Up + * counter input. The Down counter input represents the direction to count. + */ + public void setExternalDirectionMode() { + ByteBuffer status = ByteBuffer.allocateDirect(4); + status.order(ByteOrder.LITTLE_ENDIAN); + CounterJNI.setCounterExternalDirectionMode(m_counter, status.asIntBuffer()); + HALUtil.checkStatus(status.asIntBuffer()); + } - /** - * Configure the counter to count in up or down based on the length of the - * input pulse. This mode is most useful for direction sensitive gear tooth - * sensors. - * - * @param threshold - * The pulse length beyond which the counter counts the opposite - * direction. Units are seconds. - */ - public void setPulseLengthMode(double threshold) { - ByteBuffer status = ByteBuffer.allocateDirect(4); - status.order(ByteOrder.LITTLE_ENDIAN); - CounterJNI.setCounterPulseLengthMode(m_counter, threshold, - status.asIntBuffer()); - HALUtil.checkStatus(status.asIntBuffer()); - } + /** + * Set Semi-period mode on this counter. Counts up on both rising and falling + * edges. + * + * @param highSemiPeriod true to count up on both rising and falling + */ + public void setSemiPeriodMode(boolean highSemiPeriod) { + ByteBuffer status = ByteBuffer.allocateDirect(4); + status.order(ByteOrder.LITTLE_ENDIAN); + CounterJNI.setCounterSemiPeriodMode(m_counter, (byte) (highSemiPeriod ? 1 : 0), + status.asIntBuffer()); + HALUtil.checkStatus(status.asIntBuffer()); + } - /** - * Read the current counter value. Read the value at this instant. It may - * still be running, so it reflects the current value. Next time it is read, - * it might have a different value. - */ - @Override - public int get() { - ByteBuffer status = ByteBuffer.allocateDirect(4); - status.order(ByteOrder.LITTLE_ENDIAN); - int value = CounterJNI.getCounter(m_counter, status.asIntBuffer()); - HALUtil.checkStatus(status.asIntBuffer()); - return value; - } + /** + * Configure the counter to count in up or down based on the length of the + * input pulse. This mode is most useful for direction sensitive gear tooth + * sensors. + * + * @param threshold The pulse length beyond which the counter counts the + * opposite direction. Units are seconds. + */ + public void setPulseLengthMode(double threshold) { + ByteBuffer status = ByteBuffer.allocateDirect(4); + status.order(ByteOrder.LITTLE_ENDIAN); + CounterJNI.setCounterPulseLengthMode(m_counter, threshold, status.asIntBuffer()); + HALUtil.checkStatus(status.asIntBuffer()); + } - /** - * Read the current scaled counter value. Read the value at this instant, - * scaled by the distance per pulse (defaults to 1). - * - * @return The distance since the last reset - */ - public double getDistance() { - return get() * m_distancePerPulse; - } + /** + * Read the current counter value. Read the value at this instant. It may + * still be running, so it reflects the current value. Next time it is read, + * it might have a different value. + */ + @Override + public int get() { + ByteBuffer status = ByteBuffer.allocateDirect(4); + status.order(ByteOrder.LITTLE_ENDIAN); + int value = CounterJNI.getCounter(m_counter, status.asIntBuffer()); + HALUtil.checkStatus(status.asIntBuffer()); + return value; + } - /** - * Reset the Counter to zero. Set the counter value to zero. This doesn't - * effect the running state of the counter, just sets the current value to - * zero. - */ - @Override - public void reset() { - ByteBuffer status = ByteBuffer.allocateDirect(4); - status.order(ByteOrder.LITTLE_ENDIAN); - CounterJNI.resetCounter(m_counter, status.asIntBuffer()); - HALUtil.checkStatus(status.asIntBuffer()); - } + /** + * Read the current scaled counter value. Read the value at this instant, + * scaled by the distance per pulse (defaults to 1). + * + * @return The distance since the last reset + */ + public double getDistance() { + return get() * m_distancePerPulse; + } - /** - * Set the maximum period where the device is still considered "moving". - * Sets the maximum period where the device is considered moving. This value - * is used to determine the "stopped" state of the counter using the - * GetStopped method. - * - * @param maxPeriod - * The maximum period where the counted device is considered - * moving in seconds. - */ - @Override - public void setMaxPeriod(double maxPeriod) { - ByteBuffer status = ByteBuffer.allocateDirect(4); - status.order(ByteOrder.LITTLE_ENDIAN); - CounterJNI.setCounterMaxPeriod(m_counter, maxPeriod, status.asIntBuffer()); - HALUtil.checkStatus(status.asIntBuffer()); - } + /** + * Reset the Counter to zero. Set the counter value to zero. This doesn't + * effect the running state of the counter, just sets the current value to + * zero. + */ + @Override + public void reset() { + ByteBuffer status = ByteBuffer.allocateDirect(4); + status.order(ByteOrder.LITTLE_ENDIAN); + CounterJNI.resetCounter(m_counter, status.asIntBuffer()); + HALUtil.checkStatus(status.asIntBuffer()); + } - /** - * Select whether you want to continue updating the event timer output when - * there are no samples captured. The output of the event timer has a buffer - * of periods that are averaged and posted to a register on the FPGA. When - * the timer detects that the event source has stopped (based on the - * MaxPeriod) the buffer of samples to be averaged is emptied. If you enable - * the update when empty, you will be notified of the stopped source and the - * event time will report 0 samples. If you disable update when empty, the - * most recent average will remain on the output until a new sample is - * acquired. You will never see 0 samples output (except when there have - * been no events since an FPGA reset) and you will likely not see the - * stopped bit become true (since it is updated at the end of an average and - * there are no samples to average). - * - * @param enabled - * true to continue updating - */ - public void setUpdateWhenEmpty(boolean enabled) { - ByteBuffer status = ByteBuffer.allocateDirect(4); - status.order(ByteOrder.LITTLE_ENDIAN); - CounterJNI.setCounterUpdateWhenEmpty(m_counter, - (byte) (enabled ? 1 : 0), status.asIntBuffer()); - HALUtil.checkStatus(status.asIntBuffer()); - } + /** + * Set the maximum period where the device is still considered "moving". Sets + * the maximum period where the device is considered moving. This value is + * used to determine the "stopped" state of the counter using the GetStopped + * method. + * + * @param maxPeriod The maximum period where the counted device is considered + * moving in seconds. + */ + @Override + public void setMaxPeriod(double maxPeriod) { + ByteBuffer status = ByteBuffer.allocateDirect(4); + status.order(ByteOrder.LITTLE_ENDIAN); + CounterJNI.setCounterMaxPeriod(m_counter, maxPeriod, status.asIntBuffer()); + HALUtil.checkStatus(status.asIntBuffer()); + } - /** - * Determine if the clock is stopped. Determine if the clocked input is - * stopped based on the MaxPeriod value set using the SetMaxPeriod method. - * If the clock exceeds the MaxPeriod, then the device (and counter) are - * assumed to be stopped and it returns true. - * - * @return Returns true if the most recent counter period exceeds the - * MaxPeriod value set by SetMaxPeriod. - */ - @Override - public boolean getStopped() { - ByteBuffer status = ByteBuffer.allocateDirect(4); - status.order(ByteOrder.LITTLE_ENDIAN); - boolean value = CounterJNI.getCounterStopped(m_counter, status.asIntBuffer()) != 0; - HALUtil.checkStatus(status.asIntBuffer()); - return value; - } + /** + * Select whether you want to continue updating the event timer output when + * there are no samples captured. The output of the event timer has a buffer + * of periods that are averaged and posted to a register on the FPGA. When the + * timer detects that the event source has stopped (based on the MaxPeriod) + * the buffer of samples to be averaged is emptied. If you enable the update + * when empty, you will be notified of the stopped source and the event time + * will report 0 samples. If you disable update when empty, the most recent + * average will remain on the output until a new sample is acquired. You will + * never see 0 samples output (except when there have been no events since an + * FPGA reset) and you will likely not see the stopped bit become true (since + * it is updated at the end of an average and there are no samples to + * average). + * + * @param enabled true to continue updating + */ + public void setUpdateWhenEmpty(boolean enabled) { + ByteBuffer status = ByteBuffer.allocateDirect(4); + status.order(ByteOrder.LITTLE_ENDIAN); + CounterJNI.setCounterUpdateWhenEmpty(m_counter, (byte) (enabled ? 1 : 0), status.asIntBuffer()); + HALUtil.checkStatus(status.asIntBuffer()); + } - /** - * The last direction the counter value changed. - * - * @return The last direction the counter value changed. - */ - @Override - public boolean getDirection() { - ByteBuffer status = ByteBuffer.allocateDirect(4); - status.order(ByteOrder.LITTLE_ENDIAN); - boolean value = CounterJNI.getCounterDirection(m_counter, status.asIntBuffer()) != 0; - HALUtil.checkStatus(status.asIntBuffer()); - return value; - } + /** + * Determine if the clock is stopped. Determine if the clocked input is + * stopped based on the MaxPeriod value set using the SetMaxPeriod method. If + * the clock exceeds the MaxPeriod, then the device (and counter) are assumed + * to be stopped and it returns true. + * + * @return Returns true if the most recent counter period exceeds the + * MaxPeriod value set by SetMaxPeriod. + */ + @Override + public boolean getStopped() { + ByteBuffer status = ByteBuffer.allocateDirect(4); + status.order(ByteOrder.LITTLE_ENDIAN); + boolean value = CounterJNI.getCounterStopped(m_counter, status.asIntBuffer()) != 0; + HALUtil.checkStatus(status.asIntBuffer()); + return value; + } - /** - * Set the Counter to return reversed sensing on the direction. This allows - * counters to change the direction they are counting in the case of 1X and - * 2X quadrature encoding only. Any other counter mode isn't supported. - * - * @param reverseDirection - * true if the value counted should be negated. - */ - public void setReverseDirection(boolean reverseDirection) { - ByteBuffer status = ByteBuffer.allocateDirect(4); - status.order(ByteOrder.LITTLE_ENDIAN); - CounterJNI.setCounterReverseDirection(m_counter, - (byte) (reverseDirection ? 1 : 0), status.asIntBuffer()); - HALUtil.checkStatus(status.asIntBuffer()); - } + /** + * The last direction the counter value changed. + * + * @return The last direction the counter value changed. + */ + @Override + public boolean getDirection() { + ByteBuffer status = ByteBuffer.allocateDirect(4); + status.order(ByteOrder.LITTLE_ENDIAN); + boolean value = CounterJNI.getCounterDirection(m_counter, status.asIntBuffer()) != 0; + HALUtil.checkStatus(status.asIntBuffer()); + return value; + } - /** - * Get the Period of the most recent count. Returns the time interval of the - * most recent count. This can be used for velocity calculations to - * determine shaft speed. - * - * @return The period of the last two pulses in units of seconds. - */ - @Override - public double getPeriod() { - ByteBuffer status = ByteBuffer.allocateDirect(4); - status.order(ByteOrder.LITTLE_ENDIAN); - double value = CounterJNI.getCounterPeriod(m_counter, status.asIntBuffer()); - HALUtil.checkStatus(status.asIntBuffer()); - return value; - } + /** + * Set the Counter to return reversed sensing on the direction. This allows + * counters to change the direction they are counting in the case of 1X and 2X + * quadrature encoding only. Any other counter mode isn't supported. + * + * @param reverseDirection true if the value counted should be negated. + */ + public void setReverseDirection(boolean reverseDirection) { + ByteBuffer status = ByteBuffer.allocateDirect(4); + status.order(ByteOrder.LITTLE_ENDIAN); + CounterJNI.setCounterReverseDirection(m_counter, (byte) (reverseDirection ? 1 : 0), + status.asIntBuffer()); + HALUtil.checkStatus(status.asIntBuffer()); + } - /** - * Get the current rate of the Counter. Read the current rate of the counter - * accounting for the distance per pulse value. The default value for - * distance per pulse (1) yields units of pulses per second. - * - * @return The rate in units/sec - */ - public double getRate() { - return m_distancePerPulse / getPeriod(); - } + /** + * Get the Period of the most recent count. Returns the time interval of the + * most recent count. This can be used for velocity calculations to determine + * shaft speed. + * + * @return The period of the last two pulses in units of seconds. + */ + @Override + public double getPeriod() { + ByteBuffer status = ByteBuffer.allocateDirect(4); + status.order(ByteOrder.LITTLE_ENDIAN); + double value = CounterJNI.getCounterPeriod(m_counter, status.asIntBuffer()); + HALUtil.checkStatus(status.asIntBuffer()); + return value; + } - /** - * Set the Samples to Average which specifies the number of samples of the - * timer to average when calculating the period. Perform averaging to - * account for mechanical imperfections or as oversampling to increase - * resolution. - * - * @param samplesToAverage - * The number of samples to average from 1 to 127. - */ - public void setSamplesToAverage(int samplesToAverage) { - ByteBuffer status = ByteBuffer.allocateDirect(4); - status.order(ByteOrder.LITTLE_ENDIAN); - CounterJNI.setCounterSamplesToAverage(m_counter, samplesToAverage, - status.asIntBuffer()); - if (status.asIntBuffer().get(0) == HALUtil.PARAMETER_OUT_OF_RANGE) { - throw new BoundaryException(BoundaryException.getMessage( - samplesToAverage, 1, 127)); - } - HALUtil.checkStatus(status.asIntBuffer()); - } + /** + * Get the current rate of the Counter. Read the current rate of the counter + * accounting for the distance per pulse value. The default value for distance + * per pulse (1) yields units of pulses per second. + * + * @return The rate in units/sec + */ + public double getRate() { + return m_distancePerPulse / getPeriod(); + } - /** - * Get the Samples to Average which specifies the number of samples of the - * timer to average when calculating the period. Perform averaging to - * account for mechanical imperfections or as oversampling to increase - * resolution. - * - * @return SamplesToAverage The number of samples being averaged (from 1 to - * 127) - */ - public int getSamplesToAverage() { - ByteBuffer status = ByteBuffer.allocateDirect(4); - status.order(ByteOrder.LITTLE_ENDIAN); - int value = CounterJNI.getCounterSamplesToAverage(m_counter, status.asIntBuffer()); - HALUtil.checkStatus(status.asIntBuffer()); - return value; - } + /** + * Set the Samples to Average which specifies the number of samples of the + * timer to average when calculating the period. Perform averaging to account + * for mechanical imperfections or as oversampling to increase resolution. + * + * @param samplesToAverage The number of samples to average from 1 to 127. + */ + public void setSamplesToAverage(int samplesToAverage) { + ByteBuffer status = ByteBuffer.allocateDirect(4); + status.order(ByteOrder.LITTLE_ENDIAN); + CounterJNI.setCounterSamplesToAverage(m_counter, samplesToAverage, status.asIntBuffer()); + if (status.asIntBuffer().get(0) == HALUtil.PARAMETER_OUT_OF_RANGE) { + throw new BoundaryException(BoundaryException.getMessage(samplesToAverage, 1, 127)); + } + HALUtil.checkStatus(status.asIntBuffer()); + } - /** - * Set the distance per pulse for this counter. This sets the multiplier - * used to determine the distance driven based on the count value from the - * encoder. Set this value based on the Pulses per Revolution and factor in - * any gearing reductions. This distance can be in any units you like, - * linear or angular. - * - * @param distancePerPulse - * The scale factor that will be used to convert pulses to useful - * units. - */ - public void setDistancePerPulse(double distancePerPulse) { - m_distancePerPulse = distancePerPulse; - } + /** + * Get the Samples to Average which specifies the number of samples of the + * timer to average when calculating the period. Perform averaging to account + * for mechanical imperfections or as oversampling to increase resolution. + * + * @return SamplesToAverage The number of samples being averaged (from 1 to + * 127) + */ + public int getSamplesToAverage() { + ByteBuffer status = ByteBuffer.allocateDirect(4); + status.order(ByteOrder.LITTLE_ENDIAN); + int value = CounterJNI.getCounterSamplesToAverage(m_counter, status.asIntBuffer()); + HALUtil.checkStatus(status.asIntBuffer()); + return value; + } - /** - * Set which parameter of the encoder you are using as a process control - * variable. The counter class supports the rate and distance parameters. - * - * @param pidSource - * An enum to select the parameter. - */ - public void setPIDSourceParameter(PIDSourceParameter pidSource) { - if(pidSource == null){ - throw new NullPointerException("PID Source Parameter given was null"); - } - BoundaryException.assertWithinBounds(pidSource.value, 0, 1); - m_pidSource = pidSource; - } + /** + * Set the distance per pulse for this counter. This sets the multiplier used + * to determine the distance driven based on the count value from the encoder. + * Set this value based on the Pulses per Revolution and factor in any gearing + * reductions. This distance can be in any units you like, linear or angular. + * + * @param distancePerPulse The scale factor that will be used to convert + * pulses to useful units. + */ + public void setDistancePerPulse(double distancePerPulse) { + m_distancePerPulse = distancePerPulse; + } - @Override - public double pidGet() { - switch (m_pidSource.value) { - case PIDSourceParameter.kDistance_val: - return getDistance(); - case PIDSourceParameter.kRate_val: - return getRate(); - default: - return 0.0; - } - } + /** + * Set which parameter of the encoder you are using as a process control + * variable. The counter class supports the rate and distance parameters. + * + * @param pidSource An enum to select the parameter. + */ + public void setPIDSourceParameter(PIDSourceParameter pidSource) { + if (pidSource == null) { + throw new NullPointerException("PID Source Parameter given was null"); + } + BoundaryException.assertWithinBounds(pidSource.value, 0, 1); + m_pidSource = pidSource; + } - /** - * Live Window code, only does anything if live window is activated. - */ - @Override - public String getSmartDashboardType() { - return "Counter"; - } + @Override + public double pidGet() { + switch (m_pidSource.value) { + case PIDSourceParameter.kDistance_val: + return getDistance(); + case PIDSourceParameter.kRate_val: + return getRate(); + default: + return 0.0; + } + } - private ITable m_table; + /** + * Live Window code, only does anything if live window is activated. + */ + @Override + public String getSmartDashboardType() { + return "Counter"; + } - /** - * {@inheritDoc} - */ - @Override - public void initTable(ITable subtable) { - m_table = subtable; - updateTable(); - } + private ITable m_table; - /** - * {@inheritDoc} - */ - @Override - public ITable getTable() { - return m_table; - } + /** + * {@inheritDoc} + */ + @Override + public void initTable(ITable subtable) { + m_table = subtable; + updateTable(); + } - /** - * {@inheritDoc} - */ - @Override - public void updateTable() { - if (m_table != null) { - m_table.putNumber("Value", get()); - } - } + /** + * {@inheritDoc} + */ + @Override + public ITable getTable() { + return m_table; + } - /** - * {@inheritDoc} - */ - @Override - public void startLiveWindowMode() { - } + /** + * {@inheritDoc} + */ + @Override + public void updateTable() { + if (m_table != null) { + m_table.putNumber("Value", get()); + } + } - /** - * {@inheritDoc} - */ - @Override - public void stopLiveWindowMode() { - } + /** + * {@inheritDoc} + */ + @Override + public void startLiveWindowMode() {} + + /** + * {@inheritDoc} + */ + @Override + public void stopLiveWindowMode() {} } diff --git a/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/CounterBase.java b/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/CounterBase.java index 29216391ba..be26bacb91 100644 --- a/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/CounterBase.java +++ b/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/CounterBase.java @@ -1,84 +1,89 @@ /*----------------------------------------------------------------------------*/ -/* Copyright (c) FIRST 2008-2012. All Rights Reserved. */ -/* Open Source Software - may be modified and shared by FRC teams. The code */ +/* Copyright (c) FIRST 2008-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 the root directory of */ -/* the project. */ +/* the project. */ /*----------------------------------------------------------------------------*/ package edu.wpi.first.wpilibj; /** * Interface for counting the number of ticks on a digital input channel. - * Encoders, Gear tooth sensors, and counters should all subclass this so it can be used to - * build more advanced classes for control and driving. + * Encoders, Gear tooth sensors, and counters should all subclass this so it can + * be used to build more advanced classes for control and driving. * * All counters will immediately start counting - reset() them if you need them * to be zeroed before use. */ public interface CounterBase { + /** + * The number of edges for the counterbase to increment or decrement on + */ + public static class EncodingType { + /** - * The number of edges for the counterbase to increment or decrement on + * The integer value representing this enumeration */ - public static class EncodingType { + public final int value; + static final int k1X_val = 0; + static final int k2X_val = 1; + static final int k4X_val = 2; + /** + * Count only the rising edge + */ + public static final EncodingType k1X = new EncodingType(k1X_val); + /** + * Count both the rising and falling edge + */ + public static final EncodingType k2X = new EncodingType(k2X_val); + /** + * Count rising and falling on both channels + */ + public static final EncodingType k4X = new EncodingType(k4X_val); - /** - * The integer value representing this enumeration - */ - public final int value; - static final int k1X_val = 0; - static final int k2X_val = 1; - static final int k4X_val = 2; - /** - * Count only the rising edge - */ - public static final EncodingType k1X = new EncodingType(k1X_val); - /** - * Count both the rising and falling edge - */ - public static final EncodingType k2X = new EncodingType(k2X_val); - /** - * Count rising and falling on both channels - */ - public static final EncodingType k4X = new EncodingType(k4X_val); - - private EncodingType(int value) { - this.value = value; - } + private EncodingType(int value) { + this.value = value; } + } - /** - * Get the count - * @return the count - */ - int get(); + /** + * Get the count + *$ + * @return the count + */ + int get(); - /** - * Reset the count to zero - */ - void reset(); + /** + * Reset the count to zero + */ + void reset(); - /** - * Get the time between the last two edges counted - * @return the time beteween the last two ticks in seconds - */ - double getPeriod(); + /** + * Get the time between the last two edges counted + *$ + * @return the time beteween the last two ticks in seconds + */ + double getPeriod(); - /** - * Set the maximum time between edges to be considered stalled - * @param maxPeriod the maximum period in seconds - */ - void setMaxPeriod(double maxPeriod); + /** + * Set the maximum time between edges to be considered stalled + *$ + * @param maxPeriod the maximum period in seconds + */ + void setMaxPeriod(double maxPeriod); - /** - * Determine if the counter is not moving - * @return true if the counter has not changed for the max period - */ - boolean getStopped(); + /** + * Determine if the counter is not moving + *$ + * @return true if the counter has not changed for the max period + */ + boolean getStopped(); - /** - * Determine which direction the counter is going - * @return true for one direction, false for the other - */ - boolean getDirection(); + /** + * Determine which direction the counter is going + *$ + * @return true for one direction, false for the other + */ + boolean getDirection(); } diff --git a/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/CtreCanNode.java b/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/CtreCanNode.java index d1d1540717..421f96a826 100644 --- a/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/CtreCanNode.java +++ b/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/CtreCanNode.java @@ -1,10 +1,12 @@ -/* ---------------------------------------------------------------------------- - * This file was automatically generated by SWIG (http://www.swig.org). - * Version 2.0.11 - * +/* + * ---------------------------------------------------------------------------- + * This file was automatically generated by SWIG (http://www.swig.org). Version + * 2.0.11 + *$ * Do not make changes to this file unless you know what you are doing--modify * the SWIG interface file instead. - * ----------------------------------------------------------------------------- */ + * ----------------------------------------------------------------------------- + */ package edu.wpi.first.wpilibj.hal; diff --git a/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/DigitalInput.java b/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/DigitalInput.java index a5dded5266..0addea5d45 100644 --- a/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/DigitalInput.java +++ b/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/DigitalInput.java @@ -1,8 +1,8 @@ /*----------------------------------------------------------------------------*/ -/* Copyright (c) FIRST 2008-2012. All Rights Reserved. */ -/* Open Source Software - may be modified and shared by FRC teams. The code */ +/* Copyright (c) FIRST 2008-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 the root directory of */ -/* the project. */ +/* the project. */ /*----------------------------------------------------------------------------*/ package edu.wpi.first.wpilibj; @@ -27,97 +27,95 @@ import edu.wpi.first.wpilibj.tables.ITable; */ public class DigitalInput extends DigitalSource implements LiveWindowSendable { - /** - * Create an instance of a Digital Input class. Creates a digital input - * given a channel. - * - * @param channel - * the DIO channel for the digital input 0-9 are on-board, 10-25 are on the MXP - */ - public DigitalInput(int channel) { - initDigitalPort(channel, true); + /** + * Create an instance of a Digital Input class. Creates a digital input given + * a channel. + * + * @param channel the DIO channel for the digital input 0-9 are on-board, + * 10-25 are on the MXP + */ + public DigitalInput(int channel) { + initDigitalPort(channel, true); - LiveWindow.addSensor("DigitalInput", channel, this); - UsageReporting.report(tResourceType.kResourceType_DigitalInput, channel); - } + LiveWindow.addSensor("DigitalInput", channel, this); + UsageReporting.report(tResourceType.kResourceType_DigitalInput, channel); + } - /** - * Get the value from a digital input channel. Retrieve the value of a - * single digital input channel from the FPGA. - * - * @return the status of the digital input - */ - public boolean get() { - ByteBuffer status = ByteBuffer.allocateDirect(4); - // set the byte order - status.order(ByteOrder.LITTLE_ENDIAN); - boolean value = DIOJNI.getDIO(m_port, status.asIntBuffer()) != 0; - HALUtil.checkStatus(status.asIntBuffer()); - return value; - } + /** + * Get the value from a digital input channel. Retrieve the value of a single + * digital input channel from the FPGA. + * + * @return the status of the digital input + */ + public boolean get() { + ByteBuffer status = ByteBuffer.allocateDirect(4); + // set the byte order + status.order(ByteOrder.LITTLE_ENDIAN); + boolean value = DIOJNI.getDIO(m_port, status.asIntBuffer()) != 0; + HALUtil.checkStatus(status.asIntBuffer()); + return value; + } - /** - * Get the channel of the digital input - * - * @return The GPIO channel number that this object represents. - */ - public int getChannel() { - return m_channel; - } + /** + * Get the channel of the digital input + * + * @return The GPIO channel number that this object represents. + */ + public int getChannel() { + return m_channel; + } - @Override - public boolean getAnalogTriggerForRouting() { - return false; - } + @Override + public boolean getAnalogTriggerForRouting() { + return false; + } - /* - * Live Window code, only does anything if live window is activated. - */ - @Override - public String getSmartDashboardType() { - return "Digital Input"; - } + /* + * Live Window code, only does anything if live window is activated. + */ + @Override + public String getSmartDashboardType() { + return "Digital Input"; + } - private ITable m_table; + private ITable m_table; - /** - * {@inheritDoc} - */ - @Override - public void initTable(ITable subtable) { - m_table = subtable; - updateTable(); - } + /** + * {@inheritDoc} + */ + @Override + public void initTable(ITable subtable) { + m_table = subtable; + updateTable(); + } - /** - * {@inheritDoc} - */ - @Override - public void updateTable() { - if (m_table != null) { - m_table.putBoolean("Value", get()); - } - } + /** + * {@inheritDoc} + */ + @Override + public void updateTable() { + if (m_table != null) { + m_table.putBoolean("Value", get()); + } + } - /** - * {@inheritDoc} - */ - @Override - public ITable getTable() { - return m_table; - } + /** + * {@inheritDoc} + */ + @Override + public ITable getTable() { + return m_table; + } - /** - * {@inheritDoc} - */ - @Override - public void startLiveWindowMode() { - } + /** + * {@inheritDoc} + */ + @Override + public void startLiveWindowMode() {} - /** - * {@inheritDoc} - */ - @Override - public void stopLiveWindowMode() { - } + /** + * {@inheritDoc} + */ + @Override + public void stopLiveWindowMode() {} } diff --git a/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/DigitalOutput.java b/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/DigitalOutput.java index 42875e8dcb..0a2bc084bc 100644 --- a/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/DigitalOutput.java +++ b/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/DigitalOutput.java @@ -1,8 +1,8 @@ /*----------------------------------------------------------------------------*/ -/* Copyright (c) FIRST 2008-2012. All Rights Reserved. */ -/* Open Source Software - may be modified and shared by FRC teams. The code */ +/* Copyright (c) FIRST 2008-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 the root directory of */ -/* the project. */ +/* the project. */ /*----------------------------------------------------------------------------*/ package edu.wpi.first.wpilibj; @@ -17,7 +17,7 @@ import edu.wpi.first.wpilibj.hal.PWMJNI; import edu.wpi.first.wpilibj.livewindow.LiveWindowSendable; import edu.wpi.first.wpilibj.tables.ITable; import edu.wpi.first.wpilibj.tables.ITableListener; -//import com.sun.jna.Pointer; +// import com.sun.jna.Pointer; import edu.wpi.first.wpilibj.communication.FRCNetworkCommunicationsLibrary.tResourceType; /** @@ -27,248 +27,240 @@ import edu.wpi.first.wpilibj.communication.FRCNetworkCommunicationsLibrary.tReso */ public class DigitalOutput extends DigitalSource implements LiveWindowSendable { - private ByteBuffer m_pwmGenerator; + private ByteBuffer m_pwmGenerator; - /** - * Create an instance of a digital output. Create an instance of a digital - * output given a channel. - * - * @param channel - * the DIO channel to use for the digital output. 0-9 are on-board, 10-25 are on the MXP - */ - public DigitalOutput(int channel) { - initDigitalPort(channel, false); + /** + * Create an instance of a digital output. Create an instance of a digital + * output given a channel. + * + * @param channel the DIO channel to use for the digital output. 0-9 are + * on-board, 10-25 are on the MXP + */ + public DigitalOutput(int channel) { + initDigitalPort(channel, false); - UsageReporting.report(tResourceType.kResourceType_DigitalOutput, channel); - } + UsageReporting.report(tResourceType.kResourceType_DigitalOutput, channel); + } - /** - * Free the resources associated with a digital output. - */ - @Override - public void free() { - // disable the pwm only if we have allocated it - if (m_pwmGenerator != null) { - disablePWM(); - } - super.free(); - } + /** + * Free the resources associated with a digital output. + */ + @Override + public void free() { + // disable the pwm only if we have allocated it + if (m_pwmGenerator != null) { + disablePWM(); + } + super.free(); + } - /** - * Set the value of a digital output. - * - * @param value - * true is on, off is false - */ - public void set(boolean value) { - ByteBuffer status = ByteBuffer.allocateDirect(4); - // set the byte order - status.order(ByteOrder.LITTLE_ENDIAN); - DIOJNI.setDIO(m_port, (short) (value ? 1 : 0), status.asIntBuffer()); - HALUtil.checkStatus(status.asIntBuffer()); - } + /** + * Set the value of a digital output. + * + * @param value true is on, off is false + */ + public void set(boolean value) { + ByteBuffer status = ByteBuffer.allocateDirect(4); + // set the byte order + status.order(ByteOrder.LITTLE_ENDIAN); + DIOJNI.setDIO(m_port, (short) (value ? 1 : 0), status.asIntBuffer()); + HALUtil.checkStatus(status.asIntBuffer()); + } - /** - * @return The GPIO channel number that this object represents. - */ - public int getChannel() { - return m_channel; - } + /** + * @return The GPIO channel number that this object represents. + */ + public int getChannel() { + return m_channel; + } - /** - * Generate a single pulse. Write a pulse to the specified digital output - * channel. There can only be a single pulse going at any time. - * - * @param channel - * The channel to pulse. - * @param pulseLength - * The length of the pulse. - */ - public void pulse(final int channel, final float pulseLength) { - ByteBuffer status = ByteBuffer.allocateDirect(4); - // set the byte order - status.order(ByteOrder.LITTLE_ENDIAN); - DIOJNI.pulse(m_port, pulseLength, status.asIntBuffer()); - HALUtil.checkStatus(status.asIntBuffer()); - } + /** + * Generate a single pulse. Write a pulse to the specified digital output + * channel. There can only be a single pulse going at any time. + * + * @param channel The channel to pulse. + * @param pulseLength The length of the pulse. + */ + public void pulse(final int channel, final float pulseLength) { + ByteBuffer status = ByteBuffer.allocateDirect(4); + // set the byte order + status.order(ByteOrder.LITTLE_ENDIAN); + DIOJNI.pulse(m_port, pulseLength, status.asIntBuffer()); + HALUtil.checkStatus(status.asIntBuffer()); + } - /** - * @deprecated Generate a single pulse. Write a pulse to the specified - * digital output channel. There can only be a single pulse - * going at any time. - * - * @param channel - * The channel to pulse. - * @param pulseLength - * The length of the pulse. - */ - @Deprecated - public void pulse(final int channel, final int pulseLength) { - ByteBuffer status = ByteBuffer.allocateDirect(4); - // set the byte order - status.order(ByteOrder.LITTLE_ENDIAN); - float convertedPulse = (float) (pulseLength / 1.0e9 * (DIOJNI.getLoopTiming(status.asIntBuffer()) * 25)); - System.err - .println("You should use the float version of pulse for portability. This is deprecated"); - DIOJNI.pulse(m_port, convertedPulse, status.asIntBuffer()); - HALUtil.checkStatus(status.asIntBuffer()); - } + /** + * @deprecated Generate a single pulse. Write a pulse to the specified digital + * output channel. There can only be a single pulse going at any + * time. + * + * @param channel The channel to pulse. + * @param pulseLength The length of the pulse. + */ + @Deprecated + public void pulse(final int channel, final int pulseLength) { + ByteBuffer status = ByteBuffer.allocateDirect(4); + // set the byte order + status.order(ByteOrder.LITTLE_ENDIAN); + float convertedPulse = + (float) (pulseLength / 1.0e9 * (DIOJNI.getLoopTiming(status.asIntBuffer()) * 25)); + System.err + .println("You should use the float version of pulse for portability. This is deprecated"); + DIOJNI.pulse(m_port, convertedPulse, status.asIntBuffer()); + HALUtil.checkStatus(status.asIntBuffer()); + } - /** - * Determine if the pulse is still going. Determine if a previously started - * pulse is still going. - * - * @return true if pulsing - */ - public boolean isPulsing() { - ByteBuffer status = ByteBuffer.allocateDirect(4); - // set the byte order - status.order(ByteOrder.LITTLE_ENDIAN); - boolean value = DIOJNI.isPulsing(m_port, status.asIntBuffer()) != 0; - HALUtil.checkStatus(status.asIntBuffer()); - return value; - } + /** + * Determine if the pulse is still going. Determine if a previously started + * pulse is still going. + * + * @return true if pulsing + */ + public boolean isPulsing() { + ByteBuffer status = ByteBuffer.allocateDirect(4); + // set the byte order + status.order(ByteOrder.LITTLE_ENDIAN); + boolean value = DIOJNI.isPulsing(m_port, status.asIntBuffer()) != 0; + HALUtil.checkStatus(status.asIntBuffer()); + return value; + } - /** - * Change the PWM frequency of the PWM output on a Digital Output line. - * - * The valid range is from 0.6 Hz to 19 kHz. The frequency resolution is - * logarithmic. - * - * There is only one PWM frequency for all channnels. - * - * @param rate The frequency to output all digital output PWM signals. - */ - public void setPWMRate(double rate) { - ByteBuffer status = ByteBuffer.allocateDirect(4); - // set the byte order - status.order(ByteOrder.LITTLE_ENDIAN); - PWMJNI.setPWMRate(rate, status.asIntBuffer()); - HALUtil.checkStatus(status.asIntBuffer()); - } + /** + * Change the PWM frequency of the PWM output on a Digital Output line. + * + * The valid range is from 0.6 Hz to 19 kHz. The frequency resolution is + * logarithmic. + * + * There is only one PWM frequency for all channnels. + * + * @param rate The frequency to output all digital output PWM signals. + */ + public void setPWMRate(double rate) { + ByteBuffer status = ByteBuffer.allocateDirect(4); + // set the byte order + status.order(ByteOrder.LITTLE_ENDIAN); + PWMJNI.setPWMRate(rate, status.asIntBuffer()); + HALUtil.checkStatus(status.asIntBuffer()); + } - /** - * Enable a PWM Output on this line. - * - * Allocate one of the 6 DO PWM generator resources. - * - * Supply the initial duty-cycle to output so as to avoid a glitch when - * first starting. - * - * The resolution of the duty cycle is 8-bit for low frequencies (1kHz or - * less) but is reduced the higher the frequency of the PWM signal is. - * - * @param initialDutyCycle - * The duty-cycle to start generating. [0..1] - */ - public void enablePWM(double initialDutyCycle) { - if (m_pwmGenerator != null) - return; - ByteBuffer status = ByteBuffer.allocateDirect(4); - // set the byte order - status.order(ByteOrder.LITTLE_ENDIAN); - m_pwmGenerator = PWMJNI.allocatePWM(status.asIntBuffer()); - HALUtil.checkStatus(status.asIntBuffer()); - PWMJNI.setPWMDutyCycle(m_pwmGenerator, initialDutyCycle, - status.asIntBuffer()); - HALUtil.checkStatus(status.asIntBuffer()); - PWMJNI.setPWMOutputChannel(m_pwmGenerator, m_channel, status.asIntBuffer()); - } + /** + * Enable a PWM Output on this line. + * + * Allocate one of the 6 DO PWM generator resources. + * + * Supply the initial duty-cycle to output so as to avoid a glitch when first + * starting. + * + * The resolution of the duty cycle is 8-bit for low frequencies (1kHz or + * less) but is reduced the higher the frequency of the PWM signal is. + * + * @param initialDutyCycle The duty-cycle to start generating. [0..1] + */ + public void enablePWM(double initialDutyCycle) { + if (m_pwmGenerator != null) + return; + ByteBuffer status = ByteBuffer.allocateDirect(4); + // set the byte order + status.order(ByteOrder.LITTLE_ENDIAN); + m_pwmGenerator = PWMJNI.allocatePWM(status.asIntBuffer()); + HALUtil.checkStatus(status.asIntBuffer()); + PWMJNI.setPWMDutyCycle(m_pwmGenerator, initialDutyCycle, status.asIntBuffer()); + HALUtil.checkStatus(status.asIntBuffer()); + PWMJNI.setPWMOutputChannel(m_pwmGenerator, m_channel, status.asIntBuffer()); + } - /** - * Change this line from a PWM output back to a static Digital Output line. - * - * Free up one of the 6 DO PWM generator resources that were in use. - */ - public void disablePWM() { - if (m_pwmGenerator == null) - return; - // Disable the output by routing to a dead bit. - ByteBuffer status = ByteBuffer.allocateDirect(4); - // set the byte order - status.order(ByteOrder.LITTLE_ENDIAN); - PWMJNI.setPWMOutputChannel(m_pwmGenerator, kDigitalChannels, status.asIntBuffer()); - HALUtil.checkStatus(status.asIntBuffer()); - PWMJNI.freePWM(m_pwmGenerator, status.asIntBuffer()); - m_pwmGenerator = null; - } + /** + * Change this line from a PWM output back to a static Digital Output line. + * + * Free up one of the 6 DO PWM generator resources that were in use. + */ + public void disablePWM() { + if (m_pwmGenerator == null) + return; + // Disable the output by routing to a dead bit. + ByteBuffer status = ByteBuffer.allocateDirect(4); + // set the byte order + status.order(ByteOrder.LITTLE_ENDIAN); + PWMJNI.setPWMOutputChannel(m_pwmGenerator, kDigitalChannels, status.asIntBuffer()); + HALUtil.checkStatus(status.asIntBuffer()); + PWMJNI.freePWM(m_pwmGenerator, status.asIntBuffer()); + m_pwmGenerator = null; + } - /** - * Change the duty-cycle that is being generated on the line. - * - * The resolution of the duty cycle is 8-bit for low frequencies (1kHz or - * less) but is reduced the higher the frequency of the PWM signal is. - * - * @param dutyCycle - * The duty-cycle to change to. [0..1] - */ - public void updateDutyCycle(double dutyCycle) { - if (m_pwmGenerator == null) - return; - ByteBuffer status = ByteBuffer.allocateDirect(4); - // set the byte order - status.order(ByteOrder.LITTLE_ENDIAN); - PWMJNI.setPWMDutyCycle(m_pwmGenerator, dutyCycle, status.asIntBuffer()); - HALUtil.checkStatus(status.asIntBuffer()); - } + /** + * Change the duty-cycle that is being generated on the line. + * + * The resolution of the duty cycle is 8-bit for low frequencies (1kHz or + * less) but is reduced the higher the frequency of the PWM signal is. + * + * @param dutyCycle The duty-cycle to change to. [0..1] + */ + public void updateDutyCycle(double dutyCycle) { + if (m_pwmGenerator == null) + return; + ByteBuffer status = ByteBuffer.allocateDirect(4); + // set the byte order + status.order(ByteOrder.LITTLE_ENDIAN); + PWMJNI.setPWMDutyCycle(m_pwmGenerator, dutyCycle, status.asIntBuffer()); + HALUtil.checkStatus(status.asIntBuffer()); + } - /* - * Live Window code, only does anything if live window is activated. - */ - @Override - public String getSmartDashboardType() { - return "Digital Output"; - } + /* + * Live Window code, only does anything if live window is activated. + */ + @Override + public String getSmartDashboardType() { + return "Digital Output"; + } - private ITable m_table; - private ITableListener m_table_listener; + private ITable m_table; + private ITableListener m_table_listener; - /** - * {@inheritDoc} - */ - @Override - public void initTable(ITable subtable) { - m_table = subtable; - updateTable(); - } + /** + * {@inheritDoc} + */ + @Override + public void initTable(ITable subtable) { + m_table = subtable; + updateTable(); + } - /** - * {@inheritDoc} - */ - @Override - public ITable getTable() { - return m_table; - } + /** + * {@inheritDoc} + */ + @Override + public ITable getTable() { + return m_table; + } - /** - * {@inheritDoc} - */ - @Override - public void updateTable() { - // TODO: Put current value. - } + /** + * {@inheritDoc} + */ + @Override + public void updateTable() { + // TODO: Put current value. + } - /** - * {@inheritDoc} - */ - @Override - public void startLiveWindowMode() { - m_table_listener = new ITableListener() { - @Override - public void valueChanged(ITable itable, String key, Object value, - boolean bln) { - set(((Boolean) value).booleanValue()); - } - }; - m_table.addTableListener("Value", m_table_listener, true); - } + /** + * {@inheritDoc} + */ + @Override + public void startLiveWindowMode() { + m_table_listener = new ITableListener() { + @Override + public void valueChanged(ITable itable, String key, Object value, boolean bln) { + set(((Boolean) value).booleanValue()); + } + }; + m_table.addTableListener("Value", m_table_listener, true); + } - /** - * {@inheritDoc} - */ - @Override - public void stopLiveWindowMode() { - // TODO: Broken, should only remove the listener from "Value" only. - m_table.removeTableListener(m_table_listener); - } + /** + * {@inheritDoc} + */ + @Override + public void stopLiveWindowMode() { + // TODO: Broken, should only remove the listener from "Value" only. + m_table.removeTableListener(m_table_listener); + } } diff --git a/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/DigitalSource.java b/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/DigitalSource.java index 11b2760ed2..abc66b41b0 100644 --- a/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/DigitalSource.java +++ b/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/DigitalSource.java @@ -1,8 +1,8 @@ /*----------------------------------------------------------------------------*/ -/* Copyright (c) FIRST 2008-2012. All Rights Reserved. */ -/* Open Source Software - may be modified and shared by FRC teams. The code */ +/* Copyright (c) FIRST 2008-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 the root directory of */ -/* the project. */ +/* the project. */ /*----------------------------------------------------------------------------*/ package edu.wpi.first.wpilibj; @@ -24,72 +24,72 @@ import edu.wpi.first.wpilibj.util.CheckedAllocationException; */ public abstract class DigitalSource extends InterruptableSensorBase { - protected static Resource channels = new Resource(kDigitalChannels); - protected ByteBuffer m_port; - protected int m_channel; + protected static Resource channels = new Resource(kDigitalChannels); + protected ByteBuffer m_port; + protected int m_channel; - protected void initDigitalPort(int channel, boolean input) { + protected void initDigitalPort(int channel, boolean input) { - m_channel = channel; + m_channel = channel; - checkDigitalChannel(m_channel); // XXX: Replace with - // HALLibrary.checkDigitalChannel when - // implemented + checkDigitalChannel(m_channel); // XXX: Replace with + // HALLibrary.checkDigitalChannel when + // implemented - try { - channels.allocate(m_channel); - } catch (CheckedAllocationException ex) { - throw new AllocationException("Digital input " + m_channel - + " is already allocated"); - } + try { + channels.allocate(m_channel); + } catch (CheckedAllocationException ex) { + throw new AllocationException("Digital input " + m_channel + " is already allocated"); + } - ByteBuffer port_pointer = DIOJNI.getPort((byte) channel); - ByteBuffer status = ByteBuffer.allocateDirect(4); - // set the byte order - status.order(ByteOrder.LITTLE_ENDIAN); - m_port = DIOJNI.initializeDigitalPort(port_pointer, status.asIntBuffer()); - HALUtil.checkStatus(status.asIntBuffer()); - DIOJNI.allocateDIO(m_port, (byte) (input ? 1 : 0), status.asIntBuffer()); - HALUtil.checkStatus(status.asIntBuffer()); - } + ByteBuffer port_pointer = DIOJNI.getPort((byte) channel); + ByteBuffer status = ByteBuffer.allocateDirect(4); + // set the byte order + status.order(ByteOrder.LITTLE_ENDIAN); + m_port = DIOJNI.initializeDigitalPort(port_pointer, status.asIntBuffer()); + HALUtil.checkStatus(status.asIntBuffer()); + DIOJNI.allocateDIO(m_port, (byte) (input ? 1 : 0), status.asIntBuffer()); + HALUtil.checkStatus(status.asIntBuffer()); + } - @Override - public void free() { - channels.free(m_channel); - ByteBuffer status = ByteBuffer.allocateDirect(4); - // set the byte order - status.order(ByteOrder.LITTLE_ENDIAN); - DIOJNI.freeDIO(m_port, status.asIntBuffer()); - HALUtil.checkStatus(status.asIntBuffer()); - m_channel = 0; - } + @Override + public void free() { + channels.free(m_channel); + ByteBuffer status = ByteBuffer.allocateDirect(4); + // set the byte order + status.order(ByteOrder.LITTLE_ENDIAN); + DIOJNI.freeDIO(m_port, status.asIntBuffer()); + HALUtil.checkStatus(status.asIntBuffer()); + m_channel = 0; + } - /** - * Get the channel routing number - * - * @return channel routing number - */ - @Override - public int getChannelForRouting() { - return m_channel; - } + /** + * Get the channel routing number + * + * @return channel routing number + */ + @Override + public int getChannelForRouting() { + return m_channel; + } - /** - * Get the module routing number - * - * @return 0 - */ - @Override - public byte getModuleForRouting() { - return 0; - } + /** + * Get the module routing number + * + * @return 0 + */ + @Override + public byte getModuleForRouting() { + return 0; + } - /** - * Is this an analog trigger - * @return true if this is an analog trigger - */ - @Override - public boolean getAnalogTriggerForRouting() { - return false; - } + /** + * Is this an analog trigger + *$ + * @return true if this is an analog trigger + */ + @Override + public boolean getAnalogTriggerForRouting() { + return false; + } } diff --git a/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/DoubleSolenoid.java b/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/DoubleSolenoid.java index ab5e10d5bd..7527f00b8a 100644 --- a/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/DoubleSolenoid.java +++ b/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/DoubleSolenoid.java @@ -1,8 +1,8 @@ /*----------------------------------------------------------------------------*/ -/* Copyright (c) FIRST 2008-2012. All Rights Reserved. */ -/* Open Source Software - may be modified and shared by FRC teams. The code */ +/* Copyright (c) FIRST 2008-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 the root directory of */ -/* the project. */ +/* the project. */ /*----------------------------------------------------------------------------*/ package edu.wpi.first.wpilibj; @@ -18,215 +18,226 @@ import edu.wpi.first.wpilibj.util.CheckedAllocationException; /** * DoubleSolenoid class for running 2 channels of high voltage Digital Output. * - * The DoubleSolenoid class is typically used for pneumatics solenoids that - * have two positions controlled by two separate channels. + * The DoubleSolenoid class is typically used for pneumatics solenoids that have + * two positions controlled by two separate channels. */ public class DoubleSolenoid extends SolenoidBase implements LiveWindowSendable { - /** - * Possible values for a DoubleSolenoid - */ - public static class Value { + /** + * Possible values for a DoubleSolenoid + */ + public static class Value { - public final int value; - public static final int kOff_val = 0; - public static final int kForward_val = 1; - public static final int kReverse_val = 2; - public static final Value kOff = new Value(kOff_val); - public static final Value kForward = new Value(kForward_val); - public static final Value kReverse = new Value(kReverse_val); + public final int value; + public static final int kOff_val = 0; + public static final int kForward_val = 1; + public static final int kReverse_val = 2; + public static final Value kOff = new Value(kOff_val); + public static final Value kForward = new Value(kForward_val); + public static final Value kReverse = new Value(kReverse_val); - private Value(int value) { - this.value = value; - } + private Value(int value) { + this.value = value; } - private int m_forwardChannel; ///< The forward channel on the module to control. - private int m_reverseChannel; ///< The reverse channel on the module to control. - private byte m_forwardMask; ///< The mask for the forward channel. - private byte m_reverseMask; ///< The mask for the reverse channel. + } - /** - * Common function to implement constructor behavior. - */ - private synchronized void initSolenoid() { - checkSolenoidModule(m_moduleNumber); - checkSolenoidChannel(m_forwardChannel); - checkSolenoidChannel(m_reverseChannel); + private int m_forwardChannel; // /< The forward channel on the module to + // control. + private int m_reverseChannel; // /< The reverse channel on the module to + // control. + private byte m_forwardMask; // /< The mask for the forward channel. + private byte m_reverseMask; // /< The mask for the reverse channel. - try { - m_allocated.allocate(m_moduleNumber * kSolenoidChannels + m_forwardChannel); - } catch (CheckedAllocationException e) { - throw new AllocationException( - "Solenoid channel " + m_forwardChannel + " on module " + m_moduleNumber + " is already allocated"); - } - try { - m_allocated.allocate(m_moduleNumber * kSolenoidChannels + m_reverseChannel); - } catch (CheckedAllocationException e) { - throw new AllocationException( - "Solenoid channel " + m_reverseChannel + " on module " + m_moduleNumber + " is already allocated"); - } - m_forwardMask = (byte) (1 << m_forwardChannel); - m_reverseMask = (byte) (1 << m_reverseChannel); + /** + * Common function to implement constructor behavior. + */ + private synchronized void initSolenoid() { + checkSolenoidModule(m_moduleNumber); + checkSolenoidChannel(m_forwardChannel); + checkSolenoidChannel(m_reverseChannel); - UsageReporting.report(tResourceType.kResourceType_Solenoid, m_forwardChannel, m_moduleNumber); - UsageReporting.report(tResourceType.kResourceType_Solenoid, m_reverseChannel, m_moduleNumber); - LiveWindow.addActuator("DoubleSolenoid", m_moduleNumber, m_forwardChannel, this); + try { + m_allocated.allocate(m_moduleNumber * kSolenoidChannels + m_forwardChannel); + } catch (CheckedAllocationException e) { + throw new AllocationException("Solenoid channel " + m_forwardChannel + " on module " + + m_moduleNumber + " is already allocated"); + } + try { + m_allocated.allocate(m_moduleNumber * kSolenoidChannels + m_reverseChannel); + } catch (CheckedAllocationException e) { + throw new AllocationException("Solenoid channel " + m_reverseChannel + " on module " + + m_moduleNumber + " is already allocated"); + } + m_forwardMask = (byte) (1 << m_forwardChannel); + m_reverseMask = (byte) (1 << m_reverseChannel); + + UsageReporting.report(tResourceType.kResourceType_Solenoid, m_forwardChannel, m_moduleNumber); + UsageReporting.report(tResourceType.kResourceType_Solenoid, m_reverseChannel, m_moduleNumber); + LiveWindow.addActuator("DoubleSolenoid", m_moduleNumber, m_forwardChannel, this); + } + + /** + * Constructor. Uses the default PCM ID of 0 + *$ + * @param forwardChannel The forward channel number on the PCM (0..7). + * @param reverseChannel The reverse channel number on the PCM (0..7). + */ + public DoubleSolenoid(final int forwardChannel, final int reverseChannel) { + super(getDefaultSolenoidModule()); + m_forwardChannel = forwardChannel; + m_reverseChannel = reverseChannel; + initSolenoid(); + } + + /** + * Constructor. + * + * @param moduleNumber The module number of the solenoid module to use. + * @param forwardChannel The forward channel on the module to control (0..7). + * @param reverseChannel The reverse channel on the module to control (0..7). + */ + public DoubleSolenoid(final int moduleNumber, final int forwardChannel, final int reverseChannel) { + super(moduleNumber); + m_forwardChannel = forwardChannel; + m_reverseChannel = reverseChannel; + initSolenoid(); + } + + /** + * Destructor. + */ + public synchronized void free() { + m_allocated.free(m_moduleNumber * kSolenoidChannels + m_forwardChannel); + m_allocated.free(m_moduleNumber * kSolenoidChannels + m_reverseChannel); + } + + /** + * Set the value of a solenoid. + * + * @param value The value to set (Off, Forward, Reverse) + */ + public void set(final Value value) { + byte rawValue = 0; + + switch (value.value) { + case Value.kOff_val: + rawValue = 0x00; + break; + case Value.kForward_val: + rawValue = m_forwardMask; + break; + case Value.kReverse_val: + rawValue = m_reverseMask; + break; } - /** - * Constructor. - * Uses the default PCM ID of 0 - * @param forwardChannel The forward channel number on the PCM (0..7). - * @param reverseChannel The reverse channel number on the PCM (0..7). - */ - public DoubleSolenoid(final int forwardChannel, final int reverseChannel) { - super(getDefaultSolenoidModule()); - m_forwardChannel = forwardChannel; - m_reverseChannel = reverseChannel; - initSolenoid(); + set(rawValue, m_forwardMask | m_reverseMask); + } + + /** + * Read the current value of the solenoid. + * + * @return The current value of the solenoid. + */ + public Value get() { + byte value = getAll(); + + if ((value & m_forwardMask) != 0) + return Value.kForward; + if ((value & m_reverseMask) != 0) + return Value.kReverse; + return Value.kOff; + } + + /** + * Check if the forward solenoid is blacklisted. If a solenoid is shorted, it + * is added to the blacklist and disabled until power cycle, or until faults + * are cleared. + * + * @see #clearAllPCMStickyFaults() + * + * @return If solenoid is disabled due to short. + */ + public boolean isFwdSolenoidBlackListed() { + int blackList = getPCMSolenoidBlackList(); + return ((blackList & m_forwardMask) != 0); + } + + /** + * Check if the reverse solenoid is blacklisted. If a solenoid is shorted, it + * is added to the blacklist and disabled until power cycle, or until faults + * are cleared. + * + * @see #clearAllPCMStickyFaults() + * + * @return If solenoid is disabled due to short. + */ + public boolean isRevSolenoidBlackListed() { + int blackList = getPCMSolenoidBlackList(); + return ((blackList & m_reverseMask) != 0); + } + + /* + * Live Window code, only does anything if live window is activated. + */ + public String getSmartDashboardType() { + return "Double Solenoid"; + } + + private ITable m_table; + private ITableListener m_table_listener; + + /** + * {@inheritDoc} + */ + public void initTable(ITable subtable) { + m_table = subtable; + updateTable(); + } + + /** + * {@inheritDoc} + */ + public ITable getTable() { + return m_table; + } + + /** + * {@inheritDoc} + */ + public void updateTable() { + if (m_table != null) { + // TODO: this is bad + m_table.putString("Value", (get() == Value.kForward ? "Forward" + : (get() == Value.kReverse ? "Reverse" : "Off"))); } + } - /** - * Constructor. - * - * @param moduleNumber The module number of the solenoid module to use. - * @param forwardChannel The forward channel on the module to control (0..7). - * @param reverseChannel The reverse channel on the module to control (0..7). - */ - public DoubleSolenoid(final int moduleNumber, final int forwardChannel, final int reverseChannel) { - super(moduleNumber); - m_forwardChannel = forwardChannel; - m_reverseChannel = reverseChannel; - initSolenoid(); - } + /** + * {@inheritDoc} + */ + public void startLiveWindowMode() { + set(Value.kOff); // Stop for safety + m_table_listener = new ITableListener() { + public void valueChanged(ITable itable, String key, Object value, boolean bln) { + // TODO: this is bad also + if (value.toString().equals("Reverse")) + set(Value.kReverse); + else if (value.toString().equals("Forward")) + set(Value.kForward); + else + set(Value.kOff); + } + }; + m_table.addTableListener("Value", m_table_listener, true); + } - /** - * Destructor. - */ - public synchronized void free() { - m_allocated.free(m_moduleNumber * kSolenoidChannels + m_forwardChannel); - m_allocated.free(m_moduleNumber * kSolenoidChannels + m_reverseChannel); - } - - /** - * Set the value of a solenoid. - * - * @param value The value to set (Off, Forward, Reverse) - */ - public void set(final Value value) { - byte rawValue = 0; - - switch (value.value) { - case Value.kOff_val: - rawValue = 0x00; - break; - case Value.kForward_val: - rawValue = m_forwardMask; - break; - case Value.kReverse_val: - rawValue = m_reverseMask; - break; - } - - set(rawValue, m_forwardMask | m_reverseMask); - } - - /** - * Read the current value of the solenoid. - * - * @return The current value of the solenoid. - */ - public Value get() { - byte value = getAll(); - - if ((value & m_forwardMask) != 0) return Value.kForward; - if ((value & m_reverseMask) != 0) return Value.kReverse; - return Value.kOff; - } - /** - * Check if the forward solenoid is blacklisted. - * If a solenoid is shorted, it is added to the blacklist and - * disabled until power cycle, or until faults are cleared. - * @see #clearAllPCMStickyFaults() - * - * @return If solenoid is disabled due to short. - */ - public boolean isFwdSolenoidBlackListed() { - int blackList = getPCMSolenoidBlackList(); - return ((blackList & m_forwardMask) != 0); - } - /** - * Check if the reverse solenoid is blacklisted. - * If a solenoid is shorted, it is added to the blacklist and - * disabled until power cycle, or until faults are cleared. - * @see #clearAllPCMStickyFaults() - * - * @return If solenoid is disabled due to short. - */ - public boolean isRevSolenoidBlackListed() { - int blackList = getPCMSolenoidBlackList(); - return ((blackList & m_reverseMask) != 0); - } - - /* - * Live Window code, only does anything if live window is activated. - */ - public String getSmartDashboardType() { - return "Double Solenoid"; - } - private ITable m_table; - private ITableListener m_table_listener; - - /** - * {@inheritDoc} - */ - public void initTable(ITable subtable) { - m_table = subtable; - updateTable(); - } - - /** - * {@inheritDoc} - */ - public ITable getTable() { - return m_table; - } - - /** - * {@inheritDoc} - */ - public void updateTable() { - if (m_table != null) { - //TODO: this is bad - m_table.putString("Value", (get() == Value.kForward ? "Forward" : (get() == Value.kReverse ? "Reverse" : "Off"))); - } - } - - /** - * {@inheritDoc} - */ - public void startLiveWindowMode() { - set(Value.kOff); // Stop for safety - m_table_listener = new ITableListener() { - public void valueChanged(ITable itable, String key, Object value, boolean bln) { - //TODO: this is bad also - if (value.toString().equals("Reverse")) - set(Value.kReverse); - else if (value.toString().equals("Forward")) - set(Value.kForward); - else - set(Value.kOff); - } - }; - m_table.addTableListener("Value", m_table_listener, true); - } - - /** - * {@inheritDoc} - */ - public void stopLiveWindowMode() { - set(Value.kOff); // Stop for safety - // TODO: Broken, should only remove the listener from "Value" only. - m_table.removeTableListener(m_table_listener); - } + /** + * {@inheritDoc} + */ + public void stopLiveWindowMode() { + set(Value.kOff); // Stop for safety + // TODO: Broken, should only remove the listener from "Value" only. + m_table.removeTableListener(m_table_listener); + } } diff --git a/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/DriverStation.java b/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/DriverStation.java index 82bf8337d6..b226755c3d 100644 --- a/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/DriverStation.java +++ b/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/DriverStation.java @@ -1,8 +1,8 @@ /*----------------------------------------------------------------------------*/ -/* Copyright (c) FIRST 2008-2012. All Rights Reserved. */ -/* Open Source Software - may be modified and shared by FRC teams. The code */ +/* Copyright (c) FIRST 2008-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 the root directory of */ -/* the project. */ +/* the project. */ /*----------------------------------------------------------------------------*/ package edu.wpi.first.wpilibj; @@ -17,617 +17,657 @@ import edu.wpi.first.wpilibj.hal.HALUtil; import edu.wpi.first.wpilibj.hal.PowerJNI; /** - * Provide access to the network communication data to / from the Driver Station. + * Provide access to the network communication data to / from the Driver + * Station. */ public class DriverStation implements RobotState.Interface { - /** - * Number of Joystick Ports - */ - public static final int kJoystickPorts = 6; - - private class HALJoystickButtons { - public int buttons; - public byte count; - } + /** + * Number of Joystick Ports + */ + public static final int kJoystickPorts = 6; - /** - * The robot alliance that the robot is a part of - */ - public enum Alliance { Red, Blue, Invalid } + private class HALJoystickButtons { + public int buttons; + public byte count; + } - private static final double JOYSTICK_UNPLUGGED_MESSAGE_INTERVAL = 1.0; - private double m_nextMessageTime = 0.0; + /** + * The robot alliance that the robot is a part of + */ + public enum Alliance { + Red, Blue, Invalid + } - private static class DriverStationTask implements Runnable { + private static final double JOYSTICK_UNPLUGGED_MESSAGE_INTERVAL = 1.0; + private double m_nextMessageTime = 0.0; - private DriverStation m_ds; + private static class DriverStationTask implements Runnable { - DriverStationTask(DriverStation ds) { - m_ds = ds; - } + private DriverStation m_ds; - public void run() { - m_ds.task(); - } - } /* DriverStationTask */ - - private static DriverStation instance = new DriverStation(); - - private short[][] m_joystickAxes = new short[kJoystickPorts][FRCNetworkCommunicationsLibrary.kMaxJoystickAxes]; - private short[][] m_joystickPOVs = new short[kJoystickPorts][FRCNetworkCommunicationsLibrary.kMaxJoystickPOVs]; - private HALJoystickButtons[] m_joystickButtons = new HALJoystickButtons[kJoystickPorts]; - private int[] m_joystickIsXbox = new int[kJoystickPorts]; - private int[] m_joystickType = new int[kJoystickPorts]; - private String[] m_joystickName = new String[kJoystickPorts]; - private int[][] m_joystickAxisType = new int[kJoystickPorts][FRCNetworkCommunicationsLibrary.kMaxJoystickAxes]; - - private Thread m_thread; - private final Object m_dataSem; - private volatile boolean m_thread_keepalive = true; - private boolean m_userInDisabled = false; - private boolean m_userInAutonomous = false; - private boolean m_userInTeleop = false; - private boolean m_userInTest = false; - private boolean m_newControlData; - private final ByteBuffer m_packetDataAvailableMutex; - private final ByteBuffer m_packetDataAvailableSem; - - /** - * Gets an instance of the DriverStation - * - * @return The DriverStation. - */ - public static DriverStation getInstance() { - return DriverStation.instance; + DriverStationTask(DriverStation ds) { + m_ds = ds; } - /** - * DriverStation constructor. - * - * The single DriverStation instance is created statically with the - * instance static member variable. - */ - protected DriverStation() { - m_dataSem = new Object(); - for(int i=0; i= 4) { + MotorSafetyHelper.checkMotors(); + safetyCounter = 0; + } + if (m_userInDisabled) { + FRCNetworkCommunicationsLibrary.FRCNetworkCommunicationObserveUserProgramDisabled(); + } + if (m_userInAutonomous) { + FRCNetworkCommunicationsLibrary.FRCNetworkCommunicationObserveUserProgramAutonomous(); + } + if (m_userInTeleop) { + FRCNetworkCommunicationsLibrary.FRCNetworkCommunicationObserveUserProgramTeleop(); + } + if (m_userInTest) { + FRCNetworkCommunicationsLibrary.FRCNetworkCommunicationObserveUserProgramTest(); + } + } + } + + /** + * Wait for new data from the driver station. + */ + public void waitForData() { + waitForData(0); + } + + /** + * Wait for new data or for timeout, which ever comes first. If timeout is 0, + * wait for new data only. + * + * @param timeout The maximum time in milliseconds to wait. + */ + public void waitForData(long timeout) { + synchronized (m_dataSem) { + try { + m_dataSem.wait(timeout); + } catch (InterruptedException ex) { + } + } + } + + /** + * Copy data from the DS task for the user. If no new data exists, it will + * just be returned, otherwise the data will be copied from the DS polling + * loop. + */ + protected synchronized void getData() { + + // Get the status of all of the joysticks + for (byte stick = 0; stick < kJoystickPorts; stick++) { + m_joystickAxes[stick] = FRCNetworkCommunicationsLibrary.HALGetJoystickAxes(stick); + m_joystickPOVs[stick] = FRCNetworkCommunicationsLibrary.HALGetJoystickPOVs(stick); + ByteBuffer countBuffer = ByteBuffer.allocateDirect(1); + m_joystickButtons[stick].buttons = + FRCNetworkCommunicationsLibrary.HALGetJoystickButtons((byte) stick, countBuffer); + m_joystickButtons[stick].count = countBuffer.get(); } - /** - * Provides the service routine for the DS polling thread. - */ - private void task() { - int safetyCounter = 0; - while (m_thread_keepalive) { - HALUtil.takeMultiWait(m_packetDataAvailableSem, m_packetDataAvailableMutex, 0); - synchronized (this) { - getData(); - } - synchronized (m_dataSem) { - m_dataSem.notifyAll(); - } - if (++safetyCounter >= 4) { - MotorSafetyHelper.checkMotors(); - safetyCounter = 0; - } - if (m_userInDisabled) { - FRCNetworkCommunicationsLibrary.FRCNetworkCommunicationObserveUserProgramDisabled(); - } - if (m_userInAutonomous) { - FRCNetworkCommunicationsLibrary.FRCNetworkCommunicationObserveUserProgramAutonomous(); - } - if (m_userInTeleop) { - FRCNetworkCommunicationsLibrary.FRCNetworkCommunicationObserveUserProgramTeleop(); - } - if (m_userInTest) { - FRCNetworkCommunicationsLibrary.FRCNetworkCommunicationObserveUserProgramTest(); - } - } + m_newControlData = true; + } + + /** + * Read the battery voltage. + * + * @return The battery voltage in Volts. + */ + public double getBatteryVoltage() { + IntBuffer status = ByteBuffer.allocateDirect(4).asIntBuffer(); + float voltage = PowerJNI.getVinVoltage(status); + HALUtil.checkStatus(status); + + return voltage; + } + + /** + * Reports errors related to unplugged joysticks Throttles the errors so that + * they don't overwhelm the DS + */ + private void reportJoystickUnpluggedError(String message) { + double currentTime = Timer.getFPGATimestamp(); + if (currentTime > m_nextMessageTime) { + reportError(message, false); + m_nextMessageTime = currentTime + JOYSTICK_UNPLUGGED_MESSAGE_INTERVAL; + } + } + + /** + * Get the value of the axis on a joystick. This depends on the mapping of the + * joystick connected to the specified port. + * + * @param stick The joystick to read. + * @param axis The analog axis value to read from the joystick. + * @return The value of the axis on the joystick. + */ + public synchronized double getStickAxis(int stick, int axis) { + if (stick < 0 || stick >= kJoystickPorts) { + throw new RuntimeException("Joystick index is out of range, should be 0-5"); } - /** - * Wait for new data from the driver station. - */ - public void waitForData() { - waitForData(0); + if (axis < 0 || axis >= FRCNetworkCommunicationsLibrary.kMaxJoystickAxes) { + throw new RuntimeException("Joystick axis is out of range"); } - /** - * Wait for new data or for timeout, which ever comes first. If timeout is - * 0, wait for new data only. - * - * @param timeout The maximum time in milliseconds to wait. - */ - public void waitForData(long timeout) { - synchronized (m_dataSem) { - try { - m_dataSem.wait(timeout); - } catch (InterruptedException ex) { - } - } - } - /** - * Copy data from the DS task for the user. - * If no new data exists, it will just be returned, otherwise - * the data will be copied from the DS polling loop. - */ - protected synchronized void getData() { - - // Get the status of all of the joysticks - for(byte stick = 0; stick < kJoystickPorts; stick++) { - m_joystickAxes[stick] = FRCNetworkCommunicationsLibrary.HALGetJoystickAxes(stick); - m_joystickPOVs[stick] = FRCNetworkCommunicationsLibrary.HALGetJoystickPOVs(stick); - ByteBuffer countBuffer = ByteBuffer.allocateDirect(1); - m_joystickButtons[stick].buttons = FRCNetworkCommunicationsLibrary.HALGetJoystickButtons((byte)stick, countBuffer); - m_joystickButtons[stick].count = countBuffer.get(); - } - - m_newControlData = true; + if (axis >= m_joystickAxes[stick].length) { + reportJoystickUnpluggedError("WARNING: Joystick axis " + axis + " on port " + stick + + " not available, check if controller is plugged in\n"); + return 0.0; } - /** - * Read the battery voltage. - * - * @return The battery voltage in Volts. - */ - public double getBatteryVoltage() { - IntBuffer status = ByteBuffer.allocateDirect(4).asIntBuffer(); - float voltage = PowerJNI.getVinVoltage(status); - HALUtil.checkStatus(status); + byte value = (byte) m_joystickAxes[stick][axis]; - return voltage; + if (value < 0) { + return value / 128.0; + } else { + return value / 127.0; + } + } + + /** + * Returns the number of axes on a given joystick port + * + * @param stick The joystick port number + * @return The number of axes on the indicated joystick + */ + public synchronized int getStickAxisCount(int stick) { + + if (stick < 0 || stick >= kJoystickPorts) { + throw new RuntimeException("Joystick index is out of range, should be 0-5"); } - /** - * Reports errors related to unplugged joysticks - * Throttles the errors so that they don't overwhelm the DS - */ - private void reportJoystickUnpluggedError(String message) { - double currentTime = Timer.getFPGATimestamp(); - if (currentTime > m_nextMessageTime) { - reportError(message, false); - m_nextMessageTime = currentTime + JOYSTICK_UNPLUGGED_MESSAGE_INTERVAL; - } + return m_joystickAxes[stick].length; + } + + /** + * Get the state of a POV on the joystick. + * + * @return the angle of the POV in degrees, or -1 if the POV is not pressed. + */ + public synchronized int getStickPOV(int stick, int pov) { + if (stick < 0 || stick >= kJoystickPorts) { + throw new RuntimeException("Joystick index is out of range, should be 0-5"); } - /** - * Get the value of the axis on a joystick. - * This depends on the mapping of the joystick connected to the specified port. - * - * @param stick The joystick to read. - * @param axis The analog axis value to read from the joystick. - * @return The value of the axis on the joystick. - */ - public synchronized double getStickAxis(int stick, int axis) { - if(stick < 0 || stick >= kJoystickPorts) { - throw new RuntimeException("Joystick index is out of range, should be 0-5"); - } - - if (axis < 0 || axis >= FRCNetworkCommunicationsLibrary.kMaxJoystickAxes) { - throw new RuntimeException("Joystick axis is out of range"); - } - - if (axis >= m_joystickAxes[stick].length) { - reportJoystickUnpluggedError("WARNING: Joystick axis " + axis + " on port " + stick + " not available, check if controller is plugged in\n"); - return 0.0; - } - - byte value = (byte)m_joystickAxes[stick][axis]; - - if(value < 0) { - return value / 128.0; - } else { - return value / 127.0; - } + if (pov < 0 || pov >= FRCNetworkCommunicationsLibrary.kMaxJoystickPOVs) { + throw new RuntimeException("Joystick POV is out of range"); } - /** - * Returns the number of axes on a given joystick port - * - * @param stick The joystick port number - * @return The number of axes on the indicated joystick - */ - public synchronized int getStickAxisCount(int stick){ - - if(stick < 0 || stick >= kJoystickPorts) { - throw new RuntimeException("Joystick index is out of range, should be 0-5"); - } - - return m_joystickAxes[stick].length; + if (pov >= m_joystickPOVs[stick].length) { + reportJoystickUnpluggedError("WARNING: Joystick POV " + pov + " on port " + stick + + " not available, check if controller is plugged in\n"); + return -1; } - /** - * Get the state of a POV on the joystick. - * - * @return the angle of the POV in degrees, or -1 if the POV is not pressed. - */ - public synchronized int getStickPOV(int stick, int pov) { - if(stick < 0 || stick >= kJoystickPorts) { - throw new RuntimeException("Joystick index is out of range, should be 0-5"); - } + return m_joystickPOVs[stick][pov]; + } - if (pov < 0 || pov >= FRCNetworkCommunicationsLibrary.kMaxJoystickPOVs) { - throw new RuntimeException("Joystick POV is out of range"); - } + /** + * Returns the number of POVs on a given joystick port + * + * @param stick The joystick port number + * @return The number of POVs on the indicated joystick + */ + public synchronized int getStickPOVCount(int stick) { - if (pov >= m_joystickPOVs[stick].length) { - reportJoystickUnpluggedError("WARNING: Joystick POV " + pov + " on port " + stick + " not available, check if controller is plugged in\n"); - return -1; - } - - return m_joystickPOVs[stick][pov]; + if (stick < 0 || stick >= kJoystickPorts) { + throw new RuntimeException("Joystick index is out of range, should be 0-5"); } -/** - * Returns the number of POVs on a given joystick port - * - * @param stick The joystick port number - * @return The number of POVs on the indicated joystick - */ - public synchronized int getStickPOVCount(int stick){ + return m_joystickPOVs[stick].length; + } - if(stick < 0 || stick >= kJoystickPorts) { - throw new RuntimeException("Joystick index is out of range, should be 0-5"); - } - - return m_joystickPOVs[stick].length; + /** + * The state of the buttons on the joystick. + * + * @param stick The joystick to read. + * @return The state of the buttons on the joystick. + */ + public synchronized int getStickButtons(final int stick) { + if (stick < 0 || stick >= kJoystickPorts) { + throw new RuntimeException("Joystick index is out of range, should be 0-3"); } - /** - * The state of the buttons on the joystick. - * - * @param stick The joystick to read. - * @return The state of the buttons on the joystick. - */ - public synchronized int getStickButtons(final int stick) { - if(stick < 0 || stick >= kJoystickPorts) { - throw new RuntimeException("Joystick index is out of range, should be 0-3"); - } + return m_joystickButtons[stick].buttons; + } - return m_joystickButtons[stick].buttons; + /** + * The state of one joystick button. Button indexes begin at 1. + * + * @param stick The joystick to read. + * @param button The button index, beginning at 1. + * @return The state of the joystick button. + */ + public synchronized boolean getStickButton(final int stick, byte button) { + if (stick < 0 || stick >= kJoystickPorts) { + throw new RuntimeException("Joystick index is out of range, should be 0-3"); } - /** - * The state of one joystick button. Button indexes begin at 1. - * - * @param stick The joystick to read. - * @param button The button index, beginning at 1. - * @return The state of the joystick button. - */ - public synchronized boolean getStickButton(final int stick, byte button) { - if(stick < 0 || stick >= kJoystickPorts) { - throw new RuntimeException("Joystick index is out of range, should be 0-3"); - } - - if(button > m_joystickButtons[stick].count) { - reportJoystickUnpluggedError("WARNING: Joystick Button " + button + " on port " + stick + " not available, check if controller is plugged in\n"); - return false; - } - if(button <= 0) - { - reportJoystickUnpluggedError("ERROR: Button indexes begin at 1 in WPILib for C++ and Java\n"); - return false; - } - return ((0x1 << (button - 1)) & m_joystickButtons[stick].buttons) != 0; + if (button > m_joystickButtons[stick].count) { + reportJoystickUnpluggedError("WARNING: Joystick Button " + button + " on port " + stick + + " not available, check if controller is plugged in\n"); + return false; + } + if (button <= 0) { + reportJoystickUnpluggedError("ERROR: Button indexes begin at 1 in WPILib for C++ and Java\n"); + return false; + } + return ((0x1 << (button - 1)) & m_joystickButtons[stick].buttons) != 0; + } + + /** + * Gets the number of buttons on a joystick + * + * @param stick The joystick port number + * @return The number of buttons on the indicated joystick + */ + public synchronized int getStickButtonCount(int stick) { + + if (stick < 0 || stick >= kJoystickPorts) { + throw new RuntimeException("Joystick index is out of range, should be 0-5"); } - /** - * Gets the number of buttons on a joystick - * - * @param stick The joystick port number - * @return The number of buttons on the indicated joystick - */ - public synchronized int getStickButtonCount(int stick){ - if(stick < 0 || stick >= kJoystickPorts) { - throw new RuntimeException("Joystick index is out of range, should be 0-5"); - } - - - return m_joystickButtons[stick].count; + return m_joystickButtons[stick].count; + } + + /** + * Gets the value of isXbox on a joystick + * + * @param stick The joystick port number + * @return A boolean that returns the value of isXbox + */ + public synchronized boolean getJoystickIsXbox(int stick) { + + if (stick < 0 || stick >= kJoystickPorts) { + throw new RuntimeException("Joystick index is out of range, should be 0-5"); + } + // TODO: Remove this when calling for descriptor on empty stick no longer + // crashes + if (1 > m_joystickButtons[stick].count && 1 > m_joystickAxes[stick].length) { + reportJoystickUnpluggedError("WARNING: Joystick on port " + stick + + " not available, check if controller is plugged in\n"); + return false; + } + boolean retVal = false; + if (FRCNetworkCommunicationsLibrary.HALGetJoystickIsXbox((byte) stick) == 1) { + retVal = true; + } + return retVal; + } + + /** + * Gets the value of type on a joystick + * + * @param stick The joystick port number + * @return The value of type + */ + public synchronized int getJoystickType(int stick) { + + if (stick < 0 || stick >= kJoystickPorts) { + throw new RuntimeException("Joystick index is out of range, should be 0-5"); + } + // TODO: Remove this when calling for descriptor on empty stick no longer + // crashes + if (1 > m_joystickButtons[stick].count && 1 > m_joystickAxes[stick].length) { + reportJoystickUnpluggedError("WARNING: Joystick on port " + stick + + " not available, check if controller is plugged in\n"); + return -1; + } + return FRCNetworkCommunicationsLibrary.HALGetJoystickType((byte) stick); + } + + /** + * Gets the name of the joystick at a port + * + * @param stick The joystick port number + * @return The value of name + */ + public synchronized String getJoystickName(int stick) { + + if (stick < 0 || stick >= kJoystickPorts) { + throw new RuntimeException("Joystick index is out of range, should be 0-5"); + } + // TODO: Remove this when calling for descriptor on empty stick no longer + // crashes + if (1 > m_joystickButtons[stick].count && 1 > m_joystickAxes[stick].length) { + reportJoystickUnpluggedError("WARNING: Joystick on port " + stick + + " not available, check if controller is plugged in\n"); + return ""; + } + return FRCNetworkCommunicationsLibrary.HALGetJoystickName((byte) stick); + } + + /** + * Gets a value indicating whether the Driver Station requires the robot to be + * enabled. + * + * @return True if the robot is enabled, false otherwise. + */ + public boolean isEnabled() { + HALControlWord controlWord = FRCNetworkCommunicationsLibrary.HALGetControlWord(); + return controlWord.getEnabled() && controlWord.getDSAttached(); + } + + /** + * Gets a value indicating whether the Driver Station requires the robot to be + * disabled. + * + * @return True if the robot should be disabled, false otherwise. + */ + public boolean isDisabled() { + return !isEnabled(); + } + + /** + * Gets a value indicating whether the Driver Station requires the robot to be + * running in autonomous mode. + * + * @return True if autonomous mode should be enabled, false otherwise. + */ + public boolean isAutonomous() { + HALControlWord controlWord = FRCNetworkCommunicationsLibrary.HALGetControlWord(); + return controlWord.getAutonomous(); + } + + /** + * Gets a value indicating whether the Driver Station requires the robot to be + * running in test mode. + *$ + * @return True if test mode should be enabled, false otherwise. + */ + public boolean isTest() { + HALControlWord controlWord = FRCNetworkCommunicationsLibrary.HALGetControlWord(); + return controlWord.getTest(); + } + + /** + * Gets a value indicating whether the Driver Station requires the robot to be + * running in operator-controlled mode. + * + * @return True if operator-controlled mode should be enabled, false + * otherwise. + */ + public boolean isOperatorControl() { + return !(isAutonomous() || isTest()); + } + + /** + * Gets a value indicating whether the FPGA outputs are enabled. The outputs + * may be disabled if the robot is disabled or e-stopped, the watdhog has + * expired, or if the roboRIO browns out. + * + * @return True if the FPGA outputs are enabled. + */ + public boolean isSysActive() { + ByteBuffer status = ByteBuffer.allocateDirect(4); + status.order(ByteOrder.LITTLE_ENDIAN); + boolean retVal = FRCNetworkCommunicationsLibrary.HALGetSystemActive(status.asIntBuffer()); + HALUtil.checkStatus(status.asIntBuffer()); + return retVal; + } + + /** + * Check if the system is browned out. + *$ + * @return True if the system is browned out + */ + public boolean isBrownedOut() { + ByteBuffer status = ByteBuffer.allocateDirect(4); + status.order(ByteOrder.LITTLE_ENDIAN); + boolean retVal = FRCNetworkCommunicationsLibrary.HALGetBrownedOut(status.asIntBuffer()); + HALUtil.checkStatus(status.asIntBuffer()); + return retVal; + } + + /** + * Has a new control packet from the driver station arrived since the last + * time this function was called? + *$ + * @return True if the control data has been updated since the last call. + */ + public synchronized boolean isNewControlData() { + boolean result = m_newControlData; + m_newControlData = false; + return result; + } + + /** + * Get the current alliance from the FMS + *$ + * @return the current alliance + */ + public Alliance getAlliance() { + HALAllianceStationID allianceStationID = + FRCNetworkCommunicationsLibrary.HALGetAllianceStation(); + if (allianceStationID == null) { + return Alliance.Invalid; } - /** - * Gets the value of isXbox on a joystick - * - * @param stick The joystick port number - * @return A boolean that returns the value of isXbox - */ - public synchronized boolean getJoystickIsXbox(int stick){ + switch (allianceStationID) { + case Red1: + case Red2: + case Red3: + return Alliance.Red; - if(stick < 0 || stick >= kJoystickPorts) { - throw new RuntimeException("Joystick index is out of range, should be 0-5"); - } - //TODO: Remove this when calling for descriptor on empty stick no longer crashes - if(1 > m_joystickButtons[stick].count && 1 > m_joystickAxes[stick].length) { - reportJoystickUnpluggedError("WARNING: Joystick on port " + stick + " not available, check if controller is plugged in\n"); - return false; - } - boolean retVal = false; - if(FRCNetworkCommunicationsLibrary.HALGetJoystickIsXbox((byte)stick)==1) - { - retVal = true; - } - return retVal; + case Blue1: + case Blue2: + case Blue3: + return Alliance.Blue; + + default: + return Alliance.Invalid; } + } - /** - * Gets the value of type on a joystick - * - * @param stick The joystick port number - * @return The value of type - */ - public synchronized int getJoystickType(int stick){ - - if(stick < 0 || stick >= kJoystickPorts) { - throw new RuntimeException("Joystick index is out of range, should be 0-5"); - } - //TODO: Remove this when calling for descriptor on empty stick no longer crashes - if(1 > m_joystickButtons[stick].count && 1 > m_joystickAxes[stick].length) { - reportJoystickUnpluggedError("WARNING: Joystick on port " + stick + " not available, check if controller is plugged in\n"); - return -1; - } - return FRCNetworkCommunicationsLibrary.HALGetJoystickType((byte) stick); + /** + * Gets the location of the team's driver station controls. + * + * @return the location of the team's driver station controls: 1, 2, or 3 + */ + public int getLocation() { + HALAllianceStationID allianceStationID = + FRCNetworkCommunicationsLibrary.HALGetAllianceStation(); + if (allianceStationID == null) { + return 0; } - - /** - * Gets the name of the joystick at a port - * - * @param stick The joystick port number - * @return The value of name - */ - public synchronized String getJoystickName(int stick){ + switch (allianceStationID) { + case Red1: + case Blue1: + return 1; - if(stick < 0 || stick >= kJoystickPorts) { - throw new RuntimeException("Joystick index is out of range, should be 0-5"); - } - //TODO: Remove this when calling for descriptor on empty stick no longer crashes - if(1 > m_joystickButtons[stick].count && 1 > m_joystickAxes[stick].length) { - reportJoystickUnpluggedError("WARNING: Joystick on port " + stick + " not available, check if controller is plugged in\n"); - return ""; - } - return FRCNetworkCommunicationsLibrary.HALGetJoystickName((byte)stick); - } + case Red2: + case Blue2: + return 2; - /** - * Gets a value indicating whether the Driver Station requires the - * robot to be enabled. - * - * @return True if the robot is enabled, false otherwise. - */ - public boolean isEnabled() { - HALControlWord controlWord = FRCNetworkCommunicationsLibrary.HALGetControlWord(); - return controlWord.getEnabled() && controlWord.getDSAttached(); + case Blue3: + case Red3: + return 3; + + default: + return 0; } + } - /** - * Gets a value indicating whether the Driver Station requires the - * robot to be disabled. - * - * @return True if the robot should be disabled, false otherwise. - */ - public boolean isDisabled() { - return !isEnabled(); + /** + * Is the driver station attached to a Field Management System? Note: This + * does not work with the Blue DS. + *$ + * @return True if the robot is competing on a field being controlled by a + * Field Management System + */ + public boolean isFMSAttached() { + HALControlWord controlWord = FRCNetworkCommunicationsLibrary.HALGetControlWord(); + return controlWord.getFMSAttached(); + } + + public boolean isDSAttached() { + HALControlWord controlWord = FRCNetworkCommunicationsLibrary.HALGetControlWord(); + return controlWord.getDSAttached(); + } + + /** + * Return the approximate match time The FMS does not send an official match + * time to the robots, but does send an approximate match time. The value will + * count down the time remaining in the current period (auto or teleop). + * Warning: This is not an official time (so it cannot be used to dispute ref + * calls or guarantee that a function will trigger before the match ends) The + * Practice Match function of the DS approximates the behaviour seen on the + * field. + *$ + * @return Time remaining in current match period (auto or teleop) in seconds + */ + public double getMatchTime() { + return FRCNetworkCommunicationsLibrary.HALGetMatchTime(); + } + + /** + * Report error to Driver Station. Also prints error to System.err Optionally + * appends Stack trace to error message + *$ + * @param printTrace If true, append stack trace to error string + */ + public static void reportError(String error, boolean printTrace) { + String errorString = error; + if (printTrace) { + errorString += " at "; + StackTraceElement[] traces = Thread.currentThread().getStackTrace(); + for (int i = 2; i < traces.length; i++) { + errorString += traces[i].toString() + "\n"; + } } - - /** - * Gets a value indicating whether the Driver Station requires the - * robot to be running in autonomous mode. - * - * @return True if autonomous mode should be enabled, false otherwise. - */ - public boolean isAutonomous() { - HALControlWord controlWord = FRCNetworkCommunicationsLibrary.HALGetControlWord(); - return controlWord.getAutonomous(); + System.err.println(errorString); + HALControlWord controlWord = FRCNetworkCommunicationsLibrary.HALGetControlWord(); + if (controlWord.getDSAttached()) { + FRCNetworkCommunicationsLibrary.HALSetErrorData(errorString); } + } - /** - * Gets a value indicating whether the Driver Station requires the - * robot to be running in test mode. - * @return True if test mode should be enabled, false otherwise. - */ - public boolean isTest() { - HALControlWord controlWord = FRCNetworkCommunicationsLibrary.HALGetControlWord(); - return controlWord.getTest(); - } + /** + * Only to be used to tell the Driver Station what code you claim to be + * executing for diagnostic purposes only + *$ + * @param entering If true, starting disabled code; if false, leaving disabled + * code + */ + public void InDisabled(boolean entering) { + m_userInDisabled = entering; + } - /** - * Gets a value indicating whether the Driver Station requires the - * robot to be running in operator-controlled mode. - * - * @return True if operator-controlled mode should be enabled, false otherwise. - */ - public boolean isOperatorControl() { - return !(isAutonomous() || isTest()); - } - - /** - * Gets a value indicating whether the FPGA outputs are enabled. The outputs may be disabled - * if the robot is disabled or e-stopped, the watdhog has expired, or if the roboRIO browns out. - * - * @return True if the FPGA outputs are enabled. - */ - public boolean isSysActive() { - ByteBuffer status = ByteBuffer.allocateDirect(4); - status.order(ByteOrder.LITTLE_ENDIAN); - boolean retVal = FRCNetworkCommunicationsLibrary.HALGetSystemActive(status.asIntBuffer()); - HALUtil.checkStatus(status.asIntBuffer()); - return retVal; - } - - /** - * Check if the system is browned out. - * - * @return True if the system is browned out - */ - public boolean isBrownedOut() { - ByteBuffer status = ByteBuffer.allocateDirect(4); - status.order(ByteOrder.LITTLE_ENDIAN); - boolean retVal = FRCNetworkCommunicationsLibrary.HALGetBrownedOut(status.asIntBuffer()); - HALUtil.checkStatus(status.asIntBuffer()); - return retVal; - } + /** + * Only to be used to tell the Driver Station what code you claim to be + * executing for diagnostic purposes only + *$ + * @param entering If true, starting autonomous code; if false, leaving + * autonomous code + */ + public void InAutonomous(boolean entering) { + m_userInAutonomous = entering; + } - /** - * Has a new control packet from the driver station arrived since the last time this function was called? - * @return True if the control data has been updated since the last call. - */ - public synchronized boolean isNewControlData() { - boolean result = m_newControlData; - m_newControlData = false; - return result; - } + /** + * Only to be used to tell the Driver Station what code you claim to be + * executing for diagnostic purposes only + *$ + * @param entering If true, starting teleop code; if false, leaving teleop + * code + */ + public void InOperatorControl(boolean entering) { + m_userInTeleop = entering; + } - /** - * Get the current alliance from the FMS - * @return the current alliance - */ - public Alliance getAlliance() { - HALAllianceStationID allianceStationID = FRCNetworkCommunicationsLibrary.HALGetAllianceStation(); - if(allianceStationID == null) { - return Alliance.Invalid; - } - - switch (allianceStationID) { - case Red1: - case Red2: - case Red3: - return Alliance.Red; - - case Blue1: - case Blue2: - case Blue3: - return Alliance.Blue; - - default: - return Alliance.Invalid; - } - } - - /** - * Gets the location of the team's driver station controls. - * - * @return the location of the team's driver station controls: 1, 2, or 3 - */ - public int getLocation() { - HALAllianceStationID allianceStationID = FRCNetworkCommunicationsLibrary.HALGetAllianceStation(); - if(allianceStationID == null) { - return 0; - } - switch (allianceStationID) { - case Red1: - case Blue1: - return 1; - - case Red2: - case Blue2: - return 2; - - case Blue3: - case Red3: - return 3; - - default: - return 0; - } - } - - /** - * Is the driver station attached to a Field Management System? - * Note: This does not work with the Blue DS. - * @return True if the robot is competing on a field being controlled by a Field Management System - */ - public boolean isFMSAttached() { - HALControlWord controlWord = FRCNetworkCommunicationsLibrary.HALGetControlWord(); - return controlWord.getFMSAttached(); - } - - public boolean isDSAttached() { - HALControlWord controlWord = FRCNetworkCommunicationsLibrary.HALGetControlWord(); - return controlWord.getDSAttached(); - } - - /** - * Return the approximate match time - * The FMS does not send an official match time to the robots, but does send an approximate match time. - * The value will count down the time remaining in the current period (auto or teleop). - * Warning: This is not an official time (so it cannot be used to dispute ref calls or guarantee that a function - * will trigger before the match ends) - * The Practice Match function of the DS approximates the behaviour seen on the field. - * @return Time remaining in current match period (auto or teleop) in seconds - */ - public double getMatchTime() { - return FRCNetworkCommunicationsLibrary.HALGetMatchTime(); - } - - /** - * Report error to Driver Station. - * Also prints error to System.err - * Optionally appends Stack trace to error message - * @param printTrace If true, append stack trace to error string - */ - public static void reportError(String error, boolean printTrace) { - String errorString = error; - if(printTrace) { - errorString += " at "; - StackTraceElement[] traces = Thread.currentThread().getStackTrace(); - for (int i=2; i 6) { - throw new BoundaryException(BoundaryException.getMessage( - sendSize, 0, 6)); - } else if (receiveSize > 7) { - throw new BoundaryException(BoundaryException.getMessage( - receiveSize, 0, 7)); - } else { - throw new RuntimeException( - HALLibrary.PARAMETER_OUT_OF_RANGE_MESSAGE); - } - } - HALUtil.checkStatus(status);*/ - if(receiveSize > 0 && dataReceived != null) - { - dataReceivedBuffer.get(dataReceived); - } - return aborted; - } + m_port = port; + m_deviceAddress = deviceAddress; - /** - * Attempt to address a device on the I2C bus. - * - * This allows you to figure out if there is a device on the I2C bus that - * responds to the address specified in the constructor. - * - * @return Transfer Aborted... false for success, true for aborted. - */ - public boolean addressOnly() { - return transaction(null, (byte) 0, null, (byte) 0); - } + I2CJNI.i2CInitialize((byte) m_port.getValue(), status.asIntBuffer()); + HALUtil.checkStatus(status.asIntBuffer()); - /** - * Execute a write transaction with the device. - * - * Write a single byte to a register on a device and wait until the - * transaction is complete. - * - * @param registerAddress - * The address of the register on the device to be written. - * @param data - * The byte to write to the register on the device. - */ - public synchronized boolean write(int registerAddress, int data) { - byte[] buffer = new byte[2]; - buffer[0] = (byte) registerAddress; - buffer[1] = (byte) data; + UsageReporting.report(tResourceType.kResourceType_I2C, deviceAddress); + } - ByteBuffer dataToSendBuffer = ByteBuffer.allocateDirect(2); - dataToSendBuffer.put(buffer); + /** + * Destructor. + */ + public void free() {} - return I2CJNI.i2CWrite((byte)m_port.getValue(), (byte) m_deviceAddress, dataToSendBuffer, (byte)buffer.length) < 0; - } + /** + * Generic transaction. + * + * This is a lower-level interface to the I2C hardware giving you more control + * over each transaction. + * + * @param dataToSend Buffer of data to send as part of the transaction. + * @param sendSize Number of bytes to send as part of the transaction. [0..6] + * @param dataReceived Buffer to read data into. + * @param receiveSize Number of bytes to read from the device. [0..7] + * @return Transfer Aborted... false for success, true for aborted. + */ + public synchronized boolean transaction(byte[] dataToSend, int sendSize, byte[] dataReceived, + int receiveSize) { + boolean aborted = true; - /** - * Execute a write transaction with the device. - * - * Write multiple bytes to a register on a device and wait until the - * transaction is complete. - * - * @param data - * The data to write to the device. - */ - public synchronized boolean writeBulk(byte[] data) { - ByteBuffer dataToSendBuffer = ByteBuffer.allocateDirect(data.length); - dataToSendBuffer.put(data); + ByteBuffer dataToSendBuffer = ByteBuffer.allocateDirect(sendSize); + dataToSendBuffer.put(dataToSend); + ByteBuffer dataReceivedBuffer = ByteBuffer.allocateDirect(receiveSize); - return I2CJNI.i2CWrite((byte)m_port.getValue(), (byte) m_deviceAddress, dataToSendBuffer, (byte)data.length) < 0; - } + aborted = + I2CJNI.i2CTransaction((byte) m_port.getValue(), (byte) m_deviceAddress, dataToSendBuffer, + (byte) sendSize, dataReceivedBuffer, (byte) receiveSize) != 0; + /* + * if (status.get() == HALUtil.PARAMETER_OUT_OF_RANGE) { if (sendSize > 6) { + * throw new BoundaryException(BoundaryException.getMessage( sendSize, 0, + * 6)); } else if (receiveSize > 7) { throw new + * BoundaryException(BoundaryException.getMessage( receiveSize, 0, 7)); } + * else { throw new RuntimeException( + * HALLibrary.PARAMETER_OUT_OF_RANGE_MESSAGE); } } + * HALUtil.checkStatus(status); + */ + if (receiveSize > 0 && dataReceived != null) { + dataReceivedBuffer.get(dataReceived); + } + return aborted; + } - /** - * Execute a read transaction with the device. - * - * Read 1 to 7 bytes from a device. Most I2C devices will auto-increment the - * register pointer internally allowing you to read up to 7 consecutive - * registers on a device in a single transaction. - * - * @param registerAddress - * The register to read first in the transaction. - * @param count - * The number of bytes to read in the transaction. [1..7] - * @param buffer - * A pointer to the array of bytes to store the data read from - * the device. - * @return Transfer Aborted... false for success, true for aborted. - */ - public boolean read(int registerAddress, int count, byte[] buffer) { - BoundaryException.assertWithinBounds(count, 1, 7); - if (buffer == null) { - throw new NullPointerException("Null return buffer was given"); - } - byte[] registerAddressArray = new byte[1]; - registerAddressArray[0] = (byte) registerAddress; + /** + * Attempt to address a device on the I2C bus. + * + * This allows you to figure out if there is a device on the I2C bus that + * responds to the address specified in the constructor. + * + * @return Transfer Aborted... false for success, true for aborted. + */ + public boolean addressOnly() { + return transaction(null, (byte) 0, null, (byte) 0); + } - return transaction(registerAddressArray, registerAddressArray.length, - buffer, count); - } + /** + * Execute a write transaction with the device. + * + * Write a single byte to a register on a device and wait until the + * transaction is complete. + * + * @param registerAddress The address of the register on the device to be + * written. + * @param data The byte to write to the register on the device. + */ + public synchronized boolean write(int registerAddress, int data) { + byte[] buffer = new byte[2]; + buffer[0] = (byte) registerAddress; + buffer[1] = (byte) data; - /** - * Execute a read only transaction with the device. - * - * Read 1 to 7 bytes from a device. This method does not write any data to prompt - * the device. - * - * @param buffer - * A pointer to the array of bytes to store the data read from - * the device. - * @param count - * The number of bytes to read in the transaction. [1..7] - * @return Transfer Aborted... false for success, true for aborted. - */ - public boolean readOnly(byte[] buffer, int count) { - BoundaryException.assertWithinBounds(count, 1, 7); - if (buffer == null) { - throw new NullPointerException("Null return buffer was given"); - } + ByteBuffer dataToSendBuffer = ByteBuffer.allocateDirect(2); + dataToSendBuffer.put(buffer); - ByteBuffer dataReceivedBuffer = ByteBuffer.allocateDirect(count); + return I2CJNI.i2CWrite((byte) m_port.getValue(), (byte) m_deviceAddress, dataToSendBuffer, + (byte) buffer.length) < 0; + } - int retVal = I2CJNI.i2CRead((byte)m_port.getValue(), (byte) m_deviceAddress, dataReceivedBuffer, (byte)count); - dataReceivedBuffer.get(buffer); - return retVal < 0; - } + /** + * Execute a write transaction with the device. + * + * Write multiple bytes to a register on a device and wait until the + * transaction is complete. + * + * @param data The data to write to the device. + */ + public synchronized boolean writeBulk(byte[] data) { + ByteBuffer dataToSendBuffer = ByteBuffer.allocateDirect(data.length); + dataToSendBuffer.put(data); - /** - * Send a broadcast write to all devices on the I2C bus. - * - * This is not currently implemented! - * - * @param registerAddress - * The register to write on all devices on the bus. - * @param data - * The value to write to the devices. - */ - public void broadcast(int registerAddress, int data) { - } + return I2CJNI.i2CWrite((byte) m_port.getValue(), (byte) m_deviceAddress, dataToSendBuffer, + (byte) data.length) < 0; + } - /** - * Verify that a device's registers contain expected values. - * - * Most devices will have a set of registers that contain a known value that - * can be used to identify them. This allows an I2C device driver to easily - * verify that the device contains the expected value. - * - * @pre The device must support and be configured to use register - * auto-increment. - * - * @param registerAddress - * The base register to start reading from the device. - * @param count - * The size of the field to be verified. - * @param expected - * A buffer containing the values expected from the device. - * @return true if the sensor was verified to be connected - */ - public boolean verifySensor(int registerAddress, int count, byte[] expected) { - // TODO: Make use of all 7 read bytes - byte[] deviceData = new byte[4]; - for (int i = 0, curRegisterAddress = registerAddress; i < count; i += 4, curRegisterAddress += 4) { - int toRead = count - i < 4 ? count - i : 4; - // Read the chunk of data. Return false if the sensor does not - // respond. - if (read(curRegisterAddress, toRead, deviceData)) { - return false; - } + /** + * Execute a read transaction with the device. + * + * Read 1 to 7 bytes from a device. Most I2C devices will auto-increment the + * register pointer internally allowing you to read up to 7 consecutive + * registers on a device in a single transaction. + * + * @param registerAddress The register to read first in the transaction. + * @param count The number of bytes to read in the transaction. [1..7] + * @param buffer A pointer to the array of bytes to store the data read from + * the device. + * @return Transfer Aborted... false for success, true for aborted. + */ + public boolean read(int registerAddress, int count, byte[] buffer) { + BoundaryException.assertWithinBounds(count, 1, 7); + if (buffer == null) { + throw new NullPointerException("Null return buffer was given"); + } + byte[] registerAddressArray = new byte[1]; + registerAddressArray[0] = (byte) registerAddress; - for (byte j = 0; j < toRead; j++) { - if (deviceData[j] != expected[i + j]) { - return false; - } - } - } - return true; - } + return transaction(registerAddressArray, registerAddressArray.length, buffer, count); + } + + /** + * Execute a read only transaction with the device. + * + * Read 1 to 7 bytes from a device. This method does not write any data to + * prompt the device. + * + * @param buffer A pointer to the array of bytes to store the data read from + * the device. + * @param count The number of bytes to read in the transaction. [1..7] + * @return Transfer Aborted... false for success, true for aborted. + */ + public boolean readOnly(byte[] buffer, int count) { + BoundaryException.assertWithinBounds(count, 1, 7); + if (buffer == null) { + throw new NullPointerException("Null return buffer was given"); + } + + ByteBuffer dataReceivedBuffer = ByteBuffer.allocateDirect(count); + + int retVal = + I2CJNI.i2CRead((byte) m_port.getValue(), (byte) m_deviceAddress, dataReceivedBuffer, + (byte) count); + dataReceivedBuffer.get(buffer); + return retVal < 0; + } + + /** + * Send a broadcast write to all devices on the I2C bus. + * + * This is not currently implemented! + * + * @param registerAddress The register to write on all devices on the bus. + * @param data The value to write to the devices. + */ + public void broadcast(int registerAddress, int data) {} + + /** + * Verify that a device's registers contain expected values. + * + * Most devices will have a set of registers that contain a known value that + * can be used to identify them. This allows an I2C device driver to easily + * verify that the device contains the expected value. + * + * @pre The device must support and be configured to use register + * auto-increment. + * + * @param registerAddress The base register to start reading from the device. + * @param count The size of the field to be verified. + * @param expected A buffer containing the values expected from the device. + * @return true if the sensor was verified to be connected + */ + public boolean verifySensor(int registerAddress, int count, byte[] expected) { + // TODO: Make use of all 7 read bytes + byte[] deviceData = new byte[4]; + for (int i = 0, curRegisterAddress = registerAddress; i < count; i += 4, curRegisterAddress += + 4) { + int toRead = count - i < 4 ? count - i : 4; + // Read the chunk of data. Return false if the sensor does not + // respond. + if (read(curRegisterAddress, toRead, deviceData)) { + return false; + } + + for (byte j = 0; j < toRead; j++) { + if (deviceData[j] != expected[i + j]) { + return false; + } + } + } + return true; + } } diff --git a/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/InterruptHandlerFunction.java b/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/InterruptHandlerFunction.java index 215c3c5ab6..f507b96a60 100644 --- a/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/InterruptHandlerFunction.java +++ b/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/InterruptHandlerFunction.java @@ -1,8 +1,8 @@ /*----------------------------------------------------------------------------*/ -/* Copyright (c) FIRST 2008-2014. All Rights Reserved. */ -/* Open Source Software - may be modified and shared by FRC teams. The code */ +/* Copyright (c) FIRST 2008-2014. All Rights Reserved. */ +/* Open Source Software - may be modified and shared by FRC teams. The code */ /* must be accompanied by the FIRST BSD license file in the root directory of */ -/* the project. */ +/* the project. */ /*----------------------------------------------------------------------------*/ package edu.wpi.first.wpilibj; @@ -10,48 +10,53 @@ import edu.wpi.first.wpilibj.hal.InterruptJNI.InterruptJNIHandlerFunction; /** - * It is recommended that you use this class in conjunction with classes from + * It is recommended that you use this class in conjunction with classes from * {@link java.util.concurrent.atomic} as these objects are all thread safe. - * + *$ * @author Jonathan Leitschuh * * @param The type of the parameter that should be returned to the the - * method {@link #interruptFired(int, Object)} + * method {@link #interruptFired(int, Object)} */ public abstract class InterruptHandlerFunction { - /** - * The entry point for the interrupt. When the interrupt fires the - * {@link #apply(int, Object)} method is called. - * The outer class is provided as an interface to allow the implementer to - * pass a generic object to the interrupt fired method. - * @author Jonathan Leitschuh - */ - private class Function implements InterruptJNIHandlerFunction { - @SuppressWarnings("unchecked") - @Override - public void apply(int interruptAssertedMask, Object param) { - interruptFired(interruptAssertedMask, (T)param); - } - } - final Function function = new Function(); - - /** - * This method is run every time an interrupt is fired. - * @param interruptAssertedMask - * @param param The parameter provided by overriding the {@link #overridableParameter()} - * method. - */ - public abstract void interruptFired(int interruptAssertedMask, T param); - - - /** - * Override this method if you would like to pass a specific - * parameter to the {@link #interruptFired(int, Object)} when it is fired by the interrupt. - * This method is called once when {@link InterruptableSensorBase#requestInterrupts(InterruptHandlerFunction)} - * is run. - * @return The object that should be passed to the interrupt when it runs - */ - public T overridableParameter() { - return null; - } -} \ No newline at end of file + /** + * The entry point for the interrupt. When the interrupt fires the + * {@link #apply(int, Object)} method is called. The outer class is provided + * as an interface to allow the implementer to pass a generic object to the + * interrupt fired method. + *$ + * @author Jonathan Leitschuh + */ + private class Function implements InterruptJNIHandlerFunction { + @SuppressWarnings("unchecked") + @Override + public void apply(int interruptAssertedMask, Object param) { + interruptFired(interruptAssertedMask, (T) param); + } + } + + final Function function = new Function(); + + /** + * This method is run every time an interrupt is fired. + *$ + * @param interruptAssertedMask + * @param param The parameter provided by overriding the + * {@link #overridableParameter()} method. + */ + public abstract void interruptFired(int interruptAssertedMask, T param); + + + /** + * Override this method if you would like to pass a specific parameter to the + * {@link #interruptFired(int, Object)} when it is fired by the interrupt. + * This method is called once when + * {@link InterruptableSensorBase#requestInterrupts(InterruptHandlerFunction)} + * is run. + *$ + * @return The object that should be passed to the interrupt when it runs + */ + public T overridableParameter() { + return null; + } +} diff --git a/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/InterruptableSensorBase.java b/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/InterruptableSensorBase.java index 86d3df0e48..06433b3022 100644 --- a/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/InterruptableSensorBase.java +++ b/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/InterruptableSensorBase.java @@ -1,8 +1,8 @@ /*----------------------------------------------------------------------------*/ -/* Copyright (c) FIRST 2008-2012. All Rights Reserved. */ -/* Open Source Software - may be modified and shared by FRC teams. The code */ +/* Copyright (c) FIRST 2008-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 the root directory of */ -/* the project. */ +/* the project. */ /*----------------------------------------------------------------------------*/ package edu.wpi.first.wpilibj; @@ -19,274 +19,267 @@ import edu.wpi.first.wpilibj.util.CheckedAllocationException; * Base for sensors to be used with interrupts */ public abstract class InterruptableSensorBase extends SensorBase { - /** - * This is done to store the JVM variable in the InterruptJNI - * This is done because the HAL must have access to the JVM variable - * in order to attach the newly spawned thread when an interrupt is fired. - */ - static{ - ByteBuffer status = ByteBuffer.allocateDirect(4); - status.order(ByteOrder.LITTLE_ENDIAN); - InterruptJNI.initializeInterruptJVM(status.asIntBuffer()); - HALUtil.checkStatus(status.asIntBuffer()); - } + /** + * This is done to store the JVM variable in the InterruptJNI This is done + * because the HAL must have access to the JVM variable in order to attach the + * newly spawned thread when an interrupt is fired. + */ + static { + ByteBuffer status = ByteBuffer.allocateDirect(4); + status.order(ByteOrder.LITTLE_ENDIAN); + InterruptJNI.initializeInterruptJVM(status.asIntBuffer()); + HALUtil.checkStatus(status.asIntBuffer()); + } - /** - * The interrupt resource - */ - protected ByteBuffer m_interrupt = null; + /** + * The interrupt resource + */ + protected ByteBuffer m_interrupt = null; - /** - * Flags if the interrupt being allocated is synchronous - */ - protected boolean m_isSynchronousInterrupt = false; + /** + * Flags if the interrupt being allocated is synchronous + */ + protected boolean m_isSynchronousInterrupt = false; - /** - * The index of the interrupt - */ - protected int m_interruptIndex; - /** - * Resource manager - */ - protected static Resource interrupts = new Resource(8); + /** + * The index of the interrupt + */ + protected int m_interruptIndex; + /** + * Resource manager + */ + protected static Resource interrupts = new Resource(8); - /** - * Create a new InterrupatableSensorBase - */ - public InterruptableSensorBase() { - m_interrupt = null; - } + /** + * Create a new InterrupatableSensorBase + */ + public InterruptableSensorBase() { + m_interrupt = null; + } - /** - * @return true if this is an analog trigger - */ - abstract boolean getAnalogTriggerForRouting(); + /** + * @return true if this is an analog trigger + */ + abstract boolean getAnalogTriggerForRouting(); - /** - * @return channel routing number - */ - abstract int getChannelForRouting(); + /** + * @return channel routing number + */ + abstract int getChannelForRouting(); - /** - * @return module routing number - */ - abstract byte getModuleForRouting(); + /** + * @return module routing number + */ + abstract byte getModuleForRouting(); - /** - * Request one of the 8 interrupts asynchronously on this digital input. - * - * @param handler - * The {@link InterruptHandlerFunction} that contains the method - * {@link InterruptHandlerFunction#interruptFired(int, Object)} that - * will be called whenever there is an interrupt on this device. - * Request interrupts in synchronous mode where the user program - * interrupt handler will be called when an interrupt occurs. The - * default is interrupt on rising edges only. - */ - public void requestInterrupts(InterruptHandlerFunction handler) { - if(m_interrupt != null){ - throw new AllocationException("The interrupt has already been allocated"); - } + /** + * Request one of the 8 interrupts asynchronously on this digital input. + * + * @param handler The {@link InterruptHandlerFunction} that contains the + * method {@link InterruptHandlerFunction#interruptFired(int, Object)} + * that will be called whenever there is an interrupt on this device. + * Request interrupts in synchronous mode where the user program + * interrupt handler will be called when an interrupt occurs. The + * default is interrupt on rising edges only. + */ + public void requestInterrupts(InterruptHandlerFunction handler) { + if (m_interrupt != null) { + throw new AllocationException("The interrupt has already been allocated"); + } - allocateInterrupts(false); + allocateInterrupts(false); - assert (m_interrupt != null); + assert (m_interrupt != null); - ByteBuffer status = ByteBuffer.allocateDirect(4); - // set the byte order - status.order(ByteOrder.LITTLE_ENDIAN); - InterruptJNI.requestInterrupts(m_interrupt, getModuleForRouting(), - getChannelForRouting(), - (byte) (getAnalogTriggerForRouting() ? 1 : 0), status.asIntBuffer()); - HALUtil.checkStatus(status.asIntBuffer()); - setUpSourceEdge(true, false); - InterruptJNI.attachInterruptHandler(m_interrupt, handler.function, handler.overridableParameter(), status.asIntBuffer()); - HALUtil.checkStatus(status.asIntBuffer()); - } + ByteBuffer status = ByteBuffer.allocateDirect(4); + // set the byte order + status.order(ByteOrder.LITTLE_ENDIAN); + InterruptJNI.requestInterrupts(m_interrupt, getModuleForRouting(), getChannelForRouting(), + (byte) (getAnalogTriggerForRouting() ? 1 : 0), status.asIntBuffer()); + HALUtil.checkStatus(status.asIntBuffer()); + setUpSourceEdge(true, false); + InterruptJNI.attachInterruptHandler(m_interrupt, handler.function, + handler.overridableParameter(), status.asIntBuffer()); + HALUtil.checkStatus(status.asIntBuffer()); + } - /** - * Request one of the 8 interrupts synchronously on this digital input. Request - * interrupts in synchronous mode where the user program will have to - * explicitly wait for the interrupt to occur using {@link #waitForInterrupt}. - * The default is interrupt on rising edges only. - */ - public void requestInterrupts() { - if(m_interrupt != null){ - throw new AllocationException("The interrupt has already been allocated"); - } + /** + * Request one of the 8 interrupts synchronously on this digital input. + * Request interrupts in synchronous mode where the user program will have to + * explicitly wait for the interrupt to occur using {@link #waitForInterrupt}. + * The default is interrupt on rising edges only. + */ + public void requestInterrupts() { + if (m_interrupt != null) { + throw new AllocationException("The interrupt has already been allocated"); + } - allocateInterrupts(true); + allocateInterrupts(true); - assert (m_interrupt != null); + assert (m_interrupt != null); - ByteBuffer status = ByteBuffer.allocateDirect(4); - // set the byte order - status.order(ByteOrder.LITTLE_ENDIAN); - InterruptJNI.requestInterrupts(m_interrupt, getModuleForRouting(), - getChannelForRouting(), - (byte) (getAnalogTriggerForRouting() ? 1 : 0), status.asIntBuffer()); - HALUtil.checkStatus(status.asIntBuffer()); - setUpSourceEdge(true, false); + ByteBuffer status = ByteBuffer.allocateDirect(4); + // set the byte order + status.order(ByteOrder.LITTLE_ENDIAN); + InterruptJNI.requestInterrupts(m_interrupt, getModuleForRouting(), getChannelForRouting(), + (byte) (getAnalogTriggerForRouting() ? 1 : 0), status.asIntBuffer()); + HALUtil.checkStatus(status.asIntBuffer()); + setUpSourceEdge(true, false); - } + } - /** - * Allocate the interrupt - * - * @param watcher true if the interrupt should be in synchronous mode where the user - * program will have to explicitly wait for the interrupt to occur. - */ - protected void allocateInterrupts(boolean watcher) { - try { - m_interruptIndex = interrupts.allocate(); - } catch (CheckedAllocationException e) { - throw new AllocationException( - "No interrupts are left to be allocated"); - } - m_isSynchronousInterrupt = watcher; + /** + * Allocate the interrupt + * + * @param watcher true if the interrupt should be in synchronous mode where + * the user program will have to explicitly wait for the interrupt to + * occur. + */ + protected void allocateInterrupts(boolean watcher) { + try { + m_interruptIndex = interrupts.allocate(); + } catch (CheckedAllocationException e) { + throw new AllocationException("No interrupts are left to be allocated"); + } + m_isSynchronousInterrupt = watcher; - ByteBuffer status = ByteBuffer.allocateDirect(4); - status.order(ByteOrder.LITTLE_ENDIAN); - m_interrupt = InterruptJNI.initializeInterrupts(m_interruptIndex, - (byte) (watcher ? 1 : 0), status.asIntBuffer()); - HALUtil.checkStatus(status.asIntBuffer()); - } + ByteBuffer status = ByteBuffer.allocateDirect(4); + status.order(ByteOrder.LITTLE_ENDIAN); + m_interrupt = + InterruptJNI.initializeInterrupts(m_interruptIndex, (byte) (watcher ? 1 : 0), + status.asIntBuffer()); + HALUtil.checkStatus(status.asIntBuffer()); + } - /** - * Cancel interrupts on this device. This deallocates all the chipobject - * structures and disables any interrupts. - */ - public void cancelInterrupts() { - if (m_interrupt == null) { - throw new IllegalStateException("The interrupt is not allocated."); - } - ByteBuffer status = ByteBuffer.allocateDirect(4); - status.order(ByteOrder.LITTLE_ENDIAN); - InterruptJNI.cleanInterrupts(m_interrupt, status.asIntBuffer()); - HALUtil.checkStatus(status.asIntBuffer()); - m_interrupt = null; - interrupts.free(m_interruptIndex); - } + /** + * Cancel interrupts on this device. This deallocates all the chipobject + * structures and disables any interrupts. + */ + public void cancelInterrupts() { + if (m_interrupt == null) { + throw new IllegalStateException("The interrupt is not allocated."); + } + ByteBuffer status = ByteBuffer.allocateDirect(4); + status.order(ByteOrder.LITTLE_ENDIAN); + InterruptJNI.cleanInterrupts(m_interrupt, status.asIntBuffer()); + HALUtil.checkStatus(status.asIntBuffer()); + m_interrupt = null; + interrupts.free(m_interruptIndex); + } - /** - * In synchronous mode, wait for the defined interrupt to occur. - * - * @param timeout - * Timeout in seconds - * @param ignorePrevious - * If true, ignore interrupts that happened before - * waitForInterrupt was called. - */ - public void waitForInterrupt(double timeout, boolean ignorePrevious) { - if (m_interrupt == null) { - throw new IllegalStateException("The interrupt is not allocated."); - } - ByteBuffer status = ByteBuffer.allocateDirect(4); - status.order(ByteOrder.LITTLE_ENDIAN); - InterruptJNI.waitForInterrupt(m_interrupt, (float) timeout, ignorePrevious, status.asIntBuffer()); - HALUtil.checkStatus(status.asIntBuffer()); - } + /** + * In synchronous mode, wait for the defined interrupt to occur. + * + * @param timeout Timeout in seconds + * @param ignorePrevious If true, ignore interrupts that happened before + * waitForInterrupt was called. + */ + public void waitForInterrupt(double timeout, boolean ignorePrevious) { + if (m_interrupt == null) { + throw new IllegalStateException("The interrupt is not allocated."); + } + ByteBuffer status = ByteBuffer.allocateDirect(4); + status.order(ByteOrder.LITTLE_ENDIAN); + InterruptJNI.waitForInterrupt(m_interrupt, (float) timeout, ignorePrevious, + status.asIntBuffer()); + HALUtil.checkStatus(status.asIntBuffer()); + } - /** - * In synchronous mode, wait for the defined interrupt to occur. - * - * @param timeout - * Timeout in seconds - */ - public void waitForInterrupt(double timeout) { - waitForInterrupt(timeout, true); - } + /** + * In synchronous mode, wait for the defined interrupt to occur. + * + * @param timeout Timeout in seconds + */ + public void waitForInterrupt(double timeout) { + waitForInterrupt(timeout, true); + } - /** - * Enable interrupts to occur on this input. Interrupts are disabled when - * the RequestInterrupt call is made. This gives time to do the setup of the - * other options before starting to field interrupts. - */ - public void enableInterrupts() { - if (m_interrupt == null) { - throw new IllegalStateException("The interrupt is not allocated."); - } - if(m_isSynchronousInterrupt){ - throw new IllegalStateException("You do not need to enable synchronous interrupts"); - } - ByteBuffer status = ByteBuffer.allocateDirect(4); - status.order(ByteOrder.LITTLE_ENDIAN); - InterruptJNI.enableInterrupts(m_interrupt, status.asIntBuffer()); - HALUtil.checkStatus(status.asIntBuffer()); - } + /** + * Enable interrupts to occur on this input. Interrupts are disabled when the + * RequestInterrupt call is made. This gives time to do the setup of the other + * options before starting to field interrupts. + */ + public void enableInterrupts() { + if (m_interrupt == null) { + throw new IllegalStateException("The interrupt is not allocated."); + } + if (m_isSynchronousInterrupt) { + throw new IllegalStateException("You do not need to enable synchronous interrupts"); + } + ByteBuffer status = ByteBuffer.allocateDirect(4); + status.order(ByteOrder.LITTLE_ENDIAN); + InterruptJNI.enableInterrupts(m_interrupt, status.asIntBuffer()); + HALUtil.checkStatus(status.asIntBuffer()); + } - /** - * Disable Interrupts without without deallocating structures. - */ - public void disableInterrupts() { - if (m_interrupt == null) { - throw new IllegalStateException("The interrupt is not allocated."); - } - if(m_isSynchronousInterrupt){ - throw new IllegalStateException("You can not disable synchronous interrupts"); - } - ByteBuffer status = ByteBuffer.allocateDirect(4); - status.order(ByteOrder.LITTLE_ENDIAN); - InterruptJNI.disableInterrupts(m_interrupt, status.asIntBuffer()); - HALUtil.checkStatus(status.asIntBuffer()); - } + /** + * Disable Interrupts without without deallocating structures. + */ + public void disableInterrupts() { + if (m_interrupt == null) { + throw new IllegalStateException("The interrupt is not allocated."); + } + if (m_isSynchronousInterrupt) { + throw new IllegalStateException("You can not disable synchronous interrupts"); + } + ByteBuffer status = ByteBuffer.allocateDirect(4); + status.order(ByteOrder.LITTLE_ENDIAN); + InterruptJNI.disableInterrupts(m_interrupt, status.asIntBuffer()); + HALUtil.checkStatus(status.asIntBuffer()); + } - /** - * Return the timestamp for the rising interrupt that occurred most - * recently. This is in the same time domain as getClock(). - * The rising-edge interrupt should be enabled with - * {@link #setUpSourceEdge} - * @return Timestamp in seconds since boot. - */ - public double readRisingTimestamp() { - if (m_interrupt == null) { - throw new IllegalStateException("The interrupt is not allocated."); - } - ByteBuffer status = ByteBuffer.allocateDirect(4); - status.order(ByteOrder.LITTLE_ENDIAN); - double timestamp = InterruptJNI.readRisingTimestamp(m_interrupt, status.asIntBuffer()); - HALUtil.checkStatus(status.asIntBuffer()); - return timestamp; - } + /** + * Return the timestamp for the rising interrupt that occurred most recently. + * This is in the same time domain as getClock(). The rising-edge interrupt + * should be enabled with {@link #setUpSourceEdge} + *$ + * @return Timestamp in seconds since boot. + */ + public double readRisingTimestamp() { + if (m_interrupt == null) { + throw new IllegalStateException("The interrupt is not allocated."); + } + ByteBuffer status = ByteBuffer.allocateDirect(4); + status.order(ByteOrder.LITTLE_ENDIAN); + double timestamp = InterruptJNI.readRisingTimestamp(m_interrupt, status.asIntBuffer()); + HALUtil.checkStatus(status.asIntBuffer()); + return timestamp; + } - /** - * Return the timestamp for the falling interrupt that occurred most - * recently. This is in the same time domain as getClock(). - * The falling-edge interrupt should be enabled with - * {@link #setUpSourceEdge} - * @return Timestamp in seconds since boot. - */ - public double readFallingTimestamp() { - if (m_interrupt == null) { - throw new IllegalStateException("The interrupt is not allocated."); - } - ByteBuffer status = ByteBuffer.allocateDirect(4); - status.order(ByteOrder.LITTLE_ENDIAN); - double timestamp = InterruptJNI.readFallingTimestamp(m_interrupt, status.asIntBuffer()); - HALUtil.checkStatus(status.asIntBuffer()); - return timestamp; - } + /** + * Return the timestamp for the falling interrupt that occurred most recently. + * This is in the same time domain as getClock(). The falling-edge interrupt + * should be enabled with {@link #setUpSourceEdge} + *$ + * @return Timestamp in seconds since boot. + */ + public double readFallingTimestamp() { + if (m_interrupt == null) { + throw new IllegalStateException("The interrupt is not allocated."); + } + ByteBuffer status = ByteBuffer.allocateDirect(4); + status.order(ByteOrder.LITTLE_ENDIAN); + double timestamp = InterruptJNI.readFallingTimestamp(m_interrupt, status.asIntBuffer()); + HALUtil.checkStatus(status.asIntBuffer()); + return timestamp; + } - /** - * Set which edge to trigger interrupts on - * - * @param risingEdge - * true to interrupt on rising edge - * @param fallingEdge - * true to interrupt on falling edge - */ - public void setUpSourceEdge(boolean risingEdge, boolean fallingEdge) { - if (m_interrupt != null) { - ByteBuffer status = ByteBuffer.allocateDirect(4); - // set the byte order - status.order(ByteOrder.LITTLE_ENDIAN); - InterruptJNI.setInterruptUpSourceEdge(m_interrupt, - (byte) (risingEdge ? 1 : 0), (byte) (fallingEdge ? 1 : 0), - status.asIntBuffer()); - HALUtil.checkStatus(status.asIntBuffer()); - } else { - throw new IllegalArgumentException( - "You must call RequestInterrupts before setUpSourceEdge"); - } - } + /** + * Set which edge to trigger interrupts on + * + * @param risingEdge true to interrupt on rising edge + * @param fallingEdge true to interrupt on falling edge + */ + public void setUpSourceEdge(boolean risingEdge, boolean fallingEdge) { + if (m_interrupt != null) { + ByteBuffer status = ByteBuffer.allocateDirect(4); + // set the byte order + status.order(ByteOrder.LITTLE_ENDIAN); + InterruptJNI.setInterruptUpSourceEdge(m_interrupt, (byte) (risingEdge ? 1 : 0), + (byte) (fallingEdge ? 1 : 0), status.asIntBuffer()); + HALUtil.checkStatus(status.asIntBuffer()); + } else { + throw new IllegalArgumentException("You must call RequestInterrupts before setUpSourceEdge"); + } + } } diff --git a/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/IterativeRobot.java b/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/IterativeRobot.java index 5de916fed5..11440b01e3 100644 --- a/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/IterativeRobot.java +++ b/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/IterativeRobot.java @@ -1,8 +1,8 @@ /*----------------------------------------------------------------------------*/ -/* Copyright (c) FIRST 2008-2012. All Rights Reserved. */ -/* Open Source Software - may be modified and shared by FRC teams. The code */ +/* Copyright (c) FIRST 2008-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 the root directory of */ -/* the project. */ +/* the project. */ /*----------------------------------------------------------------------------*/ package edu.wpi.first.wpilibj; @@ -14,267 +14,271 @@ import edu.wpi.first.wpilibj.Timer; import edu.wpi.first.wpilibj.livewindow.LiveWindow; /** - * IterativeRobot implements a specific type of Robot Program framework, extending the RobotBase class. + * IterativeRobot implements a specific type of Robot Program framework, + * extending the RobotBase class. * - * The IterativeRobot class is intended to be subclassed by a user creating a robot program. + * The IterativeRobot class is intended to be subclassed by a user creating a + * robot program. * - * This class is intended to implement the "old style" default code, by providing - * the following functions which are called by the main loop, startCompetition(), at the appropriate times: + * This class is intended to implement the "old style" default code, by + * providing the following functions which are called by the main loop, + * startCompetition(), at the appropriate times: * * robotInit() -- provide for initialization at robot power-on * * init() functions -- each of the following functions is called once when the - * appropriate mode is entered: - * - DisabledInit() -- called only when first disabled - * - AutonomousInit() -- called each and every time autonomous is entered from another mode - * - TeleopInit() -- called each and every time teleop is entered from another mode - * - TestInit() -- called each and every time test mode is entered from anothermode + * appropriate mode is entered: - DisabledInit() -- called only when first + * disabled - AutonomousInit() -- called each and every time autonomous is + * entered from another mode - TeleopInit() -- called each and every time teleop + * is entered from another mode - TestInit() -- called each and every time test + * mode is entered from anothermode * * Periodic() functions -- each of these functions is called iteratively at the - * appropriate periodic rate (aka the "slow loop"). The period of - * the iterative robot is synced to the driver station control packets, - * giving a periodic frequency of about 50Hz (50 times per second). - * - disabledPeriodic() - * - autonomousPeriodic() - * - teleopPeriodic() - * - testPeriodoc() + * appropriate periodic rate (aka the "slow loop"). The period of the iterative + * robot is synced to the driver station control packets, giving a periodic + * frequency of about 50Hz (50 times per second). - disabledPeriodic() - + * autonomousPeriodic() - teleopPeriodic() - testPeriodoc() * */ public class IterativeRobot extends RobotBase { - private boolean m_disabledInitialized; - private boolean m_autonomousInitialized; - private boolean m_teleopInitialized; - private boolean m_testInitialized; + private boolean m_disabledInitialized; + private boolean m_autonomousInitialized; + private boolean m_teleopInitialized; + private boolean m_testInitialized; - /** - * Constructor for RobotIterativeBase - * - * The constructor initializes the instance variables for the robot to indicate - * the status of initialization for disabled, autonomous, and teleop code. - */ - public IterativeRobot() { - // set status for initialization of disabled, autonomous, and teleop code. - m_disabledInitialized = false; - m_autonomousInitialized = false; - m_teleopInitialized = false; - m_testInitialized = false; - } - - @Override - protected void prestart() { - // Don't immediately say that the robot's ready to be enabled. - // See below. - } + /** + * Constructor for RobotIterativeBase + * + * The constructor initializes the instance variables for the robot to + * indicate the status of initialization for disabled, autonomous, and teleop + * code. + */ + public IterativeRobot() { + // set status for initialization of disabled, autonomous, and teleop code. + m_disabledInitialized = false; + m_autonomousInitialized = false; + m_teleopInitialized = false; + m_testInitialized = false; + } - /** - * Provide an alternate "main loop" via startCompetition(). - * - */ - public void startCompetition() { - UsageReporting.report(tResourceType.kResourceType_Framework, tInstances.kFramework_Iterative); + @Override + protected void prestart() { + // Don't immediately say that the robot's ready to be enabled. + // See below. + } - robotInit(); - - // We call this now (not in prestart like default) so that the robot - // won't enable until the initialization has finished. This is useful - // because otherwise it's sometimes possible to enable the robot - // before the code is ready. - FRCNetworkCommunicationsLibrary.FRCNetworkCommunicationObserveUserProgramStarting(); + /** + * Provide an alternate "main loop" via startCompetition(). + * + */ + public void startCompetition() { + UsageReporting.report(tResourceType.kResourceType_Framework, tInstances.kFramework_Iterative); - // loop forever, calling the appropriate mode-dependent function - LiveWindow.setEnabled(false); - while (true) { - // Call the appropriate function depending upon the current robot mode - if (isDisabled()) { - // call DisabledInit() if we are now just entering disabled mode from - // either a different mode or from power-on - if (!m_disabledInitialized) { - LiveWindow.setEnabled(false); - disabledInit(); - m_disabledInitialized = true; - // reset the initialization flags for the other modes - m_autonomousInitialized = false; - m_teleopInitialized = false; - m_testInitialized = false; - } - if (nextPeriodReady()) { - FRCNetworkCommunicationsLibrary.FRCNetworkCommunicationObserveUserProgramDisabled(); - disabledPeriodic(); - } - } else if (isTest()) { - // call TestInit() if we are now just entering test mode from either - // a different mode or from power-on - if (!m_testInitialized) { - LiveWindow.setEnabled(true); - testInit(); - m_testInitialized = true; - m_autonomousInitialized = false; - m_teleopInitialized = false; - m_disabledInitialized = false; - } - if (nextPeriodReady()) { - FRCNetworkCommunicationsLibrary.FRCNetworkCommunicationObserveUserProgramTest(); - testPeriodic(); - } - } else if (isAutonomous()) { - // call Autonomous_Init() if this is the first time - // we've entered autonomous_mode - if (!m_autonomousInitialized) { - LiveWindow.setEnabled(false); - // KBS NOTE: old code reset all PWMs and relays to "safe values" - // whenever entering autonomous mode, before calling - // "Autonomous_Init()" - autonomousInit(); - m_autonomousInitialized = true; - m_testInitialized = false; - m_teleopInitialized = false; - m_disabledInitialized = false; - } - if (nextPeriodReady()) { - FRCNetworkCommunicationsLibrary.FRCNetworkCommunicationObserveUserProgramAutonomous(); - autonomousPeriodic(); - } - } else { - // call Teleop_Init() if this is the first time - // we've entered teleop_mode - if (!m_teleopInitialized) { - LiveWindow.setEnabled(false); - teleopInit(); - m_teleopInitialized = true; - m_testInitialized = false; - m_autonomousInitialized = false; - m_disabledInitialized = false; - } - if (nextPeriodReady()) { - FRCNetworkCommunicationsLibrary.FRCNetworkCommunicationObserveUserProgramTeleop(); - teleopPeriodic(); - } - } - m_ds.waitForData(); + robotInit(); + + // We call this now (not in prestart like default) so that the robot + // won't enable until the initialization has finished. This is useful + // because otherwise it's sometimes possible to enable the robot + // before the code is ready. + FRCNetworkCommunicationsLibrary.FRCNetworkCommunicationObserveUserProgramStarting(); + + // loop forever, calling the appropriate mode-dependent function + LiveWindow.setEnabled(false); + while (true) { + // Call the appropriate function depending upon the current robot mode + if (isDisabled()) { + // call DisabledInit() if we are now just entering disabled mode from + // either a different mode or from power-on + if (!m_disabledInitialized) { + LiveWindow.setEnabled(false); + disabledInit(); + m_disabledInitialized = true; + // reset the initialization flags for the other modes + m_autonomousInitialized = false; + m_teleopInitialized = false; + m_testInitialized = false; } - } - - /** - * Determine if the appropriate next periodic function should be called. - * Call the periodic functions whenever a packet is received from the Driver Station, or about every 20ms. - */ - private boolean nextPeriodReady() { - return m_ds.isNewControlData(); - } - - /* ----------- Overridable initialization code -----------------*/ - - /** - * Robot-wide initialization code should go here. - * - * Users should override this method for default Robot-wide initialization which will - * be called when the robot is first powered on. It will be called exactly 1 time. - */ - public void robotInit() { - System.out.println("Default IterativeRobot.robotInit() method... Overload me!"); - } - - /** - * Initialization code for disabled mode should go here. - * - * Users should override this method for initialization code which will be called each time - * the robot enters disabled mode. - */ - public void disabledInit() { - System.out.println("Default IterativeRobot.disabledInit() method... Overload me!"); - } - - /** - * Initialization code for autonomous mode should go here. - * - * Users should override this method for initialization code which will be called each time - * the robot enters autonomous mode. - */ - public void autonomousInit() { - System.out.println("Default IterativeRobot.autonomousInit() method... Overload me!"); - } - - /** - * Initialization code for teleop mode should go here. - * - * Users should override this method for initialization code which will be called each time - * the robot enters teleop mode. - */ - public void teleopInit() { - System.out.println("Default IterativeRobot.teleopInit() method... Overload me!"); - } - - /** - * Initialization code for test mode should go here. - * - * Users should override this method for initialization code which will be called each time - * the robot enters test mode. - */ - public void testInit() { - System.out.println("Default IterativeRobot.testInit() method... Overload me!"); - } - - /* ----------- Overridable periodic code -----------------*/ - - private boolean dpFirstRun = true; - /** - * Periodic code for disabled mode should go here. - * - * Users should override this method for code which will be called periodically at a regular - * rate while the robot is in disabled mode. - */ - public void disabledPeriodic() { - if (dpFirstRun) { - System.out.println("Default IterativeRobot.disabledPeriodic() method... Overload me!"); - dpFirstRun = false; + if (nextPeriodReady()) { + FRCNetworkCommunicationsLibrary.FRCNetworkCommunicationObserveUserProgramDisabled(); + disabledPeriodic(); } - Timer.delay(0.001); - } - - private boolean apFirstRun = true; - - /** - * Periodic code for autonomous mode should go here. - * - * Users should override this method for code which will be called periodically at a regular - * rate while the robot is in autonomous mode. - */ - public void autonomousPeriodic() { - if (apFirstRun) { - System.out.println("Default IterativeRobot.autonomousPeriodic() method... Overload me!"); - apFirstRun = false; + } else if (isTest()) { + // call TestInit() if we are now just entering test mode from either + // a different mode or from power-on + if (!m_testInitialized) { + LiveWindow.setEnabled(true); + testInit(); + m_testInitialized = true; + m_autonomousInitialized = false; + m_teleopInitialized = false; + m_disabledInitialized = false; } - Timer.delay(0.001); - } - - private boolean tpFirstRun = true; - - /** - * Periodic code for teleop mode should go here. - * - * Users should override this method for code which will be called periodically at a regular - * rate while the robot is in teleop mode. - */ - public void teleopPeriodic() { - if (tpFirstRun) { - System.out.println("Default IterativeRobot.teleopPeriodic() method... Overload me!"); - tpFirstRun = false; + if (nextPeriodReady()) { + FRCNetworkCommunicationsLibrary.FRCNetworkCommunicationObserveUserProgramTest(); + testPeriodic(); } - Timer.delay(0.001); - } - - private boolean tmpFirstRun = true; - - /** - * Periodic code for test mode should go here - * - * Users should override this method for code which will be called periodically at a regular rate - * while the robot is in test mode. - */ - public void testPeriodic() { - if (tmpFirstRun) { - System.out.println("Default IterativeRobot.testPeriodic() method... Overload me!"); - tmpFirstRun = false; + } else if (isAutonomous()) { + // call Autonomous_Init() if this is the first time + // we've entered autonomous_mode + if (!m_autonomousInitialized) { + LiveWindow.setEnabled(false); + // KBS NOTE: old code reset all PWMs and relays to "safe values" + // whenever entering autonomous mode, before calling + // "Autonomous_Init()" + autonomousInit(); + m_autonomousInitialized = true; + m_testInitialized = false; + m_teleopInitialized = false; + m_disabledInitialized = false; } + if (nextPeriodReady()) { + FRCNetworkCommunicationsLibrary.FRCNetworkCommunicationObserveUserProgramAutonomous(); + autonomousPeriodic(); + } + } else { + // call Teleop_Init() if this is the first time + // we've entered teleop_mode + if (!m_teleopInitialized) { + LiveWindow.setEnabled(false); + teleopInit(); + m_teleopInitialized = true; + m_testInitialized = false; + m_autonomousInitialized = false; + m_disabledInitialized = false; + } + if (nextPeriodReady()) { + FRCNetworkCommunicationsLibrary.FRCNetworkCommunicationObserveUserProgramTeleop(); + teleopPeriodic(); + } + } + m_ds.waitForData(); } + } + + /** + * Determine if the appropriate next periodic function should be called. Call + * the periodic functions whenever a packet is received from the Driver + * Station, or about every 20ms. + */ + private boolean nextPeriodReady() { + return m_ds.isNewControlData(); + } + + /* ----------- Overridable initialization code ----------------- */ + + /** + * Robot-wide initialization code should go here. + * + * Users should override this method for default Robot-wide initialization + * which will be called when the robot is first powered on. It will be called + * exactly 1 time. + */ + public void robotInit() { + System.out.println("Default IterativeRobot.robotInit() method... Overload me!"); + } + + /** + * Initialization code for disabled mode should go here. + * + * Users should override this method for initialization code which will be + * called each time the robot enters disabled mode. + */ + public void disabledInit() { + System.out.println("Default IterativeRobot.disabledInit() method... Overload me!"); + } + + /** + * Initialization code for autonomous mode should go here. + * + * Users should override this method for initialization code which will be + * called each time the robot enters autonomous mode. + */ + public void autonomousInit() { + System.out.println("Default IterativeRobot.autonomousInit() method... Overload me!"); + } + + /** + * Initialization code for teleop mode should go here. + * + * Users should override this method for initialization code which will be + * called each time the robot enters teleop mode. + */ + public void teleopInit() { + System.out.println("Default IterativeRobot.teleopInit() method... Overload me!"); + } + + /** + * Initialization code for test mode should go here. + * + * Users should override this method for initialization code which will be + * called each time the robot enters test mode. + */ + public void testInit() { + System.out.println("Default IterativeRobot.testInit() method... Overload me!"); + } + + /* ----------- Overridable periodic code ----------------- */ + + private boolean dpFirstRun = true; + + /** + * Periodic code for disabled mode should go here. + * + * Users should override this method for code which will be called + * periodically at a regular rate while the robot is in disabled mode. + */ + public void disabledPeriodic() { + if (dpFirstRun) { + System.out.println("Default IterativeRobot.disabledPeriodic() method... Overload me!"); + dpFirstRun = false; + } + Timer.delay(0.001); + } + + private boolean apFirstRun = true; + + /** + * Periodic code for autonomous mode should go here. + * + * Users should override this method for code which will be called + * periodically at a regular rate while the robot is in autonomous mode. + */ + public void autonomousPeriodic() { + if (apFirstRun) { + System.out.println("Default IterativeRobot.autonomousPeriodic() method... Overload me!"); + apFirstRun = false; + } + Timer.delay(0.001); + } + + private boolean tpFirstRun = true; + + /** + * Periodic code for teleop mode should go here. + * + * Users should override this method for code which will be called + * periodically at a regular rate while the robot is in teleop mode. + */ + public void teleopPeriodic() { + if (tpFirstRun) { + System.out.println("Default IterativeRobot.teleopPeriodic() method... Overload me!"); + tpFirstRun = false; + } + Timer.delay(0.001); + } + + private boolean tmpFirstRun = true; + + /** + * Periodic code for test mode should go here + * + * Users should override this method for code which will be called + * periodically at a regular rate while the robot is in test mode. + */ + public void testPeriodic() { + if (tmpFirstRun) { + System.out.println("Default IterativeRobot.testPeriodic() method... Overload me!"); + tmpFirstRun = false; + } + } } diff --git a/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/Jaguar.java b/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/Jaguar.java index 27c7405afc..17c0809f14 100644 --- a/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/Jaguar.java +++ b/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/Jaguar.java @@ -1,8 +1,8 @@ /*----------------------------------------------------------------------------*/ -/* Copyright (c) FIRST 2008-2012. All Rights Reserved. */ -/* Open Source Software - may be modified and shared by FRC teams. The code */ +/* Copyright (c) FIRST 2008-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 the root directory of */ -/* the project. */ +/* the project. */ /*----------------------------------------------------------------------------*/ package edu.wpi.first.wpilibj; @@ -13,112 +13,115 @@ import edu.wpi.first.wpilibj.livewindow.LiveWindow; /** * Texas Instruments / Vex Robotics Jaguar Speed Controller as a PWM device. + *$ * @see CANJaguar CANJaguar for CAN control */ public class Jaguar extends SafePWM implements SpeedController { -private boolean isInverted = false; - /** - * Common initialization code called by all constructors. - */ - private void initJaguar() { - /* - * Input profile defined by Luminary Micro. - * - * Full reverse ranges from 0.671325ms to 0.6972211ms - * Proportional reverse ranges from 0.6972211ms to 1.4482078ms - * Neutral ranges from 1.4482078ms to 1.5517922ms - * Proportional forward ranges from 1.5517922ms to 2.3027789ms - * Full forward ranges from 2.3027789ms to 2.328675ms - */ - setBounds(2.31, 1.55, 1.507, 1.454, .697); - setPeriodMultiplier(PeriodMultiplier.k1X); - setRaw(m_centerPwm); - setZeroLatch(); + private boolean isInverted = false; - UsageReporting.report(tResourceType.kResourceType_Jaguar, getChannel()); - LiveWindow.addActuator("Jaguar", getChannel(), this); - } - - /** - * Constructor. - * - * @param channel The PWM channel that the Jaguar is attached to. 0-9 are on-board, 10-19 are on the MXP port + /** + * Common initialization code called by all constructors. + */ + private void initJaguar() { + /* + * Input profile defined by Luminary Micro. + *$ + * Full reverse ranges from 0.671325ms to 0.6972211ms Proportional reverse + * ranges from 0.6972211ms to 1.4482078ms Neutral ranges from 1.4482078ms to + * 1.5517922ms Proportional forward ranges from 1.5517922ms to 2.3027789ms + * Full forward ranges from 2.3027789ms to 2.328675ms */ - public Jaguar(final int channel) { - super(channel); - initJaguar(); - } + setBounds(2.31, 1.55, 1.507, 1.454, .697); + setPeriodMultiplier(PeriodMultiplier.k1X); + setRaw(m_centerPwm); + setZeroLatch(); - /** - * Set the PWM value. - * - * @deprecated For compatibility with CANJaguar - * - * The PWM value is set using a range of -1.0 to 1.0, appropriately - * scaling the value for the FPGA. - * - * @param speed The speed to set. Value should be between -1.0 and 1.0. - * @param syncGroup The update group to add this Set() to, pending UpdateSyncGroup(). If 0, update immediately. - */ - @Deprecated - @Override - public void set(double speed, byte syncGroup) { - setSpeed(isInverted ? -speed: speed); - Feed(); - } + UsageReporting.report(tResourceType.kResourceType_Jaguar, getChannel()); + LiveWindow.addActuator("Jaguar", getChannel(), this); + } - /** - * Set the PWM value. - * - * The PWM value is set using a range of -1.0 to 1.0, appropriately - * scaling the value for the FPGA. - * - * @param speed The speed value between -1.0 and 1.0 to set. - */ - @Override - public void set(double speed) { - setSpeed(isInverted ? -speed: speed); - Feed(); - } + /** + * Constructor. + * + * @param channel The PWM channel that the Jaguar is attached to. 0-9 are + * on-board, 10-19 are on the MXP port + */ + public Jaguar(final int channel) { + super(channel); + initJaguar(); + } - /** - * Common interface for inverting direction of a speed controller. - * - * @param isInverted The state of inversion, true is inverted. - */ - @Override - public void setInverted(boolean isInverted) { - this.isInverted = isInverted; - } + /** + * Set the PWM value. + * + * @deprecated For compatibility with CANJaguar + * + * The PWM value is set using a range of -1.0 to 1.0, + * appropriately scaling the value for the FPGA. + * + * @param speed The speed to set. Value should be between -1.0 and 1.0. + * @param syncGroup The update group to add this Set() to, pending + * UpdateSyncGroup(). If 0, update immediately. + */ + @Deprecated + @Override + public void set(double speed, byte syncGroup) { + setSpeed(isInverted ? -speed : speed); + Feed(); + } - /** - * Common interface for the inverting direction of a speed controller. - * - * @return isInverted The state of inversion, true is inverted. - * - */ - @Override - public boolean getInverted() { - return this.isInverted; - } + /** + * Set the PWM value. + * + * The PWM value is set using a range of -1.0 to 1.0, appropriately scaling + * the value for the FPGA. + * + * @param speed The speed value between -1.0 and 1.0 to set. + */ + @Override + public void set(double speed) { + setSpeed(isInverted ? -speed : speed); + Feed(); + } - /** - * Get the recently set value of the PWM. - * - * @return The most recently set value for the PWM between -1.0 and 1.0. - */ - @Override - public double get() { - return getSpeed(); - } + /** + * Common interface for inverting direction of a speed controller. + * + * @param isInverted The state of inversion, true is inverted. + */ + @Override + public void setInverted(boolean isInverted) { + this.isInverted = isInverted; + } - /** - * Write out the PID value as seen in the PIDOutput base object. - * - * @param output Write out the PWM value as was found in the PIDController - */ - @Override - public void pidWrite(double output) { - set(output); - } + /** + * Common interface for the inverting direction of a speed controller. + * + * @return isInverted The state of inversion, true is inverted. + * + */ + @Override + public boolean getInverted() { + return this.isInverted; + } + + /** + * Get the recently set value of the PWM. + * + * @return The most recently set value for the PWM between -1.0 and 1.0. + */ + @Override + public double get() { + return getSpeed(); + } + + /** + * Write out the PID value as seen in the PIDOutput base object. + * + * @param output Write out the PWM value as was found in the PIDController + */ + @Override + public void pidWrite(double output) { + set(output); + } } diff --git a/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/Joystick.java b/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/Joystick.java index c6ae7a5923..68ee35ba72 100644 --- a/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/Joystick.java +++ b/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/Joystick.java @@ -1,8 +1,8 @@ /*----------------------------------------------------------------------------*/ -/* Copyright (c) FIRST 2008-2012. All Rights Reserved. */ -/* Open Source Software - may be modified and shared by FRC teams. The code */ +/* Copyright (c) FIRST 2008-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 the root directory of */ -/* the project. */ +/* the project. */ /*----------------------------------------------------------------------------*/ package edu.wpi.first.wpilibj; @@ -11,469 +11,483 @@ import edu.wpi.first.wpilibj.communication.FRCNetworkCommunicationsLibrary; import edu.wpi.first.wpilibj.communication.UsageReporting; /** - * Handle input from standard Joysticks connected to the Driver Station. - * This class handles standard input that comes from the Driver Station. Each time a value is requested - * the most recent value is returned. There is a single class instance for each joystick and the mapping - * of ports to hardware buttons depends on the code in the driver station. + * Handle input from standard Joysticks connected to the Driver Station. This + * class handles standard input that comes from the Driver Station. Each time a + * value is requested the most recent value is returned. There is a single class + * instance for each joystick and the mapping of ports to hardware buttons + * depends on the code in the driver station. */ public class Joystick extends GenericHID { - static final byte kDefaultXAxis = 0; - static final byte kDefaultYAxis = 1; - static final byte kDefaultZAxis = 2; - static final byte kDefaultTwistAxis = 2; - static final byte kDefaultThrottleAxis = 3; - static final int kDefaultTriggerButton = 1; - static final int kDefaultTopButton = 2; + static final byte kDefaultXAxis = 0; + static final byte kDefaultYAxis = 1; + static final byte kDefaultZAxis = 2; + static final byte kDefaultTwistAxis = 2; + static final byte kDefaultThrottleAxis = 3; + static final int kDefaultTriggerButton = 1; + static final int kDefaultTopButton = 2; + + /** + * Represents an analog axis on a joystick. + */ + public static class AxisType { /** - * Represents an analog axis on a joystick. + * The integer value representing this enumeration */ - public static class AxisType { - - /** - * The integer value representing this enumeration - */ - public final int value; - static final int kX_val = 0; - static final int kY_val = 1; - static final int kZ_val = 2; - static final int kTwist_val = 3; - static final int kThrottle_val = 4; - static final int kNumAxis_val = 5; - /** - * axis: x-axis - */ - public static final AxisType kX = new AxisType(kX_val); - /** - * axis: y-axis - */ - public static final AxisType kY = new AxisType(kY_val); - /** - * axis: z-axis - */ - public static final AxisType kZ = new AxisType(kZ_val); - /** - * axis: twist - */ - public static final AxisType kTwist = new AxisType(kTwist_val); - /** - * axis: throttle - */ - public static final AxisType kThrottle = new AxisType(kThrottle_val); - /** - * axis: number of axis - */ - public static final AxisType kNumAxis = new AxisType(kNumAxis_val); - - private AxisType(int value) { - this.value = value; - } - } - + public final int value; + static final int kX_val = 0; + static final int kY_val = 1; + static final int kZ_val = 2; + static final int kTwist_val = 3; + static final int kThrottle_val = 4; + static final int kNumAxis_val = 5; /** - * Represents a digital button on the JoyStick + * axis: x-axis */ - public static class ButtonType { - - /** - * The integer value representing this enumeration - */ - public final int value; - static final int kTrigger_val = 0; - static final int kTop_val = 1; - static final int kNumButton_val = 2; - /** - * button: trigger - */ - public static final ButtonType kTrigger = new ButtonType((kTrigger_val)); - /** - * button: top button - */ - public static final ButtonType kTop = new ButtonType(kTop_val); - /** - * button: num button types - */ - public static final ButtonType kNumButton = new ButtonType((kNumButton_val)); - - private ButtonType(int value) { - this.value = value; - } - } - - + public static final AxisType kX = new AxisType(kX_val); /** - * Represents a rumble output on the JoyStick + * axis: y-axis */ - public static class RumbleType { - - /** - * The integer value representing this enumeration - */ - public final int value; - static final int kLeftRumble_val = 0; - static final int kRightRumble_val = 1; - /** - * Left Rumble - */ - public static final RumbleType kLeftRumble = new RumbleType((kLeftRumble_val)); - /** - * Right Rumble - */ - public static final RumbleType kRightRumble = new RumbleType(kRightRumble_val); - - private RumbleType(int value) { - this.value = value; - } - } - - private DriverStation m_ds; - private final int m_port; - private final byte[] m_axes; - private final byte[] m_buttons; - private int m_outputs; - private short m_leftRumble; - private short m_rightRumble; - + public static final AxisType kY = new AxisType(kY_val); /** - * Construct an instance of a joystick. - * The joystick index is the usb port on the drivers station. - * - * @param port The port on the driver station that the joystick is plugged into. + * axis: z-axis */ - public Joystick(final int port) { - this(port, AxisType.kNumAxis.value, ButtonType.kNumButton.value); - - m_axes[AxisType.kX.value] = kDefaultXAxis; - m_axes[AxisType.kY.value] = kDefaultYAxis; - m_axes[AxisType.kZ.value] = kDefaultZAxis; - m_axes[AxisType.kTwist.value] = kDefaultTwistAxis; - m_axes[AxisType.kThrottle.value] = kDefaultThrottleAxis; - - m_buttons[ButtonType.kTrigger.value] = kDefaultTriggerButton; - m_buttons[ButtonType.kTop.value] = kDefaultTopButton; - - UsageReporting.report(tResourceType.kResourceType_Joystick, port); - } - + public static final AxisType kZ = new AxisType(kZ_val); /** - * Protected version of the constructor to be called by sub-classes. - * - * This constructor allows the subclass to configure the number of constants - * for axes and buttons. - * - * @param port The port on the driver station that the joystick is plugged into. - * @param numAxisTypes The number of axis types in the enum. - * @param numButtonTypes The number of button types in the enum. + * axis: twist */ - protected Joystick(int port, int numAxisTypes, int numButtonTypes) { - m_ds = DriverStation.getInstance(); - m_axes = new byte[numAxisTypes]; - m_buttons = new byte[numButtonTypes]; - m_port = port; - } - + public static final AxisType kTwist = new AxisType(kTwist_val); /** - * Get the X value of the joystick. - * This depends on the mapping of the joystick connected to the current port. - * - * @param hand Unused - * @return The X value of the joystick. + * axis: throttle */ - public double getX(Hand hand) { - return getRawAxis(m_axes[AxisType.kX.value]); - } - + public static final AxisType kThrottle = new AxisType(kThrottle_val); /** - * Get the Y value of the joystick. - * This depends on the mapping of the joystick connected to the current port. - * - * @param hand Unused - * @return The Y value of the joystick. + * axis: number of axis */ - public double getY(Hand hand) { - return getRawAxis(m_axes[AxisType.kY.value]); + public static final AxisType kNumAxis = new AxisType(kNumAxis_val); + + private AxisType(int value) { + this.value = value; } + } + + /** + * Represents a digital button on the JoyStick + */ + public static class ButtonType { /** - * Get the Z value of the joystick. - * This depends on the mapping of the joystick connected to the current port. - * - * @param hand Unused - * @return The Z value of the joystick. + * The integer value representing this enumeration */ - public double getZ(Hand hand) { - return getRawAxis(m_axes[AxisType.kZ.value]); - } - + public final int value; + static final int kTrigger_val = 0; + static final int kTop_val = 1; + static final int kNumButton_val = 2; /** - * Get the twist value of the current joystick. - * This depends on the mapping of the joystick connected to the current port. - * - * @return The Twist value of the joystick. + * button: trigger */ - public double getTwist() { - return getRawAxis(m_axes[AxisType.kTwist.value]); - } - + public static final ButtonType kTrigger = new ButtonType((kTrigger_val)); /** - * Get the throttle value of the current joystick. - * This depends on the mapping of the joystick connected to the current port. - * - * @return The Throttle value of the joystick. + * button: top button */ - public double getThrottle() { - return getRawAxis(m_axes[AxisType.kThrottle.value]); - } - + public static final ButtonType kTop = new ButtonType(kTop_val); /** - * Get the value of the axis. - * - * @param axis The axis to read, starting at 0. - * @return The value of the axis. + * button: num button types */ - public double getRawAxis(final int axis) { - return m_ds.getStickAxis(m_port, axis); + public static final ButtonType kNumButton = new ButtonType((kNumButton_val)); + + private ButtonType(int value) { + this.value = value; } + } + + + /** + * Represents a rumble output on the JoyStick + */ + public static class RumbleType { /** - * For the current joystick, return the axis determined by the argument. - * - * This is for cases where the joystick axis is returned programatically, otherwise one of the - * previous functions would be preferable (for example getX()). - * - * @param axis The axis to read. - * @return The value of the axis. + * The integer value representing this enumeration */ - public double getAxis(final AxisType axis) { - switch (axis.value) { - case AxisType.kX_val: - return getX(); - case AxisType.kY_val: - return getY(); - case AxisType.kZ_val: - return getZ(); - case AxisType.kTwist_val: - return getTwist(); - case AxisType.kThrottle_val: - return getThrottle(); - default: - return 0.0; - } - } - + public final int value; + static final int kLeftRumble_val = 0; + static final int kRightRumble_val = 1; /** - * For the current joystick, return the number of axis - */ - public int getAxisCount(){ - return m_ds.getStickAxisCount(m_port); - } - - /** - * Read the state of the trigger on the joystick. - * - * Look up which button has been assigned to the trigger and read its state. - * - * @param hand This parameter is ignored for the Joystick class and is only here to complete the GenericHID interface. - * @return The state of the trigger. + * Left Rumble */ - public boolean getTrigger(Hand hand) { - return getRawButton(m_buttons[ButtonType.kTrigger.value]); - } - + public static final RumbleType kLeftRumble = new RumbleType((kLeftRumble_val)); /** - * Read the state of the top button on the joystick. - * - * Look up which button has been assigned to the top and read its state. - * - * @param hand This parameter is ignored for the Joystick class and is only here to complete the GenericHID interface. - * @return The state of the top button. + * Right Rumble */ - public boolean getTop(Hand hand) { - return getRawButton(m_buttons[ButtonType.kTop.value]); - } + public static final RumbleType kRightRumble = new RumbleType(kRightRumble_val); - /** - * This is not supported for the Joystick. - * This method is only here to complete the GenericHID interface. - * - * @param hand This parameter is ignored for the Joystick class and is only here to complete the GenericHID interface. - * @return The state of the bumper (always false) - */ - public boolean getBumper(Hand hand) { + private RumbleType(int value) { + this.value = value; + } + } + + private DriverStation m_ds; + private final int m_port; + private final byte[] m_axes; + private final byte[] m_buttons; + private int m_outputs; + private short m_leftRumble; + private short m_rightRumble; + + /** + * Construct an instance of a joystick. The joystick index is the usb port on + * the drivers station. + * + * @param port The port on the driver station that the joystick is plugged + * into. + */ + public Joystick(final int port) { + this(port, AxisType.kNumAxis.value, ButtonType.kNumButton.value); + + m_axes[AxisType.kX.value] = kDefaultXAxis; + m_axes[AxisType.kY.value] = kDefaultYAxis; + m_axes[AxisType.kZ.value] = kDefaultZAxis; + m_axes[AxisType.kTwist.value] = kDefaultTwistAxis; + m_axes[AxisType.kThrottle.value] = kDefaultThrottleAxis; + + m_buttons[ButtonType.kTrigger.value] = kDefaultTriggerButton; + m_buttons[ButtonType.kTop.value] = kDefaultTopButton; + + UsageReporting.report(tResourceType.kResourceType_Joystick, port); + } + + /** + * Protected version of the constructor to be called by sub-classes. + * + * This constructor allows the subclass to configure the number of constants + * for axes and buttons. + * + * @param port The port on the driver station that the joystick is plugged + * into. + * @param numAxisTypes The number of axis types in the enum. + * @param numButtonTypes The number of button types in the enum. + */ + protected Joystick(int port, int numAxisTypes, int numButtonTypes) { + m_ds = DriverStation.getInstance(); + m_axes = new byte[numAxisTypes]; + m_buttons = new byte[numButtonTypes]; + m_port = port; + } + + /** + * Get the X value of the joystick. This depends on the mapping of the + * joystick connected to the current port. + * + * @param hand Unused + * @return The X value of the joystick. + */ + public double getX(Hand hand) { + return getRawAxis(m_axes[AxisType.kX.value]); + } + + /** + * Get the Y value of the joystick. This depends on the mapping of the + * joystick connected to the current port. + * + * @param hand Unused + * @return The Y value of the joystick. + */ + public double getY(Hand hand) { + return getRawAxis(m_axes[AxisType.kY.value]); + } + + /** + * Get the Z value of the joystick. This depends on the mapping of the + * joystick connected to the current port. + * + * @param hand Unused + * @return The Z value of the joystick. + */ + public double getZ(Hand hand) { + return getRawAxis(m_axes[AxisType.kZ.value]); + } + + /** + * Get the twist value of the current joystick. This depends on the mapping of + * the joystick connected to the current port. + * + * @return The Twist value of the joystick. + */ + public double getTwist() { + return getRawAxis(m_axes[AxisType.kTwist.value]); + } + + /** + * Get the throttle value of the current joystick. This depends on the mapping + * of the joystick connected to the current port. + * + * @return The Throttle value of the joystick. + */ + public double getThrottle() { + return getRawAxis(m_axes[AxisType.kThrottle.value]); + } + + /** + * Get the value of the axis. + * + * @param axis The axis to read, starting at 0. + * @return The value of the axis. + */ + public double getRawAxis(final int axis) { + return m_ds.getStickAxis(m_port, axis); + } + + /** + * For the current joystick, return the axis determined by the argument. + * + * This is for cases where the joystick axis is returned programatically, + * otherwise one of the previous functions would be preferable (for example + * getX()). + * + * @param axis The axis to read. + * @return The value of the axis. + */ + public double getAxis(final AxisType axis) { + switch (axis.value) { + case AxisType.kX_val: + return getX(); + case AxisType.kY_val: + return getY(); + case AxisType.kZ_val: + return getZ(); + case AxisType.kTwist_val: + return getTwist(); + case AxisType.kThrottle_val: + return getThrottle(); + default: + return 0.0; + } + } + + /** + * For the current joystick, return the number of axis + */ + public int getAxisCount() { + return m_ds.getStickAxisCount(m_port); + } + + /** + * Read the state of the trigger on the joystick. + * + * Look up which button has been assigned to the trigger and read its state. + * + * @param hand This parameter is ignored for the Joystick class and is only + * here to complete the GenericHID interface. + * @return The state of the trigger. + */ + public boolean getTrigger(Hand hand) { + return getRawButton(m_buttons[ButtonType.kTrigger.value]); + } + + /** + * Read the state of the top button on the joystick. + * + * Look up which button has been assigned to the top and read its state. + * + * @param hand This parameter is ignored for the Joystick class and is only + * here to complete the GenericHID interface. + * @return The state of the top button. + */ + public boolean getTop(Hand hand) { + return getRawButton(m_buttons[ButtonType.kTop.value]); + } + + /** + * This is not supported for the Joystick. This method is only here to + * complete the GenericHID interface. + * + * @param hand This parameter is ignored for the Joystick class and is only + * here to complete the GenericHID interface. + * @return The state of the bumper (always false) + */ + public boolean getBumper(Hand hand) { + return false; + } + + /** + * Get the button value (starting at button 1) + * + * The appropriate button is returned as a boolean value. + * + * @param button The button number to be read (starting at 1). + * @return The state of the button. + */ + public boolean getRawButton(final int button) { + return m_ds.getStickButton(m_port, (byte) button); + } + + /** + * For the current joystick, return the number of buttons + */ + public int getButtonCount() { + return m_ds.getStickButtonCount(m_port); + } + + /** + * Get the state of a POV on the joystick. + * + * @param pov The index of the POV to read (starting at 0) + * @return the angle of the POV in degrees, or -1 if the POV is not pressed. + */ + public int getPOV(int pov) { + return m_ds.getStickPOV(m_port, pov); + } + + /** + * For the current joystick, return the number of POVs + */ + public int getPOVCount() { + return m_ds.getStickPOVCount(m_port); + } + + /** + * Get buttons based on an enumerated type. + * + * The button type will be looked up in the list of buttons and then read. + * + * @param button The type of button to read. + * @return The state of the button. + */ + public boolean getButton(ButtonType button) { + switch (button.value) { + case ButtonType.kTrigger_val: + return getTrigger(); + case ButtonType.kTop_val: + return getTop(); + default: return false; } + } - /** - * Get the button value (starting at button 1) - * - * The appropriate button is returned as a boolean value. - * - * @param button The button number to be read (starting at 1). - * @return The state of the button. - */ - public boolean getRawButton(final int button) { - return m_ds.getStickButton(m_port, (byte)button); - } + /** + * Get the magnitude of the direction vector formed by the joystick's current + * position relative to its origin + * + * @return The magnitude of the direction vector + */ + public double getMagnitude() { + return Math.sqrt(Math.pow(getX(), 2) + Math.pow(getY(), 2)); + } - /** - * For the current joystick, return the number of buttons - */ - public int getButtonCount(){ - return m_ds.getStickButtonCount(m_port); - } + /** + * Get the direction of the vector formed by the joystick and its origin in + * radians + * + * @return The direction of the vector in radians + */ + public double getDirectionRadians() { + return Math.atan2(getX(), -getY()); + } - /** - * Get the state of a POV on the joystick. - * - * @param pov The index of the POV to read (starting at 0) - * @return the angle of the POV in degrees, or -1 if the POV is not pressed. - */ - public int getPOV(int pov) { - return m_ds.getStickPOV(m_port, pov); - } + /** + * Get the direction of the vector formed by the joystick and its origin in + * degrees + * + * uses acos(-1) to represent Pi due to absence of readily accessable Pi + * constant in C++ + * + * @return The direction of the vector in degrees + */ + public double getDirectionDegrees() { + return Math.toDegrees(getDirectionRadians()); + } - /** - * For the current joystick, return the number of POVs - */ - public int getPOVCount(){ - return m_ds.getStickPOVCount(m_port); - } + /** + * Get the channel currently associated with the specified axis. + * + * @param axis The axis to look up the channel for. + * @return The channel fr the axis. + */ + public int getAxisChannel(AxisType axis) { + return m_axes[axis.value]; + } - /** - * Get buttons based on an enumerated type. - * - * The button type will be looked up in the list of buttons and then read. - * - * @param button The type of button to read. - * @return The state of the button. - */ - public boolean getButton(ButtonType button) { - switch (button.value) { - case ButtonType.kTrigger_val: - return getTrigger(); - case ButtonType.kTop_val: - return getTop(); - default: - return false; - } - } + /** + * Set the channel associated with a specified axis. + * + * @param axis The axis to set the channel for. + * @param channel The channel to set the axis to. + */ + public void setAxisChannel(AxisType axis, int channel) { + m_axes[axis.value] = (byte) channel; + } - /** - * Get the magnitude of the direction vector formed by the joystick's - * current position relative to its origin - * - * @return The magnitude of the direction vector - */ - public double getMagnitude() { - return Math.sqrt(Math.pow(getX(), 2) + Math.pow(getY(), 2)); - } + /** + * Get the value of isXbox for the current joystick. + *$ + * @param value A boolean that is true if the controller is an xbox + * controller. + */ + public boolean getIsXbox() { + return m_ds.getJoystickIsXbox(m_port); + } - /** - * Get the direction of the vector formed by the joystick and its origin - * in radians - * - * @return The direction of the vector in radians - */ - public double getDirectionRadians() { - return Math.atan2(getX(), -getY()); - } + /** + * Get the HID type of the current joystick. + *$ + * @param value The HID type value of the current joystick. + */ + public int getType() { + return m_ds.getJoystickType(m_port); + } - /** - * Get the direction of the vector formed by the joystick and its origin - * in degrees - * - * uses acos(-1) to represent Pi due to absence of readily accessable Pi - * constant in C++ - * - * @return The direction of the vector in degrees - */ - public double getDirectionDegrees() { - return Math.toDegrees(getDirectionRadians()); - } + /** + * Get the name of the current joystick. + *$ + * @param value The name of the current joystick. + */ + public String getName() { + return m_ds.getJoystickName(m_port); + } - /** - * Get the channel currently associated with the specified axis. - * - * @param axis The axis to look up the channel for. - * @return The channel fr the axis. - */ - public int getAxisChannel(AxisType axis) { - return m_axes[axis.value]; - } + /** + * Set the rumble output for the joystick. The DS currently supports 2 rumble + * values, left rumble and right rumble + *$ + * @param type Which rumble value to set + * @param value The normalized value (0 to 1) to set the rumble to + */ + public void setRumble(RumbleType type, float value) { + if (value < 0) + value = 0; + else if (value > 1) + value = 1; + if (type.value == RumbleType.kLeftRumble_val) + m_leftRumble = (short) (value * 65535); + else + m_rightRumble = (short) (value * 65535); + FRCNetworkCommunicationsLibrary.HALSetJoystickOutputs((byte) m_port, m_outputs, m_leftRumble, + m_rightRumble); + } - /** - * Set the channel associated with a specified axis. - * - * @param axis The axis to set the channel for. - * @param channel The channel to set the axis to. - */ - public void setAxisChannel(AxisType axis, int channel) { - m_axes[axis.value] = (byte) channel; - } - - /** - * Get the value of isXbox for the current joystick. - * - * @param value A boolean that is true if the controller is an xbox controller. - */ - public boolean getIsXbox() { - return m_ds.getJoystickIsXbox(m_port); - } - - /** - * Get the HID type of the current joystick. - * - * @param value The HID type value of the current joystick. - */ - public int getType() { - return m_ds.getJoystickType(m_port); - } - - /** - * Get the name of the current joystick. - * - * @param value The name of the current joystick. - */ - public String getName() { - return m_ds.getJoystickName(m_port); - } - - /** - * Set the rumble output for the joystick. The DS currently supports 2 rumble values, - * left rumble and right rumble - * @param type Which rumble value to set - * @param value The normalized value (0 to 1) to set the rumble to - */ - public void setRumble(RumbleType type, float value) { - if (value < 0) - value = 0; - else if (value > 1) - value = 1; - if (type.value == RumbleType.kLeftRumble_val) - m_leftRumble = (short)(value*65535); - else - m_rightRumble = (short)(value*65535); - FRCNetworkCommunicationsLibrary.HALSetJoystickOutputs((byte)m_port, m_outputs, m_leftRumble, m_rightRumble); - } + /** + * Set a single HID output value for the joystick. + *$ + * @param outputNumber The index of the output to set (1-32) + * @param value The value to set the output to + */ - /** - * Set a single HID output value for the joystick. - * @param outputNumber The index of the output to set (1-32) - * @param value The value to set the output to - */ - - public void setOutput(int outputNumber, boolean value) { - m_outputs = (m_outputs & ~(1 << (outputNumber-1))) | ((value?1:0) << (outputNumber-1)); - FRCNetworkCommunicationsLibrary.HALSetJoystickOutputs((byte)m_port, m_outputs, m_leftRumble, m_rightRumble); - } + public void setOutput(int outputNumber, boolean value) { + m_outputs = (m_outputs & ~(1 << (outputNumber - 1))) | ((value ? 1 : 0) << (outputNumber - 1)); + FRCNetworkCommunicationsLibrary.HALSetJoystickOutputs((byte) m_port, m_outputs, m_leftRumble, + m_rightRumble); + } - /** - * Set all HID output values for the joystick. - * @param value The 32 bit output value (1 bit for each output) - */ - public void setOutputs(int value) { - m_outputs = value; - FRCNetworkCommunicationsLibrary.HALSetJoystickOutputs((byte)m_port, m_outputs, m_leftRumble, m_rightRumble); - } + /** + * Set all HID output values for the joystick. + *$ + * @param value The 32 bit output value (1 bit for each output) + */ + public void setOutputs(int value) { + m_outputs = value; + FRCNetworkCommunicationsLibrary.HALSetJoystickOutputs((byte) m_port, m_outputs, m_leftRumble, + m_rightRumble); + } } diff --git a/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/Notifier.java b/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/Notifier.java index f92bf78534..57dd459f44 100644 --- a/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/Notifier.java +++ b/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/Notifier.java @@ -30,8 +30,7 @@ public class Notifier { if (current.m_periodic) { current.insertInQueue(true); - } - else { + } else { current.m_queued = false; } @@ -89,21 +88,22 @@ public class Notifier { // destructed. private ReentrantLock m_handlerLock = new ReentrantLock(); - /** - * This is done to store the JVM variable in the InterruptJNI - * This is done because the HAL must have access to the JVM variable - * in order to attach the newly spawned thread when an interrupt is fired. - */ - static { - ByteBuffer status = pointer(); - NotifierJNI.initializeNotifierJVM(status.asIntBuffer()); - HALUtil.checkStatus(status.asIntBuffer()); - } + /** + * This is done to store the JVM variable in the InterruptJNI This is done + * because the HAL must have access to the JVM variable in order to attach the + * newly spawned thread when an interrupt is fired. + */ + static { + ByteBuffer status = pointer(); + NotifierJNI.initializeNotifierJVM(status.asIntBuffer()); + HALUtil.checkStatus(status.asIntBuffer()); + } /** * Create a Notifier for timer event notification. + *$ * @param handler The handler is called at the notification time which is set - * using StartSingle or StartPeriodic. + * using StartSingle or StartPeriodic. */ public Notifier(Runnable run) { if (refcount == 0) { @@ -133,37 +133,35 @@ public class Notifier { /** * Update the alarm hardware to reflect the current first element in the - * queue. - * Compute the time the next alarm should occur based on the current time and - * the period for the first element in the timer queue. - * WARNING: this method does not do synchronization! It must be called from - * somewhere that is taking care of synchronizing access to the queue. + * queue. Compute the time the next alarm should occur based on the current + * time and the period for the first element in the timer queue. WARNING: this + * method does not do synchronization! It must be called from somewhere that + * is taking care of synchronizing access to the queue. */ static protected void updateAlarm() { if (timerQueueHead != null) { ByteBuffer status = pointer(); - NotifierJNI.updateNotifierAlarm( - m_notifier, (int)(timerQueueHead.m_expirationTime * 1e6), + NotifierJNI.updateNotifierAlarm(m_notifier, (int) (timerQueueHead.m_expirationTime * 1e6), status.asIntBuffer()); HALUtil.checkStatus(status.asIntBuffer()); } } /** - * Insert this Notifier into the timer queue in right place. - * WARNING: this method does not do synchronization! It must be called from - * somewhere that is taking care of synchronizing access to the queue. + * Insert this Notifier into the timer queue in right place. WARNING: this + * method does not do synchronization! It must be called from somewhere that + * is taking care of synchronizing access to the queue. + *$ * @param reschedule If false, the scheduled alarm is based on the current - * time and UpdateAlarm method is called which will enable the alarm if - * necessary. If true, update the time by adding the period (no drift) when - * rescheduled periodic from ProcessQueue. This ensures that the public - * methods only update the queue after finishing inserting. + * time and UpdateAlarm method is called which will enable the alarm if + * necessary. If true, update the time by adding the period (no drift) + * when rescheduled periodic from ProcessQueue. This ensures that the + * public methods only update the queue after finishing inserting. */ protected void insertInQueue(boolean reschedule) { if (reschedule) { m_expirationTime += m_period; - } - else { + } else { m_expirationTime = Utility.getFPGATime() * 1e-6 + m_period; } @@ -178,14 +176,13 @@ public class Notifier { timerQueueHead = this; if (!reschedule) { - // since the first element changed, update alarm, unless we already plan to + // since the first element changed, update alarm, unless we already plan + // to updateAlarm(); } - } - else { - for (Notifier n = timerQueueHead; ; n = n.m_nextEvent) { - if (n.m_nextEvent == null || - n.m_nextEvent.m_expirationTime > this.m_expirationTime) { + } else { + for (Notifier n = timerQueueHead;; n = n.m_nextEvent) { + if (n.m_nextEvent == null || n.m_nextEvent.m_expirationTime > this.m_expirationTime) { this.m_nextEvent = n.m_nextEvent; n.m_nextEvent = this; break; @@ -197,22 +194,21 @@ public class Notifier { } /** - * Delete this Notifier from the timer queue. - * WARNING: this method does not do synchronization! It must be called from - * somewhere that is taking care of synchronizing access to the queue. - * Remove this Notifier from the timer queue and adjust the next interrupt - * time to reflect the current top of the queue. + * Delete this Notifier from the timer queue. WARNING: this method does not do + * synchronization! It must be called from somewhere that is taking care of + * synchronizing access to the queue. Remove this Notifier from the timer + * queue and adjust the next interrupt time to reflect the current top of the + * queue. */ private void deleteFromQueue() { if (m_queued) { m_queued = false; - assert(timerQueueHead != null); + assert (timerQueueHead != null); if (timerQueueHead == this) { // removing the first item in the list - update the alarm timerQueueHead = this.m_nextEvent; updateAlarm(); - } - else { + } else { for (Notifier n = timerQueueHead; n != null; n = n.m_nextEvent) { if (n.m_nextEvent == this) { // this element is the next element from *n from the queue @@ -225,8 +221,9 @@ public class Notifier { } /** - * Register for single event notification. - * A timer event is queued for a single event after the specified delay. + * Register for single event notification. A timer event is queued for a + * single event after the specified delay. + *$ * @param delay Seconds to wait before the handler is called. */ public void startSingle(double delay) { @@ -239,12 +236,12 @@ public class Notifier { } /** - * Register for periodic event notification. - * A timer event is queued for periodic event notification. Each time the - * interrupt occurs, the event will be immediately requeued for the same time - * interval. + * Register for periodic event notification. A timer event is queued for + * periodic event notification. Each time the interrupt occurs, the event will + * be immediately requeued for the same time interval. + *$ * @param period Period in seconds to call the handler starting one period - * after the call to this method. + * after the call to this method. */ public void startPeriodic(double period) { queueLock.lock(); @@ -256,10 +253,9 @@ public class Notifier { } /** - * Stop timer events from occuring. - * Stop any repeating timer events from occuring. This will also remove any - * single notification events from the queue. - * If a timer-based call to the registered handler is in progress, this + * Stop timer events from occuring. Stop any repeating timer events from + * occuring. This will also remove any single notification events from the + * queue. If a timer-based call to the registered handler is in progress, this * function will block until the handler call is complete. */ public void stop() { @@ -278,7 +274,7 @@ public class Notifier { ByteBuffer status = pointer(); m_processQueue = new ProcessQueue(); m_notifier = NotifierJNI.initializeNotifier(m_processQueue, status.asIntBuffer()); - HALUtil.checkStatus(status.asIntBuffer()); + HALUtil.checkStatus(status.asIntBuffer()); } // Returns a ByteBuffer with the appropriate length and endianness to pass to diff --git a/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/PWM.java b/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/PWM.java index 964b717d43..27ec4f8c59 100644 --- a/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/PWM.java +++ b/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/PWM.java @@ -1,8 +1,8 @@ /*----------------------------------------------------------------------------*/ -/* Copyright (c) FIRST 2008-2014. All Rights Reserved. */ -/* Open Source Software - may be modified and shared by FRC teams. The code */ +/* Copyright (c) FIRST 2008-2014. All Rights Reserved. */ +/* Open Source Software - may be modified and shared by FRC teams. The code */ /* must be accompanied by the FIRST BSD license file in the root directory of */ -/* the project. */ +/* the project. */ /*----------------------------------------------------------------------------*/ package edu.wpi.first.wpilibj; @@ -24,472 +24,481 @@ import edu.wpi.first.wpilibj.hal.HALUtil; /** * Class implements the PWM generation in the FPGA. * - * The values supplied as arguments for PWM outputs range from -1.0 to 1.0. They are mapped - * to the hardware dependent values, in this case 0-2000 for the FPGA. - * Changes are immediately sent to the FPGA, and the update occurs at the next - * FPGA cycle. There is no delay. + * The values supplied as arguments for PWM outputs range from -1.0 to 1.0. They + * are mapped to the hardware dependent values, in this case 0-2000 for the + * FPGA. Changes are immediately sent to the FPGA, and the update occurs at the + * next FPGA cycle. There is no delay. * - * As of revision 0.1.10 of the FPGA, the FPGA interprets the 0-2000 values as follows: - * - 2000 = maximum pulse width - * - 1999 to 1001 = linear scaling from "full forward" to "center" - * - 1000 = center value - * - 999 to 2 = linear scaling from "center" to "full reverse" - * - 1 = minimum pulse width (currently .5ms) - * - 0 = disabled (i.e. PWM output is held low) + * As of revision 0.1.10 of the FPGA, the FPGA interprets the 0-2000 values as + * follows: - 2000 = maximum pulse width - 1999 to 1001 = linear scaling from + * "full forward" to "center" - 1000 = center value - 999 to 2 = linear scaling + * from "center" to "full reverse" - 1 = minimum pulse width (currently .5ms) - + * 0 = disabled (i.e. PWM output is held low) */ public class PWM extends SensorBase implements LiveWindowSendable { - /** - * Represents the amount to multiply the minimum servo-pulse pwm period by. - */ - public static class PeriodMultiplier { + /** + * Represents the amount to multiply the minimum servo-pulse pwm period by. + */ + public static class PeriodMultiplier { - /** - * The integer value representing this enumeration - */ - public final int value; - static final int k1X_val = 1; - static final int k2X_val = 2; - static final int k4X_val = 4; - /** - * Period Multiplier: don't skip pulses - */ - public static final PeriodMultiplier k1X = new PeriodMultiplier(k1X_val); - /** - * Period Multiplier: skip every other pulse - */ - public static final PeriodMultiplier k2X = new PeriodMultiplier(k2X_val); - /** - * Period Multiplier: skip three out of four pulses - */ - public static final PeriodMultiplier k4X = new PeriodMultiplier(k4X_val); + /** + * The integer value representing this enumeration + */ + public final int value; + static final int k1X_val = 1; + static final int k2X_val = 2; + static final int k4X_val = 4; + /** + * Period Multiplier: don't skip pulses + */ + public static final PeriodMultiplier k1X = new PeriodMultiplier(k1X_val); + /** + * Period Multiplier: skip every other pulse + */ + public static final PeriodMultiplier k2X = new PeriodMultiplier(k2X_val); + /** + * Period Multiplier: skip three out of four pulses + */ + public static final PeriodMultiplier k4X = new PeriodMultiplier(k4X_val); - private PeriodMultiplier(int value) { - this.value = value; - } - } - private int m_channel; - private ByteBuffer m_port; - /** - * kDefaultPwmPeriod is in ms - * - * - 20ms periods (50 Hz) are the "safest" setting in that this works for all devices - * - 20ms periods seem to be desirable for Vex Motors - * - 20ms periods are the specified period for HS-322HD servos, but work reliably down - * to 10.0 ms; starting at about 8.5ms, the servo sometimes hums and get hot; - * by 5.0ms the hum is nearly continuous - * - 10ms periods work well for Victor 884 - * - 5ms periods allows higher update rates for Luminary Micro Jaguar speed controllers. - * Due to the shipping firmware on the Jaguar, we can't run the update period less - * than 5.05 ms. - * - * kDefaultPwmPeriod is the 1x period (5.05 ms). In hardware, the period scaling is implemented as an - * output squelch to get longer periods for old devices. - */ - protected static final double kDefaultPwmPeriod = 5.05; - /** - * kDefaultPwmCenter is the PWM range center in ms - */ - protected static final double kDefaultPwmCenter = 1.5; - /** - * kDefaultPWMStepsDown is the number of PWM steps below the centerpoint - */ - protected static final int kDefaultPwmStepsDown = 1000; - public static final int kPwmDisabled = 0; - boolean m_eliminateDeadband; - int m_maxPwm; - int m_deadbandMaxPwm; - int m_centerPwm; - int m_deadbandMinPwm; - int m_minPwm; + private PeriodMultiplier(int value) { + this.value = value; + } + } - /** - * Initialize PWMs given a channel. - * - * This method is private and is the common path for all the constructors - * for creating PWM instances. Checks channel value ranges and allocates - * the appropriate channel. The allocation is only done to help users - * ensure that they don't double assign channels. - * @param channel The PWM channel number. 0-9 are on-board, 10-19 are on the MXP port - */ - private void initPWM(final int channel) { - checkPWMChannel(channel); - m_channel = channel; + private int m_channel; + private ByteBuffer m_port; + /** + * kDefaultPwmPeriod is in ms + * + * - 20ms periods (50 Hz) are the "safest" setting in that this works for all + * devices - 20ms periods seem to be desirable for Vex Motors - 20ms periods + * are the specified period for HS-322HD servos, but work reliably down to + * 10.0 ms; starting at about 8.5ms, the servo sometimes hums and get hot; by + * 5.0ms the hum is nearly continuous - 10ms periods work well for Victor 884 + * - 5ms periods allows higher update rates for Luminary Micro Jaguar speed + * controllers. Due to the shipping firmware on the Jaguar, we can't run the + * update period less than 5.05 ms. + * + * kDefaultPwmPeriod is the 1x period (5.05 ms). In hardware, the period + * scaling is implemented as an output squelch to get longer periods for old + * devices. + */ + protected static final double kDefaultPwmPeriod = 5.05; + /** + * kDefaultPwmCenter is the PWM range center in ms + */ + protected static final double kDefaultPwmCenter = 1.5; + /** + * kDefaultPWMStepsDown is the number of PWM steps below the centerpoint + */ + protected static final int kDefaultPwmStepsDown = 1000; + public static final int kPwmDisabled = 0; + boolean m_eliminateDeadband; + int m_maxPwm; + int m_deadbandMaxPwm; + int m_centerPwm; + int m_deadbandMinPwm; + int m_minPwm; - ByteBuffer status = ByteBuffer.allocateDirect(4); - status.order(ByteOrder.LITTLE_ENDIAN); + /** + * Initialize PWMs given a channel. + * + * This method is private and is the common path for all the constructors for + * creating PWM instances. Checks channel value ranges and allocates the + * appropriate channel. The allocation is only done to help users ensure that + * they don't double assign channels. + *$ + * @param channel The PWM channel number. 0-9 are on-board, 10-19 are on the + * MXP port + */ + private void initPWM(final int channel) { + checkPWMChannel(channel); + m_channel = channel; - m_port = DIOJNI.initializeDigitalPort(DIOJNI.getPort((byte) m_channel), status.asIntBuffer()); - HALUtil.checkStatus(status.asIntBuffer()); + ByteBuffer status = ByteBuffer.allocateDirect(4); + status.order(ByteOrder.LITTLE_ENDIAN); - if (!PWMJNI.allocatePWMChannel(m_port, status.asIntBuffer())) - { - throw new AllocationException( - "PWM channel " + channel + " is already allocated"); - } - HALUtil.checkStatus(status.asIntBuffer()); + m_port = DIOJNI.initializeDigitalPort(DIOJNI.getPort((byte) m_channel), status.asIntBuffer()); + HALUtil.checkStatus(status.asIntBuffer()); - PWMJNI.setPWM(m_port, (short) 0, status.asIntBuffer()); - HALUtil.checkStatus(status.asIntBuffer()); + if (!PWMJNI.allocatePWMChannel(m_port, status.asIntBuffer())) { + throw new AllocationException("PWM channel " + channel + " is already allocated"); + } + HALUtil.checkStatus(status.asIntBuffer()); - m_eliminateDeadband = false; + PWMJNI.setPWM(m_port, (short) 0, status.asIntBuffer()); + HALUtil.checkStatus(status.asIntBuffer()); - UsageReporting.report(tResourceType.kResourceType_PWM, channel); - } + m_eliminateDeadband = false; - /** - * Allocate a PWM given a channel. - * - * @param channel The PWM channel. - */ - public PWM(final int channel) { - initPWM(channel); - } + UsageReporting.report(tResourceType.kResourceType_PWM, channel); + } - /** - * Free the PWM channel. - * - * Free the resource associated with the PWM channel and set the value to 0. - */ - public void free() { - ByteBuffer status = ByteBuffer.allocateDirect(4); - status.order(ByteOrder.LITTLE_ENDIAN); + /** + * Allocate a PWM given a channel. + * + * @param channel The PWM channel. + */ + public PWM(final int channel) { + initPWM(channel); + } - PWMJNI.setPWM(m_port, (short) 0, status.asIntBuffer()); - HALUtil.checkStatus(status.asIntBuffer()); + /** + * Free the PWM channel. + * + * Free the resource associated with the PWM channel and set the value to 0. + */ + public void free() { + ByteBuffer status = ByteBuffer.allocateDirect(4); + status.order(ByteOrder.LITTLE_ENDIAN); - PWMJNI.freePWMChannel(m_port, status.asIntBuffer()); - HALUtil.checkStatus(status.asIntBuffer()); + PWMJNI.setPWM(m_port, (short) 0, status.asIntBuffer()); + HALUtil.checkStatus(status.asIntBuffer()); - PWMJNI.freeDIO(m_port, status.asIntBuffer()); - HALUtil.checkStatus(status.asIntBuffer()); - } + PWMJNI.freePWMChannel(m_port, status.asIntBuffer()); + HALUtil.checkStatus(status.asIntBuffer()); - /** - * Optionally eliminate the deadband from a speed controller. - * @param eliminateDeadband If true, set the motor curve on the Jaguar to eliminate - * the deadband in the middle of the range. Otherwise, keep the full range without - * modifying any values. - */ - public void enableDeadbandElimination(boolean eliminateDeadband) { - m_eliminateDeadband = eliminateDeadband; - } + PWMJNI.freeDIO(m_port, status.asIntBuffer()); + HALUtil.checkStatus(status.asIntBuffer()); + } - /** - * Set the bounds on the PWM values. - * This sets the bounds on the PWM values for a particular each type of controller. The values - * determine the upper and lower speeds as well as the deadband bracket. - * @deprecated Recommended to set bounds in ms using {@link #setBounds(double, double, double, double, double)} - * @param max The Minimum pwm value - * @param deadbandMax The high end of the deadband range - * @param center The center speed (off) - * @param deadbandMin The low end of the deadband range - * @param min The minimum pwm value - */ - public void setBounds(final int max, final int deadbandMax, final int center, final int deadbandMin, final int min) { - m_maxPwm = max; - m_deadbandMaxPwm = deadbandMax; - m_centerPwm = center; - m_deadbandMinPwm = deadbandMin; - m_minPwm = min; - } + /** + * Optionally eliminate the deadband from a speed controller. + *$ + * @param eliminateDeadband If true, set the motor curve on the Jaguar to + * eliminate the deadband in the middle of the range. Otherwise, keep + * the full range without modifying any values. + */ + public void enableDeadbandElimination(boolean eliminateDeadband) { + m_eliminateDeadband = eliminateDeadband; + } - /** - * Set the bounds on the PWM pulse widths. - * This sets the bounds on the PWM values for a particular type of controller. The values - * determine the upper and lower speeds as well as the deadband bracket. - * @param max The max PWM pulse width in ms - * @param deadbandMax The high end of the deadband range pulse width in ms - * @param center The center (off) pulse width in ms - * @param deadbandMin The low end of the deadband pulse width in ms - * @param min The minimum pulse width in ms - */ - protected void setBounds(double max, double deadbandMax, double center, double deadbandMin, double min) { - ByteBuffer status = ByteBuffer.allocateDirect(4); - status.order(ByteOrder.LITTLE_ENDIAN); + /** + * Set the bounds on the PWM values. This sets the bounds on the PWM values + * for a particular each type of controller. The values determine the upper + * and lower speeds as well as the deadband bracket. + *$ + * @deprecated Recommended to set bounds in ms using + * {@link #setBounds(double, double, double, double, double)} + * @param max The Minimum pwm value + * @param deadbandMax The high end of the deadband range + * @param center The center speed (off) + * @param deadbandMin The low end of the deadband range + * @param min The minimum pwm value + */ + public void setBounds(final int max, final int deadbandMax, final int center, + final int deadbandMin, final int min) { + m_maxPwm = max; + m_deadbandMaxPwm = deadbandMax; + m_centerPwm = center; + m_deadbandMinPwm = deadbandMin; + m_minPwm = min; + } - double loopTime = DIOJNI.getLoopTiming(status.asIntBuffer())/(kSystemClockTicksPerMicrosecond*1e3); + /** + * Set the bounds on the PWM pulse widths. This sets the bounds on the PWM + * values for a particular type of controller. The values determine the upper + * and lower speeds as well as the deadband bracket. + *$ + * @param max The max PWM pulse width in ms + * @param deadbandMax The high end of the deadband range pulse width in ms + * @param center The center (off) pulse width in ms + * @param deadbandMin The low end of the deadband pulse width in ms + * @param min The minimum pulse width in ms + */ + protected void setBounds(double max, double deadbandMax, double center, double deadbandMin, + double min) { + ByteBuffer status = ByteBuffer.allocateDirect(4); + status.order(ByteOrder.LITTLE_ENDIAN); - m_maxPwm = (int)((max-kDefaultPwmCenter)/loopTime+kDefaultPwmStepsDown-1); - m_deadbandMaxPwm = (int)((deadbandMax-kDefaultPwmCenter)/loopTime+kDefaultPwmStepsDown-1); - m_centerPwm = (int)((center-kDefaultPwmCenter)/loopTime+kDefaultPwmStepsDown-1); - m_deadbandMinPwm = (int)((deadbandMin-kDefaultPwmCenter)/loopTime+kDefaultPwmStepsDown-1); - m_minPwm = (int)((min-kDefaultPwmCenter)/loopTime+kDefaultPwmStepsDown-1); - } + double loopTime = + DIOJNI.getLoopTiming(status.asIntBuffer()) / (kSystemClockTicksPerMicrosecond * 1e3); - /** - * Gets the channel number associated with the PWM Object. - * - * @return The channel number. - */ - public int getChannel() { - return m_channel; - } + m_maxPwm = (int) ((max - kDefaultPwmCenter) / loopTime + kDefaultPwmStepsDown - 1); + m_deadbandMaxPwm = + (int) ((deadbandMax - kDefaultPwmCenter) / loopTime + kDefaultPwmStepsDown - 1); + m_centerPwm = (int) ((center - kDefaultPwmCenter) / loopTime + kDefaultPwmStepsDown - 1); + m_deadbandMinPwm = + (int) ((deadbandMin - kDefaultPwmCenter) / loopTime + kDefaultPwmStepsDown - 1); + m_minPwm = (int) ((min - kDefaultPwmCenter) / loopTime + kDefaultPwmStepsDown - 1); + } - /** - * Set the PWM value based on a position. - * - * This is intended to be used by servos. - * - * @pre SetMaxPositivePwm() called. - * @pre SetMinNegativePwm() called. - * - * @param pos The position to set the servo between 0.0 and 1.0. - */ - public void setPosition(double pos) { - if (pos < 0.0) { - pos = 0.0; - } else if (pos > 1.0) { - pos = 1.0; - } + /** + * Gets the channel number associated with the PWM Object. + * + * @return The channel number. + */ + public int getChannel() { + return m_channel; + } - int rawValue; - // note, need to perform the multiplication below as floating point before converting to int - rawValue = (int) ((pos * (double)getFullRangeScaleFactor()) + getMinNegativePwm()); + /** + * Set the PWM value based on a position. + * + * This is intended to be used by servos. + * + * @pre SetMaxPositivePwm() called. + * @pre SetMinNegativePwm() called. + * + * @param pos The position to set the servo between 0.0 and 1.0. + */ + public void setPosition(double pos) { + if (pos < 0.0) { + pos = 0.0; + } else if (pos > 1.0) { + pos = 1.0; + } - // send the computed pwm value to the FPGA - setRaw(rawValue); - } + int rawValue; + // note, need to perform the multiplication below as floating point before + // converting to int + rawValue = (int) ((pos * (double) getFullRangeScaleFactor()) + getMinNegativePwm()); - /** - * Get the PWM value in terms of a position. - * - * This is intended to be used by servos. - * - * @pre SetMaxPositivePwm() called. - * @pre SetMinNegativePwm() called. - * - * @return The position the servo is set to between 0.0 and 1.0. - */ - public double getPosition() { - int value = getRaw(); - if (value < getMinNegativePwm()) { - return 0.0; - } else if (value > getMaxPositivePwm()) { - return 1.0; - } else { - return (double)(value - getMinNegativePwm()) / (double)getFullRangeScaleFactor(); - } - } + // send the computed pwm value to the FPGA + setRaw(rawValue); + } - /** - * Set the PWM value based on a speed. - * - * This is intended to be used by speed controllers. - * - * @pre SetMaxPositivePwm() called. - * @pre SetMinPositivePwm() called. - * @pre SetCenterPwm() called. - * @pre SetMaxNegativePwm() called. - * @pre SetMinNegativePwm() called. - * - * @param speed The speed to set the speed controller between -1.0 and 1.0. - */ - final void setSpeed(double speed) { - // clamp speed to be in the range 1.0 >= speed >= -1.0 - if (speed < -1.0) { - speed = -1.0; - } else if (speed > 1.0) { - speed = 1.0; - } + /** + * Get the PWM value in terms of a position. + * + * This is intended to be used by servos. + * + * @pre SetMaxPositivePwm() called. + * @pre SetMinNegativePwm() called. + * + * @return The position the servo is set to between 0.0 and 1.0. + */ + public double getPosition() { + int value = getRaw(); + if (value < getMinNegativePwm()) { + return 0.0; + } else if (value > getMaxPositivePwm()) { + return 1.0; + } else { + return (double) (value - getMinNegativePwm()) / (double) getFullRangeScaleFactor(); + } + } - // calculate the desired output pwm value by scaling the speed appropriately - int rawValue; - if (speed == 0.0) { - rawValue = getCenterPwm(); - } else if (speed > 0.0) { - rawValue = (int) (speed * ((double)getPositiveScaleFactor()) + - ((double)getMinPositivePwm()) + 0.5); - } else { - rawValue = (int) (speed * ((double)getNegativeScaleFactor()) + - ((double)getMaxNegativePwm()) + 0.5); - } + /** + * Set the PWM value based on a speed. + * + * This is intended to be used by speed controllers. + * + * @pre SetMaxPositivePwm() called. + * @pre SetMinPositivePwm() called. + * @pre SetCenterPwm() called. + * @pre SetMaxNegativePwm() called. + * @pre SetMinNegativePwm() called. + * + * @param speed The speed to set the speed controller between -1.0 and 1.0. + */ + final void setSpeed(double speed) { + // clamp speed to be in the range 1.0 >= speed >= -1.0 + if (speed < -1.0) { + speed = -1.0; + } else if (speed > 1.0) { + speed = 1.0; + } - // send the computed pwm value to the FPGA - setRaw(rawValue); - } + // calculate the desired output pwm value by scaling the speed appropriately + int rawValue; + if (speed == 0.0) { + rawValue = getCenterPwm(); + } else if (speed > 0.0) { + rawValue = + (int) (speed * ((double) getPositiveScaleFactor()) + ((double) getMinPositivePwm()) + 0.5); + } else { + rawValue = + (int) (speed * ((double) getNegativeScaleFactor()) + ((double) getMaxNegativePwm()) + 0.5); + } - /** - * Get the PWM value in terms of speed. - * - * This is intended to be used by speed controllers. - * - * @pre SetMaxPositivePwm() called. - * @pre SetMinPositivePwm() called. - * @pre SetMaxNegativePwm() called. - * @pre SetMinNegativePwm() called. - * - * @return The most recently set speed between -1.0 and 1.0. - */ - public double getSpeed() { - int value = getRaw(); - if (value > getMaxPositivePwm()) { - return 1.0; - } else if (value < getMinNegativePwm()) { - return -1.0; - } else if (value > getMinPositivePwm()) { - return (double) (value - getMinPositivePwm()) / (double)getPositiveScaleFactor(); - } else if (value < getMaxNegativePwm()) { - return (double) (value - getMaxNegativePwm()) / (double)getNegativeScaleFactor(); - } else { - return 0.0; - } - } + // send the computed pwm value to the FPGA + setRaw(rawValue); + } - /** - * Set the PWM value directly to the hardware. - * - * Write a raw value to a PWM channel. - * - * @param value Raw PWM value. Range 0 - 255. - */ - public void setRaw(int value) { - ByteBuffer status = ByteBuffer.allocateDirect(4); - status.order(ByteOrder.LITTLE_ENDIAN); + /** + * Get the PWM value in terms of speed. + * + * This is intended to be used by speed controllers. + * + * @pre SetMaxPositivePwm() called. + * @pre SetMinPositivePwm() called. + * @pre SetMaxNegativePwm() called. + * @pre SetMinNegativePwm() called. + * + * @return The most recently set speed between -1.0 and 1.0. + */ + public double getSpeed() { + int value = getRaw(); + if (value > getMaxPositivePwm()) { + return 1.0; + } else if (value < getMinNegativePwm()) { + return -1.0; + } else if (value > getMinPositivePwm()) { + return (double) (value - getMinPositivePwm()) / (double) getPositiveScaleFactor(); + } else if (value < getMaxNegativePwm()) { + return (double) (value - getMaxNegativePwm()) / (double) getNegativeScaleFactor(); + } else { + return 0.0; + } + } - PWMJNI.setPWM(m_port, (short) value, status.asIntBuffer()); - HALUtil.checkStatus(status.asIntBuffer()); - } + /** + * Set the PWM value directly to the hardware. + * + * Write a raw value to a PWM channel. + * + * @param value Raw PWM value. Range 0 - 255. + */ + public void setRaw(int value) { + ByteBuffer status = ByteBuffer.allocateDirect(4); + status.order(ByteOrder.LITTLE_ENDIAN); - /** - * Get the PWM value directly from the hardware. - * - * Read a raw value from a PWM channel. - * - * @return Raw PWM control value. Range: 0 - 255. - */ - public int getRaw() { - ByteBuffer status = ByteBuffer.allocateDirect(4); - status.order(ByteOrder.LITTLE_ENDIAN); + PWMJNI.setPWM(m_port, (short) value, status.asIntBuffer()); + HALUtil.checkStatus(status.asIntBuffer()); + } - int value = PWMJNI.getPWM(m_port, status.asIntBuffer()); - HALUtil.checkStatus(status.asIntBuffer()); + /** + * Get the PWM value directly from the hardware. + * + * Read a raw value from a PWM channel. + * + * @return Raw PWM control value. Range: 0 - 255. + */ + public int getRaw() { + ByteBuffer status = ByteBuffer.allocateDirect(4); + status.order(ByteOrder.LITTLE_ENDIAN); - return value; - } + int value = PWMJNI.getPWM(m_port, status.asIntBuffer()); + HALUtil.checkStatus(status.asIntBuffer()); - /** - * Slow down the PWM signal for old devices. - * - * @param mult The period multiplier to apply to this channel - */ - public void setPeriodMultiplier(PeriodMultiplier mult) { - ByteBuffer status = ByteBuffer.allocateDirect(4); - status.order(ByteOrder.LITTLE_ENDIAN); + return value; + } - switch (mult.value) { - case PeriodMultiplier.k4X_val: - // Squelch 3 out of 4 outputs - PWMJNI.setPWMPeriodScale(m_port, 3, status.asIntBuffer()); - break; - case PeriodMultiplier.k2X_val: - // Squelch 1 out of 2 outputs - PWMJNI.setPWMPeriodScale(m_port, 1, status.asIntBuffer()); - break; - case PeriodMultiplier.k1X_val: - // Don't squelch any outputs - PWMJNI.setPWMPeriodScale(m_port, 0, status.asIntBuffer()); - break; - default: - //Cannot hit this, limited by PeriodMultiplier enum - } + /** + * Slow down the PWM signal for old devices. + * + * @param mult The period multiplier to apply to this channel + */ + public void setPeriodMultiplier(PeriodMultiplier mult) { + ByteBuffer status = ByteBuffer.allocateDirect(4); + status.order(ByteOrder.LITTLE_ENDIAN); - HALUtil.checkStatus(status.asIntBuffer()); - } - - protected void setZeroLatch() - { - ByteBuffer status = ByteBuffer.allocateDirect(4); - status.order(ByteOrder.LITTLE_ENDIAN); - - PWMJNI.latchPWMZero(m_port, status.asIntBuffer()); - - HALUtil.checkStatus(status.asIntBuffer()); - } + switch (mult.value) { + case PeriodMultiplier.k4X_val: + // Squelch 3 out of 4 outputs + PWMJNI.setPWMPeriodScale(m_port, 3, status.asIntBuffer()); + break; + case PeriodMultiplier.k2X_val: + // Squelch 1 out of 2 outputs + PWMJNI.setPWMPeriodScale(m_port, 1, status.asIntBuffer()); + break; + case PeriodMultiplier.k1X_val: + // Don't squelch any outputs + PWMJNI.setPWMPeriodScale(m_port, 0, status.asIntBuffer()); + break; + default: + // Cannot hit this, limited by PeriodMultiplier enum + } - private int getMaxPositivePwm() { - return m_maxPwm; - } + HALUtil.checkStatus(status.asIntBuffer()); + } - private int getMinPositivePwm() { - return m_eliminateDeadband ? m_deadbandMaxPwm : m_centerPwm + 1; - } + protected void setZeroLatch() { + ByteBuffer status = ByteBuffer.allocateDirect(4); + status.order(ByteOrder.LITTLE_ENDIAN); - private int getCenterPwm() { - return m_centerPwm; - } + PWMJNI.latchPWMZero(m_port, status.asIntBuffer()); - private int getMaxNegativePwm() { - return m_eliminateDeadband ? m_deadbandMinPwm : m_centerPwm - 1; - } + HALUtil.checkStatus(status.asIntBuffer()); + } - private int getMinNegativePwm() { - return m_minPwm; - } + private int getMaxPositivePwm() { + return m_maxPwm; + } - private int getPositiveScaleFactor() { - return getMaxPositivePwm() - getMinPositivePwm(); - } ///< The scale for positive speeds. + private int getMinPositivePwm() { + return m_eliminateDeadband ? m_deadbandMaxPwm : m_centerPwm + 1; + } - private int getNegativeScaleFactor() { - return getMaxNegativePwm() - getMinNegativePwm(); - } ///< The scale for negative speeds. + private int getCenterPwm() { + return m_centerPwm; + } - private int getFullRangeScaleFactor() { - return getMaxPositivePwm() - getMinNegativePwm(); - } ///< The scale for positions. + private int getMaxNegativePwm() { + return m_eliminateDeadband ? m_deadbandMinPwm : m_centerPwm - 1; + } - /* - * Live Window code, only does anything if live window is activated. - */ - public String getSmartDashboardType() { - return "Speed Controller"; - } - private ITable m_table; - private ITableListener m_table_listener; + private int getMinNegativePwm() { + return m_minPwm; + } - /** - * {@inheritDoc} - */ - public void initTable(ITable subtable) { - m_table = subtable; - updateTable(); - } + private int getPositiveScaleFactor() { + return getMaxPositivePwm() - getMinPositivePwm(); + } // /< The scale for positive speeds. - /** - * {@inheritDoc} - */ - public void updateTable() { - if (m_table != null) { - m_table.putNumber("Value", getSpeed()); - } - } + private int getNegativeScaleFactor() { + return getMaxNegativePwm() - getMinNegativePwm(); + } // /< The scale for negative speeds. - /** - * {@inheritDoc} - */ - public ITable getTable() { - return m_table; - } + private int getFullRangeScaleFactor() { + return getMaxPositivePwm() - getMinNegativePwm(); + } // /< The scale for positions. - /** - * {@inheritDoc} - */ - public void startLiveWindowMode() { - setSpeed(0); // Stop for safety - m_table_listener = new ITableListener() { - public void valueChanged(ITable itable, String key, Object value, boolean bln) { - setSpeed(((Double) value).doubleValue()); - } - }; - m_table.addTableListener("Value", m_table_listener, true); - } + /* + * Live Window code, only does anything if live window is activated. + */ + public String getSmartDashboardType() { + return "Speed Controller"; + } - /** - * {@inheritDoc} - */ - public void stopLiveWindowMode() { - setSpeed(0); // Stop for safety - // TODO: Broken, should only remove the listener from "Value" only. - m_table.removeTableListener(m_table_listener); - } + private ITable m_table; + private ITableListener m_table_listener; + + /** + * {@inheritDoc} + */ + public void initTable(ITable subtable) { + m_table = subtable; + updateTable(); + } + + /** + * {@inheritDoc} + */ + public void updateTable() { + if (m_table != null) { + m_table.putNumber("Value", getSpeed()); + } + } + + /** + * {@inheritDoc} + */ + public ITable getTable() { + return m_table; + } + + /** + * {@inheritDoc} + */ + public void startLiveWindowMode() { + setSpeed(0); // Stop for safety + m_table_listener = new ITableListener() { + public void valueChanged(ITable itable, String key, Object value, boolean bln) { + setSpeed(((Double) value).doubleValue()); + } + }; + m_table.addTableListener("Value", m_table_listener, true); + } + + /** + * {@inheritDoc} + */ + public void stopLiveWindowMode() { + setSpeed(0); // Stop for safety + // TODO: Broken, should only remove the listener from "Value" only. + m_table.removeTableListener(m_table_listener); + } } diff --git a/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/PowerDistributionPanel.java b/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/PowerDistributionPanel.java index bca3de0396..50e551ee04 100644 --- a/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/PowerDistributionPanel.java +++ b/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/PowerDistributionPanel.java @@ -1,8 +1,8 @@ /*----------------------------------------------------------------------------*/ -/* Copyright (c) FIRST 2014. All Rights Reserved. */ -/* Open Source Software - may be modified and shared by FRC teams. The code */ +/* Copyright (c) FIRST 2014. All Rights Reserved. */ +/* Open Source Software - may be modified and shared by FRC teams. The code */ /* must be accompanied by the FIRST BSD license file in the root directory of */ -/* the project. */ +/* the project. */ /*----------------------------------------------------------------------------*/ package edu.wpi.first.wpilibj; @@ -17,185 +17,193 @@ import edu.wpi.first.wpilibj.livewindow.LiveWindowSendable; import edu.wpi.first.wpilibj.tables.ITable; /** - * Class for getting voltage, current, temperature, power and energy from the CAN PDP. - * The PDP must be at CAN Address 0. + * Class for getting voltage, current, temperature, power and energy from the + * CAN PDP. The PDP must be at CAN Address 0. + *$ * @author Thomas Clark */ public class PowerDistributionPanel extends SensorBase implements LiveWindowSendable { - - int m_module; - - public PowerDistributionPanel(int module) { - m_module = module; - checkPDPModule(m_module); - PDPJNI.initializePDP(m_module); - } - public PowerDistributionPanel() { - this(0); - } + int m_module; - - /** - * Query the input voltage of the PDP - * @return The voltage of the PDP in volts - */ - public double getVoltage() { - ByteBuffer status = ByteBuffer.allocateDirect(4); - status.order(ByteOrder.LITTLE_ENDIAN); + public PowerDistributionPanel(int module) { + m_module = module; + checkPDPModule(m_module); + PDPJNI.initializePDP(m_module); + } - double voltage = PDPJNI.getPDPVoltage(status.asIntBuffer(), m_module); + public PowerDistributionPanel() { + this(0); + } - return voltage; - } - /** - * Query the temperature of the PDP - * @return The temperature of the PDP in degrees Celsius - */ - public double getTemperature() { - ByteBuffer status = ByteBuffer.allocateDirect(4); - status.order(ByteOrder.LITTLE_ENDIAN); + /** + * Query the input voltage of the PDP + *$ + * @return The voltage of the PDP in volts + */ + public double getVoltage() { + ByteBuffer status = ByteBuffer.allocateDirect(4); + status.order(ByteOrder.LITTLE_ENDIAN); - double temperature = PDPJNI.getPDPTemperature(status.asIntBuffer(), m_module); + double voltage = PDPJNI.getPDPVoltage(status.asIntBuffer(), m_module); - return temperature; - } + return voltage; + } - /** - * Query the current of a single channel of the PDP - * @return The current of one of the PDP channels (channels 0-15) in Amperes - */ - public double getCurrent(int channel) { - ByteBuffer status = ByteBuffer.allocateDirect(4); - status.order(ByteOrder.LITTLE_ENDIAN); + /** + * Query the temperature of the PDP + *$ + * @return The temperature of the PDP in degrees Celsius + */ + public double getTemperature() { + ByteBuffer status = ByteBuffer.allocateDirect(4); + status.order(ByteOrder.LITTLE_ENDIAN); - double current = PDPJNI.getPDPChannelCurrent((byte)channel, status.asIntBuffer(), m_module); + double temperature = PDPJNI.getPDPTemperature(status.asIntBuffer(), m_module); - checkPDPChannel(channel); + return temperature; + } - return current; - } + /** + * Query the current of a single channel of the PDP + *$ + * @return The current of one of the PDP channels (channels 0-15) in Amperes + */ + public double getCurrent(int channel) { + ByteBuffer status = ByteBuffer.allocateDirect(4); + status.order(ByteOrder.LITTLE_ENDIAN); - /** - * Query the current of all monitored PDP channels (0-15) - * @return The current of all the channels in Amperes - */ - public double getTotalCurrent(){ - ByteBuffer status = ByteBuffer.allocateDirect(4); - status.order(ByteOrder.LITTLE_ENDIAN); + double current = PDPJNI.getPDPChannelCurrent((byte) channel, status.asIntBuffer(), m_module); - double current = PDPJNI.getPDPTotalCurrent(status.asIntBuffer(), m_module); + checkPDPChannel(channel); - return current; - } + return current; + } - /** - * Query the total power drawn from the monitored PDP channels - * @return the total power in Watts - */ - public double getTotalPower(){ - ByteBuffer status = ByteBuffer.allocateDirect(4); - status.order(ByteOrder.LITTLE_ENDIAN); + /** + * Query the current of all monitored PDP channels (0-15) + *$ + * @return The current of all the channels in Amperes + */ + public double getTotalCurrent() { + ByteBuffer status = ByteBuffer.allocateDirect(4); + status.order(ByteOrder.LITTLE_ENDIAN); - double power = PDPJNI.getPDPTotalPower(status.asIntBuffer(), m_module); + double current = PDPJNI.getPDPTotalCurrent(status.asIntBuffer(), m_module); - return power; + return current; + } - } + /** + * Query the total power drawn from the monitored PDP channels + *$ + * @return the total power in Watts + */ + public double getTotalPower() { + ByteBuffer status = ByteBuffer.allocateDirect(4); + status.order(ByteOrder.LITTLE_ENDIAN); - /** - * Query the total energy drawn from the monitored PDP channels - * @return the total energy in Joules - */ - public double getTotalEnergy(){ - ByteBuffer status = ByteBuffer.allocateDirect(4); - status.order(ByteOrder.LITTLE_ENDIAN); + double power = PDPJNI.getPDPTotalPower(status.asIntBuffer(), m_module); - double energy = PDPJNI.getPDPTotalEnergy(status.asIntBuffer(), m_module); + return power; - return energy; - } + } - /** - * Reset the total energy to 0 - */ - public void resetTotalEnergy(){ - ByteBuffer status = ByteBuffer.allocateDirect(4); - status.order(ByteOrder.LITTLE_ENDIAN); + /** + * Query the total energy drawn from the monitored PDP channels + *$ + * @return the total energy in Joules + */ + public double getTotalEnergy() { + ByteBuffer status = ByteBuffer.allocateDirect(4); + status.order(ByteOrder.LITTLE_ENDIAN); - PDPJNI.resetPDPTotalEnergy(status.asIntBuffer(), m_module); - } + double energy = PDPJNI.getPDPTotalEnergy(status.asIntBuffer(), m_module); - /** - * Clear all PDP sticky faults - */ - public void clearStickyFaults(){ - ByteBuffer status = ByteBuffer.allocateDirect(4); - status.order(ByteOrder.LITTLE_ENDIAN); - - PDPJNI.clearPDPStickyFaults(status.asIntBuffer(), m_module); - } - - public String getSmartDashboardType() { - return "PowerDistributionPanel"; + return energy; + } + + /** + * Reset the total energy to 0 + */ + public void resetTotalEnergy() { + ByteBuffer status = ByteBuffer.allocateDirect(4); + status.order(ByteOrder.LITTLE_ENDIAN); + + PDPJNI.resetPDPTotalEnergy(status.asIntBuffer(), m_module); + } + + /** + * Clear all PDP sticky faults + */ + public void clearStickyFaults() { + ByteBuffer status = ByteBuffer.allocateDirect(4); + status.order(ByteOrder.LITTLE_ENDIAN); + + PDPJNI.clearPDPStickyFaults(status.asIntBuffer(), m_module); + } + + public String getSmartDashboardType() { + return "PowerDistributionPanel"; + } + + /* + * Live Window code, only does anything if live window is activated. + */ + private ITable m_table; + + /** + * {@inheritDoc} + */ + public void initTable(ITable subtable) { + m_table = subtable; + updateTable(); + } + + /** + * {@inheritDoc} + */ + public ITable getTable() { + return m_table; + } + + /** + * {@inheritDoc} + */ + public void updateTable() { + if (m_table != null) { + m_table.putNumber("Chan0", getCurrent(0)); + m_table.putNumber("Chan1", getCurrent(1)); + m_table.putNumber("Chan2", getCurrent(2)); + m_table.putNumber("Chan3", getCurrent(3)); + m_table.putNumber("Chan4", getCurrent(4)); + m_table.putNumber("Chan5", getCurrent(5)); + m_table.putNumber("Chan6", getCurrent(6)); + m_table.putNumber("Chan7", getCurrent(7)); + m_table.putNumber("Chan8", getCurrent(8)); + m_table.putNumber("Chan9", getCurrent(9)); + m_table.putNumber("Chan10", getCurrent(10)); + m_table.putNumber("Chan11", getCurrent(11)); + m_table.putNumber("Chan12", getCurrent(12)); + m_table.putNumber("Chan13", getCurrent(13)); + m_table.putNumber("Chan14", getCurrent(14)); + m_table.putNumber("Chan15", getCurrent(15)); + m_table.putNumber("Voltage", getVoltage()); + m_table.putNumber("TotalCurrent", getTotalCurrent()); } - /* - * Live Window code, only does anything if live window is activated. - */ - private ITable m_table; + } - /** - * {@inheritDoc} - */ - public void initTable(ITable subtable) { - m_table = subtable; - updateTable(); - } + /** + * PDP doesn't have to do anything special when entering the LiveWindow. + * {@inheritDoc} + */ + public void startLiveWindowMode() {} - /** - * {@inheritDoc} - */ - public ITable getTable() { - return m_table; - } - - /** - * {@inheritDoc} - */ - public void updateTable() { - if (m_table != null) { - m_table.putNumber("Chan0", getCurrent(0)); - m_table.putNumber("Chan1", getCurrent(1)); - m_table.putNumber("Chan2", getCurrent(2)); - m_table.putNumber("Chan3", getCurrent(3)); - m_table.putNumber("Chan4", getCurrent(4)); - m_table.putNumber("Chan5", getCurrent(5)); - m_table.putNumber("Chan6", getCurrent(6)); - m_table.putNumber("Chan7", getCurrent(7)); - m_table.putNumber("Chan8", getCurrent(8)); - m_table.putNumber("Chan9", getCurrent(9)); - m_table.putNumber("Chan10", getCurrent(10)); - m_table.putNumber("Chan11", getCurrent(11)); - m_table.putNumber("Chan12", getCurrent(12)); - m_table.putNumber("Chan13", getCurrent(13)); - m_table.putNumber("Chan14", getCurrent(14)); - m_table.putNumber("Chan15", getCurrent(15)); - m_table.putNumber("Voltage", getVoltage()); - m_table.putNumber("TotalCurrent", getTotalCurrent()); - } - } - - /** - * PDP doesn't have to do anything special when entering the LiveWindow. - * {@inheritDoc} - */ - public void startLiveWindowMode() {} - - /** - * PDP doesn't have to do anything special when exiting the LiveWindow. - * {@inheritDoc} - */ - public void stopLiveWindowMode() {} + /** + * PDP doesn't have to do anything special when exiting the LiveWindow. + * {@inheritDoc} + */ + public void stopLiveWindowMode() {} } diff --git a/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/Preferences.java b/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/Preferences.java index fc58b21da2..1984868445 100644 --- a/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/Preferences.java +++ b/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/Preferences.java @@ -1,8 +1,8 @@ /*----------------------------------------------------------------------------*/ -/* Copyright (c) FIRST 2008-2012. All Rights Reserved. */ -/* Open Source Software - may be modified and shared by FRC teams. The code */ +/* Copyright (c) FIRST 2008-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 the root directory of */ -/* the project. */ +/* the project. */ /*----------------------------------------------------------------------------*/ package edu.wpi.first.wpilibj; @@ -25,813 +25,848 @@ import edu.wpi.first.wpilibj.tables.ITableListener; * The preferences class provides a relatively simple way to save important * values to the RoboRIO to access the next time the RoboRIO is booted. * - *

This class loads and saves from a file inside the RoboRIO. The user can not + *

+ * This class loads and saves from a file inside the RoboRIO. The user can not * access the file directly, but may modify values at specific fields which will - * then be saved to the file when {@link Preferences#save() save()} is - * called.

+ * then be saved to the file when {@link Preferences#save() save()} is called. + *

* - *

This class is thread safe.

+ *

+ * This class is thread safe. + *

* - *

This will also interact with {@link NetworkTable} by creating a table - * called "Preferences" with all the key-value pairs. To save using + *

+ * This will also interact with {@link NetworkTable} by creating a table called + * "Preferences" with all the key-value pairs. To save using * {@link NetworkTable}, simply set the boolean at position ~S A V E~ to true. * Also, if the value of any variable is " in the {@link NetworkTable}, then - * that represents non-existence in the {@link Preferences} table

+ * that represents non-existence in the {@link Preferences} table + *

* * @author Joe Grinstead */ public class Preferences { - /** - * The Preferences table name - */ - private static final String TABLE_NAME = "Preferences"; - /** - * The value of the save field - */ - private static final String SAVE_FIELD = "~S A V E~"; - /** - * The file to save to - */ - private static final String FILE_NAME = "/home/lvuser/wpilib-preferences.ini"; - /** - * The characters to put between a field and value - */ - private static final byte[] VALUE_PREFIX = {'=', '\"'}; - /** - * The characters to put after the value - */ - private static final byte[] VALUE_SUFFIX = {'\"', '\n'}; - /** - * The newline character - */ - private static final byte[] NEW_LINE = {'\n'}; - /** - * The singleton instance - */ - private static Preferences instance; + /** + * The Preferences table name + */ + private static final String TABLE_NAME = "Preferences"; + /** + * The value of the save field + */ + private static final String SAVE_FIELD = "~S A V E~"; + /** + * The file to save to + */ + private static final String FILE_NAME = "/home/lvuser/wpilib-preferences.ini"; + /** + * The characters to put between a field and value + */ + private static final byte[] VALUE_PREFIX = {'=', '\"'}; + /** + * The characters to put after the value + */ + private static final byte[] VALUE_SUFFIX = {'\"', '\n'}; + /** + * The newline character + */ + private static final byte[] NEW_LINE = {'\n'}; + /** + * The singleton instance + */ + private static Preferences instance; - /** - * Returns the preferences instance. - * - * @return the preferences instance - */ - public synchronized static Preferences getInstance() { - if (instance == null) { - instance = new Preferences(); + /** + * Returns the preferences instance. + * + * @return the preferences instance + */ + public synchronized static Preferences getInstance() { + if (instance == null) { + instance = new Preferences(); + } + return instance; + } + + /** + * The semaphore for beginning reads and writes to the file + */ + private final Object fileLock = new Object(); + /** + * The semaphore for reading from the table + */ + private final Object lock = new Object(); + /** + * The actual values (String->String) + */ + private Hashtable values; + /** + * The keys in the order they were read from the file + */ + private Vector keys; + /** + * The comments that were in the file sorted by which key they appeared over + * (String->Comment) + */ + private Hashtable comments; + /** + * The comment at the end of the file + */ + private Comment endComment; + + /** + * Creates a preference class that will automatically read the file in a + * different thread. Any call to its methods will be blocked until the thread + * is finished reading. + */ + private Preferences() { + values = new Hashtable(); + keys = new Vector(); + + // We synchronized on fileLock and then wait + // for it to know that the reading thread has started + synchronized (fileLock) { + new Thread() { + public void run() { + read(); } - return instance; + }.start(); + try { + fileLock.wait(); + } catch (InterruptedException ex) { + } } - /** - * The semaphore for beginning reads and writes to the file - */ - private final Object fileLock = new Object(); - /** - * The semaphore for reading from the table - */ - private final Object lock = new Object(); - /** - * The actual values (String->String) - */ - private Hashtable values; - /** - * The keys in the order they were read from the file - */ - private Vector keys; - /** - * The comments that were in the file sorted by which key they appeared over - * (String->Comment) - */ - private Hashtable comments; - /** - * The comment at the end of the file - */ - private Comment endComment; - /** - * Creates a preference class that will automatically read the file in a - * different thread. Any call to its methods will be blocked until the - * thread is finished reading. - */ - private Preferences() { - values = new Hashtable(); - keys = new Vector(); + UsageReporting.report(tResourceType.kResourceType_Preferences, 0); + } - // We synchronized on fileLock and then wait - // for it to know that the reading thread has started - synchronized (fileLock) { - new Thread() { - public void run() { - read(); - } - } .start(); - try { - fileLock.wait(); - } catch (InterruptedException ex) { - } + /** + * @return a vector of the keys + */ + public Vector getKeys() { + synchronized (lock) { + return keys; + } + } + + /** + * Puts the given value into the given key position + * + * @param key the key + * @param value the value + * @throws ImproperPreferenceKeyException if the key contains an illegal + * character + */ + private void put(String key, String value) { + synchronized (lock) { + if (key == null) { + throw new NullPointerException(); + } + ImproperPreferenceKeyException.confirmString(key); + if (values.put(key, value) == null) { + keys.addElement(key); + } + NetworkTable.getTable(TABLE_NAME).putString(key, value); + } + } + + /** + * Puts the given string into the preferences table. + * + *

+ * The value may not have quotation marks, nor may the key have any whitespace + * nor an equals sign + *

+ * + *

+ * This will NOT save the value to memory between power cycles, to do + * that you must call {@link Preferences#save() save()} (which must be used + * with care). at some point after calling this. + *

+ * + * @param key the key + * @param value the value + * @throws NullPointerException if value is null + * @throws IllegalArgumentException if value contains a quotation mark + * @throws ImproperPreferenceKeyException if the key contains any whitespace + * or an equals sign + */ + public void putString(String key, String value) { + if (value == null) { + throw new NullPointerException(); + } + if (value.indexOf('"') != -1) { + throw new IllegalArgumentException("Can not put string:" + value + + " because it contains quotation marks"); + } + put(key, value); + } + + /** + * Puts the given int into the preferences table. + * + *

+ * The key may not have any whitespace nor an equals sign + *

+ * + *

+ * This will NOT save the value to memory between power cycles, to do + * that you must call {@link Preferences#save() save()} (which must be used + * with care) at some point after calling this. + *

+ * + * @param key the key + * @param value the value + * @throws ImproperPreferenceKeyException if the key contains any whitespace + * or an equals sign + */ + public void putInt(String key, int value) { + put(key, String.valueOf(value)); + } + + /** + * Puts the given double into the preferences table. + * + *

+ * The key may not have any whitespace nor an equals sign + *

+ * + *

+ * This will NOT save the value to memory between power cycles, to do + * that you must call {@link Preferences#save() save()} (which must be used + * with care) at some point after calling this. + *

+ * + * @param key the key + * @param value the value + * @throws ImproperPreferenceKeyException if the key contains any whitespace + * or an equals sign + */ + public void putDouble(String key, double value) { + put(key, String.valueOf(value)); + } + + /** + * Puts the given float into the preferences table. + * + *

+ * The key may not have any whitespace nor an equals sign + *

+ * + *

+ * This will NOT save the value to memory between power cycles, to do + * that you must call {@link Preferences#save() save()} (which must be used + * with care) at some point after calling this. + *

+ * + * @param key the key + * @param value the value + * @throws ImproperPreferenceKeyException if the key contains any whitespace + * or an equals sign + */ + public void putFloat(String key, float value) { + put(key, String.valueOf(value)); + } + + /** + * Puts the given boolean into the preferences table. + * + *

+ * The key may not have any whitespace nor an equals sign + *

+ * + *

+ * This will NOT save the value to memory between power cycles, to do + * that you must call {@link Preferences#save() save()} (which must be used + * with care) at some point after calling this. + *

+ * + * @param key the key + * @param value the value + * @throws ImproperPreferenceKeyException if the key contains any whitespace + * or an equals sign + */ + public void putBoolean(String key, boolean value) { + put(key, String.valueOf(value)); + } + + /** + * Puts the given long into the preferences table. + * + *

+ * The key may not have any whitespace nor an equals sign + *

+ * + *

+ * This will NOT save the value to memory between power cycles, to do + * that you must call {@link Preferences#save() save()} (which must be used + * with care) at some point after calling this. + *

+ * + * @param key the key + * @param value the value + * @throws ImproperPreferenceKeyException if the key contains any whitespace + * or an equals sign + */ + public void putLong(String key, long value) { + put(key, String.valueOf(value)); + } + + /** + * Returns the value at the given key. + * + * @param key the key + * @return the value (or null if none exists) + * @throws NullPointerException if the key is null + */ + private String get(String key) { + synchronized (lock) { + if (key == null) { + throw new NullPointerException(); + } + return (String) values.get(key); + } + } + + /** + * Returns whether or not there is a key with the given name. + * + * @param key the key + * @return if there is a value at the given key + * @throws NullPointerException if key is null + */ + public boolean containsKey(String key) { + return get(key) != null; + } + + /** + * Remove a preference + * + * @param key the key + * @throws NullPointerException if key is null + */ + public void remove(String key) { + synchronized (lock) { + if (key == null) { + throw new NullPointerException(); + } + values.remove(key); + keys.removeElement(key); + } + } + + /** + * Returns the string at the given key. If this table does not have a value + * for that position, then the given backup value will be returned. + * + * @param key the key + * @param backup the value to return if none exists in the table + * @return either the value in the table, or the backup + * @throws NullPointerException if the key is null + */ + public String getString(String key, String backup) { + String value = get(key); + return value == null ? backup : value; + } + + /** + * Returns the int at the given key. If this table does not have a value for + * that position, then the given backup value will be returned. + * + * @param key the key + * @param backup the value to return if none exists in the table + * @return either the value in the table, or the backup + * @throws IncompatibleTypeException if the value in the table can not be + * converted to an int + */ + public int getInt(String key, int backup) { + String value = get(key); + if (value == null) { + return backup; + } else { + try { + return Integer.parseInt(value); + } catch (NumberFormatException e) { + throw new IncompatibleTypeException(value, "int"); + } + } + } + + /** + * Returns the double at the given key. If this table does not have a value + * for that position, then the given backup value will be returned. + * + * @param key the key + * @param backup the value to return if none exists in the table + * @return either the value in the table, or the backup + * @throws IncompatibleTypeException if the value in the table can not be + * converted to an double + */ + public double getDouble(String key, double backup) { + String value = get(key); + if (value == null) { + return backup; + } else { + try { + return Double.parseDouble(value); + } catch (NumberFormatException e) { + throw new IncompatibleTypeException(value, "double"); + } + } + } + + /** + * Returns the boolean at the given key. If this table does not have a value + * for that position, then the given backup value will be returned. + * + * @param key the key + * @param backup the value to return if none exists in the table + * @return either the value in the table, or the backup + * @throws IncompatibleTypeException if the value in the table can not be + * converted to a boolean + */ + public boolean getBoolean(String key, boolean backup) { + String value = get(key); + if (value == null) { + return backup; + } else { + if (value.equalsIgnoreCase("true")) { + return true; + } else if (value.equalsIgnoreCase("false")) { + return false; + } else { + throw new IncompatibleTypeException(value, "boolean"); + } + } + } + + /** + * Returns the float at the given key. If this table does not have a value for + * that position, then the given backup value will be returned. + * + * @param key the key + * @param backup the value to return if none exists in the table + * @return either the value in the table, or the backup + * @throws IncompatibleTypeException if the value in the table can not be + * converted to a float + */ + public float getFloat(String key, float backup) { + String value = get(key); + if (value == null) { + return backup; + } else { + try { + return Float.parseFloat(value); + } catch (NumberFormatException e) { + throw new IncompatibleTypeException(value, "float"); + } + } + } + + /** + * Returns the long at the given key. If this table does not have a value for + * that position, then the given backup value will be returned. + * + * @param key the key + * @param backup the value to return if none exists in the table + * @return either the value in the table, or the backup + * @throws IncompatibleTypeException if the value in the table can not be + * converted to a long + */ + public long getLong(String key, long backup) { + String value = get(key); + if (value == null) { + put(key, String.valueOf(backup)); + return backup; + } else { + try { + return Long.parseLong(value); + } catch (NumberFormatException e) { + throw new IncompatibleTypeException(value, "long"); + } + } + } + + /** + * Saves the preferences to a file on the RoboRIO. + * + *

+ * This should NOT be called often. Too many writes can damage the + * RoboRIO's flash memory. While it is ok to save once or twice a match, this + * should never be called every run of {@link IterativeRobot#teleopPeriodic()} + * . + *

+ * + *

+ * The actual writing of the file is done in a separate thread. However, any + * call to a get or put method will wait until the table is fully saved before + * continuing. + *

+ */ + public void save() { + synchronized (fileLock) { + new Thread() { + public void run() { + write(); } - - UsageReporting.report(tResourceType.kResourceType_Preferences, 0); + }.start(); + try { + fileLock.wait(); + } catch (InterruptedException ex) { + } } + } - /** - * @return a vector of the keys - */ - public Vector getKeys() { - synchronized (lock) { - return keys; - } - } + /** + * Internal method that actually writes the table to a file. This is called in + * its own thread when {@link Preferences#save() save()} is called. + */ + private void write() { + synchronized (lock) { + synchronized (fileLock) { + fileLock.notifyAll(); + } - /** - * Puts the given value into the given key position - * - * @param key the key - * @param value the value - * @throws ImproperPreferenceKeyException if the key contains an illegal - * character - */ - private void put(String key, String value) { - synchronized (lock) { - if (key == null) { - throw new NullPointerException(); - } - ImproperPreferenceKeyException.confirmString(key); - if (values.put(key, value) == null) { - keys.addElement(key); - } - NetworkTable.getTable(TABLE_NAME).putString(key, value); - } - } + File file = null; + FileOutputStream output = null; + try { + file = new File(FILE_NAME); - /** - * Puts the given string into the preferences table. - * - *

The value may not have quotation marks, nor may the key have any - * whitespace nor an equals sign

- * - *

This will NOT save the value to memory between power cycles, to - * do that you must call {@link Preferences#save() save()} (which must be - * used with care). at some point after calling this.

- * - * @param key the key - * @param value the value - * @throws NullPointerException if value is null - * @throws IllegalArgumentException if value contains a quotation mark - * @throws ImproperPreferenceKeyException if the key contains any whitespace - * or an equals sign - */ - public void putString(String key, String value) { - if (value == null) { - throw new NullPointerException(); - } - if (value.indexOf('"') != -1) { - throw new IllegalArgumentException("Can not put string:" + value + " because it contains quotation marks"); - } - put(key, value); - } + if (file.exists()) + file.delete(); - /** - * Puts the given int into the preferences table. - * - *

The key may not have any whitespace nor an equals sign

- * - *

This will NOT save the value to memory between power cycles, to - * do that you must call {@link Preferences#save() save()} (which must be - * used with care) at some point after calling this.

- * - * @param key the key - * @param value the value - * @throws ImproperPreferenceKeyException if the key contains any whitespace - * or an equals sign - */ - public void putInt(String key, int value) { - put(key, String.valueOf(value)); - } + file.createNewFile(); - /** - * Puts the given double into the preferences table. - * - *

The key may not have any whitespace nor an equals sign

- * - *

This will NOT save the value to memory between power cycles, to - * do that you must call {@link Preferences#save() save()} (which must be - * used with care) at some point after calling this.

- * - * @param key the key - * @param value the value - * @throws ImproperPreferenceKeyException if the key contains any whitespace - * or an equals sign - */ - public void putDouble(String key, double value) { - put(key, String.valueOf(value)); - } + output = new FileOutputStream(file); - /** - * Puts the given float into the preferences table. - * - *

The key may not have any whitespace nor an equals sign

- * - *

This will NOT save the value to memory between power cycles, to - * do that you must call {@link Preferences#save() save()} (which must be - * used with care) at some point after calling this.

- * - * @param key the key - * @param value the value - * @throws ImproperPreferenceKeyException if the key contains any whitespace - * or an equals sign - */ - public void putFloat(String key, float value) { - put(key, String.valueOf(value)); - } + output.write("[Preferences]\n".getBytes()); - /** - * Puts the given boolean into the preferences table. - * - *

The key may not have any whitespace nor an equals sign

- * - *

This will NOT save the value to memory between power cycles, to - * do that you must call {@link Preferences#save() save()} (which must be - * used with care) at some point after calling this.

- * - * @param key the key - * @param value the value - * @throws ImproperPreferenceKeyException if the key contains any whitespace - * or an equals sign - */ - public void putBoolean(String key, boolean value) { - put(key, String.valueOf(value)); - } - - /** - * Puts the given long into the preferences table. - * - *

The key may not have any whitespace nor an equals sign

- * - *

This will NOT save the value to memory between power cycles, to - * do that you must call {@link Preferences#save() save()} (which must be - * used with care) at some point after calling this.

- * - * @param key the key - * @param value the value - * @throws ImproperPreferenceKeyException if the key contains any whitespace - * or an equals sign - */ - public void putLong(String key, long value) { - put(key, String.valueOf(value)); - } - - /** - * Returns the value at the given key. - * - * @param key the key - * @return the value (or null if none exists) - * @throws NullPointerException if the key is null - */ - private String get(String key) { - synchronized (lock) { - if (key == null) { - throw new NullPointerException(); - } - return (String) values.get(key); - } - } - - /** - * Returns whether or not there is a key with the given name. - * - * @param key the key - * @return if there is a value at the given key - * @throws NullPointerException if key is null - */ - public boolean containsKey(String key) { - return get(key) != null; - } - - /** - * Remove a preference - * - * @param key the key - * @throws NullPointerException if key is null - */ - public void remove(String key) { - synchronized (lock) { - if (key == null) { - throw new NullPointerException(); - } - values.remove(key); - keys.removeElement(key); - } - } - - /** - * Returns the string at the given key. If this table does not have a value - * for that position, then the given backup value will be returned. - * - * @param key the key - * @param backup the value to return if none exists in the table - * @return either the value in the table, or the backup - * @throws NullPointerException if the key is null - */ - public String getString(String key, String backup) { - String value = get(key); - return value == null ? backup : value; - } - - /** - * Returns the int at the given key. If this table does not have a value for - * that position, then the given backup value will be returned. - * - * @param key the key - * @param backup the value to return if none exists in the table - * @return either the value in the table, or the backup - * @throws IncompatibleTypeException if the value in the table can not be - * converted to an int - */ - public int getInt(String key, int backup) { - String value = get(key); - if (value == null) { - return backup; - } else { - try { - return Integer.parseInt(value); - } catch (NumberFormatException e) { - throw new IncompatibleTypeException(value, "int"); - } - } - } - - /** - * Returns the double at the given key. If this table does not have a value - * for that position, then the given backup value will be returned. - * - * @param key the key - * @param backup the value to return if none exists in the table - * @return either the value in the table, or the backup - * @throws IncompatibleTypeException if the value in the table can not be - * converted to an double - */ - public double getDouble(String key, double backup) { - String value = get(key); - if (value == null) { - return backup; - } else { - try { - return Double.parseDouble(value); - } catch (NumberFormatException e) { - throw new IncompatibleTypeException(value, "double"); - } - } - } - - /** - * Returns the boolean at the given key. If this table does not have a value - * for that position, then the given backup value will be returned. - * - * @param key the key - * @param backup the value to return if none exists in the table - * @return either the value in the table, or the backup - * @throws IncompatibleTypeException if the value in the table can not be - * converted to a boolean - */ - public boolean getBoolean(String key, boolean backup) { - String value = get(key); - if (value == null) { - return backup; - } else { - if (value.equalsIgnoreCase("true")) { - return true; - } else if (value.equalsIgnoreCase("false")) { - return false; - } else { - throw new IncompatibleTypeException(value, "boolean"); - } - } - } - - /** - * Returns the float at the given key. If this table does not have a value - * for that position, then the given backup value will be returned. - * - * @param key the key - * @param backup the value to return if none exists in the table - * @return either the value in the table, or the backup - * @throws IncompatibleTypeException if the value in the table can not be - * converted to a float - */ - public float getFloat(String key, float backup) { - String value = get(key); - if (value == null) { - return backup; - } else { - try { - return Float.parseFloat(value); - } catch (NumberFormatException e) { - throw new IncompatibleTypeException(value, "float"); - } - } - } - - /** - * Returns the long at the given key. If this table does not have a value - * for that position, then the given backup value will be returned. - * - * @param key the key - * @param backup the value to return if none exists in the table - * @return either the value in the table, or the backup - * @throws IncompatibleTypeException if the value in the table can not be - * converted to a long - */ - public long getLong(String key, long backup) { - String value = get(key); - if (value == null) { - put(key, String.valueOf(backup)); - return backup; - } else { - try { - return Long.parseLong(value); - } catch (NumberFormatException e) { - throw new IncompatibleTypeException(value, "long"); - } - } - } - - /** - * Saves the preferences to a file on the RoboRIO. - * - *

This should NOT be called often. Too many writes can damage the - * RoboRIO's flash memory. While it is ok to save once or twice a match, this - * should never be called every run of - * {@link IterativeRobot#teleopPeriodic()}.

- * - *

The actual writing of the file is done in a separate thread. However, - * any call to a get or put method will wait until the table is fully saved - * before continuing.

- */ - public void save() { - synchronized (fileLock) { - new Thread() { - public void run() { - write(); - } - } .start(); - try { - fileLock.wait(); - } catch (InterruptedException ex) { - } - } - } - - /** - * Internal method that actually writes the table to a file. This is called - * in its own thread when {@link Preferences#save() save()} is called. - */ - private void write() { - synchronized (lock) { - synchronized (fileLock) { - fileLock.notifyAll(); - } - - File file = null; - FileOutputStream output = null; - try { - file = new File(FILE_NAME); - - if (file.exists()) - file.delete(); - - file.createNewFile(); - - output = new FileOutputStream(file); - - output.write("[Preferences]\n".getBytes()); - - for (int i = 0; i < keys.size(); i++) { - String key = (String) keys.elementAt(i); - String value = (String) values.get(key); - - if (comments != null) { - Comment comment = (Comment) comments.get(key); - if (comment != null) { - comment.write(output); - } - } - - output.write(key.getBytes()); - output.write(VALUE_PREFIX); - output.write(value.getBytes()); - output.write(VALUE_SUFFIX); - } - - if (endComment != null) { - endComment.write(output); - } - } catch (IOException ex) { - ex.printStackTrace(); - } finally { - if (output != null) { - try { - output.close(); - } catch (IOException ex) { - } - } - NetworkTable.getTable(TABLE_NAME).putBoolean(SAVE_FIELD, false); - } - } - } - - /** - * The internal method to read from a file. This will be called in its own - * thread when the preferences singleton is first created. - */ - private void read() { - class EndOfStreamException extends Exception { - } - - class Reader { - - InputStream stream; - - Reader(InputStream stream) { - this.stream = stream; - } - - public char read() throws IOException, EndOfStreamException { - int input = stream.read(); - if (input == -1) { - throw new EndOfStreamException(); - } else { - // Check for carriage returns - return input == '\r' ? '\n' : (char) input; - } - } - - char readWithoutWhitespace() throws IOException, EndOfStreamException { - while (true) { - char value = read(); - switch (value) { - case ' ': - case '\t': - continue; - default: - return value; - } - } - } - } - - synchronized (lock) { - synchronized (fileLock) { - fileLock.notifyAll(); - } - - Comment comment = null; - - - - File file = null; - FileInputStream input = null; - try { - file = new File(FILE_NAME); - - if (file.exists()) { - input = new FileInputStream(file); - Reader reader = new Reader(input); - - StringBuffer buffer; - - while (true) { - char value = reader.readWithoutWhitespace(); - - if (value == '\n' || value == ';') { - if (comment == null) { - comment = new Comment(); - } - - if (value == '\n') { - comment.addBytes(NEW_LINE); - } else { - buffer = new StringBuffer(30); - for (; value != '\n'; value = reader.read()) { - buffer.append(value); - } - buffer.append('\n'); - comment.addBytes(buffer.toString().getBytes()); - } - } else if (value == '[') { - // Find the end of the section and the new line after it and throw it away - while (reader.read() !=']'); - while (reader.read() != '\n'); - } else { - buffer = new StringBuffer(30); - for (; value != '='; value = reader.readWithoutWhitespace()) { - buffer.append(value); - } - String name = buffer.toString(); - buffer = new StringBuffer(30); - - boolean shouldBreak = false; - - value = reader.readWithoutWhitespace(); - if (value == '"') { - for (value = reader.read(); value != '"'; value = reader.read()) { - buffer.append(value); - } - // Clear the line - while (reader.read() != '\n'); - } else { - try { - for (; value != '\n'; value = reader.readWithoutWhitespace()) { - buffer.append(value); - } - } catch (EndOfStreamException e) { - shouldBreak = true; - } - } - - String result = buffer.toString(); - - keys.addElement(name); - values.put(name, result); - NetworkTable.getTable(TABLE_NAME).putString(name, result); - - if (comment != null) { - if (comments == null) { - comments = new Hashtable(); - } - comments.put(name, comment); - comment = null; - } - - - if (shouldBreak) { - break; - } - } - } - } - } catch (IOException ex) { - ex.printStackTrace(); - } catch (EndOfStreamException ex) { - System.out.println("Done Reading"); - } - - if (input != null) { - try { - input.close(); - } catch (IOException ex) { - } - } + for (int i = 0; i < keys.size(); i++) { + String key = (String) keys.elementAt(i); + String value = (String) values.get(key); + if (comments != null) { + Comment comment = (Comment) comments.get(key); if (comment != null) { - endComment = comment; + comment.write(output); } + } + + output.write(key.getBytes()); + output.write(VALUE_PREFIX); + output.write(value.getBytes()); + output.write(VALUE_SUFFIX); } + if (endComment != null) { + endComment.write(output); + } + } catch (IOException ex) { + ex.printStackTrace(); + } finally { + if (output != null) { + try { + output.close(); + } catch (IOException ex) { + } + } NetworkTable.getTable(TABLE_NAME).putBoolean(SAVE_FIELD, false); - // TODO: Verify that this works even though it changes with subtables. - // Should work since preferences shouldn't have subtables. - NetworkTable.getTable(TABLE_NAME).addTableListener(new ITableListener() { - public void valueChanged(ITable source, String key, Object value, boolean isNew) { - if (key.equals(SAVE_FIELD)) { - if (((Boolean) value).booleanValue()) { - save(); - } - } else { - synchronized (lock) { - if (!ImproperPreferenceKeyException.isAcceptable(key) || value.toString().indexOf('"') != -1) { - if (values.contains(key) || keys.contains(key)) { - values.remove(key); - keys.removeElement(key); - NetworkTable.getTable(TABLE_NAME).putString(key, "\""); - } - } else { - if (values.put(key, value.toString()) == null) { - keys.addElement(key); - } - } - } + } + } + } + + /** + * The internal method to read from a file. This will be called in its own + * thread when the preferences singleton is first created. + */ + private void read() { + class EndOfStreamException extends Exception { + } + + class Reader { + + InputStream stream; + + Reader(InputStream stream) { + this.stream = stream; + } + + public char read() throws IOException, EndOfStreamException { + int input = stream.read(); + if (input == -1) { + throw new EndOfStreamException(); + } else { + // Check for carriage returns + return input == '\r' ? '\n' : (char) input; + } + } + + char readWithoutWhitespace() throws IOException, EndOfStreamException { + while (true) { + char value = read(); + switch (value) { + case ' ': + case '\t': + continue; + default: + return value; + } + } + } + } + + synchronized (lock) { + synchronized (fileLock) { + fileLock.notifyAll(); + } + + Comment comment = null; + + + + File file = null; + FileInputStream input = null; + try { + file = new File(FILE_NAME); + + if (file.exists()) { + input = new FileInputStream(file); + Reader reader = new Reader(input); + + StringBuffer buffer; + + while (true) { + char value = reader.readWithoutWhitespace(); + + if (value == '\n' || value == ';') { + if (comment == null) { + comment = new Comment(); + } + + if (value == '\n') { + comment.addBytes(NEW_LINE); + } else { + buffer = new StringBuffer(30); + for (; value != '\n'; value = reader.read()) { + buffer.append(value); } + buffer.append('\n'); + comment.addBytes(buffer.toString().getBytes()); + } + } else if (value == '[') { + // Find the end of the section and the new line after it and throw + // it away + while (reader.read() != ']'); + while (reader.read() != '\n'); + } else { + buffer = new StringBuffer(30); + for (; value != '='; value = reader.readWithoutWhitespace()) { + buffer.append(value); + } + String name = buffer.toString(); + buffer = new StringBuffer(30); + + boolean shouldBreak = false; + + value = reader.readWithoutWhitespace(); + if (value == '"') { + for (value = reader.read(); value != '"'; value = reader.read()) { + buffer.append(value); + } + // Clear the line + while (reader.read() != '\n'); + } else { + try { + for (; value != '\n'; value = reader.readWithoutWhitespace()) { + buffer.append(value); + } + } catch (EndOfStreamException e) { + shouldBreak = true; + } + } + + String result = buffer.toString(); + + keys.addElement(name); + values.put(name, result); + NetworkTable.getTable(TABLE_NAME).putString(name, result); + + if (comment != null) { + if (comments == null) { + comments = new Hashtable(); + } + comments.put(name, comment); + comment = null; + } + + + if (shouldBreak) { + break; + } } - }); + } + } + } catch (IOException ex) { + ex.printStackTrace(); + } catch (EndOfStreamException ex) { + System.out.println("Done Reading"); + } + + if (input != null) { + try { + input.close(); + } catch (IOException ex) { + } + } + + if (comment != null) { + endComment = comment; + } + } + + NetworkTable.getTable(TABLE_NAME).putBoolean(SAVE_FIELD, false); + // TODO: Verify that this works even though it changes with subtables. + // Should work since preferences shouldn't have subtables. + NetworkTable.getTable(TABLE_NAME).addTableListener(new ITableListener() { + public void valueChanged(ITable source, String key, Object value, boolean isNew) { + if (key.equals(SAVE_FIELD)) { + if (((Boolean) value).booleanValue()) { + save(); + } + } else { + synchronized (lock) { + if (!ImproperPreferenceKeyException.isAcceptable(key) + || value.toString().indexOf('"') != -1) { + if (values.contains(key) || keys.contains(key)) { + values.remove(key); + keys.removeElement(key); + NetworkTable.getTable(TABLE_NAME).putString(key, "\""); + } + } else { + if (values.put(key, value.toString()) == null) { + keys.addElement(key); + } + } + } + } + } + }); + } + + /** + * A class representing some comment lines in the ini file. This is used so + * that if a programmer ever directly modifies the ini file, then his/her + * comments will still be there after {@link Preferences#save() save()} is + * called. + */ + private static class Comment { + + /** + * A vector of byte arrays. Each array represents a line to write + */ + private Vector bytes = new Vector(); + + /** + * Appends the given bytes to the comment. + * + * @param bytes the bytes to add + */ + private void addBytes(byte[] bytes) { + this.bytes.addElement(bytes); } /** - * A class representing some comment lines in the ini file. This is used so - * that if a programmer ever directly modifies the ini file, then his/her - * comments will still be there after {@link Preferences#save() save()} is - * called. + * Writes this comment to the given stream + * + * @param stream the stream to write to + * @throws IOException if the stream has a problem */ - private static class Comment { + private void write(OutputStream stream) throws IOException { + for (int i = 0; i < bytes.size(); i++) { + stream.write((byte[]) bytes.elementAt(i)); + } + } + } - /** - * A vector of byte arrays. Each array represents a line to write - */ - private Vector bytes = new Vector(); + /** + * This exception is thrown if the a value requested cannot be converted to + * the requested type. + */ + public static class IncompatibleTypeException extends RuntimeException { - /** - * Appends the given bytes to the comment. - * - * @param bytes the bytes to add - */ - private void addBytes(byte[] bytes) { - this.bytes.addElement(bytes); - } + /** + * Creates an exception with a description based on the input + * + * @param value the value that can not be converted + * @param type the type that the value can not be converted to + */ + public IncompatibleTypeException(String value, String type) { + super("Cannot convert \"" + value + "\" into " + type); + } + } - /** - * Writes this comment to the given stream - * - * @param stream the stream to write to - * @throws IOException if the stream has a problem - */ - private void write(OutputStream stream) throws IOException { - for (int i = 0; i < bytes.size(); i++) { - stream.write((byte[]) bytes.elementAt(i)); - } - } + /** + * Should be thrown if a string can not be used as a key in the preferences + * file. This happens if the string contains a new line, a space, a tab, or an + * equals sign. + */ + public static class ImproperPreferenceKeyException extends RuntimeException { + + /** + * Instantiates an exception with a descriptive message based on the input. + * + * @param value the illegal key + * @param letter the specific character that made it illegal + */ + public ImproperPreferenceKeyException(String value, char letter) { + super("Preference key \"" + value + "\" is not allowed to contain letter with ASCII code:" + + (byte) letter); } /** - * This exception is thrown if the a value requested cannot be converted to - * the requested type. + * Tests if the given string is ok to use as a key in the preference table. + * If not, then a {@link ImproperPreferenceKeyException} will be thrown. + * + * @param value the value to test */ - public static class IncompatibleTypeException extends RuntimeException { - - /** - * Creates an exception with a description based on the input - * - * @param value the value that can not be converted - * @param type the type that the value can not be converted to - */ - public IncompatibleTypeException(String value, String type) { - super("Cannot convert \"" + value + "\" into " + type); + public static void confirmString(String value) { + for (int i = 0; i < value.length(); i++) { + char letter = value.charAt(i); + switch (letter) { + case '=': + case '\n': + case '\r': + case ' ': + case '\t': + case '[': + case ']': + throw new ImproperPreferenceKeyException(value, letter); } + } } /** - * Should be thrown if a string can not be used as a key in the preferences - * file. This happens if the string contains a new line, a space, a tab, or - * an equals sign. + * Returns whether or not the given string is ok to use in the preference + * table. + * + * @param value the string to check + * @return true if the given string is ok to use in the preference table */ - public static class ImproperPreferenceKeyException extends RuntimeException { - - /** - * Instantiates an exception with a descriptive message based on the - * input. - * - * @param value the illegal key - * @param letter the specific character that made it illegal - */ - public ImproperPreferenceKeyException(String value, char letter) { - super("Preference key \"" - + value + "\" is not allowed to contain letter with ASCII code:" + (byte) letter); - } - - /** - * Tests if the given string is ok to use as a key in the preference - * table. If not, then a {@link ImproperPreferenceKeyException} will be - * thrown. - * - * @param value the value to test - */ - public static void confirmString(String value) { - for (int i = 0; i < value.length(); i++) { - char letter = value.charAt(i); - switch (letter) { - case '=': - case '\n': - case '\r': - case ' ': - case '\t': - case '[': - case ']': - throw new ImproperPreferenceKeyException(value, letter); - } - } - } - - /** - * Returns whether or not the given string is ok to use in the - * preference table. - * - * @param value the string to check - * @return true if the given string is ok to use in the preference table - */ - public static boolean isAcceptable(String value) { - for (int i = 0; i < value.length(); i++) { - char letter = value.charAt(i); - switch (letter) { - case '=': - case '\n': - case '\r': - case ' ': - case '\t': - case '[': - case ']': - return false; - } - } - return true; + public static boolean isAcceptable(String value) { + for (int i = 0; i < value.length(); i++) { + char letter = value.charAt(i); + switch (letter) { + case '=': + case '\n': + case '\r': + case ' ': + case '\t': + case '[': + case ']': + return false; } + } + return true; } + } } diff --git a/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/Relay.java b/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/Relay.java index 8d2d06d37c..f48adf62a2 100644 --- a/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/Relay.java +++ b/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/Relay.java @@ -1,8 +1,8 @@ /*----------------------------------------------------------------------------*/ -/* Copyright (c) FIRST 2008-2012. All Rights Reserved. */ -/* Open Source Software - may be modified and shared by FRC teams. The code */ +/* Copyright (c) FIRST 2008-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 the root directory of */ -/* the project. */ +/* the project. */ /*----------------------------------------------------------------------------*/ package edu.wpi.first.wpilibj; @@ -34,378 +34,361 @@ import edu.wpi.first.wpilibj.util.CheckedAllocationException; */ public class Relay extends SensorBase implements LiveWindowSendable { - /** - * This class represents errors in trying to set relay values contradictory - * to the direction to which the relay is set. - */ - public class InvalidValueException extends RuntimeException { + /** + * This class represents errors in trying to set relay values contradictory to + * the direction to which the relay is set. + */ + public class InvalidValueException extends RuntimeException { - /** - * Create a new exception with the given message - * - * @param message - * the message to pass with the exception - */ - public InvalidValueException(String message) { - super(message); - } - } + /** + * Create a new exception with the given message + * + * @param message the message to pass with the exception + */ + public InvalidValueException(String message) { + super(message); + } + } - /** - * The state to drive a Relay to. - */ - public static enum Value { - /** - * value: off - */ - kOff(0), - /** - * value: on for relays with defined direction - */ - kOn(1), - /** - * value: forward - */ - kForward(2), - /** - * value: reverse - */ - kReverse(3); + /** + * The state to drive a Relay to. + */ + public static enum Value { + /** + * value: off + */ + kOff(0), + /** + * value: on for relays with defined direction + */ + kOn(1), + /** + * value: forward + */ + kForward(2), + /** + * value: reverse + */ + kReverse(3); - /** - * The integer value representing this enumeration - */ - public final int value; + /** + * The integer value representing this enumeration + */ + public final int value; - private Value(int value) { - this.value = value; - } - } + private Value(int value) { + this.value = value; + } + } - /** - * The Direction(s) that a relay is configured to operate in. - */ - public static enum Direction { - /** - * direction: both directions are valid - */ + /** + * The Direction(s) that a relay is configured to operate in. + */ + public static enum Direction { + /** + * direction: both directions are valid + */ - kBoth(0), - /** - * direction: Only forward is valid - */ - kForward(1), - /** - * direction: only reverse is valid - */ - kReverse(2); + kBoth(0), + /** + * direction: Only forward is valid + */ + kForward(1), + /** + * direction: only reverse is valid + */ + kReverse(2); - /** - * The integer value representing this enumeration - */ - public final int value; + /** + * The integer value representing this enumeration + */ + public final int value; - private Direction(int value) { - this.value = value; - } + private Direction(int value) { + this.value = value; + } - } + } - private final int m_channel; - private ByteBuffer m_port; + private final int m_channel; + private ByteBuffer m_port; - private Direction m_direction; - private static Resource relayChannels = new Resource(kRelayChannels * 2); + private Direction m_direction; + private static Resource relayChannels = new Resource(kRelayChannels * 2); - /** - * Common relay initialization method. This code is common to all Relay - * constructors and initializes the relay and reserves all resources that - * need to be locked. Initially the relay is set to both lines at 0v. - */ - private void initRelay() { - SensorBase.checkRelayChannel(m_channel); - try { - if (m_direction == Direction.kBoth - || m_direction == Direction.kForward) { - relayChannels.allocate(m_channel * 2); - UsageReporting.report(tResourceType.kResourceType_Relay, m_channel); - } - if (m_direction == Direction.kBoth - || m_direction == Direction.kReverse) { - relayChannels.allocate(m_channel * 2 + 1); - UsageReporting.report(tResourceType.kResourceType_Relay, m_channel + 128); - } - } catch (CheckedAllocationException e) { - throw new AllocationException("Relay channel " + m_channel + " is already allocated"); - } + /** + * Common relay initialization method. This code is common to all Relay + * constructors and initializes the relay and reserves all resources that need + * to be locked. Initially the relay is set to both lines at 0v. + */ + private void initRelay() { + SensorBase.checkRelayChannel(m_channel); + try { + if (m_direction == Direction.kBoth || m_direction == Direction.kForward) { + relayChannels.allocate(m_channel * 2); + UsageReporting.report(tResourceType.kResourceType_Relay, m_channel); + } + if (m_direction == Direction.kBoth || m_direction == Direction.kReverse) { + relayChannels.allocate(m_channel * 2 + 1); + UsageReporting.report(tResourceType.kResourceType_Relay, m_channel + 128); + } + } catch (CheckedAllocationException e) { + throw new AllocationException("Relay channel " + m_channel + " is already allocated"); + } - ByteBuffer status = ByteBuffer.allocateDirect(4); - status.order(ByteOrder.LITTLE_ENDIAN); + ByteBuffer status = ByteBuffer.allocateDirect(4); + status.order(ByteOrder.LITTLE_ENDIAN); - m_port = DIOJNI.initializeDigitalPort(DIOJNI.getPort((byte) m_channel), status.asIntBuffer()); - HALUtil.checkStatus(status.asIntBuffer()); + m_port = DIOJNI.initializeDigitalPort(DIOJNI.getPort((byte) m_channel), status.asIntBuffer()); + HALUtil.checkStatus(status.asIntBuffer()); - LiveWindow.addActuator("Relay", m_channel, this); - } + LiveWindow.addActuator("Relay", m_channel, this); + } - /** - * Relay constructor given a channel. - * - * @param channel - * The channel number for this relay (0 - 3). - * @param direction - * The direction that the Relay object will control. - */ - public Relay(final int channel, Direction direction) { - if (direction == null) - throw new NullPointerException("Null Direction was given"); - m_channel = channel; - m_direction = direction; - initRelay(); - set(Value.kOff); - } + /** + * Relay constructor given a channel. + * + * @param channel The channel number for this relay (0 - 3). + * @param direction The direction that the Relay object will control. + */ + public Relay(final int channel, Direction direction) { + if (direction == null) + throw new NullPointerException("Null Direction was given"); + m_channel = channel; + m_direction = direction; + initRelay(); + set(Value.kOff); + } - /** - * Relay constructor given a channel, allowing both directions. - * - * @param channel - * The channel number for this relay (0 - 3). - */ - public Relay(final int channel) { - this(channel, Direction.kBoth); - } + /** + * Relay constructor given a channel, allowing both directions. + * + * @param channel The channel number for this relay (0 - 3). + */ + public Relay(final int channel) { + this(channel, Direction.kBoth); + } - @Override - public void free() { - if (m_direction == Direction.kBoth || m_direction == Direction.kForward) { - relayChannels.free(m_channel*2); - } - if (m_direction == Direction.kBoth || m_direction == Direction.kReverse) { - relayChannels.free(m_channel*2 + 1); - } + @Override + public void free() { + if (m_direction == Direction.kBoth || m_direction == Direction.kForward) { + relayChannels.free(m_channel * 2); + } + if (m_direction == Direction.kBoth || m_direction == Direction.kReverse) { + relayChannels.free(m_channel * 2 + 1); + } - ByteBuffer status = ByteBuffer.allocateDirect(4); - status.order(ByteOrder.LITTLE_ENDIAN); + ByteBuffer status = ByteBuffer.allocateDirect(4); + status.order(ByteOrder.LITTLE_ENDIAN); - RelayJNI.setRelayForward(m_port, (byte) 0, status.asIntBuffer()); - HALUtil.checkStatus(status.asIntBuffer()); - RelayJNI.setRelayReverse(m_port, (byte) 0, status.asIntBuffer()); - HALUtil.checkStatus(status.asIntBuffer()); + RelayJNI.setRelayForward(m_port, (byte) 0, status.asIntBuffer()); + HALUtil.checkStatus(status.asIntBuffer()); + RelayJNI.setRelayReverse(m_port, (byte) 0, status.asIntBuffer()); + HALUtil.checkStatus(status.asIntBuffer()); - DIOJNI.freeDIO(m_port, status.asIntBuffer()); - HALUtil.checkStatus(status.asIntBuffer()); - } + DIOJNI.freeDIO(m_port, status.asIntBuffer()); + HALUtil.checkStatus(status.asIntBuffer()); + } - /** - * Set the relay state. - * - * Valid values depend on which directions of the relay are controlled by - * the object. - * - * When set to kBothDirections, the relay can be set to any of the four - * states: 0v-0v, 12v-0v, 0v-12v, 12v-12v - * - * When set to kForwardOnly or kReverseOnly, you can specify the constant - * for the direction or you can simply specify kOff_val and kOn_val. Using - * only kOff_val and kOn_val is recommended. - * - * @param value - * The state to set the relay. - */ - public void set(Value value) { - ByteBuffer status = ByteBuffer.allocateDirect(4); - status.order(ByteOrder.LITTLE_ENDIAN); + /** + * Set the relay state. + * + * Valid values depend on which directions of the relay are controlled by the + * object. + * + * When set to kBothDirections, the relay can be set to any of the four + * states: 0v-0v, 12v-0v, 0v-12v, 12v-12v + * + * When set to kForwardOnly or kReverseOnly, you can specify the constant for + * the direction or you can simply specify kOff_val and kOn_val. Using only + * kOff_val and kOn_val is recommended. + * + * @param value The state to set the relay. + */ + public void set(Value value) { + ByteBuffer status = ByteBuffer.allocateDirect(4); + status.order(ByteOrder.LITTLE_ENDIAN); - switch (value) { - case kOff: - if (m_direction == Direction.kBoth - || m_direction == Direction.kForward) { - RelayJNI.setRelayForward(m_port, (byte) 0, status.asIntBuffer()); - } - if (m_direction == Direction.kBoth - || m_direction == Direction.kReverse) { - RelayJNI.setRelayReverse(m_port, (byte) 0, status.asIntBuffer()); - } - break; - case kOn: - if (m_direction == Direction.kBoth - || m_direction == Direction.kForward) { - RelayJNI.setRelayForward(m_port, (byte) 1, status.asIntBuffer()); - } - if (m_direction == Direction.kBoth - || m_direction == Direction.kReverse) { - RelayJNI.setRelayReverse(m_port, (byte) 1, status.asIntBuffer()); - } - break; - case kForward: - if (m_direction == Direction.kReverse) - throw new InvalidValueException( - "A relay configured for reverse cannot be set to forward"); - if (m_direction == Direction.kBoth - || m_direction == Direction.kForward) { - RelayJNI.setRelayForward(m_port, (byte) 1, status.asIntBuffer()); - } - if (m_direction == Direction.kBoth) { - RelayJNI.setRelayReverse(m_port, (byte) 0, status.asIntBuffer()); - } - break; - case kReverse: - if (m_direction == Direction.kForward) - throw new InvalidValueException( - "A relay configured for forward cannot be set to reverse"); - if (m_direction == Direction.kBoth) { - RelayJNI.setRelayForward(m_port, (byte) 0, status.asIntBuffer()); - } - if (m_direction == Direction.kBoth - || m_direction == Direction.kReverse) { - RelayJNI.setRelayReverse(m_port, (byte) 1, status.asIntBuffer()); - } - break; - default: - // Cannot hit this, limited by Value enum - } + switch (value) { + case kOff: + if (m_direction == Direction.kBoth || m_direction == Direction.kForward) { + RelayJNI.setRelayForward(m_port, (byte) 0, status.asIntBuffer()); + } + if (m_direction == Direction.kBoth || m_direction == Direction.kReverse) { + RelayJNI.setRelayReverse(m_port, (byte) 0, status.asIntBuffer()); + } + break; + case kOn: + if (m_direction == Direction.kBoth || m_direction == Direction.kForward) { + RelayJNI.setRelayForward(m_port, (byte) 1, status.asIntBuffer()); + } + if (m_direction == Direction.kBoth || m_direction == Direction.kReverse) { + RelayJNI.setRelayReverse(m_port, (byte) 1, status.asIntBuffer()); + } + break; + case kForward: + if (m_direction == Direction.kReverse) + throw new InvalidValueException("A relay configured for reverse cannot be set to forward"); + if (m_direction == Direction.kBoth || m_direction == Direction.kForward) { + RelayJNI.setRelayForward(m_port, (byte) 1, status.asIntBuffer()); + } + if (m_direction == Direction.kBoth) { + RelayJNI.setRelayReverse(m_port, (byte) 0, status.asIntBuffer()); + } + break; + case kReverse: + if (m_direction == Direction.kForward) + throw new InvalidValueException("A relay configured for forward cannot be set to reverse"); + if (m_direction == Direction.kBoth) { + RelayJNI.setRelayForward(m_port, (byte) 0, status.asIntBuffer()); + } + if (m_direction == Direction.kBoth || m_direction == Direction.kReverse) { + RelayJNI.setRelayReverse(m_port, (byte) 1, status.asIntBuffer()); + } + break; + default: + // Cannot hit this, limited by Value enum + } - HALUtil.checkStatus(status.asIntBuffer()); - } + HALUtil.checkStatus(status.asIntBuffer()); + } - /** - * Get the Relay State - * - * Gets the current state of the relay. - * - * When set to kForwardOnly or kReverseOnly, value is returned as kOn/kOff - * not kForward/kReverse (per the recommendation in Set) - * - * @return The current state of the relay as a Relay::Value - */ - public Value get() { - ByteBuffer status = ByteBuffer.allocateDirect(4); - status.order(ByteOrder.LITTLE_ENDIAN); + /** + * Get the Relay State + * + * Gets the current state of the relay. + * + * When set to kForwardOnly or kReverseOnly, value is returned as kOn/kOff not + * kForward/kReverse (per the recommendation in Set) + * + * @return The current state of the relay as a Relay::Value + */ + public Value get() { + ByteBuffer status = ByteBuffer.allocateDirect(4); + status.order(ByteOrder.LITTLE_ENDIAN); - if (RelayJNI.getRelayForward(m_port, status.asIntBuffer()) != 0) { - if (RelayJNI.getRelayReverse(m_port, status.asIntBuffer()) != 0) { - return Value.kOn; - } else { - if (m_direction == Direction.kForward) { - return Value.kOn; - } else { - return Value.kForward; - } - } - } else { - if (RelayJNI.getRelayReverse(m_port, status.asIntBuffer()) != 0) { - if (m_direction == Direction.kReverse) { - return Value.kOn; - } else { - return Value.kReverse; - } - } else { - return Value.kOff; - } - } - } + if (RelayJNI.getRelayForward(m_port, status.asIntBuffer()) != 0) { + if (RelayJNI.getRelayReverse(m_port, status.asIntBuffer()) != 0) { + return Value.kOn; + } else { + if (m_direction == Direction.kForward) { + return Value.kOn; + } else { + return Value.kForward; + } + } + } else { + if (RelayJNI.getRelayReverse(m_port, status.asIntBuffer()) != 0) { + if (m_direction == Direction.kReverse) { + return Value.kOn; + } else { + return Value.kReverse; + } + } else { + return Value.kOff; + } + } + } - /** - * Set the Relay Direction - * - * Changes which values the relay can be set to depending on which direction - * is used - * - * Valid inputs are kBothDirections, kForwardOnly, and kReverseOnly - * - * @param direction - * The direction for the relay to operate in - */ - public void setDirection(Direction direction) { - if (direction == null) - throw new NullPointerException("Null Direction was given"); - if (m_direction == direction) { - return; - } + /** + * Set the Relay Direction + * + * Changes which values the relay can be set to depending on which direction + * is used + * + * Valid inputs are kBothDirections, kForwardOnly, and kReverseOnly + * + * @param direction The direction for the relay to operate in + */ + public void setDirection(Direction direction) { + if (direction == null) + throw new NullPointerException("Null Direction was given"); + if (m_direction == direction) { + return; + } - free(); + free(); - m_direction = direction; + m_direction = direction; - initRelay(); - } + initRelay(); + } - /* - * Live Window code, only does anything if live window is activated. - */ - @Override - public String getSmartDashboardType() { - return "Relay"; - } + /* + * Live Window code, only does anything if live window is activated. + */ + @Override + public String getSmartDashboardType() { + return "Relay"; + } - private ITable m_table; - private ITableListener m_table_listener; + private ITable m_table; + private ITableListener m_table_listener; - /** - * {@inheritDoc} - */ - @Override - public void initTable(ITable subtable) { - m_table = subtable; - updateTable(); - } + /** + * {@inheritDoc} + */ + @Override + public void initTable(ITable subtable) { + m_table = subtable; + updateTable(); + } - /** - * {@inheritDoc} - */ - @Override - public ITable getTable() { - return m_table; - } + /** + * {@inheritDoc} + */ + @Override + public ITable getTable() { + return m_table; + } - /** - * {@inheritDoc} - */ - @Override - public void updateTable() { - if (m_table != null) { - if (get() == Value.kOn) { - m_table.putString("Value", "On"); - } else if (get() == Value.kForward) { - m_table.putString("Value", "Forward"); - } else if (get() == Value.kReverse) { - m_table.putString("Value", "Reverse"); - } else { - m_table.putString("Value", "Off"); - } - } - } + /** + * {@inheritDoc} + */ + @Override + public void updateTable() { + if (m_table != null) { + if (get() == Value.kOn) { + m_table.putString("Value", "On"); + } else if (get() == Value.kForward) { + m_table.putString("Value", "Forward"); + } else if (get() == Value.kReverse) { + m_table.putString("Value", "Reverse"); + } else { + m_table.putString("Value", "Off"); + } + } + } - /** - * {@inheritDoc} - */ - @Override - public void startLiveWindowMode() { - m_table_listener = new ITableListener() { - @Override - public void valueChanged(ITable itable, String key, Object value, - boolean bln) { - String val = ((String) value); - if (val.equals("Off")) { - set(Value.kOff); - } else if (val.equals("On")) { - set(Value.kOn); - } else if (val.equals("Forward")) { - set(Value.kForward); - } else if (val.equals("Reverse")) { - set(Value.kReverse); - } - } - }; - m_table.addTableListener("Value", m_table_listener, true); - } + /** + * {@inheritDoc} + */ + @Override + public void startLiveWindowMode() { + m_table_listener = new ITableListener() { + @Override + public void valueChanged(ITable itable, String key, Object value, boolean bln) { + String val = ((String) value); + if (val.equals("Off")) { + set(Value.kOff); + } else if (val.equals("On")) { + set(Value.kOn); + } else if (val.equals("Forward")) { + set(Value.kForward); + } else if (val.equals("Reverse")) { + set(Value.kReverse); + } + } + }; + m_table.addTableListener("Value", m_table_listener, true); + } - /** - * {@inheritDoc} - */ - @Override - public void stopLiveWindowMode() { - // TODO: Broken, should only remove the listener from "Value" only. - m_table.removeTableListener(m_table_listener); - } + /** + * {@inheritDoc} + */ + @Override + public void stopLiveWindowMode() { + // TODO: Broken, should only remove the listener from "Value" only. + m_table.removeTableListener(m_table_listener); + } } diff --git a/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/Resource.java b/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/Resource.java index e6d2204990..e22c206e6f 100644 --- a/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/Resource.java +++ b/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/Resource.java @@ -1,8 +1,8 @@ /*----------------------------------------------------------------------------*/ -/* Copyright (c) FIRST 2008-2012. All Rights Reserved. */ -/* Open Source Software - may be modified and shared by FRC teams. The code */ +/* Copyright (c) FIRST 2008-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 the root directory of */ -/* the project. */ +/* the project. */ /*----------------------------------------------------------------------------*/ package edu.wpi.first.wpilibj; @@ -11,102 +11,105 @@ import edu.wpi.first.wpilibj.util.AllocationException; import edu.wpi.first.wpilibj.util.CheckedAllocationException; /** - * Track resources in the program. - * The Resource class is a convenient way of keeping track of allocated arbitrary resources - * in the program. Resources are just indicies that have an lower and upper bound that are - * tracked by this class. In the library they are used for tracking allocation of hardware channels - * but this is purely arbitrary. The resource class does not do any actual allocation, but - * simply tracks if a given index is currently in use. + * Track resources in the program. The Resource class is a convenient way of + * keeping track of allocated arbitrary resources in the program. Resources are + * just indicies that have an lower and upper bound that are tracked by this + * class. In the library they are used for tracking allocation of hardware + * channels but this is purely arbitrary. The resource class does not do any + * actual allocation, but simply tracks if a given index is currently in use. * - * WARNING: this should only be statically allocated. When the program loads into memory all the - * static constructors are called. At that time a linked list of all the "Resources" is created. - * Then when the program actually starts - in the Robot constructor, all resources are initialized. - * This ensures that the program is restartable in memory without having to unload/reload. + * WARNING: this should only be statically allocated. When the program loads + * into memory all the static constructors are called. At that time a linked + * list of all the "Resources" is created. Then when the program actually starts + * - in the Robot constructor, all resources are initialized. This ensures that + * the program is restartable in memory without having to unload/reload. */ public class Resource { - private static Resource m_resourceList = null; - private final boolean m_numAllocated[]; - private final int m_size; - private final Resource m_nextResource; + private static Resource m_resourceList = null; + private final boolean m_numAllocated[]; + private final int m_size; + private final Resource m_nextResource; - /** - * Clears all allocated resources - */ - public static void restartProgram() { - for (Resource r = Resource.m_resourceList; r != null; r = r.m_nextResource) { - for (int i = 0; i < r.m_size; i++) { - r.m_numAllocated[i] = false; - } - } + /** + * Clears all allocated resources + */ + public static void restartProgram() { + for (Resource r = Resource.m_resourceList; r != null; r = r.m_nextResource) { + for (int i = 0; i < r.m_size; i++) { + r.m_numAllocated[i] = false; + } } + } - /** - * 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..size-1. - * - * @param size The number of blocks to allocate - */ - public Resource(final int size) { - m_size = size; - m_numAllocated = new boolean[m_size]; - for (int i = 0; i < m_size; i++) { - m_numAllocated[i] = false; - } - m_nextResource = Resource.m_resourceList; - Resource.m_resourceList = this; + /** + * 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..size-1. + * + * @param size The number of blocks to allocate + */ + public Resource(final int size) { + m_size = size; + m_numAllocated = new boolean[m_size]; + for (int i = 0; i < m_size; i++) { + m_numAllocated[i] = false; } + m_nextResource = Resource.m_resourceList; + Resource.m_resourceList = this; + } - /** - * Allocate a resource. - * 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. - * - * @return The index of the allocated block. - * @throws CheckedAllocationException If there are no resources available to be allocated. - */ - public int allocate() throws CheckedAllocationException { - for (int i = 0; i < m_size; i++) { - if (m_numAllocated[i] == false) { - m_numAllocated[i] = true; - return i; - } - } - throw new CheckedAllocationException("No available resources"); + /** + * Allocate a resource. 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. + * + * @return The index of the allocated block. + * @throws CheckedAllocationException If there are no resources available to + * be allocated. + */ + public int allocate() throws CheckedAllocationException { + for (int i = 0; i < m_size; i++) { + if (m_numAllocated[i] == false) { + m_numAllocated[i] = true; + return i; + } } + throw new CheckedAllocationException("No available resources"); + } - /** - * Allocate a specific resource value. - * The user requests a specific resource value, i.e. channel number and it is verified - * unallocated, then returned. - * - * @param index The resource to allocate - * @return The index of the allocated block - * @throws CheckedAllocationException If there are no resources available to be allocated. - */ - public int allocate(final int index) throws CheckedAllocationException { - if (index >= m_size || index < 0) { - throw new CheckedAllocationException("Index " + index + " out of range"); - } - if (m_numAllocated[index] == true) { - throw new CheckedAllocationException("Resource at index " + index + " already allocated"); - } - m_numAllocated[index] = true; - return index; + /** + * Allocate a specific resource value. The user requests a specific resource + * value, i.e. channel number and it is verified unallocated, then returned. + * + * @param index The resource to allocate + * @return The index of the allocated block + * @throws CheckedAllocationException If there are no resources available to + * be allocated. + */ + public int allocate(final int index) throws CheckedAllocationException { + if (index >= m_size || index < 0) { + throw new CheckedAllocationException("Index " + index + " out of range"); } + if (m_numAllocated[index] == true) { + throw new CheckedAllocationException("Resource at index " + index + " already allocated"); + } + m_numAllocated[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. + * + * @param index The index of the resource to free. + */ + public void free(final int index) { + if (m_numAllocated[index] == false) + throw new AllocationException("No resource available to be freed"); + m_numAllocated[index] = false; + } - /** - * 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. - * - * @param index The index of the resource to free. - */ - public void free(final int index) { - if (m_numAllocated[index] == false) - throw new AllocationException("No resource available to be freed"); - m_numAllocated[index] = false; - } - } diff --git a/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/RobotBase.java b/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/RobotBase.java index 04802e5d01..eba0a7adb6 100644 --- a/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/RobotBase.java +++ b/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/RobotBase.java @@ -1,8 +1,8 @@ /*----------------------------------------------------------------------------*/ -/* Copyright (c) FIRST 2008-2012. All Rights Reserved. */ -/* Open Source Software - may be modified and shared by FRC teams. The code */ +/* Copyright (c) FIRST 2008-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 the root directory of */ -/* the project. */ +/* the project. */ /*----------------------------------------------------------------------------*/ package edu.wpi.first.wpilibj; @@ -27,223 +27,244 @@ import edu.wpi.first.wpilibj.networktables.NetworkTable; import edu.wpi.first.wpilibj.Utility; /** - * Implement a Robot Program framework. - * The RobotBase class is intended to be subclassed by a user creating a robot program. - * Overridden autonomous() and operatorControl() methods are called at the appropriate time - * as the match proceeds. In the current implementation, the Autonomous code will run to - * completion before the OperatorControl code could start. In the future the Autonomous code - * might be spawned as a task, then killed at the end of the Autonomous period. + * Implement a Robot Program framework. The RobotBase class is intended to be + * subclassed by a user creating a robot program. Overridden autonomous() and + * operatorControl() methods are called at the appropriate time as the match + * proceeds. In the current implementation, the Autonomous code will run to + * completion before the OperatorControl code could start. In the future the + * Autonomous code might be spawned as a task, then killed at the end of the + * Autonomous period. */ public abstract class RobotBase { - /** - * The VxWorks priority that robot code should work at (so Java code should run at) - */ - public static final int ROBOT_TASK_PRIORITY = 101; + /** + * The VxWorks priority that robot code should work at (so Java code should + * run at) + */ + public static final int ROBOT_TASK_PRIORITY = 101; - protected final DriverStation m_ds; + protected final DriverStation m_ds; - /** - * Constructor for a generic robot program. - * User code should be placed in the constructor that runs before the Autonomous or Operator - * Control period starts. The constructor will run to completion before Autonomous is entered. - * - * This must be used to ensure that the communications code starts. In the future it would be - * nice to put this code into it's own task that loads on boot so ensure that it runs. - */ - protected RobotBase() { - // TODO: StartCAPI(); - // TODO: See if the next line is necessary - // Resource.RestartProgram(); + /** + * Constructor for a generic robot program. User code should be placed in the + * constructor that runs before the Autonomous or Operator Control period + * starts. The constructor will run to completion before Autonomous is + * entered. + * + * This must be used to ensure that the communications code starts. In the + * future it would be nice to put this code into it's own task that loads on + * boot so ensure that it runs. + */ + protected RobotBase() { + // TODO: StartCAPI(); + // TODO: See if the next line is necessary + // Resource.RestartProgram(); - NetworkTable.setServerMode();//must be before b - m_ds = DriverStation.getInstance(); - NetworkTable.getTable(""); // forces network tables to initialize - NetworkTable.getTable("LiveWindow").getSubTable("~STATUS~").putBoolean("LW Enabled", false); - } + NetworkTable.setServerMode();// must be before b + m_ds = DriverStation.getInstance(); + NetworkTable.getTable(""); // forces network tables to initialize + NetworkTable.getTable("LiveWindow").getSubTable("~STATUS~").putBoolean("LW Enabled", false); + } - /** - * Free the resources for a RobotBase class. - */ - public void free() { - } + /** + * Free the resources for a RobotBase class. + */ + public void free() {} - /** - * @return If the robot is running in simulation. - */ - public static boolean isSimulation() { - return false; - } + /** + * @return If the robot is running in simulation. + */ + public static boolean isSimulation() { + return false; + } - /** - * @return If the robot is running in the real world. - */ - public static boolean isReal() { - return true; - } + /** + * @return If the robot is running in the real world. + */ + public static boolean isReal() { + return true; + } - /** - * Determine if the Robot is currently disabled. - * @return True if the Robot is currently disabled by the field controls. - */ - public boolean isDisabled() { - return m_ds.isDisabled(); - } + /** + * Determine if the Robot is currently disabled. + *$ + * @return True if the Robot is currently disabled by the field controls. + */ + public boolean isDisabled() { + return m_ds.isDisabled(); + } - /** - * Determine if the Robot is currently enabled. - * @return True if the Robot is currently enabled by the field controls. - */ - public boolean isEnabled() { - return m_ds.isEnabled(); - } + /** + * Determine if the Robot is currently enabled. + *$ + * @return True if the Robot is currently enabled by the field controls. + */ + public boolean isEnabled() { + return m_ds.isEnabled(); + } - /** - * Determine if the robot is currently in Autonomous mode. - * @return True if the robot is currently operating Autonomously as determined by the field controls. - */ - public boolean isAutonomous() { - return m_ds.isAutonomous(); - } + /** + * Determine if the robot is currently in Autonomous mode. + *$ + * @return True if the robot is currently operating Autonomously as determined + * by the field controls. + */ + public boolean isAutonomous() { + return m_ds.isAutonomous(); + } - /** - * Determine if the robot is currently in Test mode - * @return True if the robot is currently operating in Test mode as determined by the driver station. - */ - public boolean isTest() { - return m_ds.isTest(); - } + /** + * Determine if the robot is currently in Test mode + *$ + * @return True if the robot is currently operating in Test mode as determined + * by the driver station. + */ + public boolean isTest() { + return m_ds.isTest(); + } - /** - * Determine if the robot is currently in Operator Control mode. - * @return True if the robot is currently operating in Tele-Op mode as determined by the field controls. - */ - public boolean isOperatorControl() { - return m_ds.isOperatorControl(); - } + /** + * Determine if the robot is currently in Operator Control mode. + *$ + * @return True if the robot is currently operating in Tele-Op mode as + * determined by the field controls. + */ + public boolean isOperatorControl() { + return m_ds.isOperatorControl(); + } - /** - * Indicates if new data is available from the driver station. - * @return Has new data arrived over the network since the last time this function was called? - */ - public boolean isNewDataAvailable() { - return m_ds.isNewControlData(); - } + /** + * Indicates if new data is available from the driver station. + *$ + * @return Has new data arrived over the network since the last time this + * function was called? + */ + public boolean isNewDataAvailable() { + return m_ds.isNewControlData(); + } - /** - * Provide an alternate "main loop" via startCompetition(). - */ - public abstract void startCompetition(); + /** + * Provide an alternate "main loop" via startCompetition(). + */ + public abstract void startCompetition(); - /** - * This hook is called right before startCompetition(). By default, tell the - * DS that the robot is now ready to be enabled. If you don't want for the - * robot to be enabled yet, you can override this method to do nothing. - * If you do so, you will need to call - * FRCNetworkCommunicationsLibrary.FRCNetworkCommunicationOvserveUserProgramStarting() from - * your code when you are ready for the robot to be enabled. - */ - protected void prestart() { - FRCNetworkCommunicationsLibrary.FRCNetworkCommunicationObserveUserProgramStarting(); - } + /** + * This hook is called right before startCompetition(). By default, tell the + * DS that the robot is now ready to be enabled. If you don't want for the + * robot to be enabled yet, you can override this method to do nothing. If you + * do so, you will need to call FRCNetworkCommunicationsLibrary. + * FRCNetworkCommunicationOvserveUserProgramStarting() from your code when you + * are ready for the robot to be enabled. + */ + protected void prestart() { + FRCNetworkCommunicationsLibrary.FRCNetworkCommunicationObserveUserProgramStarting(); + } - public static boolean getBooleanProperty(String name, boolean defaultValue) { - String propVal = System.getProperty(name); - if (propVal == null) { - return defaultValue; - } - if (propVal.equalsIgnoreCase("false")) { - return false; - } else if (propVal.equalsIgnoreCase("true")) { - return true; - } else { - throw new IllegalStateException(propVal); - } - } + public static boolean getBooleanProperty(String name, boolean defaultValue) { + String propVal = System.getProperty(name); + if (propVal == null) { + return defaultValue; + } + if (propVal.equalsIgnoreCase("false")) { + return false; + } else if (propVal.equalsIgnoreCase("true")) { + return true; + } else { + throw new IllegalStateException(propVal); + } + } - /** - * Common initialization for all robot programs. - */ - public static void initializeHardwareConfiguration(){ - FRCNetworkCommunicationsLibrary.FRCNetworkCommunicationReserve(); + /** + * Common initialization for all robot programs. + */ + public static void initializeHardwareConfiguration() { + FRCNetworkCommunicationsLibrary.FRCNetworkCommunicationReserve(); - // Set some implementations so that the static methods work properly - Timer.SetImplementation(new HardwareTimer()); - HLUsageReporting.SetImplementation(new HardwareHLUsageReporting()); - RobotState.SetImplementation(DriverStation.getInstance()); - } + // Set some implementations so that the static methods work properly + Timer.SetImplementation(new HardwareTimer()); + HLUsageReporting.SetImplementation(new HardwareHLUsageReporting()); + RobotState.SetImplementation(DriverStation.getInstance()); + } - /** - * Starting point for the applications. - */ - public static void main(String args[]) { - initializeHardwareConfiguration(); + /** + * Starting point for the applications. + */ + public static void main(String args[]) { + initializeHardwareConfiguration(); - UsageReporting.report(tResourceType.kResourceType_Language, tInstances.kLanguage_Java); + UsageReporting.report(tResourceType.kResourceType_Language, tInstances.kLanguage_Java); - String robotName = ""; - Enumeration resources = null; - try { - resources = RobotBase.class.getClassLoader().getResources("META-INF/MANIFEST.MF"); - } catch (IOException e) {e.printStackTrace();} - while (resources != null && resources.hasMoreElements()) { - try { - Manifest manifest = new Manifest(resources.nextElement().openStream()); - robotName = manifest.getMainAttributes().getValue("Robot-Class"); - } catch (IOException e) {e.printStackTrace();} - } + String robotName = ""; + Enumeration resources = null; + try { + resources = RobotBase.class.getClassLoader().getResources("META-INF/MANIFEST.MF"); + } catch (IOException e) { + e.printStackTrace(); + } + while (resources != null && resources.hasMoreElements()) { + try { + Manifest manifest = new Manifest(resources.nextElement().openStream()); + robotName = manifest.getMainAttributes().getValue("Robot-Class"); + } catch (IOException e) { + e.printStackTrace(); + } + } - RobotBase robot; - try { - robot = (RobotBase) Class.forName(robotName).newInstance(); - robot.prestart(); - } catch (Throwable t) { - DriverStation.reportError("ERROR Unhandled exception instantiating robot " + robotName + " " + t.toString() + " at " + Arrays.toString(t.getStackTrace()), false); - System.err.println("WARNING: Robots don't quit!"); - System.err.println("ERROR: Could not instantiate robot " + robotName + "!"); - System.exit(1); - return; - } - - File file = null; - FileOutputStream output = null; - try { - file = new File("/tmp/frc_versions/FRC_Lib_Version.ini"); + RobotBase robot; + try { + robot = (RobotBase) Class.forName(robotName).newInstance(); + robot.prestart(); + } catch (Throwable t) { + DriverStation.reportError("ERROR Unhandled exception instantiating robot " + robotName + " " + + t.toString() + " at " + Arrays.toString(t.getStackTrace()), false); + System.err.println("WARNING: Robots don't quit!"); + System.err.println("ERROR: Could not instantiate robot " + robotName + "!"); + System.exit(1); + return; + } - if (file.exists()) - file.delete(); + File file = null; + FileOutputStream output = null; + try { + file = new File("/tmp/frc_versions/FRC_Lib_Version.ini"); - file.createNewFile(); + if (file.exists()) + file.delete(); - output = new FileOutputStream(file); + file.createNewFile(); - output.write("2015 Java 1.2.0".getBytes()); + output = new FileOutputStream(file); - } catch (IOException ex) { - ex.printStackTrace(); - } finally { - if (output != null) { - try { - output.close(); - } catch (IOException ex) { - } - } - } + output.write("2015 Java 1.2.0".getBytes()); - boolean errorOnExit = false; - try { - robot.startCompetition(); - } catch (Throwable t) { - DriverStation.reportError("ERROR Unhandled exception: " + t.toString() + " at " + Arrays.toString(t.getStackTrace()), false); - errorOnExit = true; - } finally { - // startCompetition never returns unless exception occurs.... - System.err.println("WARNING: Robots don't quit!"); - if (errorOnExit) { - System.err.println("---> The startCompetition() method (or methods called by it) should have handled the exception above."); - } else { - System.err.println("---> Unexpected return from startCompetition() method."); - } - } - System.exit(1); - } + } catch (IOException ex) { + ex.printStackTrace(); + } finally { + if (output != null) { + try { + output.close(); + } catch (IOException ex) { + } + } + } + + boolean errorOnExit = false; + try { + robot.startCompetition(); + } catch (Throwable t) { + DriverStation.reportError( + "ERROR Unhandled exception: " + t.toString() + " at " + + Arrays.toString(t.getStackTrace()), false); + errorOnExit = true; + } finally { + // startCompetition never returns unless exception occurs.... + System.err.println("WARNING: Robots don't quit!"); + if (errorOnExit) { + System.err + .println("---> The startCompetition() method (or methods called by it) should have handled the exception above."); + } else { + System.err.println("---> Unexpected return from startCompetition() method."); + } + } + System.exit(1); + } } diff --git a/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/RobotDrive.java b/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/RobotDrive.java index 36622941f6..0ccca510b0 100644 --- a/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/RobotDrive.java +++ b/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/RobotDrive.java @@ -1,8 +1,8 @@ /*----------------------------------------------------------------------------*/ -/* Copyright (c) FIRST 2008-2012. All Rights Reserved. */ -/* Open Source Software - may be modified and shared by FRC teams. The code */ +/* Copyright (c) FIRST 2008-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 the root directory of */ -/* the project. */ +/* the project. */ /*----------------------------------------------------------------------------*/ package edu.wpi.first.wpilibj; @@ -11,728 +11,811 @@ import edu.wpi.first.wpilibj.communication.FRCNetworkCommunicationsLibrary.tReso import edu.wpi.first.wpilibj.communication.UsageReporting; /** - * Utility class for handling Robot drive based on a definition of the motor configuration. - * The robot drive class handles basic driving for a robot. Currently, 2 and 4 motor tank and - * mecanum drive trains are supported. In the future other drive types like swerve might - * be implemented. Motor channel numbers are supplied on creation of the class. Those are - * used for either the drive function (intended for hand created drive code, such as autonomous) - * or with the Tank/Arcade functions intended to be used for Operator Control driving. + * Utility class for handling Robot drive based on a definition of the motor + * configuration. The robot drive class handles basic driving for a robot. + * Currently, 2 and 4 motor tank and mecanum drive trains are supported. In the + * future other drive types like swerve might be implemented. Motor channel + * numbers are supplied on creation of the class. Those are used for either the + * drive function (intended for hand created drive code, such as autonomous) or + * with the Tank/Arcade functions intended to be used for Operator Control + * driving. */ public class RobotDrive implements MotorSafety { - protected MotorSafetyHelper m_safetyHelper; + protected MotorSafetyHelper m_safetyHelper; + + /** + * The location of a motor on the robot for the purpose of driving + */ + public static class MotorType { /** - * The location of a motor on the robot for the purpose of driving + * The integer value representing this enumeration */ - public static class MotorType { - - /** - * The integer value representing this enumeration - */ - public final int value; - static final int kFrontLeft_val = 0; - static final int kFrontRight_val = 1; - static final int kRearLeft_val = 2; - static final int kRearRight_val = 3; - /** - * motortype: front left - */ - public static final MotorType kFrontLeft = new MotorType(kFrontLeft_val); - /** - * motortype: front right - */ - public static final MotorType kFrontRight = new MotorType(kFrontRight_val); - /** - * motortype: rear left - */ - public static final MotorType kRearLeft = new MotorType(kRearLeft_val); - /** - * motortype: rear right - */ - public static final MotorType kRearRight = new MotorType(kRearRight_val); - - private MotorType(int value) { - this.value = value; - } - } - public static final double kDefaultExpirationTime = 0.1; - public static final double kDefaultSensitivity = 0.5; - public static final double kDefaultMaxOutput = 1.0; - protected static final int kMaxNumberOfMotors = 4; - protected double m_sensitivity; - protected double m_maxOutput; - protected SpeedController m_frontLeftMotor; - protected SpeedController m_frontRightMotor; - protected SpeedController m_rearLeftMotor; - protected SpeedController m_rearRightMotor; - protected boolean m_allocatedSpeedControllers; - protected byte m_syncGroup = 0; - protected static boolean kArcadeRatioCurve_Reported = false; - protected static boolean kTank_Reported = false; - protected static boolean kArcadeStandard_Reported = false; - protected static boolean kMecanumCartesian_Reported = false; - protected static boolean kMecanumPolar_Reported = false; - - /** Constructor for RobotDrive with 2 motors specified with channel numbers. - * Set up parameters for a two wheel drive system where the - * left and right motor pwm channels are specified in the call. - * This call assumes Talons for controlling the motors. - * @param leftMotorChannel The PWM channel number that drives the left motor. - * @param rightMotorChannel The PWM channel number that drives the right motor. - */ - public RobotDrive(final int leftMotorChannel, final int rightMotorChannel) { - m_sensitivity = kDefaultSensitivity; - m_maxOutput = kDefaultMaxOutput; - m_frontLeftMotor = null; - m_rearLeftMotor = new Talon(leftMotorChannel); - m_frontRightMotor = null; - m_rearRightMotor = new Talon(rightMotorChannel); - m_allocatedSpeedControllers = true; - setupMotorSafety(); - drive(0, 0); - } - + public final int value; + static final int kFrontLeft_val = 0; + static final int kFrontRight_val = 1; + static final int kRearLeft_val = 2; + static final int kRearRight_val = 3; /** - * Constructor for RobotDrive with 4 motors specified with channel numbers. - * Set up parameters for a four wheel drive system where all four motor - * pwm channels are specified in the call. - * This call assumes Talons for controlling the motors. - * @param frontLeftMotor Front left motor channel number - * @param rearLeftMotor Rear Left motor channel number - * @param frontRightMotor Front right motor channel number - * @param rearRightMotor Rear Right motor channel number + * motortype: front left */ - public RobotDrive(final int frontLeftMotor, final int rearLeftMotor, - final int frontRightMotor, final int rearRightMotor) { - m_sensitivity = kDefaultSensitivity; - m_maxOutput = kDefaultMaxOutput; - m_rearLeftMotor = new Talon(rearLeftMotor); - m_rearRightMotor = new Talon(rearRightMotor); - m_frontLeftMotor = new Talon(frontLeftMotor); - m_frontRightMotor = new Talon(frontRightMotor); - m_allocatedSpeedControllers = true; - setupMotorSafety(); - drive(0, 0); - } - + public static final MotorType kFrontLeft = new MotorType(kFrontLeft_val); /** - * Constructor for RobotDrive with 2 motors specified as SpeedController objects. - * The SpeedController version of the constructor enables programs to use the RobotDrive classes with - * subclasses of the SpeedController objects, for example, versions with ramping or reshaping of - * the curve to suit motor bias or dead-band elimination. - * @param leftMotor The left SpeedController object used to drive the robot. - * @param rightMotor the right SpeedController object used to drive the robot. + * motortype: front right */ - public RobotDrive(SpeedController leftMotor, SpeedController rightMotor) { - if (leftMotor == null || rightMotor == null) { - m_rearLeftMotor = m_rearRightMotor = null; - throw new NullPointerException("Null motor provided"); - } - m_frontLeftMotor = null; - m_rearLeftMotor = leftMotor; - m_frontRightMotor = null; - m_rearRightMotor = rightMotor; - m_sensitivity = kDefaultSensitivity; - m_maxOutput = kDefaultMaxOutput; - m_allocatedSpeedControllers = false; - setupMotorSafety(); - drive(0, 0); - } - + public static final MotorType kFrontRight = new MotorType(kFrontRight_val); /** - * Constructor for RobotDrive with 4 motors specified as SpeedController objects. - * Speed controller input version of RobotDrive (see previous comments). - * @param rearLeftMotor The back left SpeedController object used to drive the robot. - * @param frontLeftMotor The front left SpeedController object used to drive the robot - * @param rearRightMotor The back right SpeedController object used to drive the robot. - * @param frontRightMotor The front right SpeedController object used to drive the robot. + * motortype: rear left */ - public RobotDrive(SpeedController frontLeftMotor, SpeedController rearLeftMotor, - SpeedController frontRightMotor, SpeedController rearRightMotor) { - if (frontLeftMotor == null || rearLeftMotor == null || frontRightMotor == null || rearRightMotor == null) { - m_frontLeftMotor = m_rearLeftMotor = m_frontRightMotor = m_rearRightMotor = null; - throw new NullPointerException("Null motor provided"); - } - m_frontLeftMotor = frontLeftMotor; - m_rearLeftMotor = rearLeftMotor; - m_frontRightMotor = frontRightMotor; - m_rearRightMotor = rearRightMotor; - m_sensitivity = kDefaultSensitivity; - m_allocatedSpeedControllers = false; - setupMotorSafety(); - drive(0, 0); - } - + public static final MotorType kRearLeft = new MotorType(kRearLeft_val); /** - * Drive the motors at "speed" and "curve". - * - * The speed and curve are -1.0 to +1.0 values where 0.0 represents stopped and - * not turning. The algorithm for adding in the direction attempts to provide a constant - * turn radius for differing speeds. - * - * This function will most likely be used in an autonomous routine. - * - * @param outputMagnitude The forward component of the output magnitude to send to the motors. - * @param curve The rate of turn, constant for different forward speeds. + * motortype: rear right */ - public void drive(double outputMagnitude, double curve) { - double leftOutput, rightOutput; + public static final MotorType kRearRight = new MotorType(kRearRight_val); - if(!kArcadeRatioCurve_Reported) { - UsageReporting.report(tResourceType.kResourceType_RobotDrive, getNumMotors(), tInstances.kRobotDrive_ArcadeRatioCurve); - kArcadeRatioCurve_Reported = true; - } - if (curve < 0) { - double value = Math.log(-curve); - double ratio = (value - m_sensitivity) / (value + m_sensitivity); - if (ratio == 0) { - ratio = .0000000001; - } - leftOutput = outputMagnitude / ratio; - rightOutput = outputMagnitude; - } else if (curve > 0) { - double value = Math.log(curve); - double ratio = (value - m_sensitivity) / (value + m_sensitivity); - if (ratio == 0) { - ratio = .0000000001; - } - leftOutput = outputMagnitude; - rightOutput = outputMagnitude / ratio; - } else { - leftOutput = outputMagnitude; - rightOutput = outputMagnitude; - } - setLeftRightMotorOutputs(leftOutput, rightOutput); + private MotorType(int value) { + this.value = value; + } + } + + public static final double kDefaultExpirationTime = 0.1; + public static final double kDefaultSensitivity = 0.5; + public static final double kDefaultMaxOutput = 1.0; + protected static final int kMaxNumberOfMotors = 4; + protected double m_sensitivity; + protected double m_maxOutput; + protected SpeedController m_frontLeftMotor; + protected SpeedController m_frontRightMotor; + protected SpeedController m_rearLeftMotor; + protected SpeedController m_rearRightMotor; + protected boolean m_allocatedSpeedControllers; + protected byte m_syncGroup = 0; + protected static boolean kArcadeRatioCurve_Reported = false; + protected static boolean kTank_Reported = false; + protected static boolean kArcadeStandard_Reported = false; + protected static boolean kMecanumCartesian_Reported = false; + protected static boolean kMecanumPolar_Reported = false; + + /** + * Constructor for RobotDrive with 2 motors specified with channel numbers. + * Set up parameters for a two wheel drive system where the left and right + * motor pwm channels are specified in the call. This call assumes Talons for + * controlling the motors. + *$ + * @param leftMotorChannel The PWM channel number that drives the left motor. + * @param rightMotorChannel The PWM channel number that drives the right + * motor. + */ + public RobotDrive(final int leftMotorChannel, final int rightMotorChannel) { + m_sensitivity = kDefaultSensitivity; + m_maxOutput = kDefaultMaxOutput; + m_frontLeftMotor = null; + m_rearLeftMotor = new Talon(leftMotorChannel); + m_frontRightMotor = null; + m_rearRightMotor = new Talon(rightMotorChannel); + m_allocatedSpeedControllers = true; + setupMotorSafety(); + drive(0, 0); + } + + /** + * Constructor for RobotDrive with 4 motors specified with channel numbers. + * Set up parameters for a four wheel drive system where all four motor pwm + * channels are specified in the call. This call assumes Talons for + * controlling the motors. + *$ + * @param frontLeftMotor Front left motor channel number + * @param rearLeftMotor Rear Left motor channel number + * @param frontRightMotor Front right motor channel number + * @param rearRightMotor Rear Right motor channel number + */ + public RobotDrive(final int frontLeftMotor, final int rearLeftMotor, final int frontRightMotor, + final int rearRightMotor) { + m_sensitivity = kDefaultSensitivity; + m_maxOutput = kDefaultMaxOutput; + m_rearLeftMotor = new Talon(rearLeftMotor); + m_rearRightMotor = new Talon(rearRightMotor); + m_frontLeftMotor = new Talon(frontLeftMotor); + m_frontRightMotor = new Talon(frontRightMotor); + m_allocatedSpeedControllers = true; + setupMotorSafety(); + drive(0, 0); + } + + /** + * Constructor for RobotDrive with 2 motors specified as SpeedController + * objects. The SpeedController version of the constructor enables programs to + * use the RobotDrive classes with subclasses of the SpeedController objects, + * for example, versions with ramping or reshaping of the curve to suit motor + * bias or dead-band elimination. + *$ + * @param leftMotor The left SpeedController object used to drive the robot. + * @param rightMotor the right SpeedController object used to drive the robot. + */ + public RobotDrive(SpeedController leftMotor, SpeedController rightMotor) { + if (leftMotor == null || rightMotor == null) { + m_rearLeftMotor = m_rearRightMotor = null; + throw new NullPointerException("Null motor provided"); + } + m_frontLeftMotor = null; + m_rearLeftMotor = leftMotor; + m_frontRightMotor = null; + m_rearRightMotor = rightMotor; + m_sensitivity = kDefaultSensitivity; + m_maxOutput = kDefaultMaxOutput; + m_allocatedSpeedControllers = false; + setupMotorSafety(); + drive(0, 0); + } + + /** + * Constructor for RobotDrive with 4 motors specified as SpeedController + * objects. Speed controller input version of RobotDrive (see previous + * comments). + *$ + * @param rearLeftMotor The back left SpeedController object used to drive the + * robot. + * @param frontLeftMotor The front left SpeedController object used to drive + * the robot + * @param rearRightMotor The back right SpeedController object used to drive + * the robot. + * @param frontRightMotor The front right SpeedController object used to drive + * the robot. + */ + public RobotDrive(SpeedController frontLeftMotor, SpeedController rearLeftMotor, + SpeedController frontRightMotor, SpeedController rearRightMotor) { + if (frontLeftMotor == null || rearLeftMotor == null || frontRightMotor == null + || rearRightMotor == null) { + m_frontLeftMotor = m_rearLeftMotor = m_frontRightMotor = m_rearRightMotor = null; + throw new NullPointerException("Null motor provided"); + } + m_frontLeftMotor = frontLeftMotor; + m_rearLeftMotor = rearLeftMotor; + m_frontRightMotor = frontRightMotor; + m_rearRightMotor = rearRightMotor; + m_sensitivity = kDefaultSensitivity; + m_allocatedSpeedControllers = false; + setupMotorSafety(); + drive(0, 0); + } + + /** + * Drive the motors at "speed" and "curve". + * + * The speed and curve are -1.0 to +1.0 values where 0.0 represents stopped + * and not turning. The algorithm for adding in the direction attempts to + * provide a constant turn radius for differing speeds. + * + * This function will most likely be used in an autonomous routine. + * + * @param outputMagnitude The forward component of the output magnitude to + * send to the motors. + * @param curve The rate of turn, constant for different forward speeds. + */ + public void drive(double outputMagnitude, double curve) { + double leftOutput, rightOutput; + + if (!kArcadeRatioCurve_Reported) { + UsageReporting.report(tResourceType.kResourceType_RobotDrive, getNumMotors(), + tInstances.kRobotDrive_ArcadeRatioCurve); + kArcadeRatioCurve_Reported = true; + } + if (curve < 0) { + double value = Math.log(-curve); + double ratio = (value - m_sensitivity) / (value + m_sensitivity); + if (ratio == 0) { + ratio = .0000000001; + } + leftOutput = outputMagnitude / ratio; + rightOutput = outputMagnitude; + } else if (curve > 0) { + double value = Math.log(curve); + double ratio = (value - m_sensitivity) / (value + m_sensitivity); + if (ratio == 0) { + ratio = .0000000001; + } + leftOutput = outputMagnitude; + rightOutput = outputMagnitude / ratio; + } else { + leftOutput = outputMagnitude; + rightOutput = outputMagnitude; + } + setLeftRightMotorOutputs(leftOutput, rightOutput); + } + + /** + * Provide tank steering using the stored robot configuration. drive the robot + * using two joystick inputs. The Y-axis will be selected from each Joystick + * object. + *$ + * @param leftStick The joystick to control the left side of the robot. + * @param rightStick The joystick to control the right side of the robot. + */ + public void tankDrive(GenericHID leftStick, GenericHID rightStick) { + if (leftStick == null || rightStick == null) { + throw new NullPointerException("Null HID provided"); + } + tankDrive(leftStick.getY(), rightStick.getY(), true); + } + + /** + * Provide tank steering using the stored robot configuration. drive the robot + * using two joystick inputs. The Y-axis will be selected from each Joystick + * object. + *$ + * @param leftStick The joystick to control the left side of the robot. + * @param rightStick The joystick to control the right side of the robot. + * @param squaredInputs Setting this parameter to true decreases the + * sensitivity at lower speeds + */ + public void tankDrive(GenericHID leftStick, GenericHID rightStick, boolean squaredInputs) { + if (leftStick == null || rightStick == null) { + throw new NullPointerException("Null HID provided"); + } + tankDrive(leftStick.getY(), rightStick.getY(), squaredInputs); + } + + /** + * Provide tank steering using the stored robot configuration. This function + * lets you pick the axis to be used on each Joystick object for the left and + * right sides of the robot. + *$ + * @param leftStick The Joystick object to use for the left side of the robot. + * @param leftAxis The axis to select on the left side Joystick object. + * @param rightStick The Joystick object to use for the right side of the + * robot. + * @param rightAxis The axis to select on the right side Joystick object. + */ + public void tankDrive(GenericHID leftStick, final int leftAxis, GenericHID rightStick, + final int rightAxis) { + if (leftStick == null || rightStick == null) { + throw new NullPointerException("Null HID provided"); + } + tankDrive(leftStick.getRawAxis(leftAxis), rightStick.getRawAxis(rightAxis), true); + } + + /** + * Provide tank steering using the stored robot configuration. This function + * lets you pick the axis to be used on each Joystick object for the left and + * right sides of the robot. + *$ + * @param leftStick The Joystick object to use for the left side of the robot. + * @param leftAxis The axis to select on the left side Joystick object. + * @param rightStick The Joystick object to use for the right side of the + * robot. + * @param rightAxis The axis to select on the right side Joystick object. + * @param squaredInputs Setting this parameter to true decreases the + * sensitivity at lower speeds + */ + public void tankDrive(GenericHID leftStick, final int leftAxis, GenericHID rightStick, + final int rightAxis, boolean squaredInputs) { + if (leftStick == null || rightStick == null) { + throw new NullPointerException("Null HID provided"); + } + tankDrive(leftStick.getRawAxis(leftAxis), rightStick.getRawAxis(rightAxis), squaredInputs); + } + + /** + * Provide tank steering using the stored robot configuration. This function + * lets you directly provide joystick values from any source. + *$ + * @param leftValue The value of the left stick. + * @param rightValue The value of the right stick. + * @param squaredInputs Setting this parameter to true decreases the + * sensitivity at lower speeds + */ + public void tankDrive(double leftValue, double rightValue, boolean squaredInputs) { + + if (!kTank_Reported) { + UsageReporting.report(tResourceType.kResourceType_RobotDrive, getNumMotors(), + tInstances.kRobotDrive_Tank); + kTank_Reported = true; } - /** - * Provide tank steering using the stored robot configuration. - * drive the robot using two joystick inputs. The Y-axis will be selected from - * each Joystick object. - * @param leftStick The joystick to control the left side of the robot. - * @param rightStick The joystick to control the right side of the robot. - */ - public void tankDrive(GenericHID leftStick, GenericHID rightStick) { - if (leftStick == null || rightStick == null) { - throw new NullPointerException("Null HID provided"); - } - tankDrive(leftStick.getY(), rightStick.getY(), true); + // square the inputs (while preserving the sign) to increase fine control + // while permitting full power + leftValue = limit(leftValue); + rightValue = limit(rightValue); + if (squaredInputs) { + if (leftValue >= 0.0) { + leftValue = (leftValue * leftValue); + } else { + leftValue = -(leftValue * leftValue); + } + if (rightValue >= 0.0) { + rightValue = (rightValue * rightValue); + } else { + rightValue = -(rightValue * rightValue); + } + } + setLeftRightMotorOutputs(leftValue, rightValue); + } + + /** + * Provide tank steering using the stored robot configuration. This function + * lets you directly provide joystick values from any source. + *$ + * @param leftValue The value of the left stick. + * @param rightValue The value of the right stick. + */ + public void tankDrive(double leftValue, double rightValue) { + tankDrive(leftValue, rightValue, true); + } + + /** + * Arcade drive implements single stick driving. Given a single Joystick, the + * class assumes the Y axis for the move value and the X axis for the rotate + * value. (Should add more information here regarding the way that arcade + * drive works.) + *$ + * @param stick The joystick to use for Arcade single-stick driving. The + * Y-axis will be selected for forwards/backwards and the X-axis will + * be selected for rotation rate. + * @param squaredInputs If true, the sensitivity will be decreased for small + * values + */ + public void arcadeDrive(GenericHID stick, boolean squaredInputs) { + // simply call the full-featured arcadeDrive with the appropriate values + arcadeDrive(stick.getY(), stick.getX(), squaredInputs); + } + + /** + * Arcade drive implements single stick driving. Given a single Joystick, the + * class assumes the Y axis for the move value and the X axis for the rotate + * value. (Should add more information here regarding the way that arcade + * drive works.) + *$ + * @param stick The joystick to use for Arcade single-stick driving. The + * Y-axis will be selected for forwards/backwards and the X-axis will + * be selected for rotation rate. + */ + public void arcadeDrive(GenericHID stick) { + this.arcadeDrive(stick, true); + } + + /** + * Arcade drive implements single stick driving. Given two joystick instances + * and two axis, compute the values to send to either two or four motors. + *$ + * @param moveStick The Joystick object that represents the forward/backward + * direction + * @param moveAxis The axis on the moveStick object to use for + * forwards/backwards (typically Y_AXIS) + * @param rotateStick The Joystick object that represents the rotation value + * @param rotateAxis The axis on the rotation object to use for the rotate + * right/left (typically X_AXIS) + * @param squaredInputs Setting this parameter to true decreases the + * sensitivity at lower speeds + */ + public void arcadeDrive(GenericHID moveStick, final int moveAxis, GenericHID rotateStick, + final int rotateAxis, boolean squaredInputs) { + double moveValue = moveStick.getRawAxis(moveAxis); + double rotateValue = rotateStick.getRawAxis(rotateAxis); + + arcadeDrive(moveValue, rotateValue, squaredInputs); + } + + /** + * Arcade drive implements single stick driving. Given two joystick instances + * and two axis, compute the values to send to either two or four motors. + *$ + * @param moveStick The Joystick object that represents the forward/backward + * direction + * @param moveAxis The axis on the moveStick object to use for + * forwards/backwards (typically Y_AXIS) + * @param rotateStick The Joystick object that represents the rotation value + * @param rotateAxis The axis on the rotation object to use for the rotate + * right/left (typically X_AXIS) + */ + public void arcadeDrive(GenericHID moveStick, final int moveAxis, GenericHID rotateStick, + final int rotateAxis) { + this.arcadeDrive(moveStick, moveAxis, rotateStick, rotateAxis, true); + } + + /** + * Arcade drive implements single stick driving. This function lets you + * directly provide joystick values from any source. + *$ + * @param moveValue The value to use for forwards/backwards + * @param rotateValue The value to use for the rotate right/left + * @param squaredInputs If set, decreases the sensitivity at low speeds + */ + public void arcadeDrive(double moveValue, double rotateValue, boolean squaredInputs) { + // local variables to hold the computed PWM values for the motors + if (!kArcadeStandard_Reported) { + UsageReporting.report(tResourceType.kResourceType_RobotDrive, getNumMotors(), + tInstances.kRobotDrive_ArcadeStandard); + kArcadeStandard_Reported = true; } - /** - * Provide tank steering using the stored robot configuration. - * drive the robot using two joystick inputs. The Y-axis will be selected from - * each Joystick object. - * @param leftStick The joystick to control the left side of the robot. - * @param rightStick The joystick to control the right side of the robot. - * @param squaredInputs Setting this parameter to true decreases the sensitivity at lower speeds - */ - public void tankDrive(GenericHID leftStick, GenericHID rightStick, boolean squaredInputs) { - if (leftStick == null || rightStick == null) { - throw new NullPointerException("Null HID provided"); - } - tankDrive(leftStick.getY(), rightStick.getY(), squaredInputs); + double leftMotorSpeed; + double rightMotorSpeed; + + moveValue = limit(moveValue); + rotateValue = limit(rotateValue); + + if (squaredInputs) { + // square the inputs (while preserving the sign) to increase fine control + // while permitting full power + if (moveValue >= 0.0) { + moveValue = (moveValue * moveValue); + } else { + moveValue = -(moveValue * moveValue); + } + if (rotateValue >= 0.0) { + rotateValue = (rotateValue * rotateValue); + } else { + rotateValue = -(rotateValue * rotateValue); + } } - /** - * Provide tank steering using the stored robot configuration. - * This function lets you pick the axis to be used on each Joystick object for the left - * and right sides of the robot. - * @param leftStick The Joystick object to use for the left side of the robot. - * @param leftAxis The axis to select on the left side Joystick object. - * @param rightStick The Joystick object to use for the right side of the robot. - * @param rightAxis The axis to select on the right side Joystick object. - */ - public void tankDrive(GenericHID leftStick, final int leftAxis, - GenericHID rightStick, final int rightAxis) { - if (leftStick == null || rightStick == null) { - throw new NullPointerException("Null HID provided"); - } - tankDrive(leftStick.getRawAxis(leftAxis), rightStick.getRawAxis(rightAxis), true); + if (moveValue > 0.0) { + if (rotateValue > 0.0) { + leftMotorSpeed = moveValue - rotateValue; + rightMotorSpeed = Math.max(moveValue, rotateValue); + } else { + leftMotorSpeed = Math.max(moveValue, -rotateValue); + rightMotorSpeed = moveValue + rotateValue; + } + } else { + if (rotateValue > 0.0) { + leftMotorSpeed = -Math.max(-moveValue, rotateValue); + rightMotorSpeed = moveValue + rotateValue; + } else { + leftMotorSpeed = moveValue - rotateValue; + rightMotorSpeed = -Math.max(-moveValue, -rotateValue); + } } - /** - * Provide tank steering using the stored robot configuration. - * This function lets you pick the axis to be used on each Joystick object for the left - * and right sides of the robot. - * @param leftStick The Joystick object to use for the left side of the robot. - * @param leftAxis The axis to select on the left side Joystick object. - * @param rightStick The Joystick object to use for the right side of the robot. - * @param rightAxis The axis to select on the right side Joystick object. - * @param squaredInputs Setting this parameter to true decreases the sensitivity at lower speeds - */ - public void tankDrive(GenericHID leftStick, final int leftAxis, - GenericHID rightStick, final int rightAxis, boolean squaredInputs) { - if (leftStick == null || rightStick == null) { - throw new NullPointerException("Null HID provided"); - } - tankDrive(leftStick.getRawAxis(leftAxis), rightStick.getRawAxis(rightAxis), squaredInputs); + setLeftRightMotorOutputs(leftMotorSpeed, rightMotorSpeed); + } + + /** + * Arcade drive implements single stick driving. This function lets you + * directly provide joystick values from any source. + *$ + * @param moveValue The value to use for fowards/backwards + * @param rotateValue The value to use for the rotate right/left + */ + public void arcadeDrive(double moveValue, double rotateValue) { + this.arcadeDrive(moveValue, rotateValue, true); + } + + /** + * Drive method for Mecanum wheeled robots. + * + * A method for driving with Mecanum wheeled robots. There are 4 wheels on the + * robot, arranged so that the front and back wheels are toed in 45 degrees. + * When looking at the wheels from the top, the roller axles should form an X + * across the robot. + * + * This is designed to be directly driven by joystick axes. + * + * @param x The speed that the robot should drive in the X direction. + * [-1.0..1.0] + * @param y The speed that the robot should drive in the Y direction. This + * input is inverted to match the forward == -1.0 that joysticks + * produce. [-1.0..1.0] + * @param rotation The rate of rotation for the robot that is completely + * independent of the translation. [-1.0..1.0] + * @param gyroAngle The current angle reading from the gyro. Use this to + * implement field-oriented controls. + */ + public void mecanumDrive_Cartesian(double x, double y, double rotation, double gyroAngle) { + if (!kMecanumCartesian_Reported) { + UsageReporting.report(tResourceType.kResourceType_RobotDrive, getNumMotors(), + tInstances.kRobotDrive_MecanumCartesian); + kMecanumCartesian_Reported = true; + } + double xIn = x; + double yIn = y; + // Negate y for the joystick. + yIn = -yIn; + // Compenstate for gyro angle. + double rotated[] = rotateVector(xIn, yIn, gyroAngle); + xIn = rotated[0]; + yIn = rotated[1]; + + double wheelSpeeds[] = new double[kMaxNumberOfMotors]; + wheelSpeeds[MotorType.kFrontLeft_val] = xIn + yIn + rotation; + wheelSpeeds[MotorType.kFrontRight_val] = -xIn + yIn - rotation; + wheelSpeeds[MotorType.kRearLeft_val] = -xIn + yIn + rotation; + wheelSpeeds[MotorType.kRearRight_val] = xIn + yIn - rotation; + + normalize(wheelSpeeds); + m_frontLeftMotor.set(wheelSpeeds[MotorType.kFrontLeft_val] * m_maxOutput, m_syncGroup); + m_frontRightMotor.set(wheelSpeeds[MotorType.kFrontRight_val] * m_maxOutput, m_syncGroup); + m_rearLeftMotor.set(wheelSpeeds[MotorType.kRearLeft_val] * m_maxOutput, m_syncGroup); + m_rearRightMotor.set(wheelSpeeds[MotorType.kRearRight_val] * m_maxOutput, m_syncGroup); + + if (m_syncGroup != 0) { + CANJaguar.updateSyncGroup(m_syncGroup); } - /** - * Provide tank steering using the stored robot configuration. - * This function lets you directly provide joystick values from any source. - * @param leftValue The value of the left stick. - * @param rightValue The value of the right stick. - * @param squaredInputs Setting this parameter to true decreases the sensitivity at lower speeds - */ - public void tankDrive(double leftValue, double rightValue, boolean squaredInputs) { + if (m_safetyHelper != null) + m_safetyHelper.feed(); + } - if(!kTank_Reported) { - UsageReporting.report(tResourceType.kResourceType_RobotDrive, getNumMotors(), tInstances.kRobotDrive_Tank); - kTank_Reported = true; - } + /** + * Drive method for Mecanum wheeled robots. + * + * A method for driving with Mecanum wheeled robots. There are 4 wheels on the + * robot, arranged so that the front and back wheels are toed in 45 degrees. + * When looking at the wheels from the top, the roller axles should form an X + * across the robot. + * + * @param magnitude The speed that the robot should drive in a given + * direction. + * @param direction The direction the robot should drive in degrees. The + * direction and maginitute are independent of the rotation rate. + * @param rotation The rate of rotation for the robot that is completely + * independent of the magnitute or direction. [-1.0..1.0] + */ + public void mecanumDrive_Polar(double magnitude, double direction, double rotation) { + if (!kMecanumPolar_Reported) { + UsageReporting.report(tResourceType.kResourceType_RobotDrive, getNumMotors(), + tInstances.kRobotDrive_MecanumPolar); + kMecanumPolar_Reported = true; + } + double frontLeftSpeed, rearLeftSpeed, frontRightSpeed, rearRightSpeed; + // Normalized for full power along the Cartesian axes. + magnitude = limit(magnitude) * Math.sqrt(2.0); + // The rollers are at 45 degree angles. + double dirInRad = (direction + 45.0) * 3.14159 / 180.0; + double cosD = Math.cos(dirInRad); + double sinD = Math.sin(dirInRad); - // square the inputs (while preserving the sign) to increase fine control while permitting full power - leftValue = limit(leftValue); - rightValue = limit(rightValue); - if(squaredInputs) { - if (leftValue >= 0.0) { - leftValue = (leftValue * leftValue); - } else { - leftValue = -(leftValue * leftValue); - } - if (rightValue >= 0.0) { - rightValue = (rightValue * rightValue); - } else { - rightValue = -(rightValue * rightValue); - } - } - setLeftRightMotorOutputs(leftValue, rightValue); + double wheelSpeeds[] = new double[kMaxNumberOfMotors]; + wheelSpeeds[MotorType.kFrontLeft_val] = (sinD * magnitude + rotation); + wheelSpeeds[MotorType.kFrontRight_val] = (cosD * magnitude - rotation); + wheelSpeeds[MotorType.kRearLeft_val] = (cosD * magnitude + rotation); + wheelSpeeds[MotorType.kRearRight_val] = (sinD * magnitude - rotation); + + normalize(wheelSpeeds); + + m_frontLeftMotor.set(wheelSpeeds[MotorType.kFrontLeft_val] * m_maxOutput, m_syncGroup); + m_frontRightMotor.set(wheelSpeeds[MotorType.kFrontRight_val] * m_maxOutput, m_syncGroup); + m_rearLeftMotor.set(wheelSpeeds[MotorType.kRearLeft_val] * m_maxOutput, m_syncGroup); + m_rearRightMotor.set(wheelSpeeds[MotorType.kRearRight_val] * m_maxOutput, m_syncGroup); + + if (this.m_syncGroup != 0) { + CANJaguar.updateSyncGroup(m_syncGroup); } - /** - * Provide tank steering using the stored robot configuration. - * This function lets you directly provide joystick values from any source. - * @param leftValue The value of the left stick. - * @param rightValue The value of the right stick. - */ - public void tankDrive(double leftValue, double rightValue) { - tankDrive(leftValue, rightValue, true); + if (m_safetyHelper != null) + m_safetyHelper.feed(); + } + + /** + * Holonomic Drive method for Mecanum wheeled robots. + * + * This is an alias to mecanumDrive_Polar() for backward compatability + * + * @param magnitude The speed that the robot should drive in a given + * direction. [-1.0..1.0] + * @param direction The direction the robot should drive. The direction and + * maginitute are independent of the rotation rate. + * @param rotation The rate of rotation for the robot that is completely + * independent of the magnitute or direction. [-1.0..1.0] + */ + void holonomicDrive(float magnitude, float direction, float rotation) { + mecanumDrive_Polar(magnitude, direction, rotation); + } + + /** + * Set the speed of the right and left motors. This is used once an + * appropriate drive setup function is called such as twoWheelDrive(). The + * motors are set to "leftSpeed" and "rightSpeed" and includes flipping the + * direction of one side for opposing motors. + *$ + * @param leftOutput The speed to send to the left side of the robot. + * @param rightOutput The speed to send to the right side of the robot. + */ + public void setLeftRightMotorOutputs(double leftOutput, double rightOutput) { + if (m_rearLeftMotor == null || m_rearRightMotor == null) { + throw new NullPointerException("Null motor provided"); } - /** - * Arcade drive implements single stick driving. - * Given a single Joystick, the class assumes the Y axis for the move value and the X axis - * for the rotate value. - * (Should add more information here regarding the way that arcade drive works.) - * @param stick The joystick to use for Arcade single-stick driving. The Y-axis will be selected - * for forwards/backwards and the X-axis will be selected for rotation rate. - * @param squaredInputs If true, the sensitivity will be decreased for small values - */ - public void arcadeDrive(GenericHID stick, boolean squaredInputs) { - // simply call the full-featured arcadeDrive with the appropriate values - arcadeDrive(stick.getY(), stick.getX(), squaredInputs); + if (m_frontLeftMotor != null) { + m_frontLeftMotor.set(limit(leftOutput) * m_maxOutput, m_syncGroup); + } + m_rearLeftMotor.set(limit(leftOutput) * m_maxOutput, m_syncGroup); + + if (m_frontRightMotor != null) { + m_frontRightMotor.set(-limit(rightOutput) * m_maxOutput, m_syncGroup); + } + m_rearRightMotor.set(-limit(rightOutput) * m_maxOutput, m_syncGroup); + + if (this.m_syncGroup != 0) { + CANJaguar.updateSyncGroup(m_syncGroup); } - /** - * Arcade drive implements single stick driving. - * Given a single Joystick, the class assumes the Y axis for the move value and the X axis - * for the rotate value. - * (Should add more information here regarding the way that arcade drive works.) - * @param stick The joystick to use for Arcade single-stick driving. The Y-axis will be selected - * for forwards/backwards and the X-axis will be selected for rotation rate. - */ - public void arcadeDrive(GenericHID stick) { - this.arcadeDrive(stick, true); + if (m_safetyHelper != null) + m_safetyHelper.feed(); + } + + /** + * Limit motor values to the -1.0 to +1.0 range. + */ + protected static double limit(double num) { + if (num > 1.0) { + return 1.0; } - - /** - * Arcade drive implements single stick driving. - * Given two joystick instances and two axis, compute the values to send to either two - * or four motors. - * @param moveStick The Joystick object that represents the forward/backward direction - * @param moveAxis The axis on the moveStick object to use for forwards/backwards (typically Y_AXIS) - * @param rotateStick The Joystick object that represents the rotation value - * @param rotateAxis The axis on the rotation object to use for the rotate right/left (typically X_AXIS) - * @param squaredInputs Setting this parameter to true decreases the sensitivity at lower speeds - */ - public void arcadeDrive(GenericHID moveStick, final int moveAxis, - GenericHID rotateStick, final int rotateAxis, - boolean squaredInputs) { - double moveValue = moveStick.getRawAxis(moveAxis); - double rotateValue = rotateStick.getRawAxis(rotateAxis); - - arcadeDrive(moveValue, rotateValue, squaredInputs); + if (num < -1.0) { + return -1.0; } + return num; + } - /** - * Arcade drive implements single stick driving. - * Given two joystick instances and two axis, compute the values to send to either two - * or four motors. - * @param moveStick The Joystick object that represents the forward/backward direction - * @param moveAxis The axis on the moveStick object to use for forwards/backwards (typically Y_AXIS) - * @param rotateStick The Joystick object that represents the rotation value - * @param rotateAxis The axis on the rotation object to use for the rotate right/left (typically X_AXIS) - */ - public void arcadeDrive(GenericHID moveStick, final int moveAxis, - GenericHID rotateStick, final int rotateAxis) { - this.arcadeDrive(moveStick, moveAxis, rotateStick, rotateAxis, true); + /** + * Normalize all wheel speeds if the magnitude of any wheel is greater than + * 1.0. + */ + protected static void normalize(double wheelSpeeds[]) { + double maxMagnitude = Math.abs(wheelSpeeds[0]); + int i; + for (i = 1; i < kMaxNumberOfMotors; i++) { + double temp = Math.abs(wheelSpeeds[i]); + if (maxMagnitude < temp) + maxMagnitude = temp; } - - /** - * Arcade drive implements single stick driving. - * This function lets you directly provide joystick values from any source. - * @param moveValue The value to use for forwards/backwards - * @param rotateValue The value to use for the rotate right/left - * @param squaredInputs If set, decreases the sensitivity at low speeds - */ - public void arcadeDrive(double moveValue, double rotateValue, boolean squaredInputs) { - // local variables to hold the computed PWM values for the motors - if(!kArcadeStandard_Reported) { - UsageReporting.report(tResourceType.kResourceType_RobotDrive, getNumMotors(), tInstances.kRobotDrive_ArcadeStandard); - kArcadeStandard_Reported = true; - } - - double leftMotorSpeed; - double rightMotorSpeed; - - moveValue = limit(moveValue); - rotateValue = limit(rotateValue); - - if (squaredInputs) { - // square the inputs (while preserving the sign) to increase fine control while permitting full power - if (moveValue >= 0.0) { - moveValue = (moveValue * moveValue); - } else { - moveValue = -(moveValue * moveValue); - } - if (rotateValue >= 0.0) { - rotateValue = (rotateValue * rotateValue); - } else { - rotateValue = -(rotateValue * rotateValue); - } - } - - if (moveValue > 0.0) { - if (rotateValue > 0.0) { - leftMotorSpeed = moveValue - rotateValue; - rightMotorSpeed = Math.max(moveValue, rotateValue); - } else { - leftMotorSpeed = Math.max(moveValue, -rotateValue); - rightMotorSpeed = moveValue + rotateValue; - } - } else { - if (rotateValue > 0.0) { - leftMotorSpeed = -Math.max(-moveValue, rotateValue); - rightMotorSpeed = moveValue + rotateValue; - } else { - leftMotorSpeed = moveValue - rotateValue; - rightMotorSpeed = -Math.max(-moveValue, -rotateValue); - } - } - - setLeftRightMotorOutputs(leftMotorSpeed, rightMotorSpeed); + if (maxMagnitude > 1.0) { + for (i = 0; i < kMaxNumberOfMotors; i++) { + wheelSpeeds[i] = wheelSpeeds[i] / maxMagnitude; + } } + } - /** - * Arcade drive implements single stick driving. - * This function lets you directly provide joystick values from any source. - * @param moveValue The value to use for fowards/backwards - * @param rotateValue The value to use for the rotate right/left - */ - public void arcadeDrive(double moveValue, double rotateValue) { - this.arcadeDrive(moveValue, rotateValue, true); + /** + * Rotate a vector in Cartesian space. + */ + protected static double[] rotateVector(double x, double y, double angle) { + double cosA = Math.cos(angle * (3.14159 / 180.0)); + double sinA = Math.sin(angle * (3.14159 / 180.0)); + double out[] = new double[2]; + out[0] = x * cosA - y * sinA; + out[1] = x * sinA + y * cosA; + return out; + } + + /** + * Invert a motor direction. This is used when a motor should run in the + * opposite direction as the drive code would normally run it. Motors that are + * direct drive would be inverted, the drive code assumes that the motors are + * geared with one reversal. + *$ + * @param motor The motor index to invert. + * @param isInverted True if the motor should be inverted when operated. + */ + public void setInvertedMotor(MotorType motor, boolean isInverted) { + switch (motor.value) { + case MotorType.kFrontLeft_val: + m_frontLeftMotor.setInverted(isInverted); + break; + case MotorType.kFrontRight_val: + m_frontRightMotor.setInverted(isInverted); + break; + case MotorType.kRearLeft_val: + m_rearLeftMotor.setInverted(isInverted); + break; + case MotorType.kRearRight_val: + m_rearRightMotor.setInverted(isInverted); + break; } + } - /** - * Drive method for Mecanum wheeled robots. - * - * A method for driving with Mecanum wheeled robots. There are 4 wheels - * on the robot, arranged so that the front and back wheels are toed in 45 degrees. - * When looking at the wheels from the top, the roller axles should form an X across the robot. - * - * This is designed to be directly driven by joystick axes. - * - * @param x The speed that the robot should drive in the X direction. [-1.0..1.0] - * @param y The speed that the robot should drive in the Y direction. - * This input is inverted to match the forward == -1.0 that joysticks produce. [-1.0..1.0] - * @param rotation The rate of rotation for the robot that is completely independent of - * the translation. [-1.0..1.0] - * @param gyroAngle The current angle reading from the gyro. Use this to implement field-oriented controls. - */ - public void mecanumDrive_Cartesian(double x, double y, double rotation, double gyroAngle) { - if(!kMecanumCartesian_Reported) { - UsageReporting.report(tResourceType.kResourceType_RobotDrive, getNumMotors(), tInstances.kRobotDrive_MecanumCartesian); - kMecanumCartesian_Reported = true; - } - double xIn = x; - double yIn = y; - // Negate y for the joystick. - yIn = -yIn; - // Compenstate for gyro angle. - double rotated[] = rotateVector(xIn, yIn, gyroAngle); - xIn = rotated[0]; - yIn = rotated[1]; + /** + * Set the turning sensitivity. + * + * This only impacts the drive() entry-point. + *$ + * @param sensitivity Effectively sets the turning sensitivity (or turn radius + * for a given value) + */ + public void setSensitivity(double sensitivity) { + m_sensitivity = sensitivity; + } - double wheelSpeeds[] = new double[kMaxNumberOfMotors]; - wheelSpeeds[MotorType.kFrontLeft_val] = xIn + yIn + rotation; - wheelSpeeds[MotorType.kFrontRight_val] = -xIn + yIn - rotation; - wheelSpeeds[MotorType.kRearLeft_val] = -xIn + yIn + rotation; - wheelSpeeds[MotorType.kRearRight_val] = xIn + yIn - rotation; + /** + * Configure the scaling factor for using RobotDrive with motor controllers in + * a mode other than PercentVbus. + *$ + * @param maxOutput Multiplied with the output percentage computed by the + * drive functions. + */ + public void setMaxOutput(double maxOutput) { + m_maxOutput = maxOutput; + } - normalize(wheelSpeeds); - m_frontLeftMotor.set(wheelSpeeds[MotorType.kFrontLeft_val] * m_maxOutput, m_syncGroup); - m_frontRightMotor.set(wheelSpeeds[MotorType.kFrontRight_val] * m_maxOutput, m_syncGroup); - m_rearLeftMotor.set(wheelSpeeds[MotorType.kRearLeft_val] * m_maxOutput, m_syncGroup); - m_rearRightMotor.set(wheelSpeeds[MotorType.kRearRight_val] * m_maxOutput, m_syncGroup); + /** + * Set the number of the sync group for the motor controllers. If the motor + * controllers are {@link CANJaguar}s, then they will all be added to this + * sync group, causing them to update their values at the same time. + * + * @param syncGroup the update group to add the motor controllers to + */ + public void setCANJaguarSyncGroup(byte syncGroup) { + m_syncGroup = syncGroup; + } - if (m_syncGroup != 0) { - CANJaguar.updateSyncGroup(m_syncGroup); - } - - if (m_safetyHelper != null) m_safetyHelper.feed(); + /** + * Free the speed controllers if they were allocated locally + */ + public void free() { + if (m_allocatedSpeedControllers) { + if (m_frontLeftMotor != null) { + ((PWM) m_frontLeftMotor).free(); + } + if (m_frontRightMotor != null) { + ((PWM) m_frontRightMotor).free(); + } + if (m_rearLeftMotor != null) { + ((PWM) m_rearLeftMotor).free(); + } + if (m_rearRightMotor != null) { + ((PWM) m_rearRightMotor).free(); + } } + } - /** - * Drive method for Mecanum wheeled robots. - * - * A method for driving with Mecanum wheeled robots. There are 4 wheels - * on the robot, arranged so that the front and back wheels are toed in 45 degrees. - * When looking at the wheels from the top, the roller axles should form an X across the robot. - * - * @param magnitude The speed that the robot should drive in a given direction. - * @param direction The direction the robot should drive in degrees. The direction and maginitute are - * independent of the rotation rate. - * @param rotation The rate of rotation for the robot that is completely independent of - * the magnitute or direction. [-1.0..1.0] - */ - public void mecanumDrive_Polar(double magnitude, double direction, double rotation) { - if(!kMecanumPolar_Reported) { - UsageReporting.report(tResourceType.kResourceType_RobotDrive, getNumMotors(), tInstances.kRobotDrive_MecanumPolar); - kMecanumPolar_Reported = true; - } - double frontLeftSpeed, rearLeftSpeed, frontRightSpeed, rearRightSpeed; - // Normalized for full power along the Cartesian axes. - magnitude = limit(magnitude) * Math.sqrt(2.0); - // The rollers are at 45 degree angles. - double dirInRad = (direction + 45.0) * 3.14159 / 180.0; - double cosD = Math.cos(dirInRad); - double sinD = Math.sin(dirInRad); + public void setExpiration(double timeout) { + m_safetyHelper.setExpiration(timeout); + } - double wheelSpeeds[] = new double[kMaxNumberOfMotors]; - wheelSpeeds[MotorType.kFrontLeft_val] = (sinD * magnitude + rotation); - wheelSpeeds[MotorType.kFrontRight_val] = (cosD * magnitude - rotation); - wheelSpeeds[MotorType.kRearLeft_val] = (cosD * magnitude + rotation); - wheelSpeeds[MotorType.kRearRight_val] = (sinD * magnitude - rotation); + public double getExpiration() { + return m_safetyHelper.getExpiration(); + } - normalize(wheelSpeeds); + public boolean isAlive() { + return m_safetyHelper.isAlive(); + } - m_frontLeftMotor.set(wheelSpeeds[MotorType.kFrontLeft_val] * m_maxOutput, m_syncGroup); - m_frontRightMotor.set(wheelSpeeds[MotorType.kFrontRight_val] * m_maxOutput, m_syncGroup); - m_rearLeftMotor.set(wheelSpeeds[MotorType.kRearLeft_val] * m_maxOutput, m_syncGroup); - m_rearRightMotor.set(wheelSpeeds[MotorType.kRearRight_val] * m_maxOutput, m_syncGroup); + public boolean isSafetyEnabled() { + return m_safetyHelper.isSafetyEnabled(); + } - if (this.m_syncGroup != 0) { - CANJaguar.updateSyncGroup(m_syncGroup); - } + public void setSafetyEnabled(boolean enabled) { + m_safetyHelper.setSafetyEnabled(enabled); + } - if (m_safetyHelper != null) m_safetyHelper.feed(); + public String getDescription() { + return "Robot Drive"; + } + + public void stopMotor() { + if (m_frontLeftMotor != null) { + m_frontLeftMotor.set(0.0); } - - /** - * Holonomic Drive method for Mecanum wheeled robots. - * - * This is an alias to mecanumDrive_Polar() for backward compatability - * - * @param magnitude The speed that the robot should drive in a given direction. [-1.0..1.0] - * @param direction The direction the robot should drive. The direction and maginitute are - * independent of the rotation rate. - * @param rotation The rate of rotation for the robot that is completely independent of - * the magnitute or direction. [-1.0..1.0] - */ - void holonomicDrive(float magnitude, float direction, float rotation) { - mecanumDrive_Polar(magnitude, direction, rotation); + if (m_frontRightMotor != null) { + m_frontRightMotor.set(0.0); } - - /** Set the speed of the right and left motors. - * This is used once an appropriate drive setup function is called such as - * twoWheelDrive(). The motors are set to "leftSpeed" and "rightSpeed" - * and includes flipping the direction of one side for opposing motors. - * @param leftOutput The speed to send to the left side of the robot. - * @param rightOutput The speed to send to the right side of the robot. - */ - public void setLeftRightMotorOutputs(double leftOutput, double rightOutput) { - if (m_rearLeftMotor == null || m_rearRightMotor == null) { - throw new NullPointerException("Null motor provided"); - } - - if (m_frontLeftMotor != null) { - m_frontLeftMotor.set(limit(leftOutput) * m_maxOutput, m_syncGroup); - } - m_rearLeftMotor.set(limit(leftOutput) * m_maxOutput, m_syncGroup); - - if (m_frontRightMotor != null) { - m_frontRightMotor.set(-limit(rightOutput) * m_maxOutput, m_syncGroup); - } - m_rearRightMotor.set(-limit(rightOutput) * m_maxOutput, m_syncGroup); - - if (this.m_syncGroup != 0) { - CANJaguar.updateSyncGroup(m_syncGroup); - } - - if (m_safetyHelper != null) m_safetyHelper.feed(); + if (m_rearLeftMotor != null) { + m_rearLeftMotor.set(0.0); } + if (m_rearRightMotor != null) { + m_rearRightMotor.set(0.0); + } + if (m_safetyHelper != null) + m_safetyHelper.feed(); + } - /** - * Limit motor values to the -1.0 to +1.0 range. - */ - protected static double limit(double num) { - if (num > 1.0) { - return 1.0; - } - if (num < -1.0) { - return -1.0; - } - return num; - } + private void setupMotorSafety() { + m_safetyHelper = new MotorSafetyHelper(this); + m_safetyHelper.setExpiration(kDefaultExpirationTime); + m_safetyHelper.setSafetyEnabled(true); + } - /** - * Normalize all wheel speeds if the magnitude of any wheel is greater than 1.0. - */ - protected static void normalize(double wheelSpeeds[]) { - double maxMagnitude = Math.abs(wheelSpeeds[0]); - int i; - for (i=1; i 1.0) { - for (i=0; i= kDigitalChannels) { + throw new IndexOutOfBoundsException("Requested digital channel number is out of range."); } + } - /** - * Set the default location for the Solenoid module. - * - * @param moduleNumber The number of the solenoid module to use. - */ - public static void setDefaultSolenoidModule(final int moduleNumber) { - checkSolenoidModule(moduleNumber); - SensorBase.m_defaultSolenoidModule = moduleNumber; + /** + * Check that the digital channel number is valid. Verify that the channel + * number is one of the legal channel numbers. Channel numbers are 1-based. + * + * @param channel The channel number to check. + */ + protected static void checkRelayChannel(final int channel) { + if (channel < 0 || channel >= kRelayChannels) { + throw new IndexOutOfBoundsException("Requested relay channel number is out of range."); } + } - /** - * Verify that the solenoid module is correct. - * - * @param moduleNumber The solenoid module module number to check. - */ - protected static void checkSolenoidModule(final int moduleNumber) { -// if(HALLibrary.checkSolenoidModule((byte) (moduleNumber - 1)) != 0) { -// System.err.println("Solenoid module " + moduleNumber + " is not present."); -// } + /** + * Check that the digital channel number is valid. Verify that the channel + * number is one of the legal channel numbers. Channel numbers are 1-based. + * + * @param channel The channel number to check. + */ + protected static void checkPWMChannel(final int channel) { + if (channel < 0 || channel >= kPwmChannels) { + throw new IndexOutOfBoundsException("Requested PWM channel number is out of range."); } + } - /** - * Check that the digital channel number is valid. - * Verify that the channel number is one of the legal channel numbers. Channel numbers are - * 1-based. - * - * @param channel The channel number to check. - */ - protected static void checkDigitalChannel(final int channel) { - if (channel < 0 || channel >= kDigitalChannels) { - throw new IndexOutOfBoundsException("Requested digital channel number is out of range."); - } + /** + * Check that the analog input number is value. Verify that the analog input + * number is one of the legal channel numbers. Channel numbers are 0-based. + * + * @param channel The channel number to check. + */ + protected static void checkAnalogInputChannel(final int channel) { + if (channel < 0 || channel >= kAnalogInputChannels) { + throw new IndexOutOfBoundsException("Requested analog input channel number is out of range."); } + } - /** - * Check that the digital channel number is valid. - * Verify that the channel number is one of the legal channel numbers. Channel numbers are - * 1-based. - * - * @param channel The channel number to check. - */ - protected static void checkRelayChannel(final int channel) { - if (channel < 0 || channel >= kRelayChannels) { - throw new IndexOutOfBoundsException("Requested relay channel number is out of range."); - } + /** + * Check that the analog input number is value. Verify that the analog input + * number is one of the legal channel numbers. Channel numbers are 0-based. + * + * @param channel The channel number to check. + */ + protected static void checkAnalogOutputChannel(final int channel) { + if (channel < 0 || channel >= kAnalogOutputChannels) { + throw new IndexOutOfBoundsException("Requested analog output channel number is out of range."); } + } - /** - * Check that the digital channel number is valid. - * Verify that the channel number is one of the legal channel numbers. Channel numbers are - * 1-based. - * - * @param channel The channel number to check. - */ - protected static void checkPWMChannel(final int channel) { - if (channel < 0 || channel >= kPwmChannels) { - throw new IndexOutOfBoundsException("Requested PWM channel number is out of range."); - } + /** + * Verify that the solenoid channel number is within limits. Channel numbers + * are 1-based. + * + * @param channel The channel number to check. + */ + protected static void checkSolenoidChannel(final int channel) { + if (channel < 0 || channel >= kSolenoidChannels) { + throw new IndexOutOfBoundsException("Requested solenoid channel number is out of range."); } + } - /** - * Check that the analog input number is value. - * Verify that the analog input number is one of the legal channel numbers. Channel numbers - * are 0-based. - * - * @param channel The channel number to check. - */ - protected static void checkAnalogInputChannel(final int channel) { - if (channel < 0 || channel >= kAnalogInputChannels) { - throw new IndexOutOfBoundsException("Requested analog input channel number is out of range."); - } + /** + * Verify that the power distribution channel number is within limits. Channel + * numbers are 1-based. + * + * @param channel The channel number to check. + */ + protected static void checkPDPChannel(final int channel) { + if (channel < 0 || channel >= kPDPChannels) { + throw new IndexOutOfBoundsException("Requested PDP channel number is out of range."); } + } - /** - * Check that the analog input number is value. - * Verify that the analog input number is one of the legal channel numbers. Channel numbers - * are 0-based. - * - * @param channel The channel number to check. - */ - protected static void checkAnalogOutputChannel(final int channel) { - if (channel < 0 || channel >= kAnalogOutputChannels) { - throw new IndexOutOfBoundsException("Requested analog output channel number is out of range."); - } + /** + * Verify that the PDP module number is within limits. module numbers are + * 0-based. + *$ + * @param channel The module number to check. + */ + protected static void checkPDPModule(final int module) { + if (module < 0 || module > kPDPModules) { + throw new IndexOutOfBoundsException("Requested PDP module number is out of range."); } + } - /** - * Verify that the solenoid channel number is within limits. Channel numbers - * are 1-based. - * - * @param channel The channel number to check. - */ - protected static void checkSolenoidChannel(final int channel) { - if (channel < 0 || channel >= kSolenoidChannels) { - throw new IndexOutOfBoundsException("Requested solenoid channel number is out of range."); - } - } + /** + * Get the number of the default solenoid module. + * + * @return The number of the default solenoid module. + */ + public static int getDefaultSolenoidModule() { + return SensorBase.m_defaultSolenoidModule; + } - /** - * Verify that the power distribution channel number is within limits. - * Channel numbers are 1-based. - * - * @param channel The channel number to check. - */ - protected static void checkPDPChannel(final int channel) { - if (channel < 0 || channel >= kPDPChannels) { - throw new IndexOutOfBoundsException("Requested PDP channel number is out of range."); - } - } - - /** - * Verify that the PDP module number is within limits. - * module numbers are 0-based. - * - * @param channel The module number to check. - */ - protected static void checkPDPModule(final int module) { - if (module < 0 || module > kPDPModules) { - throw new IndexOutOfBoundsException("Requested PDP module number is out of range."); - } - } - - /** - * Get the number of the default solenoid module. - * - * @return The number of the default solenoid module. - */ - public static int getDefaultSolenoidModule() { - return SensorBase.m_defaultSolenoidModule; - } - - /** - * Free the resources used by this object - */ - public void free() {} + /** + * Free the resources used by this object + */ + public void free() {} } diff --git a/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/SerialPort.java b/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/SerialPort.java index 56d164fd9a..7f1a16bc50 100644 --- a/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/SerialPort.java +++ b/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/SerialPort.java @@ -1,8 +1,8 @@ /*----------------------------------------------------------------------------*/ -/* Copyright (c) FIRST 2008-2012. All Rights Reserved. */ -/* Open Source Software - may be modified and shared by FRC teams. The code */ +/* Copyright (c) FIRST 2008-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 the root directory of */ -/* the project. */ +/* the project. */ /*----------------------------------------------------------------------------*/ package edu.wpi.first.wpilibj; @@ -21,471 +21,475 @@ import edu.wpi.first.wpilibj.hal.SerialPortJNI; /** * Driver for the RS-232 serial port on the RoboRIO. * - * The current implementation uses the VISA formatted I/O mode. This means that - * all traffic goes through the formatted buffers. This allows the intermingled - * use of print(), readString(), and the raw buffer accessors read() and write(). + * The current implementation uses the VISA formatted I/O mode. This means that + * all traffic goes through the formatted buffers. This allows the intermingled + * use of print(), readString(), and the raw buffer accessors read() and + * write(). * * More information can be found in the NI-VISA User Manual here: - * http://www.ni.com/pdf/manuals/370423a.pdf - * and the NI-VISA Programmer's Reference Manual here: - * http://www.ni.com/pdf/manuals/370132c.pdf + * http://www.ni.com/pdf/manuals/370423a.pdf and the NI-VISA Programmer's + * Reference Manual here: http://www.ni.com/pdf/manuals/370132c.pdf */ public class SerialPort { - private byte m_port; - - public enum Port { - kOnboard(0), - kMXP(1), - kUSB(2); - - private int value; - - private Port(int value){ - this.value = value; - } - - public int getValue(){ - return this.value; - } - }; + private byte m_port; - /** - * Represents the parity to use for serial communications - */ - public static class Parity { + public enum Port { + kOnboard(0), kMXP(1), kUSB(2); - /** - * The integer value representing this enumeration - */ - public final int value; - static final int kNone_val = 0; - static final int kOdd_val = 1; - static final int kEven_val = 2; - static final int kMark_val = 3; - static final int kSpace_val = 4; - /** - * parity: Use no parity - */ - public static final Parity kNone = new Parity(kNone_val); - /** - * parity: Use odd parity - */ - public static final Parity kOdd = new Parity(kOdd_val); - /** - * parity: Use even parity - */ - public static final Parity kEven = new Parity(kEven_val); - /** - * parity: Use mark parity - */ - public static final Parity kMark = new Parity(kMark_val); - /** - * parity: Use space parity - */ - public static final Parity kSpace = new Parity((kSpace_val)); + private int value; - private Parity(int value) { - this.value = value; - } + private Port(int value) { + this.value = value; } - /** - * Represents the number of stop bits to use for Serial Communication - */ - public static class StopBits { - - /** - * The integer value representing this enumeration - */ - public final int value; - static final int kOne_val = 10; - static final int kOnePointFive_val = 15; - static final int kTwo_val = 20; - /** - * stopBits: use 1 - */ - public static final StopBits kOne = new StopBits(kOne_val); - /** - * stopBits: use 1.5 - */ - public static final StopBits kOnePointFive = new StopBits(kOnePointFive_val); - /** - * stopBits: use 2 - */ - public static final StopBits kTwo = new StopBits(kTwo_val); - - private StopBits(int value) { - this.value = value; - } + public int getValue() { + return this.value; } + }; + + /** + * Represents the parity to use for serial communications + */ + public static class Parity { /** - * Represents what type of flow control to use for serial communication + * The integer value representing this enumeration */ - public static class FlowControl { + public final int value; + static final int kNone_val = 0; + static final int kOdd_val = 1; + static final int kEven_val = 2; + static final int kMark_val = 3; + static final int kSpace_val = 4; + /** + * parity: Use no parity + */ + public static final Parity kNone = new Parity(kNone_val); + /** + * parity: Use odd parity + */ + public static final Parity kOdd = new Parity(kOdd_val); + /** + * parity: Use even parity + */ + public static final Parity kEven = new Parity(kEven_val); + /** + * parity: Use mark parity + */ + public static final Parity kMark = new Parity(kMark_val); + /** + * parity: Use space parity + */ + public static final Parity kSpace = new Parity((kSpace_val)); - /** - * The integer value representing this enumeration - */ - public final int value; - static final int kNone_val = 0; - static final int kXonXoff_val = 1; - static final int kRtsCts_val = 2; - static final int kDtrDsr_val = 4; - /** - * flowControl: use none - */ - public static final FlowControl kNone = new FlowControl(kNone_val); - /** - * flowcontrol: use on/off - */ - public static final FlowControl kXonXoff = new FlowControl(kXonXoff_val); - /** - * flowcontrol: use rts cts - */ - public static final FlowControl kRtsCts = new FlowControl(kRtsCts_val); - /** - * flowcontrol: use dts dsr - */ - public static final FlowControl kDtrDsr = new FlowControl(kDtrDsr_val); - - private FlowControl(int value) { - this.value = value; - } + private Parity(int value) { + this.value = value; } + } + + /** + * Represents the number of stop bits to use for Serial Communication + */ + public static class StopBits { /** - * Represents which type of buffer mode to use when writing to a serial port + * The integer value representing this enumeration */ - public static class WriteBufferMode { + public final int value; + static final int kOne_val = 10; + static final int kOnePointFive_val = 15; + static final int kTwo_val = 20; + /** + * stopBits: use 1 + */ + public static final StopBits kOne = new StopBits(kOne_val); + /** + * stopBits: use 1.5 + */ + public static final StopBits kOnePointFive = new StopBits(kOnePointFive_val); + /** + * stopBits: use 2 + */ + public static final StopBits kTwo = new StopBits(kTwo_val); - /** - * The integer value representing this enumeration - */ - public final int value; - static final int kFlushOnAccess_val = 1; - static final int kFlushWhenFull_val = 2; - /** - * Flush on access - */ - public static final WriteBufferMode kFlushOnAccess = new WriteBufferMode(kFlushOnAccess_val); - /** - * Flush when full - */ - public static final WriteBufferMode kFlushWhenFull = new WriteBufferMode(kFlushWhenFull_val); - - private WriteBufferMode(int value) { - this.value = value; - } + private StopBits(int value) { + this.value = value; } + } + + /** + * Represents what type of flow control to use for serial communication + */ + public static class FlowControl { /** - * Create an instance of a Serial Port class. - * - * @param baudRate The baud rate to configure the serial port. - * @param port The Serial port to use - * @param dataBits The number of data bits per transfer. Valid values are between 5 and 8 bits. - * @param parity Select the type of parity checking to use. - * @param stopBits The number of stop bits to use as defined by the enum StopBits. + * The integer value representing this enumeration */ - public SerialPort(final int baudRate, Port port, final int dataBits, Parity parity, StopBits stopBits) { - ByteBuffer status = ByteBuffer.allocateDirect(4); - status.order(ByteOrder.LITTLE_ENDIAN); - m_port = (byte) port.getValue(); - - SerialPortJNI.serialInitializePort(m_port, status.asIntBuffer()); - HALUtil.checkStatus(status.asIntBuffer()); - SerialPortJNI.serialSetBaudRate(m_port, baudRate, status.asIntBuffer()); - HALUtil.checkStatus(status.asIntBuffer()); - SerialPortJNI.serialSetDataBits(m_port, (byte) dataBits, status.asIntBuffer()); - HALUtil.checkStatus(status.asIntBuffer()); - SerialPortJNI.serialSetParity(m_port, (byte) parity.value, status.asIntBuffer()); - HALUtil.checkStatus(status.asIntBuffer()); - SerialPortJNI.serialSetStopBits(m_port, (byte) stopBits.value, status.asIntBuffer()); - HALUtil.checkStatus(status.asIntBuffer()); - - // Set the default read buffer size to 1 to return bytes immediately - setReadBufferSize(1); + public final int value; + static final int kNone_val = 0; + static final int kXonXoff_val = 1; + static final int kRtsCts_val = 2; + static final int kDtrDsr_val = 4; + /** + * flowControl: use none + */ + public static final FlowControl kNone = new FlowControl(kNone_val); + /** + * flowcontrol: use on/off + */ + public static final FlowControl kXonXoff = new FlowControl(kXonXoff_val); + /** + * flowcontrol: use rts cts + */ + public static final FlowControl kRtsCts = new FlowControl(kRtsCts_val); + /** + * flowcontrol: use dts dsr + */ + public static final FlowControl kDtrDsr = new FlowControl(kDtrDsr_val); - // Set the default timeout to 5 seconds. - setTimeout(5.0f); - - // Don't wait until the buffer is full to transmit. - setWriteBufferMode(WriteBufferMode.kFlushOnAccess); - - disableTermination(); - - UsageReporting.report(tResourceType.kResourceType_SerialPort,0); + private FlowControl(int value) { + this.value = value; } + } + + /** + * Represents which type of buffer mode to use when writing to a serial port + */ + public static class WriteBufferMode { /** - * Create an instance of a Serial Port class. Defaults to one stop bit. - * - * @param baudRate The baud rate to configure the serial port. - * @param dataBits The number of data bits per transfer. Valid values are between 5 and 8 bits. - * @param parity Select the type of parity checking to use. + * The integer value representing this enumeration */ - public SerialPort(final int baudRate, Port port, final int dataBits, Parity parity) { - this(baudRate, port, dataBits, parity, StopBits.kOne); - } - + public final int value; + static final int kFlushOnAccess_val = 1; + static final int kFlushWhenFull_val = 2; /** - * Create an instance of a Serial Port class. Defaults to no parity and one - * stop bit. - * - * @param baudRate The baud rate to configure the serial port. - * @param dataBits The number of data bits per transfer. Valid values are between 5 and 8 bits. + * Flush on access */ - public SerialPort(final int baudRate, Port port, final int dataBits) { - this(baudRate, port, dataBits, Parity.kNone, StopBits.kOne); - } - + public static final WriteBufferMode kFlushOnAccess = new WriteBufferMode(kFlushOnAccess_val); /** - * Create an instance of a Serial Port class. Defaults to 8 databits, - * no parity, and one stop bit. - * - * @param baudRate The baud rate to configure the serial port. + * Flush when full */ - public SerialPort(final int baudRate, Port port) { - this(baudRate, port, 8, Parity.kNone, StopBits.kOne); - } + public static final WriteBufferMode kFlushWhenFull = new WriteBufferMode(kFlushWhenFull_val); - /** - * Destructor. - */ - public void free() { - ByteBuffer status = ByteBuffer.allocateDirect(4); - status.order(ByteOrder.LITTLE_ENDIAN); - SerialPortJNI.serialClose(m_port, status.asIntBuffer()); - HALUtil.checkStatus(status.asIntBuffer()); + private WriteBufferMode(int value) { + this.value = value; } + } - /** - * Set the type of flow control to enable on this port. - * - * By default, flow control is disabled. - * @param flowControl the FlowControl value to use - */ - public void setFlowControl(FlowControl flowControl) { - ByteBuffer status = ByteBuffer.allocateDirect(4); - status.order(ByteOrder.LITTLE_ENDIAN); - SerialPortJNI.serialSetFlowControl(m_port, (byte) flowControl.value, status.asIntBuffer()); - HALUtil.checkStatus(status.asIntBuffer()); - } + /** + * Create an instance of a Serial Port class. + * + * @param baudRate The baud rate to configure the serial port. + * @param port The Serial port to use + * @param dataBits The number of data bits per transfer. Valid values are + * between 5 and 8 bits. + * @param parity Select the type of parity checking to use. + * @param stopBits The number of stop bits to use as defined by the enum + * StopBits. + */ + public SerialPort(final int baudRate, Port port, final int dataBits, Parity parity, + StopBits stopBits) { + ByteBuffer status = ByteBuffer.allocateDirect(4); + status.order(ByteOrder.LITTLE_ENDIAN); + m_port = (byte) port.getValue(); - /** - * Enable termination and specify the termination character. - * - * Termination is currently only implemented for receive. - * When the the terminator is received, the read() or readString() will return - * fewer bytes than requested, stopping after the terminator. - * - * @param terminator The character to use for termination. - */ - public void enableTermination(char terminator) { - ByteBuffer status = ByteBuffer.allocateDirect(4); - status.order(ByteOrder.LITTLE_ENDIAN); - SerialPortJNI.serialEnableTermination(m_port, terminator, status.asIntBuffer()); - HALUtil.checkStatus(status.asIntBuffer()); - } + SerialPortJNI.serialInitializePort(m_port, status.asIntBuffer()); + HALUtil.checkStatus(status.asIntBuffer()); + SerialPortJNI.serialSetBaudRate(m_port, baudRate, status.asIntBuffer()); + HALUtil.checkStatus(status.asIntBuffer()); + SerialPortJNI.serialSetDataBits(m_port, (byte) dataBits, status.asIntBuffer()); + HALUtil.checkStatus(status.asIntBuffer()); + SerialPortJNI.serialSetParity(m_port, (byte) parity.value, status.asIntBuffer()); + HALUtil.checkStatus(status.asIntBuffer()); + SerialPortJNI.serialSetStopBits(m_port, (byte) stopBits.value, status.asIntBuffer()); + HALUtil.checkStatus(status.asIntBuffer()); - /** - * Enable termination with the default terminator '\n' - * - * Termination is currently only implemented for receive. - * When the the terminator is received, the read() or readString() will return - * fewer bytes than requested, stopping after the terminator. - * - * The default terminator is '\n' - */ - public void enableTermination() { - this.enableTermination('\n'); - } + // Set the default read buffer size to 1 to return bytes immediately + setReadBufferSize(1); - /** - * Disable termination behavior. - */ - public void disableTermination() { - ByteBuffer status = ByteBuffer.allocateDirect(4); - status.order(ByteOrder.LITTLE_ENDIAN); - SerialPortJNI.serialDisableTermination(m_port, status.asIntBuffer()); - HALUtil.checkStatus(status.asIntBuffer()); - } + // Set the default timeout to 5 seconds. + setTimeout(5.0f); - /** - * Get the number of bytes currently available to read from the serial port. - * - * @return The number of bytes available to read. - */ - public int getBytesReceived() { - int retVal = 0; - ByteBuffer status = ByteBuffer.allocateDirect(4); - status.order(ByteOrder.LITTLE_ENDIAN); - retVal = SerialPortJNI.serialGetBytesRecieved(m_port, status.asIntBuffer()); - HALUtil.checkStatus(status.asIntBuffer()); - return retVal; - } + // Don't wait until the buffer is full to transmit. + setWriteBufferMode(WriteBufferMode.kFlushOnAccess); - /** - * Read a string out of the buffer. Reads the entire contents of the buffer - * - * @return The read string - */ - public String readString() { - return readString(getBytesReceived()); - } + disableTermination(); - /** - * Read a string out of the buffer. Reads the entire contents of the buffer - * - * @param count the number of characters to read into the string - * @return The read string - */ - public String readString(int count) { - byte[] out = read(count); - try { - return new String(out, 0, count, "US-ASCII"); - } catch (UnsupportedEncodingException ex) { - ex.printStackTrace(); - return new String(); - } - } + UsageReporting.report(tResourceType.kResourceType_SerialPort, 0); + } - /** - * Read raw bytes out of the buffer. - * - * @param count The maximum number of bytes to read. - * @return An array of the read bytes - */ - public byte[] read(final int count) { - ByteBuffer status = ByteBuffer.allocateDirect(4); - status.order(ByteOrder.LITTLE_ENDIAN); - ByteBuffer dataReceivedBuffer = ByteBuffer.allocateDirect(count); - int gotten = SerialPortJNI.serialRead(m_port, dataReceivedBuffer, count, status.asIntBuffer()); - HALUtil.checkStatus(status.asIntBuffer()); - byte[] retVal = new byte[gotten]; - dataReceivedBuffer.get(retVal); - return retVal; - } + /** + * Create an instance of a Serial Port class. Defaults to one stop bit. + * + * @param baudRate The baud rate to configure the serial port. + * @param dataBits The number of data bits per transfer. Valid values are + * between 5 and 8 bits. + * @param parity Select the type of parity checking to use. + */ + public SerialPort(final int baudRate, Port port, final int dataBits, Parity parity) { + this(baudRate, port, dataBits, parity, StopBits.kOne); + } - /** - * Write raw bytes to the serial port. - * - * @param buffer The buffer of bytes to write. - * @param count The maximum number of bytes to write. - * @return The number of bytes actually written into the port. - */ - public int write(byte[] buffer, int count) { - ByteBuffer status = ByteBuffer.allocateDirect(4); - status.order(ByteOrder.LITTLE_ENDIAN); - ByteBuffer dataToSendBuffer = ByteBuffer.allocateDirect(count); - dataToSendBuffer.put(buffer, 0, count); - int retVal = SerialPortJNI.serialWrite(m_port, dataToSendBuffer, count, status.asIntBuffer()); - HALUtil.checkStatus(status.asIntBuffer()); - return retVal; - } - - /** - * Write a string to the serial port - * - * @param data The string to write to the serial port. - * @return The number of bytes actually written into the port. - */ - public int writeString(String data) { - return write(data.getBytes(), data.length()); - } + /** + * Create an instance of a Serial Port class. Defaults to no parity and one + * stop bit. + * + * @param baudRate The baud rate to configure the serial port. + * @param dataBits The number of data bits per transfer. Valid values are + * between 5 and 8 bits. + */ + public SerialPort(final int baudRate, Port port, final int dataBits) { + this(baudRate, port, dataBits, Parity.kNone, StopBits.kOne); + } - /** - * Configure the timeout of the serial port. - * - * This defines the timeout for transactions with the hardware. - * It will affect reads if less bytes are available than the - * read buffer size (defaults to 1) and very large writes. - * - * @param timeout The number of seconds to to wait for I/O. - */ - public void setTimeout(double timeout) { - ByteBuffer status = ByteBuffer.allocateDirect(4); - status.order(ByteOrder.LITTLE_ENDIAN); - SerialPortJNI.serialSetTimeout(m_port, (float)timeout, status.asIntBuffer()); - HALUtil.checkStatus(status.asIntBuffer()); - } + /** + * Create an instance of a Serial Port class. Defaults to 8 databits, no + * parity, and one stop bit. + * + * @param baudRate The baud rate to configure the serial port. + */ + public SerialPort(final int baudRate, Port port) { + this(baudRate, port, 8, Parity.kNone, StopBits.kOne); + } - /** - * Specify the size of the input buffer. - * - * Specify the amount of data that can be stored before data - * from the device is returned to Read. If you want - * data that is received to be returned immediately, set this to 1. - * - * It the buffer is not filled before the read timeout expires, all - * data that has been received so far will be returned. - * - * @param size The read buffer size. - */ - public void setReadBufferSize(int size) { - ByteBuffer status = ByteBuffer.allocateDirect(4); - status.order(ByteOrder.LITTLE_ENDIAN); - SerialPortJNI.serialSetReadBufferSize(m_port, size, status.asIntBuffer()); - HALUtil.checkStatus(status.asIntBuffer()); - } + /** + * Destructor. + */ + public void free() { + ByteBuffer status = ByteBuffer.allocateDirect(4); + status.order(ByteOrder.LITTLE_ENDIAN); + SerialPortJNI.serialClose(m_port, status.asIntBuffer()); + HALUtil.checkStatus(status.asIntBuffer()); + } - /** - * Specify the size of the output buffer. - * - * Specify the amount of data that can be stored before being - * transmitted to the device. - * - * @param size The write buffer size. - */ - public void setWriteBufferSize(int size) { - ByteBuffer status = ByteBuffer.allocateDirect(4); - status.order(ByteOrder.LITTLE_ENDIAN); - SerialPortJNI.serialSetWriteBufferSize(m_port, size, status.asIntBuffer()); - HALUtil.checkStatus(status.asIntBuffer()); - } + /** + * Set the type of flow control to enable on this port. + * + * By default, flow control is disabled. + *$ + * @param flowControl the FlowControl value to use + */ + public void setFlowControl(FlowControl flowControl) { + ByteBuffer status = ByteBuffer.allocateDirect(4); + status.order(ByteOrder.LITTLE_ENDIAN); + SerialPortJNI.serialSetFlowControl(m_port, (byte) flowControl.value, status.asIntBuffer()); + HALUtil.checkStatus(status.asIntBuffer()); + } - /** - * Specify the flushing behavior of the output buffer. - * - * When set to kFlushOnAccess, data is synchronously written to the serial port - * after each call to either print() or write(). - * - * When set to kFlushWhenFull, data will only be written to the serial port when - * the buffer is full or when flush() is called. - * - * @param mode The write buffer mode. - */ - public void setWriteBufferMode(WriteBufferMode mode) { - ByteBuffer status = ByteBuffer.allocateDirect(4); - status.order(ByteOrder.LITTLE_ENDIAN); - SerialPortJNI.serialSetWriteMode(m_port, (byte)mode.value, status.asIntBuffer()); - HALUtil.checkStatus(status.asIntBuffer()); - } + /** + * Enable termination and specify the termination character. + * + * Termination is currently only implemented for receive. When the the + * terminator is received, the read() or readString() will return fewer bytes + * than requested, stopping after the terminator. + * + * @param terminator The character to use for termination. + */ + public void enableTermination(char terminator) { + ByteBuffer status = ByteBuffer.allocateDirect(4); + status.order(ByteOrder.LITTLE_ENDIAN); + SerialPortJNI.serialEnableTermination(m_port, terminator, status.asIntBuffer()); + HALUtil.checkStatus(status.asIntBuffer()); + } - /** - * Force the output buffer to be written to the port. - * - * This is used when setWriteBufferMode() is set to kFlushWhenFull to force a - * flush before the buffer is full. - */ - public void flush() { - ByteBuffer status = ByteBuffer.allocateDirect(4); - status.order(ByteOrder.LITTLE_ENDIAN); - SerialPortJNI.serialFlush(m_port, status.asIntBuffer()); - HALUtil.checkStatus(status.asIntBuffer()); - } + /** + * Enable termination with the default terminator '\n' + * + * Termination is currently only implemented for receive. When the the + * terminator is received, the read() or readString() will return fewer bytes + * than requested, stopping after the terminator. + * + * The default terminator is '\n' + */ + public void enableTermination() { + this.enableTermination('\n'); + } - /** - * Reset the serial port driver to a known state. - * - * Empty the transmit and receive buffers in the device and formatted I/O. - */ - public void reset() { - ByteBuffer status = ByteBuffer.allocateDirect(4); - status.order(ByteOrder.LITTLE_ENDIAN); - SerialPortJNI.serialClear(m_port, status.asIntBuffer()); - HALUtil.checkStatus(status.asIntBuffer()); + /** + * Disable termination behavior. + */ + public void disableTermination() { + ByteBuffer status = ByteBuffer.allocateDirect(4); + status.order(ByteOrder.LITTLE_ENDIAN); + SerialPortJNI.serialDisableTermination(m_port, status.asIntBuffer()); + HALUtil.checkStatus(status.asIntBuffer()); + } + + /** + * Get the number of bytes currently available to read from the serial port. + * + * @return The number of bytes available to read. + */ + public int getBytesReceived() { + int retVal = 0; + ByteBuffer status = ByteBuffer.allocateDirect(4); + status.order(ByteOrder.LITTLE_ENDIAN); + retVal = SerialPortJNI.serialGetBytesRecieved(m_port, status.asIntBuffer()); + HALUtil.checkStatus(status.asIntBuffer()); + return retVal; + } + + /** + * Read a string out of the buffer. Reads the entire contents of the buffer + * + * @return The read string + */ + public String readString() { + return readString(getBytesReceived()); + } + + /** + * Read a string out of the buffer. Reads the entire contents of the buffer + * + * @param count the number of characters to read into the string + * @return The read string + */ + public String readString(int count) { + byte[] out = read(count); + try { + return new String(out, 0, count, "US-ASCII"); + } catch (UnsupportedEncodingException ex) { + ex.printStackTrace(); + return new String(); } + } + + /** + * Read raw bytes out of the buffer. + * + * @param count The maximum number of bytes to read. + * @return An array of the read bytes + */ + public byte[] read(final int count) { + ByteBuffer status = ByteBuffer.allocateDirect(4); + status.order(ByteOrder.LITTLE_ENDIAN); + ByteBuffer dataReceivedBuffer = ByteBuffer.allocateDirect(count); + int gotten = SerialPortJNI.serialRead(m_port, dataReceivedBuffer, count, status.asIntBuffer()); + HALUtil.checkStatus(status.asIntBuffer()); + byte[] retVal = new byte[gotten]; + dataReceivedBuffer.get(retVal); + return retVal; + } + + /** + * Write raw bytes to the serial port. + * + * @param buffer The buffer of bytes to write. + * @param count The maximum number of bytes to write. + * @return The number of bytes actually written into the port. + */ + public int write(byte[] buffer, int count) { + ByteBuffer status = ByteBuffer.allocateDirect(4); + status.order(ByteOrder.LITTLE_ENDIAN); + ByteBuffer dataToSendBuffer = ByteBuffer.allocateDirect(count); + dataToSendBuffer.put(buffer, 0, count); + int retVal = SerialPortJNI.serialWrite(m_port, dataToSendBuffer, count, status.asIntBuffer()); + HALUtil.checkStatus(status.asIntBuffer()); + return retVal; + } + + /** + * Write a string to the serial port + * + * @param data The string to write to the serial port. + * @return The number of bytes actually written into the port. + */ + public int writeString(String data) { + return write(data.getBytes(), data.length()); + } + + /** + * Configure the timeout of the serial port. + * + * This defines the timeout for transactions with the hardware. It will affect + * reads if less bytes are available than the read buffer size (defaults to 1) + * and very large writes. + * + * @param timeout The number of seconds to to wait for I/O. + */ + public void setTimeout(double timeout) { + ByteBuffer status = ByteBuffer.allocateDirect(4); + status.order(ByteOrder.LITTLE_ENDIAN); + SerialPortJNI.serialSetTimeout(m_port, (float) timeout, status.asIntBuffer()); + HALUtil.checkStatus(status.asIntBuffer()); + } + + /** + * Specify the size of the input buffer. + * + * Specify the amount of data that can be stored before data from the device + * is returned to Read. If you want data that is received to be returned + * immediately, set this to 1. + * + * It the buffer is not filled before the read timeout expires, all data that + * has been received so far will be returned. + * + * @param size The read buffer size. + */ + public void setReadBufferSize(int size) { + ByteBuffer status = ByteBuffer.allocateDirect(4); + status.order(ByteOrder.LITTLE_ENDIAN); + SerialPortJNI.serialSetReadBufferSize(m_port, size, status.asIntBuffer()); + HALUtil.checkStatus(status.asIntBuffer()); + } + + /** + * Specify the size of the output buffer. + * + * Specify the amount of data that can be stored before being transmitted to + * the device. + * + * @param size The write buffer size. + */ + public void setWriteBufferSize(int size) { + ByteBuffer status = ByteBuffer.allocateDirect(4); + status.order(ByteOrder.LITTLE_ENDIAN); + SerialPortJNI.serialSetWriteBufferSize(m_port, size, status.asIntBuffer()); + HALUtil.checkStatus(status.asIntBuffer()); + } + + /** + * Specify the flushing behavior of the output buffer. + * + * When set to kFlushOnAccess, data is synchronously written to the serial + * port after each call to either print() or write(). + * + * When set to kFlushWhenFull, data will only be written to the serial port + * when the buffer is full or when flush() is called. + * + * @param mode The write buffer mode. + */ + public void setWriteBufferMode(WriteBufferMode mode) { + ByteBuffer status = ByteBuffer.allocateDirect(4); + status.order(ByteOrder.LITTLE_ENDIAN); + SerialPortJNI.serialSetWriteMode(m_port, (byte) mode.value, status.asIntBuffer()); + HALUtil.checkStatus(status.asIntBuffer()); + } + + /** + * Force the output buffer to be written to the port. + * + * This is used when setWriteBufferMode() is set to kFlushWhenFull to force a + * flush before the buffer is full. + */ + public void flush() { + ByteBuffer status = ByteBuffer.allocateDirect(4); + status.order(ByteOrder.LITTLE_ENDIAN); + SerialPortJNI.serialFlush(m_port, status.asIntBuffer()); + HALUtil.checkStatus(status.asIntBuffer()); + } + + /** + * Reset the serial port driver to a known state. + * + * Empty the transmit and receive buffers in the device and formatted I/O. + */ + public void reset() { + ByteBuffer status = ByteBuffer.allocateDirect(4); + status.order(ByteOrder.LITTLE_ENDIAN); + SerialPortJNI.serialClear(m_port, status.asIntBuffer()); + HALUtil.checkStatus(status.asIntBuffer()); + } } diff --git a/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/Servo.java b/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/Servo.java index 584e2d6b5b..93a20b2579 100644 --- a/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/Servo.java +++ b/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/Servo.java @@ -1,8 +1,8 @@ /*----------------------------------------------------------------------------*/ -/* Copyright (c) FIRST 2008-2014. All Rights Reserved. */ -/* Open Source Software - may be modified and shared by FRC teams. The code */ +/* Copyright (c) FIRST 2008-2014. All Rights Reserved. */ +/* Open Source Software - may be modified and shared by FRC teams. The code */ /* must be accompanied by the FIRST BSD license file in the root directory of */ -/* the project. */ +/* the project. */ /*----------------------------------------------------------------------------*/ package edu.wpi.first.wpilibj; @@ -16,146 +16,156 @@ import edu.wpi.first.wpilibj.tables.ITableListener; /** * Standard hobby style servo. * - * The range parameters default to the appropriate values for the Hitec HS-322HD servo provided - * in the FIRST Kit of Parts in 2008. + * The range parameters default to the appropriate values for the Hitec HS-322HD + * servo provided in the FIRST Kit of Parts in 2008. */ public class Servo extends PWM { - private static final double kMaxServoAngle = 180.0; - private static final double kMinServoAngle = 0.0; + private static final double kMaxServoAngle = 180.0; + private static final double kMinServoAngle = 0.0; - protected static final double kDefaultMaxServoPWM = 2.4; - protected static final double kDefaultMinServoPWM = .6; + protected static final double kDefaultMaxServoPWM = 2.4; + protected static final double kDefaultMinServoPWM = .6; - /** - * Common initialization code called by all constructors. - * - * InitServo() assigns defaults for the period multiplier for the servo PWM control signal, as - * well as the minimum and maximum PWM values supported by the servo. - * - */ - private void initServo() { - setBounds(kDefaultMaxServoPWM, 0, 0, 0, kDefaultMinServoPWM); - setPeriodMultiplier(PeriodMultiplier.k4X); + /** + * Common initialization code called by all constructors. + * + * InitServo() assigns defaults for the period multiplier for the servo PWM + * control signal, as well as the minimum and maximum PWM values supported by + * the servo. + * + */ + private void initServo() { + setBounds(kDefaultMaxServoPWM, 0, 0, 0, kDefaultMinServoPWM); + setPeriodMultiplier(PeriodMultiplier.k4X); - LiveWindow.addActuator("Servo", getChannel(), this); - UsageReporting.report(tResourceType.kResourceType_Servo, getChannel()); + LiveWindow.addActuator("Servo", getChannel(), this); + UsageReporting.report(tResourceType.kResourceType_Servo, getChannel()); + } + + /** + * Constructor.
+ * + * By default {@value #kDefaultMaxServoPWM} ms is used as the maxPWM value
+ * By default {@value #kDefaultMinServoPWM} ms is used as the minPWM value
+ * + * @param channel The PWM channel to which the servo is attached. 0-9 are + * on-board, 10-19 are on the MXP port + */ + public Servo(final int channel) { + super(channel); + initServo(); + } + + + /** + * Set the servo position. + * + * Servo values range from 0.0 to 1.0 corresponding to the range of full left + * to full right. + * + * @param value Position from 0.0 to 1.0. + */ + public void set(double value) { + setPosition(value); + } + + /** + * Get the servo position. + * + * Servo values range from 0.0 to 1.0 corresponding to the range of full left + * to full right. + * + * @return Position from 0.0 to 1.0. + */ + public double get() { + return getPosition(); + } + + /** + * Set the servo angle. + * + * Assume that the servo angle is linear with respect to the PWM value (big + * assumption, need to test). + * + * Servo angles that are out of the supported range of the servo simply + * "saturate" in that direction In other words, if the servo has a range of (X + * degrees to Y degrees) than angles of less than X result in an angle of X + * being set and angles of more than Y degrees result in an angle of Y being + * set. + * + * @param degrees The angle in degrees to set the servo. + */ + public void setAngle(double degrees) { + if (degrees < kMinServoAngle) { + degrees = kMinServoAngle; + } else if (degrees > kMaxServoAngle) { + degrees = kMaxServoAngle; } - /** - * Constructor.
- * - * By default {@value #kDefaultMaxServoPWM} ms is used as the maxPWM value
- * By default {@value #kDefaultMinServoPWM} ms is used as the minPWM value
- * - * @param channel The PWM channel to which the servo is attached. 0-9 are on-board, 10-19 are on the MXP port - */ - public Servo(final int channel) { - super(channel); - initServo(); + setPosition(((degrees - kMinServoAngle)) / getServoAngleRange()); + } + + /** + * Get the servo angle. + * + * Assume that the servo angle is linear with respect to the PWM value (big + * assumption, need to test). + *$ + * @return The angle in degrees to which the servo is set. + */ + public double getAngle() { + return getPosition() * getServoAngleRange() + kMinServoAngle; + } + + private double getServoAngleRange() { + return kMaxServoAngle - kMinServoAngle; + } + + /* + * Live Window code, only does anything if live window is activated. + */ + public String getSmartDashboardType() { + return "Servo"; + } + + private ITable m_table; + private ITableListener m_table_listener; + + /** + * {@inheritDoc} + */ + public void initTable(ITable subtable) { + m_table = subtable; + updateTable(); + } + + /** + * {@inheritDoc} + */ + public void updateTable() { + if (m_table != null) { + m_table.putNumber("Value", get()); } + } + /** + * {@inheritDoc} + */ + public void startLiveWindowMode() { + m_table_listener = new ITableListener() { + public void valueChanged(ITable itable, String key, Object value, boolean bln) { + set(((Double) value).doubleValue()); + } + }; + m_table.addTableListener("Value", m_table_listener, true); + } - /** - * Set the servo position. - * - * Servo values range from 0.0 to 1.0 corresponding to the range of full left to full right. - * - * @param value Position from 0.0 to 1.0. - */ - public void set(double value) { - setPosition(value); - } - - /** - * Get the servo position. - * - * Servo values range from 0.0 to 1.0 corresponding to the range of full left to full right. - * - * @return Position from 0.0 to 1.0. - */ - public double get() { - return getPosition(); - } - - /** - * Set the servo angle. - * - * Assume that the servo angle is linear with respect to the PWM value (big assumption, need to test). - * - * Servo angles that are out of the supported range of the servo simply "saturate" in that direction - * In other words, if the servo has a range of (X degrees to Y degrees) than angles of less than X - * result in an angle of X being set and angles of more than Y degrees result in an angle of Y being set. - * - * @param degrees The angle in degrees to set the servo. - */ - public void setAngle(double degrees) { - if (degrees < kMinServoAngle) { - degrees = kMinServoAngle; - } else if (degrees > kMaxServoAngle) { - degrees = kMaxServoAngle; - } - - setPosition(((degrees - kMinServoAngle)) / getServoAngleRange()); - } - - /** - * Get the servo angle. - * - * Assume that the servo angle is linear with respect to the PWM value (big assumption, need to test). - * @return The angle in degrees to which the servo is set. - */ - public double getAngle() { - return getPosition() * getServoAngleRange() + kMinServoAngle; - } - - private double getServoAngleRange() { - return kMaxServoAngle - kMinServoAngle; - } - - /* - * Live Window code, only does anything if live window is activated. - */ - public String getSmartDashboardType() { - return "Servo"; - } - private ITable m_table; - private ITableListener m_table_listener; - - /** - * {@inheritDoc} - */ - public void initTable(ITable subtable) { - m_table = subtable; - updateTable(); - } - - /** - * {@inheritDoc} - */ - public void updateTable() { - if (m_table != null) { - m_table.putNumber("Value", get()); - } - } - - /** - * {@inheritDoc} - */ - public void startLiveWindowMode() { - m_table_listener = new ITableListener() { - public void valueChanged(ITable itable, String key, Object value, boolean bln) { - set(((Double) value).doubleValue()); - } - }; - m_table.addTableListener("Value", m_table_listener, true); - } - - /** - * {@inheritDoc} - */ - public void stopLiveWindowMode() { - // TODO: Broken, should only remove the listener from "Value" only. - m_table.removeTableListener(m_table_listener); - } + /** + * {@inheritDoc} + */ + public void stopLiveWindowMode() { + // TODO: Broken, should only remove the listener from "Value" only. + m_table.removeTableListener(m_table_listener); + } } diff --git a/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/Solenoid.java b/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/Solenoid.java index 15c5307267..fb9f360600 100644 --- a/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/Solenoid.java +++ b/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/Solenoid.java @@ -1,8 +1,8 @@ /*----------------------------------------------------------------------------*/ -/* Copyright (c) FIRST 2008-2012. All Rights Reserved. */ -/* Open Source Software - may be modified and shared by FRC teams. The code */ +/* Copyright (c) FIRST 2008-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 the root directory of */ -/* the project. */ +/* the project. */ /*----------------------------------------------------------------------------*/ package edu.wpi.first.wpilibj; @@ -24,148 +24,152 @@ import edu.wpi.first.wpilibj.util.CheckedAllocationException; /** * Solenoid class for running high voltage Digital Output. * - * The Solenoid class is typically used for pneumatics solenoids, but could be used - * for any device within the current spec of the PCM. + * The Solenoid class is typically used for pneumatics solenoids, but could be + * used for any device within the current spec of the PCM. */ public class Solenoid extends SolenoidBase implements LiveWindowSendable { - private int m_channel; ///< The channel to control. - private ByteBuffer m_solenoid_port; + private int m_channel; // /< The channel to control. + private ByteBuffer m_solenoid_port; - /** - * Common function to implement constructor behavior. - */ - private synchronized void initSolenoid() { - checkSolenoidModule(m_moduleNumber); - checkSolenoidChannel(m_channel); + /** + * Common function to implement constructor behavior. + */ + private synchronized void initSolenoid() { + checkSolenoidModule(m_moduleNumber); + checkSolenoidChannel(m_channel); - ByteBuffer status = ByteBuffer.allocateDirect(4); - status.order(ByteOrder.LITTLE_ENDIAN); + ByteBuffer status = ByteBuffer.allocateDirect(4); + status.order(ByteOrder.LITTLE_ENDIAN); - ByteBuffer port = SolenoidJNI.getPortWithModule((byte) m_moduleNumber, (byte) m_channel); - m_solenoid_port = SolenoidJNI.initializeSolenoidPort(port, status.asIntBuffer()); - HALUtil.checkStatus(status.asIntBuffer()); + ByteBuffer port = SolenoidJNI.getPortWithModule((byte) m_moduleNumber, (byte) m_channel); + m_solenoid_port = SolenoidJNI.initializeSolenoidPort(port, status.asIntBuffer()); + HALUtil.checkStatus(status.asIntBuffer()); - LiveWindow.addActuator("Solenoid", m_moduleNumber, m_channel, this); - UsageReporting.report(tResourceType.kResourceType_Solenoid, m_channel, m_moduleNumber); - } - - /** - * Constructor using the default PCM ID (0) - * - * @param channel The channel on the PCM to control (0..7). - */ - public Solenoid(final int channel) { - super(getDefaultSolenoidModule()); - m_channel = channel; - initSolenoid(); - } - - /** - * Constructor. - * - * @param moduleNumber The CAN ID of the PCM the solenoid is attached to. - * @param channel The channel on the PCM to control (0..7). - */ - public Solenoid(final int moduleNumber, final int channel) { - super(moduleNumber); - m_channel = channel; - initSolenoid(); - } - - /** - * Destructor. - */ - public synchronized void free() { - // m_allocated.free((m_moduleNumber - 1) * kSolenoidChannels + m_channel - 1); - } - - /** - * Set the value of a solenoid. - * - * @param on Turn the solenoid output off or on. - */ - public void set(boolean on) { - byte value = (byte) (on ? 0xFF : 0x00); - byte mask = (byte) (1 << m_channel); - - set(value, mask); - } - - /** - * Read the current value of the solenoid. - * - * @return The current value of the solenoid. - */ - public boolean get() { - int value = getAll() & ( 1 << m_channel); - return (value != 0); - } - /** - * Check if solenoid is blacklisted. - * If a solenoid is shorted, it is added to the blacklist and - * disabled until power cycle, or until faults are cleared. - * @see clearAllPCMStickyFaults() - * - * @return If solenoid is disabled due to short. - */ - public boolean isBlackListed() { - int value = getPCMSolenoidBlackList() & ( 1 << m_channel); - return (value != 0); - } - /* - * Live Window code, only does anything if live window is activated. - */ - public String getSmartDashboardType() { - return "Solenoid"; - } - private ITable m_table; - private ITableListener m_table_listener; - - /** - * {@inheritDoc} - */ - public void initTable(ITable subtable) { - m_table = subtable; - updateTable(); - } - - /** - * {@inheritDoc} - */ - public ITable getTable() { - return m_table; - } - - /** - * {@inheritDoc} - */ - public void updateTable() { - if (m_table != null) { - m_table.putBoolean("Value", get()); - } + LiveWindow.addActuator("Solenoid", m_moduleNumber, m_channel, this); + UsageReporting.report(tResourceType.kResourceType_Solenoid, m_channel, m_moduleNumber); + } + + /** + * Constructor using the default PCM ID (0) + * + * @param channel The channel on the PCM to control (0..7). + */ + public Solenoid(final int channel) { + super(getDefaultSolenoidModule()); + m_channel = channel; + initSolenoid(); + } + + /** + * Constructor. + * + * @param moduleNumber The CAN ID of the PCM the solenoid is attached to. + * @param channel The channel on the PCM to control (0..7). + */ + public Solenoid(final int moduleNumber, final int channel) { + super(moduleNumber); + m_channel = channel; + initSolenoid(); + } + + /** + * Destructor. + */ + public synchronized void free() { + // m_allocated.free((m_moduleNumber - 1) * kSolenoidChannels + m_channel - + // 1); + } + + /** + * Set the value of a solenoid. + * + * @param on Turn the solenoid output off or on. + */ + public void set(boolean on) { + byte value = (byte) (on ? 0xFF : 0x00); + byte mask = (byte) (1 << m_channel); + + set(value, mask); + } + + /** + * Read the current value of the solenoid. + * + * @return The current value of the solenoid. + */ + public boolean get() { + int value = getAll() & (1 << m_channel); + return (value != 0); + } + + /** + * Check if solenoid is blacklisted. If a solenoid is shorted, it is added to + * the blacklist and disabled until power cycle, or until faults are cleared. + * + * @see clearAllPCMStickyFaults() + * + * @return If solenoid is disabled due to short. + */ + public boolean isBlackListed() { + int value = getPCMSolenoidBlackList() & (1 << m_channel); + return (value != 0); + } + + /* + * Live Window code, only does anything if live window is activated. + */ + public String getSmartDashboardType() { + return "Solenoid"; + } + + private ITable m_table; + private ITableListener m_table_listener; + + /** + * {@inheritDoc} + */ + public void initTable(ITable subtable) { + m_table = subtable; + updateTable(); + } + + /** + * {@inheritDoc} + */ + public ITable getTable() { + return m_table; + } + + /** + * {@inheritDoc} + */ + public void updateTable() { + if (m_table != null) { + m_table.putBoolean("Value", get()); } + } - /** - * {@inheritDoc} - */ - public void startLiveWindowMode() { - set(false); // Stop for safety - m_table_listener = new ITableListener() { - public void valueChanged(ITable itable, String key, Object value, boolean bln) { - set(((Boolean) value).booleanValue()); - } - }; - m_table.addTableListener("Value", m_table_listener, true); - } + /** + * {@inheritDoc} + */ + public void startLiveWindowMode() { + set(false); // Stop for safety + m_table_listener = new ITableListener() { + public void valueChanged(ITable itable, String key, Object value, boolean bln) { + set(((Boolean) value).booleanValue()); + } + }; + m_table.addTableListener("Value", m_table_listener, true); + } - /** - * {@inheritDoc} - */ - public void stopLiveWindowMode() { - set(false); // Stop for safety - // TODO: Broken, should only remove the listener from "Value" only. - m_table.removeTableListener(m_table_listener); - } + /** + * {@inheritDoc} + */ + public void stopLiveWindowMode() { + set(false); // Stop for safety + // TODO: Broken, should only remove the listener from "Value" only. + m_table.removeTableListener(m_table_listener); + } } diff --git a/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/SolenoidBase.java b/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/SolenoidBase.java index d8bf7991a5..a227bd0a91 100644 --- a/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/SolenoidBase.java +++ b/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/SolenoidBase.java @@ -1,8 +1,8 @@ /*----------------------------------------------------------------------------*/ -/* Copyright (c) FIRST 2008-2012. All Rights Reserved. */ -/* Open Source Software - may be modified and shared by FRC teams. The code */ +/* Copyright (c) FIRST 2008-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 the root directory of */ -/* the project. */ +/* the project. */ /*----------------------------------------------------------------------------*/ package edu.wpi.first.wpilibj; @@ -19,113 +19,117 @@ import edu.wpi.first.wpilibj.hal.SolenoidJNI; */ public abstract class SolenoidBase extends SensorBase { - private ByteBuffer[] m_ports; - protected int m_moduleNumber; ///< The number of the solenoid module being used. - protected Resource m_allocated = new Resource(63* SensorBase.kSolenoidChannels); + private ByteBuffer[] m_ports; + protected int m_moduleNumber; // /< The number of the solenoid module being + // used. + protected Resource m_allocated = new Resource(63 * SensorBase.kSolenoidChannels); - /** - * Constructor. - * - * @param moduleNumber The PCM CAN ID - */ - public SolenoidBase(final int moduleNumber) { - m_moduleNumber = moduleNumber; - m_ports = new ByteBuffer[SensorBase.kSolenoidChannels]; - for (int i = 0; i < SensorBase.kSolenoidChannels; i++) { - ByteBuffer port = SolenoidJNI.getPortWithModule((byte) moduleNumber, (byte) i); - IntBuffer status = IntBuffer.allocate(1); - m_ports[i] = SolenoidJNI.initializeSolenoidPort(port, status); - HALUtil.checkStatus(status); - } + /** + * Constructor. + * + * @param moduleNumber The PCM CAN ID + */ + public SolenoidBase(final int moduleNumber) { + m_moduleNumber = moduleNumber; + m_ports = new ByteBuffer[SensorBase.kSolenoidChannels]; + for (int i = 0; i < SensorBase.kSolenoidChannels; i++) { + ByteBuffer port = SolenoidJNI.getPortWithModule((byte) moduleNumber, (byte) i); + IntBuffer status = IntBuffer.allocate(1); + m_ports[i] = SolenoidJNI.initializeSolenoidPort(port, status); + HALUtil.checkStatus(status); } + } - /** - * Set the value of a solenoid. - * - * @param value The value you want to set on the module. - * @param mask The channels you want to be affected. - */ - protected synchronized void set(int value, int mask) { - IntBuffer status = ByteBuffer.allocateDirect(4).asIntBuffer(); - for (int i = 0; i < SensorBase.kSolenoidChannels; i++) { - int local_mask = 1 << i; - if ((mask & local_mask) != 0) - SolenoidJNI.setSolenoid(m_ports[i], (byte) (value & local_mask), status); - } - HALUtil.checkStatus(status); + /** + * Set the value of a solenoid. + * + * @param value The value you want to set on the module. + * @param mask The channels you want to be affected. + */ + protected synchronized void set(int value, int mask) { + IntBuffer status = ByteBuffer.allocateDirect(4).asIntBuffer(); + for (int i = 0; i < SensorBase.kSolenoidChannels; i++) { + int local_mask = 1 << i; + if ((mask & local_mask) != 0) + SolenoidJNI.setSolenoid(m_ports[i], (byte) (value & local_mask), status); } + HALUtil.checkStatus(status); + } - /** - * Read all 8 solenoids from the module used by this solenoid as a single byte - * - * @return The current value of all 8 solenoids on this module. - */ - public byte getAll() { - byte value = 0; - IntBuffer status = ByteBuffer.allocateDirect(4).asIntBuffer(); - for (int i = 0; i < SensorBase.kSolenoidChannels; i++) { - value |= SolenoidJNI.getSolenoid(m_ports[i], status) << i; - } - HALUtil.checkStatus(status); - return value; + /** + * Read all 8 solenoids from the module used by this solenoid as a single byte + * + * @return The current value of all 8 solenoids on this module. + */ + public byte getAll() { + byte value = 0; + IntBuffer status = ByteBuffer.allocateDirect(4).asIntBuffer(); + for (int i = 0; i < SensorBase.kSolenoidChannels; i++) { + value |= SolenoidJNI.getSolenoid(m_ports[i], status) << i; } - /** - * Reads complete solenoid blacklist for all 8 solenoids as a single byte. - * - * If a solenoid is shorted, it is added to the blacklist and - * disabled until power cycle, or until faults are cleared. - * @see #clearAllPCMStickyFaults() - * - * @return The solenoid blacklist of all 8 solenoids on the module. - */ - public byte getPCMSolenoidBlackList() { - IntBuffer status = ByteBuffer.allocateDirect(4).asIntBuffer(); + HALUtil.checkStatus(status); + return value; + } - byte retval = SolenoidJNI.getPCMSolenoidBlackList(m_ports[0], status); - HALUtil.checkStatus(status); + /** + * Reads complete solenoid blacklist for all 8 solenoids as a single byte. + *$ + * If a solenoid is shorted, it is added to the blacklist and disabled until + * power cycle, or until faults are cleared. + * + * @see #clearAllPCMStickyFaults() + *$ + * @return The solenoid blacklist of all 8 solenoids on the module. + */ + public byte getPCMSolenoidBlackList() { + IntBuffer status = ByteBuffer.allocateDirect(4).asIntBuffer(); - return retval; - } - /** - * @return true if PCM sticky fault is set : The common - * highside solenoid voltage rail is too low, - * most likely a solenoid channel is shorted. - */ - public boolean getPCMSolenoidVoltageStickyFault() { - IntBuffer status = ByteBuffer.allocateDirect(4).asIntBuffer(); + byte retval = SolenoidJNI.getPCMSolenoidBlackList(m_ports[0], status); + HALUtil.checkStatus(status); - boolean retval = SolenoidJNI.getPCMSolenoidVoltageStickyFault(m_ports[0], status); - HALUtil.checkStatus(status); + return retval; + } - return retval; - } - /** - * @return true if PCM is in fault state : The common - * highside solenoid voltage rail is too low, - * most likely a solenoid channel is shorted. - */ - public boolean getPCMSolenoidVoltageFault() { - IntBuffer status = ByteBuffer.allocateDirect(4).asIntBuffer(); + /** + * @return true if PCM sticky fault is set : The common highside solenoid + * voltage rail is too low, most likely a solenoid channel is shorted. + */ + public boolean getPCMSolenoidVoltageStickyFault() { + IntBuffer status = ByteBuffer.allocateDirect(4).asIntBuffer(); - boolean retval = SolenoidJNI.getPCMSolenoidVoltageFault(m_ports[0], status); - HALUtil.checkStatus(status); + boolean retval = SolenoidJNI.getPCMSolenoidVoltageStickyFault(m_ports[0], status); + HALUtil.checkStatus(status); - return retval; - } - /** - * Clear ALL sticky faults inside PCM that Compressor is wired to. - * - * If a sticky fault is set, then it will be persistently cleared. Compressor drive - * maybe momentarily disable while flags are being cleared. Care should be - * taken to not call this too frequently, otherwise normal compressor - * functionality may be prevented. - * - * If no sticky faults are set then this call will have no effect. - */ - public void clearAllPCMStickyFaults() { - IntBuffer status = ByteBuffer.allocateDirect(4).asIntBuffer(); + return retval; + } - SolenoidJNI.clearAllPCMStickyFaults(m_ports[0], status); - HALUtil.checkStatus(status); - } + /** + * @return true if PCM is in fault state : The common highside solenoid + * voltage rail is too low, most likely a solenoid channel is shorted. + */ + public boolean getPCMSolenoidVoltageFault() { + IntBuffer status = ByteBuffer.allocateDirect(4).asIntBuffer(); + + boolean retval = SolenoidJNI.getPCMSolenoidVoltageFault(m_ports[0], status); + HALUtil.checkStatus(status); + + return retval; + } + + /** + * Clear ALL sticky faults inside PCM that Compressor is wired to. + * + * If a sticky fault is set, then it will be persistently cleared. Compressor + * drive maybe momentarily disable while flags are being cleared. Care should + * be taken to not call this too frequently, otherwise normal compressor + * functionality may be prevented. + * + * If no sticky faults are set then this call will have no effect. + */ + public void clearAllPCMStickyFaults() { + IntBuffer status = ByteBuffer.allocateDirect(4).asIntBuffer(); + + SolenoidJNI.clearAllPCMStickyFaults(m_ports[0], status); + HALUtil.checkStatus(status); + } } diff --git a/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/SpeedController.java b/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/SpeedController.java index 51f3f04977..0e636e4163 100644 --- a/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/SpeedController.java +++ b/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/SpeedController.java @@ -1,8 +1,8 @@ /*----------------------------------------------------------------------------*/ -/* Copyright (c) FIRST 2008-2012. All Rights Reserved. */ -/* Open Source Software - may be modified and shared by FRC teams. The code */ +/* Copyright (c) FIRST 2008-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 the root directory of */ -/* the project. */ +/* the project. */ /*----------------------------------------------------------------------------*/ package edu.wpi.first.wpilibj; @@ -12,48 +12,49 @@ package edu.wpi.first.wpilibj; */ public interface SpeedController extends PIDOutput { - /** - * Common interface for getting the current set speed of a speed controller. - * - * @return The current set speed. Value is between -1.0 and 1.0. - */ - double get(); + /** + * Common interface for getting the current set speed of a speed controller. + * + * @return The current set speed. Value is between -1.0 and 1.0. + */ + double get(); - /** - * Common interface for setting the speed of a speed controller. - * - * @param speed The speed to set. Value should be between -1.0 and 1.0. - * @param syncGroup The update group to add this Set() to, pending UpdateSyncGroup(). If 0, update immediately. - */ - void set(double speed, byte syncGroup); + /** + * Common interface for setting the speed of a speed controller. + * + * @param speed The speed to set. Value should be between -1.0 and 1.0. + * @param syncGroup The update group to add this Set() to, pending + * UpdateSyncGroup(). If 0, update immediately. + */ + void set(double speed, byte syncGroup); - /** - * Common interface for setting the speed of a speed controller. - * - * @param speed The speed to set. Value should be between -1.0 and 1.0. - */ - void set(double speed); + /** + * Common interface for setting the speed of a speed controller. + * + * @param speed The speed to set. Value should be between -1.0 and 1.0. + */ + void set(double speed); - /** - * Common interface for inverting direction of a speed controller. - * - * @param isInverted The state of inversion true is inverted. - */ - void setInverted(boolean isInverted); + /** + * Common interface for inverting direction of a speed controller. + * + * @param isInverted The state of inversion true is inverted. + */ + void setInverted(boolean isInverted); - /** - * Common interface for returning if a speed controller - * is in the inverted state or not. - * - * @return isInverted The state of the inversion true is inverted. - * - */ - boolean getInverted(); + /** + * Common interface for returning if a speed controller is in the inverted + * state or not. + *$ + * @return isInverted The state of the inversion true is inverted. + * + */ + boolean getInverted(); - /** - * Disable the speed controller - */ - void disable(); + /** + * Disable the speed controller + */ + void disable(); } diff --git a/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/Talon.java b/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/Talon.java index 29cba2ed12..595cc1a527 100644 --- a/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/Talon.java +++ b/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/Talon.java @@ -1,8 +1,8 @@ /*----------------------------------------------------------------------------*/ -/* Copyright (c) FIRST 2008-2012. All Rights Reserved. */ -/* Open Source Software - may be modified and shared by FRC teams. The code */ +/* Copyright (c) FIRST 2008-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 the root directory of */ -/* the project. */ +/* the project. */ /*----------------------------------------------------------------------------*/ package edu.wpi.first.wpilibj; @@ -15,106 +15,110 @@ import edu.wpi.first.wpilibj.livewindow.LiveWindow; * Cross the Road Electronics (CTRE) Talon and Talon SR Speed Controller */ public class Talon extends SafePWM implements SpeedController { -private boolean isInverted = false; - /** - * Common initialization code called by all constructors. - * - * Note that the Talon uses the following bounds for PWM values. These values should work reasonably well for - * most controllers, but if users experience issues such as asymmetric behavior around - * the deadband or inability to saturate the controller in either direction, calibration is recommended. - * The calibration procedure can be found in the Talon User Manual available from CTRE. - * - * - 2.037ms = full "forward" - * - 1.539ms = the "high end" of the deadband range - * - 1.513ms = center of the deadband range (off) - * - 1.487ms = the "low end" of the deadband range - * - .989ms = full "reverse" - */ - private void initTalon() { - setBounds(2.037, 1.539, 1.513, 1.487, .989); - setPeriodMultiplier(PeriodMultiplier.k1X); - setRaw(m_centerPwm); - setZeroLatch(); + private boolean isInverted = false; - LiveWindow.addActuator("Talon", getChannel(), this); - UsageReporting.report(tResourceType.kResourceType_Talon, getChannel()); - } + /** + * Common initialization code called by all constructors. + * + * Note that the Talon uses the following bounds for PWM values. These values + * should work reasonably well for most controllers, but if users experience + * issues such as asymmetric behavior around the deadband or inability to + * saturate the controller in either direction, calibration is recommended. + * The calibration procedure can be found in the Talon User Manual available + * from CTRE. + * + * - 2.037ms = full "forward" - 1.539ms = the "high end" of the deadband range + * - 1.513ms = center of the deadband range (off) - 1.487ms = the "low end" of + * the deadband range - .989ms = full "reverse" + */ + private void initTalon() { + setBounds(2.037, 1.539, 1.513, 1.487, .989); + setPeriodMultiplier(PeriodMultiplier.k1X); + setRaw(m_centerPwm); + setZeroLatch(); - /** - * Constructor for a Talon (original or Talon SR) - * - * @param channel The PWM channel that the Talon is attached to. 0-9 are on-board, 10-19 are on the MXP port - */ - public Talon(final int channel) { - super(channel); - initTalon(); - } + LiveWindow.addActuator("Talon", getChannel(), this); + UsageReporting.report(tResourceType.kResourceType_Talon, getChannel()); + } - /** - * Set the PWM value. - * - * @deprecated For compatibility with CANJaguar - * - * The PWM value is set using a range of -1.0 to 1.0, appropriately - * scaling the value for the FPGA. - * - * @param speed The speed to set. Value should be between -1.0 and 1.0. - * @param syncGroup The update group to add this Set() to, pending UpdateSyncGroup(). If 0, update immediately. - */ - public void set(double speed, byte syncGroup) { - setSpeed(isInverted ? -speed: speed); - Feed(); - } + /** + * Constructor for a Talon (original or Talon SR) + * + * @param channel The PWM channel that the Talon is attached to. 0-9 are + * on-board, 10-19 are on the MXP port + */ + public Talon(final int channel) { + super(channel); + initTalon(); + } + + /** + * Set the PWM value. + * + * @deprecated For compatibility with CANJaguar + * + * The PWM value is set using a range of -1.0 to 1.0, + * appropriately scaling the value for the FPGA. + * + * @param speed The speed to set. Value should be between -1.0 and 1.0. + * @param syncGroup The update group to add this Set() to, pending + * UpdateSyncGroup(). If 0, update immediately. + */ + public void set(double speed, byte syncGroup) { + setSpeed(isInverted ? -speed : speed); + Feed(); + } - /** - * Set the PWM value. - * - * The PWM value is set using a range of -1.0 to 1.0, appropriately - * scaling the value for the FPGA. - * - * @param speed The speed value between -1.0 and 1.0 to set. - */ - public void set(double speed) { - setSpeed(isInverted ? -speed: speed); - Feed(); - } - /** - * Common interface for inverting direction of a speed controller - * - * @param isInverted The state of inversion true is inverted - */ - @Override - public void setInverted(boolean isInverted) { - this.isInverted = isInverted; - } + /** + * Set the PWM value. + * + * The PWM value is set using a range of -1.0 to 1.0, appropriately scaling + * the value for the FPGA. + * + * @param speed The speed value between -1.0 and 1.0 to set. + */ + public void set(double speed) { + setSpeed(isInverted ? -speed : speed); + Feed(); + } - /** - * Common interface for the inverting direction of a speed controller. - * - * @return isInverted The state of inversion, true is inverted. - * - */ - @Override - public boolean getInverted() { - return this.isInverted; - } - - /** - * Get the recently set value of the PWM. - * - * @return The most recently set value for the PWM between -1.0 and 1.0. - */ - public double get() { - return getSpeed(); - } + /** + * Common interface for inverting direction of a speed controller + * + * @param isInverted The state of inversion true is inverted + */ + @Override + public void setInverted(boolean isInverted) { + this.isInverted = isInverted; + } - /** - * Write out the PID value as seen in the PIDOutput base object. - * - * @param output Write out the PWM value as was found in the PIDController - */ - public void pidWrite(double output) { - set(output); - } + /** + * Common interface for the inverting direction of a speed controller. + * + * @return isInverted The state of inversion, true is inverted. + * + */ + @Override + public boolean getInverted() { + return this.isInverted; + } + + /** + * Get the recently set value of the PWM. + * + * @return The most recently set value for the PWM between -1.0 and 1.0. + */ + public double get() { + return getSpeed(); + } + + /** + * Write out the PID value as seen in the PIDOutput base object. + * + * @param output Write out the PWM value as was found in the PIDController + */ + public void pidWrite(double output) { + set(output); + } } diff --git a/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/TalonSRX.java b/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/TalonSRX.java index b083bab355..eefb05b858 100644 --- a/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/TalonSRX.java +++ b/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/TalonSRX.java @@ -1,8 +1,8 @@ /*----------------------------------------------------------------------------*/ -/* Copyright (c) FIRST 2008-2014. All Rights Reserved. */ -/* Open Source Software - may be modified and shared by FRC teams. The code */ +/* Copyright (c) FIRST 2008-2014. All Rights Reserved. */ +/* Open Source Software - may be modified and shared by FRC teams. The code */ /* must be accompanied by the FIRST BSD license file in the root directory of */ -/* the project. */ +/* the project. */ /*----------------------------------------------------------------------------*/ package edu.wpi.first.wpilibj; @@ -13,109 +13,113 @@ import edu.wpi.first.wpilibj.livewindow.LiveWindow; /** * Cross the Road Electronics (CTRE) Talon SRX Speed Controller with PWM control + *$ * @see CANTalon CANTalon for CAN control of Talon SRX */ public class TalonSRX extends SafePWM implements SpeedController { - private boolean isInverted = false; - /** - * Common initialization code called by all constructors. - * - * Note that the TalonSRX uses the following bounds for PWM values. These values should work reasonably well for - * most controllers, but if users experience issues such as asymmetric behavior around - * the deadband or inability to saturate the controller in either direction, calibration is recommended. - * The calibration procedure can be found in the TalonSRX User Manual available from CTRE. - * - * - 2.0004ms = full "forward" - * - 1.52ms = the "high end" of the deadband range - * - 1.50ms = center of the deadband range (off) - * - 1.48ms = the "low end" of the deadband range - * - .997ms = full "reverse" - */ - protected void initTalonSRX() { - setBounds(2.004, 1.52, 1.50, 1.48, .997); - setPeriodMultiplier(PeriodMultiplier.k1X); - setRaw(m_centerPwm); - setZeroLatch(); + private boolean isInverted = false; - LiveWindow.addActuator("TalonSRX", getChannel(), this); - UsageReporting.report(tResourceType.kResourceType_TalonSRX, getChannel()); - } + /** + * Common initialization code called by all constructors. + * + * Note that the TalonSRX uses the following bounds for PWM values. These + * values should work reasonably well for most controllers, but if users + * experience issues such as asymmetric behavior around the deadband or + * inability to saturate the controller in either direction, calibration is + * recommended. The calibration procedure can be found in the TalonSRX User + * Manual available from CTRE. + * + * - 2.0004ms = full "forward" - 1.52ms = the "high end" of the deadband range + * - 1.50ms = center of the deadband range (off) - 1.48ms = the "low end" of + * the deadband range - .997ms = full "reverse" + */ + protected void initTalonSRX() { + setBounds(2.004, 1.52, 1.50, 1.48, .997); + setPeriodMultiplier(PeriodMultiplier.k1X); + setRaw(m_centerPwm); + setZeroLatch(); - /** - * Constructor for a TalonSRX connected via PWM - * - * @param channel The PWM channel that the TalonSRX is attached to. 0-9 are on-board, 10-19 are on the MXP port - */ - public TalonSRX(final int channel) { - super(channel); - initTalonSRX(); - } + LiveWindow.addActuator("TalonSRX", getChannel(), this); + UsageReporting.report(tResourceType.kResourceType_TalonSRX, getChannel()); + } - /** - * Set the PWM value. - * - * @deprecated For compatibility with CANJaguar - * - * The PWM value is set using a range of -1.0 to 1.0, appropriately - * scaling the value for the FPGA. - * - * @param speed The speed to set. Value should be between -1.0 and 1.0. - * @param syncGroup The update group to add this Set() to, pending UpdateSyncGroup(). If 0, update immediately. - */ - public void set(double speed, byte syncGroup) { - setSpeed(isInverted ? -speed: speed); - Feed(); - } + /** + * Constructor for a TalonSRX connected via PWM + * + * @param channel The PWM channel that the TalonSRX is attached to. 0-9 are + * on-board, 10-19 are on the MXP port + */ + public TalonSRX(final int channel) { + super(channel); + initTalonSRX(); + } - /** - * Set the PWM value. - * - * The PWM value is set using a range of -1.0 to 1.0, appropriately - * scaling the value for the FPGA. - * - * @param speed The speed value between -1.0 and 1.0 to set. - */ - public void set(double speed) { - setSpeed(isInverted ? -speed: speed); - Feed(); - } + /** + * Set the PWM value. + * + * @deprecated For compatibility with CANJaguar + * + * The PWM value is set using a range of -1.0 to 1.0, + * appropriately scaling the value for the FPGA. + * + * @param speed The speed to set. Value should be between -1.0 and 1.0. + * @param syncGroup The update group to add this Set() to, pending + * UpdateSyncGroup(). If 0, update immediately. + */ + public void set(double speed, byte syncGroup) { + setSpeed(isInverted ? -speed : speed); + Feed(); + } - /** - * Common interface for inverting direction of a speed controller. - * - * @param isInverted The state of inversion, true is inverted. - */ - @Override - public void setInverted(boolean isInverted) { - this.isInverted = isInverted; - } + /** + * Set the PWM value. + * + * The PWM value is set using a range of -1.0 to 1.0, appropriately scaling + * the value for the FPGA. + * + * @param speed The speed value between -1.0 and 1.0 to set. + */ + public void set(double speed) { + setSpeed(isInverted ? -speed : speed); + Feed(); + } - /** - * Common interface for the inverting direction of a speed controller. - * - * @return isInverted The state of inversion, true is inverted. - * - */ - @Override - public boolean getInverted() { - return this.isInverted; - } + /** + * Common interface for inverting direction of a speed controller. + * + * @param isInverted The state of inversion, true is inverted. + */ + @Override + public void setInverted(boolean isInverted) { + this.isInverted = isInverted; + } - /** - * Get the recently set value of the PWM. - * - * @return The most recently set value for the PWM between -1.0 and 1.0. - */ - public double get() { - return getSpeed(); - } + /** + * Common interface for the inverting direction of a speed controller. + * + * @return isInverted The state of inversion, true is inverted. + * + */ + @Override + public boolean getInverted() { + return this.isInverted; + } - /** - * Write out the PID value as seen in the PIDOutput base object. - * - * @param output Write out the PWM value as was found in the PIDController - */ - public void pidWrite(double output) { - set(output); - } + /** + * Get the recently set value of the PWM. + * + * @return The most recently set value for the PWM between -1.0 and 1.0. + */ + public double get() { + return getSpeed(); + } + + /** + * Write out the PID value as seen in the PIDOutput base object. + * + * @param output Write out the PWM value as was found in the PIDController + */ + public void pidWrite(double output) { + set(output); + } } diff --git a/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/Ultrasonic.java b/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/Ultrasonic.java index 73c5078221..213b829974 100644 --- a/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/Ultrasonic.java +++ b/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/Ultrasonic.java @@ -1,8 +1,8 @@ /*----------------------------------------------------------------------------*/ -/* Copyright (c) FIRST 2008-2012. All Rights Reserved. */ -/* Open Source Software - may be modified and shared by FRC teams. The code */ +/* Copyright (c) FIRST 2008-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 the root directory of */ -/* the project. */ +/* the project. */ /*----------------------------------------------------------------------------*/ package edu.wpi.first.wpilibj; @@ -26,438 +26,417 @@ import edu.wpi.first.wpilibj.tables.ITable; */ public class Ultrasonic extends SensorBase implements PIDSource, LiveWindowSendable { - /** - * The units to return when PIDGet is called - */ - public static class Unit { + /** + * The units to return when PIDGet is called + */ + public static class Unit { - /** - * The integer value representing this enumeration - */ - public final int value; - static final int kInches_val = 0; - static final int kMillimeters_val = 1; - /** - * Use inches for PIDGet - */ - public static final Unit kInches = new Unit(kInches_val); - /** - * Use millimeters for PIDGet - */ - public static final Unit kMillimeter = new Unit(kMillimeters_val); + /** + * The integer value representing this enumeration + */ + public final int value; + static final int kInches_val = 0; + static final int kMillimeters_val = 1; + /** + * Use inches for PIDGet + */ + public static final Unit kInches = new Unit(kInches_val); + /** + * Use millimeters for PIDGet + */ + public static final Unit kMillimeter = new Unit(kMillimeters_val); - private Unit(int value) { - this.value = value; - } - } + private Unit(int value) { + this.value = value; + } + } - private static final double kPingTime = 10 * 1e-6; // /< Time (sec) for the - // ping trigger pulse. - private static final int kPriority = 90; // /< Priority that the ultrasonic - // round robin task runs. - private static final double kMaxUltrasonicTime = 0.1; // /< Max time (ms) - // between readings. - private static final double kSpeedOfSoundInchesPerSec = 1130.0 * 12.0; - private static Ultrasonic m_firstSensor = null; // head of the ultrasonic - // sensor list - private static boolean m_automaticEnabled = false; // automatic round robin - // mode - private DigitalInput m_echoChannel = null; - private DigitalOutput m_pingChannel = null; - private boolean m_allocatedChannels; - private boolean m_enabled = false; - private Counter m_counter = null; - private Ultrasonic m_nextSensor = null; - private static Thread m_task = null; // task doing the round-robin automatic - // sensing - private Unit m_units; - private static int m_instances = 0; + private static final double kPingTime = 10 * 1e-6; // /< Time (sec) for the + // ping trigger pulse. + private static final int kPriority = 90; // /< Priority that the ultrasonic + // round robin task runs. + private static final double kMaxUltrasonicTime = 0.1; // /< Max time (ms) + // between readings. + private static final double kSpeedOfSoundInchesPerSec = 1130.0 * 12.0; + private static Ultrasonic m_firstSensor = null; // head of the ultrasonic + // sensor list + private static boolean m_automaticEnabled = false; // automatic round robin + // mode + private DigitalInput m_echoChannel = null; + private DigitalOutput m_pingChannel = null; + private boolean m_allocatedChannels; + private boolean m_enabled = false; + private Counter m_counter = null; + private Ultrasonic m_nextSensor = null; + private static Thread m_task = null; // task doing the round-robin automatic + // sensing + private Unit m_units; + private static int m_instances = 0; - /** - * Background task that goes through the list of ultrasonic sensors and - * pings each one in turn. The counter is configured to read the timing of - * the returned echo pulse. - * - * DANGER WILL ROBINSON, DANGER WILL ROBINSON: This code runs as a task and - * assumes that none of the ultrasonic sensors will change while it's - * running. If one does, then this will certainly break. Make sure to - * disable automatic mode before changing anything with the sensors!! - */ - private class UltrasonicChecker extends Thread { + /** + * Background task that goes through the list of ultrasonic sensors and pings + * each one in turn. The counter is configured to read the timing of the + * returned echo pulse. + * + * DANGER WILL ROBINSON, DANGER WILL ROBINSON: This code runs as a task and + * assumes that none of the ultrasonic sensors will change while it's running. + * If one does, then this will certainly break. Make sure to disable automatic + * mode before changing anything with the sensors!! + */ + private class UltrasonicChecker extends Thread { - public synchronized void run() { - Ultrasonic u = null; - while (m_automaticEnabled) { - if (u == null) { - u = m_firstSensor; - } - if (u == null) { - return; - } - if (u.isEnabled()) { - u.m_pingChannel.pulse(m_pingChannel.m_channel, - (float) kPingTime); // do the ping - } - u = u.m_nextSensor; - Timer.delay(.1); // wait for ping to return - } - } - } + public synchronized void run() { + Ultrasonic u = null; + while (m_automaticEnabled) { + if (u == null) { + u = m_firstSensor; + } + if (u == null) { + return; + } + if (u.isEnabled()) { + u.m_pingChannel.pulse(m_pingChannel.m_channel, (float) kPingTime); // do + // the + // ping + } + u = u.m_nextSensor; + Timer.delay(.1); // wait for ping to return + } + } + } - /** - * Initialize the Ultrasonic Sensor. This is the common code that - * initializes the ultrasonic sensor given that there are two digital I/O - * channels allocated. If the system was running in automatic mode (round - * robin) when the new sensor is added, it is stopped, the sensor is added, - * then automatic mode is restored. - */ - private synchronized void initialize() { - if (m_task == null) { - m_task = new UltrasonicChecker(); - } - boolean originalMode = m_automaticEnabled; - setAutomaticMode(false); // kill task when adding a new sensor - m_nextSensor = m_firstSensor; - m_firstSensor = this; + /** + * Initialize the Ultrasonic Sensor. This is the common code that initializes + * the ultrasonic sensor given that there are two digital I/O channels + * allocated. If the system was running in automatic mode (round robin) when + * the new sensor is added, it is stopped, the sensor is added, then automatic + * mode is restored. + */ + private synchronized void initialize() { + if (m_task == null) { + m_task = new UltrasonicChecker(); + } + boolean originalMode = m_automaticEnabled; + setAutomaticMode(false); // kill task when adding a new sensor + m_nextSensor = m_firstSensor; + m_firstSensor = this; - m_counter = new Counter(m_echoChannel); // set up counter for this - // sensor - m_counter.setMaxPeriod(1.0); - m_counter.setSemiPeriodMode(true); - m_counter.reset(); - m_enabled = true; // make it available for round robin scheduling - setAutomaticMode(originalMode); + m_counter = new Counter(m_echoChannel); // set up counter for this + // sensor + m_counter.setMaxPeriod(1.0); + m_counter.setSemiPeriodMode(true); + m_counter.reset(); + m_enabled = true; // make it available for round robin scheduling + setAutomaticMode(originalMode); - m_instances++; - UsageReporting.report(tResourceType.kResourceType_Ultrasonic, - m_instances); - LiveWindow.addSensor("Ultrasonic", m_echoChannel.getChannel(), this); - } + m_instances++; + UsageReporting.report(tResourceType.kResourceType_Ultrasonic, m_instances); + LiveWindow.addSensor("Ultrasonic", m_echoChannel.getChannel(), this); + } - /** - * Create an instance of the Ultrasonic Sensor. - * This is designed to supchannel the Daventech SRF04 and Vex ultrasonic - * sensors. - * - * @param pingChannel - * The digital output channel that sends the pulse to initiate - * the sensor sending the ping. - * @param echoChannel - * The digital input channel that receives the echo. The length - * of time that the echo is high represents the round trip time - * of the ping, and the distance. - * @param units - * The units returned in either kInches or kMilliMeters - */ - public Ultrasonic(final int pingChannel, final int echoChannel, Unit units) { - m_pingChannel = new DigitalOutput(pingChannel); - m_echoChannel = new DigitalInput(echoChannel); - m_allocatedChannels = true; - m_units = units; - initialize(); - } + /** + * Create an instance of the Ultrasonic Sensor. This is designed to supchannel + * the Daventech SRF04 and Vex ultrasonic sensors. + * + * @param pingChannel The digital output channel that sends the pulse to + * initiate the sensor sending the ping. + * @param echoChannel The digital input channel that receives the echo. The + * length of time that the echo is high represents the round trip time + * of the ping, and the distance. + * @param units The units returned in either kInches or kMilliMeters + */ + public Ultrasonic(final int pingChannel, final int echoChannel, Unit units) { + m_pingChannel = new DigitalOutput(pingChannel); + m_echoChannel = new DigitalInput(echoChannel); + m_allocatedChannels = true; + m_units = units; + initialize(); + } - /** - * Create an instance of the Ultrasonic Sensor. - * This is designed to supchannel the Daventech SRF04 and Vex ultrasonic - * sensors. Default unit is inches. - * - * @param pingChannel - * The digital output channel that sends the pulse to initiate - * the sensor sending the ping. - * @param echoChannel - * The digital input channel that receives the echo. The length - * of time that the echo is high represents the round trip time - * of the ping, and the distance. - */ - public Ultrasonic(final int pingChannel, final int echoChannel) { - this(pingChannel, echoChannel, Unit.kInches); - } + /** + * Create an instance of the Ultrasonic Sensor. This is designed to supchannel + * the Daventech SRF04 and Vex ultrasonic sensors. Default unit is inches. + * + * @param pingChannel The digital output channel that sends the pulse to + * initiate the sensor sending the ping. + * @param echoChannel The digital input channel that receives the echo. The + * length of time that the echo is high represents the round trip time + * of the ping, and the distance. + */ + public Ultrasonic(final int pingChannel, final int echoChannel) { + this(pingChannel, echoChannel, Unit.kInches); + } - /** - * Create an instance of an Ultrasonic Sensor from a DigitalInput for the - * echo channel and a DigitalOutput for the ping channel. - * - * @param pingChannel - * The digital output object that starts the sensor doing a ping. - * Requires a 10uS pulse to start. - * @param echoChannel - * The digital input object that times the return pulse to - * determine the range. - * @param units - * The units returned in either kInches or kMilliMeters - */ - public Ultrasonic(DigitalOutput pingChannel, DigitalInput echoChannel, - Unit units) { - if (pingChannel == null || echoChannel == null) { - throw new NullPointerException("Null Channel Provided"); - } - m_allocatedChannels = false; - m_pingChannel = pingChannel; - m_echoChannel = echoChannel; - m_units = units; - initialize(); - } + /** + * Create an instance of an Ultrasonic Sensor from a DigitalInput for the echo + * channel and a DigitalOutput for the ping channel. + * + * @param pingChannel The digital output object that starts the sensor doing a + * ping. Requires a 10uS pulse to start. + * @param echoChannel The digital input object that times the return pulse to + * determine the range. + * @param units The units returned in either kInches or kMilliMeters + */ + public Ultrasonic(DigitalOutput pingChannel, DigitalInput echoChannel, Unit units) { + if (pingChannel == null || echoChannel == null) { + throw new NullPointerException("Null Channel Provided"); + } + m_allocatedChannels = false; + m_pingChannel = pingChannel; + m_echoChannel = echoChannel; + m_units = units; + initialize(); + } - /** - * Create an instance of an Ultrasonic Sensor from a DigitalInput for the - * echo channel and a DigitalOutput for the ping channel. Default unit is - * inches. - * - * @param pingChannel - * The digital output object that starts the sensor doing a ping. - * Requires a 10uS pulse to start. - * @param echoChannel - * The digital input object that times the return pulse to - * determine the range. - */ - public Ultrasonic(DigitalOutput pingChannel, DigitalInput echoChannel) { - this(pingChannel, echoChannel, Unit.kInches); - } + /** + * Create an instance of an Ultrasonic Sensor from a DigitalInput for the echo + * channel and a DigitalOutput for the ping channel. Default unit is inches. + * + * @param pingChannel The digital output object that starts the sensor doing a + * ping. Requires a 10uS pulse to start. + * @param echoChannel The digital input object that times the return pulse to + * determine the range. + */ + public Ultrasonic(DigitalOutput pingChannel, DigitalInput echoChannel) { + this(pingChannel, echoChannel, Unit.kInches); + } - /** - * Destructor for the ultrasonic sensor. Delete the instance of the - * ultrasonic sensor by freeing the allocated digital channels. If the - * system was in automatic mode (round robin), then it is stopped, then - * started again after this sensor is removed (provided this wasn't the last - * sensor). - */ - public synchronized void free() { - boolean wasAutomaticMode = m_automaticEnabled; - setAutomaticMode(false); - if (m_allocatedChannels) { - if (m_pingChannel != null) { - m_pingChannel.free(); - } - if (m_echoChannel != null) { - m_echoChannel.free(); - } - } + /** + * Destructor for the ultrasonic sensor. Delete the instance of the ultrasonic + * sensor by freeing the allocated digital channels. If the system was in + * automatic mode (round robin), then it is stopped, then started again after + * this sensor is removed (provided this wasn't the last sensor). + */ + public synchronized void free() { + boolean wasAutomaticMode = m_automaticEnabled; + setAutomaticMode(false); + if (m_allocatedChannels) { + if (m_pingChannel != null) { + m_pingChannel.free(); + } + if (m_echoChannel != null) { + m_echoChannel.free(); + } + } - if (m_counter != null) { - m_counter.free(); - m_counter = null; - } + if (m_counter != null) { + m_counter.free(); + m_counter = null; + } - m_pingChannel = null; - m_echoChannel = null; + m_pingChannel = null; + m_echoChannel = null; - if (this == m_firstSensor) { - m_firstSensor = m_nextSensor; - if (m_firstSensor == null) { - setAutomaticMode(false); - } - } else { - for (Ultrasonic s = m_firstSensor; s != null; s = s.m_nextSensor) { - if (this == s.m_nextSensor) { - s.m_nextSensor = s.m_nextSensor.m_nextSensor; - break; - } - } - } - if (m_firstSensor != null && wasAutomaticMode) { - setAutomaticMode(true); - } - } + if (this == m_firstSensor) { + m_firstSensor = m_nextSensor; + if (m_firstSensor == null) { + setAutomaticMode(false); + } + } else { + for (Ultrasonic s = m_firstSensor; s != null; s = s.m_nextSensor) { + if (this == s.m_nextSensor) { + s.m_nextSensor = s.m_nextSensor.m_nextSensor; + break; + } + } + } + if (m_firstSensor != null && wasAutomaticMode) { + setAutomaticMode(true); + } + } - /** - * Turn Automatic mode on/off. When in Automatic mode, all sensors will fire - * in round robin, waiting a set time between each sensor. - * - * @param enabling - * Set to true if round robin scheduling should start for all the - * ultrasonic sensors. This scheduling method assures that the - * sensors are non-interfering because no two sensors fire at the - * same time. If another scheduling algorithm is preffered, it - * can be implemented by pinging the sensors manually and waiting - * for the results to come back. - */ - public void setAutomaticMode(boolean enabling) { - if (enabling == m_automaticEnabled) { - return; // ignore the case of no change - } - m_automaticEnabled = enabling; + /** + * Turn Automatic mode on/off. When in Automatic mode, all sensors will fire + * in round robin, waiting a set time between each sensor. + * + * @param enabling Set to true if round robin scheduling should start for all + * the ultrasonic sensors. This scheduling method assures that the + * sensors are non-interfering because no two sensors fire at the same + * time. If another scheduling algorithm is preffered, it can be + * implemented by pinging the sensors manually and waiting for the + * results to come back. + */ + public void setAutomaticMode(boolean enabling) { + if (enabling == m_automaticEnabled) { + return; // ignore the case of no change + } + m_automaticEnabled = enabling; - if (enabling) { - // enabling automatic mode. - // Clear all the counters so no data is valid - for (Ultrasonic u = m_firstSensor; u != null; u = u.m_nextSensor) { - u.m_counter.reset(); - } - // Start round robin task - m_task.start(); - } else { - // disabling automatic mode. Wait for background task to stop - // running. - while (m_task.isAlive()) { - Timer.delay(.15); // just a little longer than the ping time for - // round-robin to stop - } - // clear all the counters (data now invalid) since automatic mode is - // stopped - for (Ultrasonic u = m_firstSensor; u != null; u = u.m_nextSensor) { - u.m_counter.reset(); - } - } - } + if (enabling) { + // enabling automatic mode. + // Clear all the counters so no data is valid + for (Ultrasonic u = m_firstSensor; u != null; u = u.m_nextSensor) { + u.m_counter.reset(); + } + // Start round robin task + m_task.start(); + } else { + // disabling automatic mode. Wait for background task to stop + // running. + while (m_task.isAlive()) { + Timer.delay(.15); // just a little longer than the ping time for + // round-robin to stop + } + // clear all the counters (data now invalid) since automatic mode is + // stopped + for (Ultrasonic u = m_firstSensor; u != null; u = u.m_nextSensor) { + u.m_counter.reset(); + } + } + } - /** - * Single ping to ultrasonic sensor. Send out a single ping to the - * ultrasonic sensor. This only works if automatic (round robin) mode is - * disabled. A single ping is sent out, and the counter should count the - * semi-period when it comes in. The counter is reset to make the current - * value invalid. - */ - public void ping() { - setAutomaticMode(false); // turn off automatic round robin if pinging - // single sensor - m_counter.reset(); // reset the counter to zero (invalid data now) - m_pingChannel.pulse(m_pingChannel.m_channel, (float) kPingTime); // do - // the - // ping - // to - // start - // getting - // a - // single - // range - } + /** + * Single ping to ultrasonic sensor. Send out a single ping to the ultrasonic + * sensor. This only works if automatic (round robin) mode is disabled. A + * single ping is sent out, and the counter should count the semi-period when + * it comes in. The counter is reset to make the current value invalid. + */ + public void ping() { + setAutomaticMode(false); // turn off automatic round robin if pinging + // single sensor + m_counter.reset(); // reset the counter to zero (invalid data now) + m_pingChannel.pulse(m_pingChannel.m_channel, (float) kPingTime); // do + // the + // ping + // to + // start + // getting + // a + // single + // range + } - /** - * Check if there is a valid range measurement. The ranges are accumulated - * in a counter that will increment on each edge of the echo (return) - * signal. If the count is not at least 2, then the range has not yet been - * measured, and is invalid. - * - * @return true if the range is valid - */ - public boolean isRangeValid() { - return m_counter.get() > 1; - } + /** + * Check if there is a valid range measurement. The ranges are accumulated in + * a counter that will increment on each edge of the echo (return) signal. If + * the count is not at least 2, then the range has not yet been measured, and + * is invalid. + * + * @return true if the range is valid + */ + public boolean isRangeValid() { + return m_counter.get() > 1; + } - /** - * Get the range in inches from the ultrasonic sensor. - * - * @return double Range in inches of the target returned from the ultrasonic - * sensor. If there is no valid value yet, i.e. at least one - * measurement hasn't completed, then return 0. - */ - public double getRangeInches() { - if (isRangeValid()) { - return m_counter.getPeriod() * kSpeedOfSoundInchesPerSec / 2.0; - } else { - return 0; - } - } + /** + * Get the range in inches from the ultrasonic sensor. + * + * @return double Range in inches of the target returned from the ultrasonic + * sensor. If there is no valid value yet, i.e. at least one + * measurement hasn't completed, then return 0. + */ + public double getRangeInches() { + if (isRangeValid()) { + return m_counter.getPeriod() * kSpeedOfSoundInchesPerSec / 2.0; + } else { + return 0; + } + } - /** - * Get the range in millimeters from the ultrasonic sensor. - * - * @return double Range in millimeters of the target returned by the - * ultrasonic sensor. If there is no valid value yet, i.e. at least - * one measurement hasn't complted, then return 0. - */ - public double getRangeMM() { - return getRangeInches() * 25.4; - } + /** + * Get the range in millimeters from the ultrasonic sensor. + * + * @return double Range in millimeters of the target returned by the + * ultrasonic sensor. If there is no valid value yet, i.e. at least + * one measurement hasn't complted, then return 0. + */ + public double getRangeMM() { + return getRangeInches() * 25.4; + } - /** - * Get the range in the current DistanceUnit for the PIDSource base object. - * - * @return The range in DistanceUnit - */ - public double pidGet() { - switch (m_units.value) { - case Unit.kInches_val: - return getRangeInches(); - case Unit.kMillimeters_val: - return getRangeMM(); - default: - return 0.0; - } - } + /** + * Get the range in the current DistanceUnit for the PIDSource base object. + * + * @return The range in DistanceUnit + */ + public double pidGet() { + switch (m_units.value) { + case Unit.kInches_val: + return getRangeInches(); + case Unit.kMillimeters_val: + return getRangeMM(); + default: + return 0.0; + } + } - /** - * Set the current DistanceUnit that should be used for the PIDSource base - * object. - * - * @param units - * The DistanceUnit that should be used. - */ - public void setDistanceUnits(Unit units) { - m_units = units; - } + /** + * Set the current DistanceUnit that should be used for the PIDSource base + * object. + * + * @param units The DistanceUnit that should be used. + */ + public void setDistanceUnits(Unit units) { + m_units = units; + } - /** - * Get the current DistanceUnit that is used for the PIDSource base object. - * - * @return The type of DistanceUnit that is being used. - */ - public Unit getDistanceUnits() { - return m_units; - } + /** + * Get the current DistanceUnit that is used for the PIDSource base object. + * + * @return The type of DistanceUnit that is being used. + */ + public Unit getDistanceUnits() { + return m_units; + } - /** - * Is the ultrasonic enabled - * - * @return true if the ultrasonic is enabled - */ - public boolean isEnabled() { - return m_enabled; - } + /** + * Is the ultrasonic enabled + * + * @return true if the ultrasonic is enabled + */ + public boolean isEnabled() { + return m_enabled; + } - /** - * Set if the ultrasonic is enabled - * - * @param enable - * set to true to enable the ultrasonic - */ - public void setEnabled(boolean enable) { - m_enabled = enable; - } + /** + * Set if the ultrasonic is enabled + * + * @param enable set to true to enable the ultrasonic + */ + public void setEnabled(boolean enable) { + m_enabled = enable; + } - /* - * Live Window code, only does anything if live window is activated. - */ - public String getSmartDashboardType() { - return "Ultrasonic"; - } + /* + * Live Window code, only does anything if live window is activated. + */ + public String getSmartDashboardType() { + return "Ultrasonic"; + } - private ITable m_table; + private ITable m_table; - /** - * {@inheritDoc} - */ - public void initTable(ITable subtable) { - m_table = subtable; - updateTable(); - } + /** + * {@inheritDoc} + */ + public void initTable(ITable subtable) { + m_table = subtable; + updateTable(); + } - /** - * {@inheritDoc} - */ - public ITable getTable() { - return m_table; - } + /** + * {@inheritDoc} + */ + public ITable getTable() { + return m_table; + } - /** - * {@inheritDoc} - */ - public void updateTable() { - if (m_table != null) { - m_table.putNumber("Value", getRangeInches()); - } - } + /** + * {@inheritDoc} + */ + public void updateTable() { + if (m_table != null) { + m_table.putNumber("Value", getRangeInches()); + } + } - /** - * {@inheritDoc} - */ - public void startLiveWindowMode() { - } + /** + * {@inheritDoc} + */ + public void startLiveWindowMode() {} - /** - * {@inheritDoc} - */ - public void stopLiveWindowMode() { - } + /** + * {@inheritDoc} + */ + public void stopLiveWindowMode() {} } diff --git a/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/Utility.java b/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/Utility.java index ec5884fc90..6d8d0f0336 100644 --- a/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/Utility.java +++ b/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/Utility.java @@ -1,8 +1,8 @@ /*----------------------------------------------------------------------------*/ -/* Copyright (c) FIRST 2008-2012. All Rights Reserved. */ -/* Open Source Software - may be modified and shared by FRC teams. The code */ +/* Copyright (c) FIRST 2008-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 the root directory of */ -/* the project. */ +/* the project. */ /*----------------------------------------------------------------------------*/ package edu.wpi.first.wpilibj; @@ -21,65 +21,65 @@ import edu.wpi.first.wpilibj.communication.FRCNetworkCommunicationsLibrary; */ public class Utility { - private Utility() { - } + private Utility() {} - /** - * Return the FPGA Version number. For now, expect this to be 2009. - * - * @return FPGA Version number. - */ - int getFPGAVersion() { - ByteBuffer status = ByteBuffer.allocateDirect(4); - // set the byte order - status.order(ByteOrder.LITTLE_ENDIAN); - int value = HALUtil.getFPGAVersion(status.asIntBuffer()); - HALUtil.checkStatus(status.asIntBuffer()); - return value; - } + /** + * Return the FPGA Version number. For now, expect this to be 2009. + * + * @return FPGA Version number. + */ + int getFPGAVersion() { + ByteBuffer status = ByteBuffer.allocateDirect(4); + // set the byte order + status.order(ByteOrder.LITTLE_ENDIAN); + int value = HALUtil.getFPGAVersion(status.asIntBuffer()); + HALUtil.checkStatus(status.asIntBuffer()); + return value; + } - /** - * Return the FPGA Revision number. The format of the revision is 3 numbers. - * The 12 most significant bits are the Major Revision. the next 8 bits are - * the Minor Revision. The 12 least significant bits are the Build Number. - * - * @return FPGA Revision number. - */ - long getFPGARevision() { - ByteBuffer status = ByteBuffer.allocateDirect(4); - // set the byte order - status.order(ByteOrder.LITTLE_ENDIAN); - int value = HALUtil.getFPGARevision(status.asIntBuffer()); - HALUtil.checkStatus(status.asIntBuffer()); - return (long) value; - } + /** + * Return the FPGA Revision number. The format of the revision is 3 numbers. + * The 12 most significant bits are the Major Revision. the next 8 bits are + * the Minor Revision. The 12 least significant bits are the Build Number. + * + * @return FPGA Revision number. + */ + long getFPGARevision() { + ByteBuffer status = ByteBuffer.allocateDirect(4); + // set the byte order + status.order(ByteOrder.LITTLE_ENDIAN); + int value = HALUtil.getFPGARevision(status.asIntBuffer()); + HALUtil.checkStatus(status.asIntBuffer()); + return (long) value; + } - /** - * Read the microsecond timer from the FPGA. - * - * @return The current time in microseconds according to the FPGA. - */ - public static long getFPGATime() { - ByteBuffer status = ByteBuffer.allocateDirect(4); - // set the byte order - status.order(ByteOrder.LITTLE_ENDIAN); + /** + * Read the microsecond timer from the FPGA. + * + * @return The current time in microseconds according to the FPGA. + */ + public static long getFPGATime() { + ByteBuffer status = ByteBuffer.allocateDirect(4); + // set the byte order + status.order(ByteOrder.LITTLE_ENDIAN); - long value = HALUtil.getFPGATime(status.asIntBuffer()); - HALUtil.checkStatus(status.asIntBuffer()); - return value; - } + long value = HALUtil.getFPGATime(status.asIntBuffer()); + HALUtil.checkStatus(status.asIntBuffer()); + return value; + } - /** - * Get the state of the "USER" button on the RoboRIO - * @return true if the button is currently pressed down - */ - public static boolean getUserButton() { - ByteBuffer status = ByteBuffer.allocateDirect(4); - // set the byte order - status.order(ByteOrder.LITTLE_ENDIAN); + /** + * Get the state of the "USER" button on the RoboRIO + *$ + * @return true if the button is currently pressed down + */ + public static boolean getUserButton() { + ByteBuffer status = ByteBuffer.allocateDirect(4); + // set the byte order + status.order(ByteOrder.LITTLE_ENDIAN); - boolean value = HALUtil.getFPGAButton(status.asIntBuffer()); - HALUtil.checkStatus(status.asIntBuffer()); - return value; - } + boolean value = HALUtil.getFPGAButton(status.asIntBuffer()); + HALUtil.checkStatus(status.asIntBuffer()); + return value; + } } diff --git a/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/Victor.java b/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/Victor.java index 054fd254c4..66be22a865 100644 --- a/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/Victor.java +++ b/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/Victor.java @@ -1,8 +1,8 @@ /*----------------------------------------------------------------------------*/ -/* Copyright (c) FIRST 2008-2012. All Rights Reserved. */ -/* Open Source Software - may be modified and shared by FRC teams. The code */ +/* Copyright (c) FIRST 2008-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 the root directory of */ -/* the project. */ +/* the project. */ /*----------------------------------------------------------------------------*/ package edu.wpi.first.wpilibj; @@ -13,113 +13,116 @@ import edu.wpi.first.wpilibj.livewindow.LiveWindow; /** * VEX Robotics Victor 888 Speed Controller - * - * The Vex Robotics Victor 884 Speed Controller can also be used with this - * class but may need to be calibrated per the Victor 884 user manual. + *$ + * The Vex Robotics Victor 884 Speed Controller can also be used with this class + * but may need to be calibrated per the Victor 884 user manual. */ public class Victor extends SafePWM implements SpeedController { -private boolean isInverted = false; - /** - * Common initialization code called by all constructors. - * - * Note that the Victor uses the following bounds for PWM values. These values were determined - * empirically and optimized for the Victor 888. These values should work reasonably well for - * Victor 884 controllers also but if users experience issues such as asymmetric behaviour around - * the deadband or inability to saturate the controller in either direction, calibration is recommended. - * The calibration procedure can be found in the Victor 884 User Manual available from VEX Robotics: - * http://content.vexrobotics.com/docs/ifi-v884-users-manual-9-25-06.pdf - * - * - 2.027ms = full "forward" - * - 1.525ms = the "high end" of the deadband range - * - 1.507ms = center of the deadband range (off) - * - 1.49ms = the "low end" of the deadband range - * - 1.026ms = full "reverse" - */ - private void initVictor() { - setBounds(2.027, 1.525, 1.507, 1.49, 1.026); - setPeriodMultiplier(PeriodMultiplier.k2X); - setRaw(m_centerPwm); - setZeroLatch(); + private boolean isInverted = false; - LiveWindow.addActuator("Victor", getChannel(), this); - UsageReporting.report(tResourceType.kResourceType_Victor, getChannel()); - } + /** + * Common initialization code called by all constructors. + * + * Note that the Victor uses the following bounds for PWM values. These values + * were determined empirically and optimized for the Victor 888. These values + * should work reasonably well for Victor 884 controllers also but if users + * experience issues such as asymmetric behaviour around the deadband or + * inability to saturate the controller in either direction, calibration is + * recommended. The calibration procedure can be found in the Victor 884 User + * Manual available from VEX Robotics: + * http://content.vexrobotics.com/docs/ifi-v884-users-manual-9-25-06.pdf + * + * - 2.027ms = full "forward" - 1.525ms = the "high end" of the deadband range + * - 1.507ms = center of the deadband range (off) - 1.49ms = the "low end" of + * the deadband range - 1.026ms = full "reverse" + */ + private void initVictor() { + setBounds(2.027, 1.525, 1.507, 1.49, 1.026); + setPeriodMultiplier(PeriodMultiplier.k2X); + setRaw(m_centerPwm); + setZeroLatch(); - /** - * Constructor. - * - * @param channel The PWM channel that the Victor is attached to. 0-9 are on-board, 10-19 are on the MXP port - */ - public Victor(final int channel) { - super(channel); - initVictor(); - } + LiveWindow.addActuator("Victor", getChannel(), this); + UsageReporting.report(tResourceType.kResourceType_Victor, getChannel()); + } - /** - * Set the PWM value. - * - * @deprecated For compatibility with CANJaguar - * - * The PWM value is set using a range of -1.0 to 1.0, appropriately - * scaling the value for the FPGA. - * - * @param speed The speed to set. Value should be between -1.0 and 1.0. - * @param syncGroup The update group to add this Set() to, pending UpdateSyncGroup(). If 0, update immediately. - */ - public void set(double speed, byte syncGroup) { - setSpeed(isInverted ? -speed: speed); - Feed(); - } + /** + * Constructor. + * + * @param channel The PWM channel that the Victor is attached to. 0-9 are + * on-board, 10-19 are on the MXP port + */ + public Victor(final int channel) { + super(channel); + initVictor(); + } - /** - * Set the PWM value. - * - * The PWM value is set using a range of -1.0 to 1.0, appropriately - * scaling the value for the FPGA. - * - * @param speed The speed value between -1.0 and 1.0 to set. - */ - public void set(double speed) { - setSpeed(isInverted ? -speed: speed); - Feed(); - } + /** + * Set the PWM value. + * + * @deprecated For compatibility with CANJaguar + * + * The PWM value is set using a range of -1.0 to 1.0, + * appropriately scaling the value for the FPGA. + * + * @param speed The speed to set. Value should be between -1.0 and 1.0. + * @param syncGroup The update group to add this Set() to, pending + * UpdateSyncGroup(). If 0, update immediately. + */ + public void set(double speed, byte syncGroup) { + setSpeed(isInverted ? -speed : speed); + Feed(); + } - /** - * Common interface for inverting direction of a speed controller - * - * @param isInverted The state of inversion true is inverted - */ - @Override - public void setInverted(boolean isInverted) { + /** + * Set the PWM value. + * + * The PWM value is set using a range of -1.0 to 1.0, appropriately scaling + * the value for the FPGA. + * + * @param speed The speed value between -1.0 and 1.0 to set. + */ + public void set(double speed) { + setSpeed(isInverted ? -speed : speed); + Feed(); + } + + /** + * Common interface for inverting direction of a speed controller + * + * @param isInverted The state of inversion true is inverted + */ + @Override + public void setInverted(boolean isInverted) { this.isInverted = isInverted; - } + } - /** - * Common interface for the inverting direction of a speed controller. - * - * @return isInverted The state of inversion, true is inverted. - * - */ - @Override - public boolean getInverted() { - return this.isInverted; - } + /** + * Common interface for the inverting direction of a speed controller. + * + * @return isInverted The state of inversion, true is inverted. + * + */ + @Override + public boolean getInverted() { + return this.isInverted; + } - /** - * Get the recently set value of the PWM. - * - * @return The most recently set value for the PWM between -1.0 and 1.0. - */ - public double get() { - return getSpeed(); - } + /** + * Get the recently set value of the PWM. + * + * @return The most recently set value for the PWM between -1.0 and 1.0. + */ + public double get() { + return getSpeed(); + } - /** - * Write out the PID value as seen in the PIDOutput base object. - * - * @param output Write out the PWM value as was found in the PIDController - */ - public void pidWrite(double output) { - set(output); - } + /** + * Write out the PID value as seen in the PIDOutput base object. + * + * @param output Write out the PWM value as was found in the PIDController + */ + public void pidWrite(double output) { + set(output); + } } diff --git a/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/VictorSP.java b/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/VictorSP.java index b7e309fab2..dbefdb7094 100644 --- a/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/VictorSP.java +++ b/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/VictorSP.java @@ -1,8 +1,8 @@ /*----------------------------------------------------------------------------*/ -/* Copyright (c) FIRST 2008-2012. All Rights Reserved. */ -/* Open Source Software - may be modified and shared by FRC teams. The code */ +/* Copyright (c) FIRST 2008-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 the root directory of */ -/* the project. */ +/* the project. */ /*----------------------------------------------------------------------------*/ package edu.wpi.first.wpilibj; @@ -15,106 +15,109 @@ import edu.wpi.first.wpilibj.livewindow.LiveWindow; * VEX Robotics Victor SP Speed Controller */ public class VictorSP extends SafePWM implements SpeedController { -private boolean isInverted = false; - /** - * Common initialization code called by all constructors. - * - * Note that the VictorSP uses the following bounds for PWM values. These values should work reasonably well for - * most controllers, but if users experience issues such as asymmetric behavior around - * the deadband or inability to saturate the controller in either direction, calibration is recommended. - * The calibration procedure can be found in the VictorSP User Manual available from CTRE. - * - * - 2.004ms = full "forward" - * - 1.52ms = the "high end" of the deadband range - * - 1.50ms = center of the deadband range (off) - * - 1.48ms = the "low end" of the deadband range - * - .997ms = full "reverse" - */ - protected void initVictorSP() { - setBounds(2.004, 1.52, 1.50, 1.48, .997); - setPeriodMultiplier(PeriodMultiplier.k1X); - setRaw(m_centerPwm); - setZeroLatch(); + private boolean isInverted = false; - LiveWindow.addActuator("VictorSP", getChannel(), this); - UsageReporting.report(tResourceType.kResourceType_VictorSP, getChannel()); - } + /** + * Common initialization code called by all constructors. + * + * Note that the VictorSP uses the following bounds for PWM values. These + * values should work reasonably well for most controllers, but if users + * experience issues such as asymmetric behavior around the deadband or + * inability to saturate the controller in either direction, calibration is + * recommended. The calibration procedure can be found in the VictorSP User + * Manual available from CTRE. + * + * - 2.004ms = full "forward" - 1.52ms = the "high end" of the deadband range + * - 1.50ms = center of the deadband range (off) - 1.48ms = the "low end" of + * the deadband range - .997ms = full "reverse" + */ + protected void initVictorSP() { + setBounds(2.004, 1.52, 1.50, 1.48, .997); + setPeriodMultiplier(PeriodMultiplier.k1X); + setRaw(m_centerPwm); + setZeroLatch(); - /** - * Constructor. - * - * @param channel The PWM channel that the VictorSP is attached to. 0-9 are on-board, 10-19 are on the MXP port - */ - public VictorSP(final int channel) { - super(channel); - initVictorSP(); - } + LiveWindow.addActuator("VictorSP", getChannel(), this); + UsageReporting.report(tResourceType.kResourceType_VictorSP, getChannel()); + } - /** - * Set the PWM value. - * - * @deprecated For compatibility with CANJaguar - * - * The PWM value is set using a range of -1.0 to 1.0, appropriately - * scaling the value for the FPGA. - * - * @param speed The speed to set. Value should be between -1.0 and 1.0. - * @param syncGroup The update group to add this Set() to, pending UpdateSyncGroup(). If 0, update immediately. - */ - public void set(double speed, byte syncGroup) { - setSpeed(isInverted ? -speed: speed); - Feed(); - } + /** + * Constructor. + * + * @param channel The PWM channel that the VictorSP is attached to. 0-9 are + * on-board, 10-19 are on the MXP port + */ + public VictorSP(final int channel) { + super(channel); + initVictorSP(); + } - /** - * Set the PWM value. - * - * The PWM value is set using a range of -1.0 to 1.0, appropriately - * scaling the value for the FPGA. - * - * @param speed The speed value between -1.0 and 1.0 to set. - */ - public void set(double speed) { - setSpeed(isInverted ? -speed: speed); - Feed(); - } + /** + * Set the PWM value. + * + * @deprecated For compatibility with CANJaguar + * + * The PWM value is set using a range of -1.0 to 1.0, + * appropriately scaling the value for the FPGA. + * + * @param speed The speed to set. Value should be between -1.0 and 1.0. + * @param syncGroup The update group to add this Set() to, pending + * UpdateSyncGroup(). If 0, update immediately. + */ + public void set(double speed, byte syncGroup) { + setSpeed(isInverted ? -speed : speed); + Feed(); + } - /** - * Common interface for inverting direction of a speed controller - * - * @param isInverted The state of inversion true is inverted - */ - @Override - public void setInverted(boolean isInverted) { - this.isInverted = isInverted; - } + /** + * Set the PWM value. + * + * The PWM value is set using a range of -1.0 to 1.0, appropriately scaling + * the value for the FPGA. + * + * @param speed The speed value between -1.0 and 1.0 to set. + */ + public void set(double speed) { + setSpeed(isInverted ? -speed : speed); + Feed(); + } - /** - * Common interface for the inverting direction of a speed controller. - * - * @return isInverted The state of inversion, true is inverted. - * - */ - @Override - public boolean getInverted() { - return this.isInverted; - } + /** + * Common interface for inverting direction of a speed controller + * + * @param isInverted The state of inversion true is inverted + */ + @Override + public void setInverted(boolean isInverted) { + this.isInverted = isInverted; + } - /** - * Get the recently set value of the PWM. - * - * @return The most recently set value for the PWM between -1.0 and 1.0. - */ - public double get() { - return getSpeed(); - } + /** + * Common interface for the inverting direction of a speed controller. + * + * @return isInverted The state of inversion, true is inverted. + * + */ + @Override + public boolean getInverted() { + return this.isInverted; + } - /** - * Write out the PID value as seen in the PIDOutput base object. - * - * @param output Write out the PWM value as was found in the PIDController - */ - public void pidWrite(double output) { - set(output); - } + /** + * Get the recently set value of the PWM. + * + * @return The most recently set value for the PWM between -1.0 and 1.0. + */ + public double get() { + return getSpeed(); + } + + /** + * Write out the PID value as seen in the PIDOutput base object. + * + * @param output Write out the PWM value as was found in the PIDController + */ + public void pidWrite(double output) { + set(output); + } } diff --git a/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/can/CANExceptionFactory.java b/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/can/CANExceptionFactory.java index e8e94f3de3..44fb9d0ca2 100644 --- a/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/can/CANExceptionFactory.java +++ b/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/can/CANExceptionFactory.java @@ -1,8 +1,8 @@ /*----------------------------------------------------------------------------*/ -/* Copyright (c) FIRST 2008-2012. All Rights Reserved. */ -/* Open Source Software - may be modified and shared by FRC teams. The code */ +/* Copyright (c) FIRST 2008-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 the root directory of */ -/* the project. */ +/* the project. */ /*----------------------------------------------------------------------------*/ package edu.wpi.first.wpilibj.can; @@ -11,33 +11,32 @@ import edu.wpi.first.wpilibj.communication.NIRioStatus; import edu.wpi.first.wpilibj.util.UncleanStatusException; public class CANExceptionFactory { - // FRC Error codes - static final int ERR_CANSessionMux_InvalidBuffer = -44086; - static final int ERR_CANSessionMux_MessageNotFound = -44087; - static final int ERR_CANSessionMux_NotAllowed = -44088; - static final int ERR_CANSessionMux_NotInitialized = -44089; + // FRC Error codes + static final int ERR_CANSessionMux_InvalidBuffer = -44086; + static final int ERR_CANSessionMux_MessageNotFound = -44087; + static final int ERR_CANSessionMux_NotAllowed = -44088; + static final int ERR_CANSessionMux_NotInitialized = -44089; - public static void checkStatus(int status, int messageID) throws - CANInvalidBufferException, CANMessageNotAllowedException, - CANNotInitializedException, UncleanStatusException { - switch (status) { - case NIRioStatus.kRioStatusSuccess: - // Everything is ok... don't throw. - return; - case ERR_CANSessionMux_InvalidBuffer: - case NIRioStatus.kRIOStatusBufferInvalidSize: - throw new CANInvalidBufferException(); - case ERR_CANSessionMux_MessageNotFound: - case NIRioStatus.kRIOStatusOperationTimedOut: - throw new CANMessageNotFoundException(); - case ERR_CANSessionMux_NotAllowed: - case NIRioStatus.kRIOStatusFeatureNotSupported: - throw new CANMessageNotAllowedException("MessageID = " + Integer.toString(messageID)); - case ERR_CANSessionMux_NotInitialized: - case NIRioStatus.kRIOStatusResourceNotInitialized: - throw new CANNotInitializedException(); - default: - throw new UncleanStatusException("Fatal status code detected: " + Integer.toString(status)); - } + public static void checkStatus(int status, int messageID) throws CANInvalidBufferException, + CANMessageNotAllowedException, CANNotInitializedException, UncleanStatusException { + switch (status) { + case NIRioStatus.kRioStatusSuccess: + // Everything is ok... don't throw. + return; + case ERR_CANSessionMux_InvalidBuffer: + case NIRioStatus.kRIOStatusBufferInvalidSize: + throw new CANInvalidBufferException(); + case ERR_CANSessionMux_MessageNotFound: + case NIRioStatus.kRIOStatusOperationTimedOut: + throw new CANMessageNotFoundException(); + case ERR_CANSessionMux_NotAllowed: + case NIRioStatus.kRIOStatusFeatureNotSupported: + throw new CANMessageNotAllowedException("MessageID = " + Integer.toString(messageID)); + case ERR_CANSessionMux_NotInitialized: + case NIRioStatus.kRIOStatusResourceNotInitialized: + throw new CANNotInitializedException(); + default: + throw new UncleanStatusException("Fatal status code detected: " + Integer.toString(status)); } + } } diff --git a/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/can/CANInvalidBufferException.java b/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/can/CANInvalidBufferException.java index 78be0eb98c..0891be6dd0 100644 --- a/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/can/CANInvalidBufferException.java +++ b/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/can/CANInvalidBufferException.java @@ -1,19 +1,19 @@ /*----------------------------------------------------------------------------*/ -/* Copyright (c) FIRST 2008-2012. All Rights Reserved. */ -/* Open Source Software - may be modified and shared by FRC teams. The code */ +/* Copyright (c) FIRST 2008-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 the root directory of */ -/* the project. */ +/* the project. */ /*----------------------------------------------------------------------------*/ package edu.wpi.first.wpilibj.can; /** - * Exception indicating that a CAN driver library entry-point - * was passed an invalid buffer. Typically, this is due to a - * buffer being too small to include the needed safety token. + * Exception indicating that a CAN driver library entry-point was passed an + * invalid buffer. Typically, this is due to a buffer being too small to include + * the needed safety token. */ public class CANInvalidBufferException extends RuntimeException { - public CANInvalidBufferException() { - super(); - } + public CANInvalidBufferException() { + super(); + } } diff --git a/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/can/CANJNI.java b/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/can/CANJNI.java index bd05cd8076..825e304403 100644 --- a/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/can/CANJNI.java +++ b/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/can/CANJNI.java @@ -1,459 +1,504 @@ package edu.wpi.first.wpilibj.can; -//import com.ochafik.lang.jnaerator.runtime.LibraryExtractor; -//import com.ochafik.lang.jnaerator.runtime.MangledFunctionMapper; -//import com.sun.jna.Library; -//import com.sun.jna.Native; -//import com.sun.jna.NativeLibrary; -//import com.sun.jna.Pointer; -//import com.sun.jna.ptr.IntByReference; + +// import com.ochafik.lang.jnaerator.runtime.LibraryExtractor; +// import com.ochafik.lang.jnaerator.runtime.MangledFunctionMapper; +// import com.sun.jna.Library; +// import com.sun.jna.Native; +// import com.sun.jna.NativeLibrary; +// import com.sun.jna.Pointer; +// import com.sun.jna.ptr.IntByReference; import edu.wpi.first.wpilibj.hal.JNIWrapper; import java.nio.ByteBuffer; import java.nio.IntBuffer; + /** * JNA Wrapper for library CAN
- * This file was autogenerated by JNAerator,
- * a tool written by Olivier Chafik that uses a few opensource projects..
- * For help, please visit NativeLibs4Java , Rococoa, or JNA. + * This file was autogenerated by JNAerator,
+ * a tool written by Olivier Chafik that uses a few + * opensource projects..
+ * For help, please visit NativeLibs4Java , Rococoa, or JNA. */ -public class CANJNI extends JNIWrapper{ - /** native declaration : src\main\include\CAN\can_proto.h */ - public static final int LM_STATUS_LIMIT_REV = 0x02; - /** native declaration : src\main\include\CAN\can_proto.h */ - public static final int LM_API_CFG_MAX_VOUT = ((0x00020000 | 0x02000000 | 0x00001c00) | (7 << 6)); - /** native declaration : src\main\include\CAN\can_proto.h */ - public static final int LM_PSTAT_CANERR_B0 = 30; - /** native declaration : src\main\include\CAN\can_proto.h */ - public static final int LM_API_SPD_DIS = ((0x00020000 | 0x02000000 | 0x00000400) | (1 << 6)); - /** native declaration : src\main\include\CAN\can_proto.h */ - public static final int CAN_MSGID_DTYPE_ACCEL = 0x05000000; - /** native declaration : src\main\include\CAN\can_proto.h */ - public static final int LM_API_STATUS_FAULT = ((0x00020000 | 0x02000000 | 0x00001400) | (7 << 6)); - /** native declaration : src\main\include\CAN\can_proto.h */ - public static final int CAN_MSGID_API_FIRMVER = 0x00000200; - /** native declaration : src\main\include\CAN\can_proto.h */ - public static final int LM_API_ICTRL_EN = ((0x00020000 | 0x02000000 | 0x00001000) | (0 << 6)); - /** native declaration : src\main\include\CAN\can_proto.h */ - public static final int CAN_MSGID_API_ENUMERATE = 0x00000240; - /** native declaration : src\main\include\CAN\can_proto.h */ - public static final int LM_API_SPD_EN = ((0x00020000 | 0x02000000 | 0x00000400) | (0 << 6)); - /** native declaration : src\main\include\CAN\can_proto.h */ - public static final int LM_API_CFG_LIMIT_REV = ((0x00020000 | 0x02000000 | 0x00001c00) | (6 << 6)); - /** native declaration : src\main\include\CAN\can_proto.h */ - public static final int LM_PSTAT_POS_B2 = 11; - /** native declaration : src\main\include\CAN\can_proto.h */ - public static final int LM_PSTAT_POS_B3 = 12; - /** native declaration : src\main\include\CAN\can_proto.h */ - public static final int LM_API_VCOMP_EN = ((0x00020000 | 0x02000000 | 0x00000800) | (0 << 6)); - /** native declaration : src\main\include\CAN\can_proto.h */ - public static final int LM_PSTAT_POS_B0 = 9; - /** native declaration : src\main\include\CAN\can_proto.h */ - public static final int LM_PSTAT_POS_B1 = 10; - /** native declaration : src\main\include\CAN\can_proto.h */ - public static final int LM_API_HWVER = ((0x00020000 | 0x1f000000) | (5 << 6)); - /** native declaration : src\main\include\CAN\can_proto.h */ - public static final int LM_STATUS_FAULT_ILIMIT = 0x01; - /** native declaration : src\main\include\CAN\can_proto.h */ - public static final int LM_API_ICTRL_DC = ((0x00020000 | 0x02000000 | 0x00001000) | (5 << 6)); - /** native declaration : src\main\include\CAN\can_proto.h */ - public static final int LM_API_VOLT = (0x00020000 | 0x02000000 | 0x00000000); - /** native declaration : src\main\include\CAN\can_proto.h */ - public static final int CAN_API_MC_VCOMP = 0x00000800; - /** native declaration : src\main\include\CAN\can_proto.h */ - public static final int LM_PSTAT_END = 0; - /** native declaration : src\main\include\CAN\can_proto.h */ - public static final int LM_API_CFG_LIMIT_FWD = ((0x00020000 | 0x02000000 | 0x00001c00) | (5 << 6)); - /** native declaration : src\main\include\CAN\can_proto.h */ - public static final int CAN_MSGID_DTYPE_M = 0x1f000000; - /** native declaration : src\main\include\CAN\can_proto.h */ - public static final int CAN_API_MC_ICTRL = 0x00001000; - /** native declaration : src\main\include\CAN\can_proto.h */ - public static final int CAN_API_MC_CFG = 0x00001c00; - /** native declaration : src\main\include\CAN\can_proto.h */ - public static final int CAN_MSGID_MFR_DEKA = 0x00030000; - /** native declaration : src\main\include\CAN\can_proto.h */ - public static final int CAN_MSGID_API_SYSRST = 0x00000040; - /** native declaration : src\main\include\CAN\can_proto.h */ - public static final int LM_REF_QUAD_ENCODER = 0x03; - /** native declaration : src\main\include\CAN\can_proto.h */ - public static final int LM_API_SYNC_PEND_NOW = 0; - /** native declaration : src\main\include\CAN\can_proto.h */ - public static final int LM_STATUS_CMODE_CURRENT = 0x01; - /** native declaration : src\main\include\CAN\can_proto.h */ - public static final int LM_API_STATUS_TEMP = ((0x00020000 | 0x02000000 | 0x00001400) | (3 << 6)); - /** native declaration : src\main\include\CAN\can_proto.h */ - public static final int LM_API_SPD_DC = ((0x00020000 | 0x02000000 | 0x00000400) | (5 << 6)); - /** native declaration : src\main\include\CAN\can_proto.h */ - public static final int CAN_API_MC_POS = 0x00000c00; - /** native declaration : src\main\include\CAN\can_proto.h */ - public static final int LM_STATUS_LIMIT_SFWD = 0x04; - /** native declaration : src\main\include\CAN\can_proto.h */ - public static final int LM_API_ICTRL_DIS = ((0x00020000 | 0x02000000 | 0x00001000) | (1 << 6)); - /** native declaration : src\main\include\CAN\can_proto.h */ - public static final int LM_API_VOLT_SET = ((0x00020000 | 0x02000000 | 0x00000000) | (2 << 6)); - /** native declaration : src\main\include\CAN\can_proto.h */ - public static final int CAN_MSGID_API_HEARTBEAT = 0x00000140; - /** native declaration : src\main\include\CAN\can_proto.h */ - public static final int LM_FAULT_CURRENT = 0x01; - /** native declaration : src\main\include\CAN\can_proto.h */ - public static final int CAN_MSGID_DTYPE_GYRO = 0x04000000; - /** native declaration : src\main\include\CAN\can_proto.h */ - public static final int LM_STATUS_FAULT_TLIMIT = 0x02; - /** native declaration : src\main\include\CAN\can_proto.h */ - public static final int CAN_MSGID_MFR_S = 16; - /** native declaration : src\main\include\CAN\can_proto.h */ - public static final int LM_API_SPD_T_SET_NO_ACK = ((0x00020000 | 0x02000000 | 0x00000400) | (10 << 6)); - /** native declaration : src\main\include\CAN\can_proto.h */ - public static final int CAN_MSGID_MFR_M = 0x00ff0000; - /** native declaration : src\main\include\CAN\can_proto.h */ - public static final int LM_STATUS_CMODE_POS = 0x03; - /** native declaration : src\main\include\CAN\can_proto.h */ - public static final int LM_REF_POT = 0x01; - /** native declaration : src\main\include\CAN\can_proto.h */ - public static final int LM_HWVER_UNKNOWN = 0x00; - /** native declaration : src\main\include\CAN\can_proto.h */ - public static final int LM_API_CFG_BRAKE_COAST = ((0x00020000 | 0x02000000 | 0x00001c00) | (3 << 6)); - /** native declaration : src\main\include\CAN\can_proto.h */ - public static final int LM_HWVER_JAG_1_0 = 0x01; - /** native declaration : src\main\include\CAN\can_proto.h */ - public static final int CAN_MSGID_DEVNO_BCAST = 0x00000000; - /** native declaration : src\main\include\CAN\can_proto.h */ - public static final int LM_API_VOLT_T_SET = ((0x00020000 | 0x02000000 | 0x00000000) | (5 << 6)); - /** native declaration : src\main\include\CAN\can_proto.h */ - public static final int LM_STATUS_LIMIT_STKY_SREV = 0x80; - /** native declaration : src\main\include\CAN\can_proto.h */ - public static final int LM_API_ICTRL_IC = ((0x00020000 | 0x02000000 | 0x00001000) | (4 << 6)); - /** native declaration : src\main\include\CAN\can_proto.h */ - public static final int LM_FAULT_COMM = 0x10; - /** native declaration : src\main\include\CAN\can_proto.h */ - public static final int LM_API_ICTRL_T_SET_NO_ACK = ((0x00020000 | 0x02000000 | 0x00001000) | (9 << 6)); - /** native declaration : src\main\include\CAN\can_proto.h */ - public static final int LM_PSTAT_SPD_B2 = 15; - /** native declaration : src\main\include\CAN\can_proto.h */ - public static final int LM_PSTAT_SPD_B1 = 14; - /** native declaration : src\main\include\CAN\can_proto.h */ - public static final int LM_PSTAT_STKY_FLT_CLR = 21; - /** native declaration : src\main\include\CAN\can_proto.h */ - public static final int LM_PSTAT_SPD_B3 = 16; - /** native declaration : src\main\include\CAN\can_proto.h */ - public static final int CAN_STATUS_MFG_S = 16; - /** native declaration : src\main\include\CAN\can_proto.h */ - public static final int LM_API_SPD_SET_NO_ACK = ((0x00020000 | 0x02000000 | 0x00000400) | (11 << 6)); - /** native declaration : src\main\include\CAN\can_proto.h */ - public static final int LM_API_STATUS_LIMIT = ((0x00020000 | 0x02000000 | 0x00001400) | (6 << 6)); - /** native declaration : src\main\include\CAN\can_proto.h */ - public static final int LM_API_VOLT_EN = ((0x00020000 | 0x02000000 | 0x00000000) | (0 << 6)); - /** native declaration : src\main\include\CAN\can_proto.h */ - public static final int LM_API_VOLT_RAMP_DIS = 0; - /** native declaration : src\main\include\CAN\can_proto.h */ - public static final int LM_PSTAT_TEMP_B0 = 7; - /** native declaration : src\main\include\CAN\can_proto.h */ - public static final int LM_PSTAT_TEMP_B1 = 8; - /** native declaration : src\main\include\CAN\can_proto.h */ - public static final int LM_API_POS_IC = ((0x00020000 | 0x02000000 | 0x00000c00) | (4 << 6)); - /** native declaration : src\main\include\CAN\can_proto.h */ - public static final int CAN_MSGID_DTYPE_MOTOR = 0x02000000; - /** native declaration : src\main\include\CAN\can_proto.h */ - public static final int LM_API_SPD_T_EN = ((0x00020000 | 0x02000000 | 0x00000400) | (7 << 6)); - /** native declaration : src\main\include\CAN\can_proto.h */ - public static final int CAN_MSGID_DEVNO_M = 0x0000003f; - /** native declaration : src\main\include\CAN\can_proto.h */ - public static final int LM_PSTAT_VOLTBUS_B1 = 4; - /** native declaration : src\main\include\CAN\can_proto.h */ - public static final int LM_API_UPD_PING = ((0x00020000 | 0x1f000000) | (0 << 6)); - /** native declaration : src\main\include\CAN\can_proto.h */ - public static final int LM_API_POS_T_SET_NO_ACK = ((0x00020000 | 0x02000000 | 0x00000c00) | (10 << 6)); - /** native declaration : src\main\include\CAN\can_proto.h */ - public static final int CAN_MSGID_DEVNO_S = 0; - /** native declaration : src\main\include\CAN\can_proto.h */ - public static final int LM_API_TRUST_HEARTBEAT = ((0x00020000 | 0x1f000000) | (13 << 6)); - /** native declaration : src\main\include\CAN\can_proto.h */ - public static final int LM_PSTAT_VOLTBUS_B0 = 3; - /** native declaration : src\main\include\CAN\can_proto.h */ - public static final int LM_PSTAT_SPD_B0 = 13; - /** native declaration : src\main\include\CAN\can_proto.h */ - public static final int LM_API_CFG = (0x00020000 | 0x02000000 | 0x00001c00); - /** native declaration : src\main\include\CAN\can_proto.h */ - public static final int LM_PSTAT_FLT_COUNT_COMM = 28; - /** native declaration : src\main\include\CAN\can_proto.h */ - public static final int CAN_MSGID_API_SYSHALT = 0x00000000; - /** native declaration : src\main\include\CAN\can_proto.h */ - public static final int LM_API_UPD_DOWNLOAD = ((0x00020000 | 0x1f000000) | (1 << 6)); - /** native declaration : src\main\include\CAN\can_proto.h */ - public static final int LM_API_STATUS_CMODE = ((0x00020000 | 0x02000000 | 0x00001400) | (9 << 6)); - /** native declaration : src\main\include\CAN\can_proto.h */ - public static final int LM_API_VCOMP_IN_RAMP = ((0x00020000 | 0x02000000 | 0x00000800) | (3 << 6)); - /** native declaration : src\main\include\CAN\can_proto.h */ - public static final int LM_STATUS_FAULT_VLIMIT = 0x04; - /** native declaration : src\main\include\CAN\can_proto.h */ - public static final int LM_STATUS_LIMIT_SREV = 0x08; - /** native declaration : src\main\include\CAN\can_proto.h */ - public static final int CAN_MSGID_DTYPE_S = 24; - /** native declaration : src\main\include\CAN\can_proto.h */ - public static final int LM_PSTAT_FLT_COUNT_VOLTBUS = 26; - /** native declaration : src\main\include\CAN\can_proto.h */ - public static final int CAN_API_MC_STATUS = 0x00001400; - /** native declaration : src\main\include\CAN\can_proto.h */ - public static final int LM_API_VOLT_T_EN = ((0x00020000 | 0x02000000 | 0x00000000) | (4 << 6)); - /** native declaration : src\main\include\CAN\can_proto.h */ - public static final int LM_API_STATUS_VOLTBUS = ((0x00020000 | 0x02000000 | 0x00001400) | (1 << 6)); - /** native declaration : src\main\include\CAN\can_proto.h */ - public static final int LM_API_UPD = (0x00020000 | 0x1f000000); - /** native declaration : src\main\include\CAN\can_proto.h */ - public static final int LM_API_UPD_REQUEST = ((0x00020000 | 0x1f000000) | (6 << 6)); - /** native declaration : src\main\include\CAN\can_proto.h */ - public static final int CAN_API_MC_VOLTAGE = 0x00000000; - /** native declaration : src\main\include\CAN\can_proto.h */ - public static final int LM_API_PSTAT_PER_EN_S3 = ((0x00020000 | 0x02000000 | 0x00001800) | (3 << 6)); - /** native declaration : src\main\include\CAN\can_proto.h */ - public static final int LM_API_PSTAT_PER_EN_S2 = ((0x00020000 | 0x02000000 | 0x00001800) | (2 << 6)); - /** native declaration : src\main\include\CAN\can_proto.h */ - public static final int CAN_API_MC_PSTAT = 0x00001800; - /** native declaration : src\main\include\CAN\can_proto.h */ - public static final int LM_PSTAT_CANERR_B1 = 31; - /** native declaration : src\main\include\CAN\can_proto.h */ - public static final int LM_API_PSTAT_PER_EN_S1 = ((0x00020000 | 0x02000000 | 0x00001800) | (1 << 6)); - /** native declaration : src\main\include\CAN\can_proto.h */ - public static final int LM_REF_ENCODER = 0x00; - /** native declaration : src\main\include\CAN\can_proto.h */ - public static final int LM_API_PSTAT_PER_EN_S0 = ((0x00020000 | 0x02000000 | 0x00001800) | (0 << 6)); - /** native declaration : src\main\include\CAN\can_proto.h */ - public static final int LM_API_STATUS_CURRENT = ((0x00020000 | 0x02000000 | 0x00001400) | (2 << 6)); - /** native declaration : src\main\include\CAN\can_proto.h */ - public static final int LM_API_POS_SET = ((0x00020000 | 0x02000000 | 0x00000c00) | (2 << 6)); - /** native declaration : src\main\include\CAN\can_proto.h */ - public static final int LM_STATUS_LIMIT_STKY_FWD = 0x10; - /** native declaration : src\main\include\CAN\can_proto.h */ - public static final int LM_API_ICTRL = (0x00020000 | 0x02000000 | 0x00001000); - /** native declaration : src\main\include\CAN\can_proto.h */ - public static final int LM_HWVER_JAG_2_0 = 0x02; - /** native declaration : src\main\include\CAN\can_proto.h */ - public static final int CAN_STATUS_MFG_M = 0x00ff0000; - /** native declaration : src\main\include\CAN\can_proto.h */ - public static final int LM_PSTAT_LIMIT_CLR = 18; - /** native declaration : src\main\include\CAN\can_proto.h */ - public static final int LM_API_CFG_POT_TURNS = ((0x00020000 | 0x02000000 | 0x00001c00) | (2 << 6)); - /** native declaration : src\main\include\CAN\can_proto.h */ - public static final int LM_API_POS_REF = ((0x00020000 | 0x02000000 | 0x00000c00) | (6 << 6)); - /** native declaration : src\main\include\CAN\can_proto.h */ - public static final int LM_API_SPD_PC = ((0x00020000 | 0x02000000 | 0x00000400) | (3 << 6)); - /** native declaration : src\main\include\CAN\can_proto.h */ - public static final int LM_API_STATUS_VOUT = ((0x00020000 | 0x02000000 | 0x00001400) | (10 << 6)); - /** native declaration : src\main\include\CAN\can_proto.h */ - public static final int CAN_MSGID_API_SYSRESUME = 0x00000280; - /** native declaration : src\main\include\CAN\can_proto.h */ - public static final int LM_API_UNTRUST_EN = ((0x00020000 | 0x1f000000) | (11 << 6)); - /** native declaration : src\main\include\CAN\can_proto.h */ - public static final int LM_PSTAT_CANSTS = 29; - /** native declaration : src\main\include\CAN\can_proto.h */ - public static final int LM_API_POS_DC = ((0x00020000 | 0x02000000 | 0x00000c00) | (5 << 6)); - /** native declaration : src\main\include\CAN\can_proto.h */ - public static final int LM_API_STATUS_POS = ((0x00020000 | 0x02000000 | 0x00001400) | (4 << 6)); - /** native declaration : src\main\include\CAN\can_proto.h */ - public static final int LM_API_SPD_SET = ((0x00020000 | 0x02000000 | 0x00000400) | (2 << 6)); - /** native declaration : src\main\include\CAN\can_proto.h */ - public static final int CAN_MSGID_FULL_M = 0x1fffffff; - /** native declaration : src\main\include\CAN\can_proto.h */ - public static final int LM_API_STATUS_SPD = ((0x00020000 | 0x02000000 | 0x00001400) | (5 << 6)); - /** native declaration : src\main\include\CAN\can_proto.h */ - public static final int LM_PSTAT_STKY_FLT_NCLR = 20; - /** native declaration : src\main\include\CAN\can_proto.h */ - public static final int LM_API_STATUS = (0x00020000 | 0x02000000 | 0x00001400); - /** native declaration : src\main\include\CAN\can_proto.h */ - public static final int LM_API_TRUST_EN = ((0x00020000 | 0x1f000000) | (12 << 6)); - /** native declaration : src\main\include\CAN\can_proto.h */ - public static final int LM_API_ICTRL_T_SET = ((0x00020000 | 0x02000000 | 0x00001000) | (7 << 6)); - /** native declaration : src\main\include\CAN\can_proto.h */ - public static final int CAN_STATUS_CODE_M = 0x0000ffff; - /** native declaration : src\main\include\CAN\can_proto.h */ - public static final int CAN_STATUS_CODE_S = 0; - /** native declaration : src\main\include\CAN\can_proto.h */ - public static final int LM_API_POS_T_EN = ((0x00020000 | 0x02000000 | 0x00000c00) | (7 << 6)); - /** native declaration : src\main\include\CAN\can_proto.h */ - public static final int LM_API_PSTAT = (0x00020000 | 0x02000000 | 0x00001800); - /** native declaration : src\main\include\CAN\can_proto.h */ - public static final int LM_PSTAT_FAULT = 19; - /** native declaration : src\main\include\CAN\can_proto.h */ - public static final int LM_PSTAT_FLT_COUNT_GATE = 27; - /** native declaration : src\main\include\CAN\can_proto.h */ - public static final int LM_API_ICTRL_T_EN = ((0x00020000 | 0x02000000 | 0x00001000) | (6 << 6)); - /** native declaration : src\main\include\CAN\can_proto.h */ - public static final int CAN_MSGID_API_DEVQUERY = 0x000000c0; - /** native declaration : src\main\include\CAN\can_proto.h */ - public static final int CAN_MSGID_DTYPE_USONIC = 0x06000000; - /** native declaration : src\main\include\CAN\can_proto.h */ - public static final int LM_STATUS_CMODE_VCOMP = 0x04; - /** native declaration : src\main\include\CAN\can_proto.h */ - public static final int LM_API_SPD_T_SET = ((0x00020000 | 0x02000000 | 0x00000400) | (8 << 6)); - /** native declaration : src\main\include\CAN\can_proto.h */ - public static final int LM_API_POS_EN = ((0x00020000 | 0x02000000 | 0x00000c00) | (0 << 6)); - /** native declaration : src\main\include\CAN\can_proto.h */ - public static final int LM_API_VOLT_DIS = ((0x00020000 | 0x02000000 | 0x00000000) | (1 << 6)); - /** native declaration : src\main\include\CAN\can_proto.h */ - public static final int LM_STATUS_LIMIT_FWD = 0x01; - /** native declaration : src\main\include\CAN\can_proto.h */ - public static final int LM_API_VCOMP_DIS = ((0x00020000 | 0x02000000 | 0x00000800) | (1 << 6)); - /** native declaration : src\main\include\CAN\can_proto.h */ - public static final int LM_REF_INV_ENCODER = 0x02; - /** native declaration : src\main\include\CAN\can_proto.h */ - public static final int LM_API_CFG_NUM_BRUSHES = ((0x00020000 | 0x02000000 | 0x00001c00) | (0 << 6)); - /** native declaration : src\main\include\CAN\can_proto.h */ - public static final int CAN_MSGID_DTYPE_RELAY = 0x03000000; - /** native declaration : src\main\include\CAN\can_proto.h */ - public static final int CAN_MSGID_API_DEVASSIGN = 0x00000080; - /** native declaration : src\main\include\CAN\can_proto.h */ - public static final int LM_API_VOLT_T_SET_NO_ACK = ((0x00020000 | 0x02000000 | 0x00000000) | (7 << 6)); - /** native declaration : src\main\include\CAN\can_proto.h */ - public static final int CAN_API_MC_SPD = 0x00000400; - /** native declaration : src\main\include\CAN\can_proto.h */ - public static final int LM_API_CFG_ENC_LINES = ((0x00020000 | 0x02000000 | 0x00001c00) | (1 << 6)); - /** native declaration : src\main\include\CAN\can_proto.h */ - public static final int LM_REF_NONE = 0xff; - /** native declaration : src\main\include\CAN\can_proto.h */ - public static final int LM_FAULT_VBUS = 0x04; - /** native declaration : src\main\include\CAN\can_proto.h */ - public static final int LM_API_VOLT_SET_RAMP = ((0x00020000 | 0x02000000 | 0x00000000) | (3 << 6)); - /** native declaration : src\main\include\CAN\can_proto.h */ - public static final int LM_API_SPD_REF = ((0x00020000 | 0x02000000 | 0x00000400) | (6 << 6)); - /** native declaration : src\main\include\CAN\can_proto.h */ - public static final int LM_API_STATUS_POWER = ((0x00020000 | 0x02000000 | 0x00001400) | (8 << 6)); - /** native declaration : src\main\include\CAN\can_proto.h */ - public static final int LM_PSTAT_VOLTOUT_B1 = 2; - /** native declaration : src\main\include\CAN\can_proto.h */ - public static final int LM_API_VCOMP_SET_NO_ACK = ((0x00020000 | 0x02000000 | 0x00000800) | (9 << 6)); - /** native declaration : src\main\include\CAN\can_proto.h */ - public static final int LM_PSTAT_VOLTOUT_B0 = 1; - /** native declaration : src\main\include\CAN\can_proto.h */ - public static final int LM_API_CFG_LIMIT_MODE = ((0x00020000 | 0x02000000 | 0x00001c00) | (4 << 6)); - /** native declaration : src\main\include\CAN\can_proto.h */ - public static final int LM_PSTAT_VOUT_B1 = 23; - /** native declaration : src\main\include\CAN\can_proto.h */ - public static final int LM_API_UPD_SEND_DATA = ((0x00020000 | 0x1f000000) | (2 << 6)); - /** native declaration : src\main\include\CAN\can_proto.h */ - public static final int LM_PSTAT_FLT_COUNT_CURRENT = 24; - /** native declaration : src\main\include\CAN\can_proto.h */ - public static final int LM_PSTAT_VOUT_B0 = 22; - /** native declaration : src\main\include\CAN\can_proto.h */ - public static final int LM_API_PSTAT_CFG_S0 = ((0x00020000 | 0x02000000 | 0x00001800) | (4 << 6)); - /** native declaration : src\main\include\CAN\can_proto.h */ - public static final int LM_PSTAT_LIMIT_NCLR = 17; - /** native declaration : src\main\include\CAN\can_proto.h */ - public static final int LM_API_PSTAT_CFG_S1 = ((0x00020000 | 0x02000000 | 0x00001800) | (5 << 6)); - /** native declaration : src\main\include\CAN\can_proto.h */ - public static final int LM_API_PSTAT_CFG_S2 = ((0x00020000 | 0x02000000 | 0x00001800) | (6 << 6)); - /** native declaration : src\main\include\CAN\can_proto.h */ - public static final int LM_API_PSTAT_CFG_S3 = ((0x00020000 | 0x02000000 | 0x00001800) | (7 << 6)); - /** native declaration : src\main\include\CAN\can_proto.h */ - public static final int LM_API_VCOMP_SET = ((0x00020000 | 0x02000000 | 0x00000800) | (2 << 6)); - /** native declaration : src\main\include\CAN\can_proto.h */ - public static final int CAN_MSGID_API_UPDATE = 0x000001c0; - /** native declaration : src\main\include\CAN\can_proto.h */ - public static final int LM_API_CFG_FAULT_TIME = ((0x00020000 | 0x02000000 | 0x00001c00) | (8 << 6)); - /** native declaration : src\main\include\CAN\can_proto.h */ - public static final int LM_API_STATUS_VOLTOUT = ((0x00020000 | 0x02000000 | 0x00001400) | (0 << 6)); - /** native declaration : src\main\include\CAN\can_proto.h */ - public static final int LM_API_ICTRL_SET = ((0x00020000 | 0x02000000 | 0x00001000) | (2 << 6)); - /** native declaration : src\main\include\CAN\can_proto.h */ - public static final int CAN_MSGID_API_M = 0x0000ffc0; - /** native declaration : src\main\include\CAN\can_proto.h */ - public static final int LM_STATUS_CMODE_SPEED = 0x02; - /** native declaration : src\main\include\CAN\can_proto.h */ - public static final int CAN_MSGID_API_CLASS_M = 0x0000fc00; - /** native declaration : src\main\include\CAN\can_proto.h */ - public static final int LM_API_PSTAT_DATA_S3 = ((0x00020000 | 0x02000000 | 0x00001800) | (11 << 6)); - /** native declaration : src\main\include\CAN\can_proto.h */ - public static final int CAN_MSGID_API_S = 6; - /** native declaration : src\main\include\CAN\can_proto.h */ - public static final int LM_API_STATUS_FLT_COUNT = ((0x00020000 | 0x02000000 | 0x00001400) | (12 << 6)); - /** native declaration : src\main\include\CAN\can_proto.h */ - public static final int LM_API_PSTAT_DATA_S2 = ((0x00020000 | 0x02000000 | 0x00001800) | (10 << 6)); - /** native declaration : src\main\include\CAN\can_proto.h */ - public static final int LM_API_PSTAT_DATA_S1 = ((0x00020000 | 0x02000000 | 0x00001800) | (9 << 6)); - /** native declaration : src\main\include\CAN\can_proto.h */ - public static final int LM_API_PSTAT_DATA_S0 = ((0x00020000 | 0x02000000 | 0x00001800) | (8 << 6)); - /** native declaration : src\main\include\CAN\can_proto.h */ - public static final int LM_API_ICTRL_PC = ((0x00020000 | 0x02000000 | 0x00001000) | (3 << 6)); - /** native declaration : src\main\include\CAN\can_proto.h */ - public static final int LM_API_POS_PC = ((0x00020000 | 0x02000000 | 0x00000c00) | (3 << 6)); - /** native declaration : src\main\include\CAN\can_proto.h */ - public static final int CAN_MSGID_MFR_LM = 0x00020000; - /** native declaration : src\main\include\CAN\can_proto.h */ - public static final int LM_API_POS_DIS = ((0x00020000 | 0x02000000 | 0x00000c00) | (1 << 6)); - /** native declaration : src\main\include\CAN\can_proto.h */ - public static final int CAN_MSGID_DTYPE_BCAST = 0x00000000; - /** native declaration : src\main\include\CAN\can_proto.h */ - public static final int LM_STATUS_CMODE_VOLT = 0x00; - /** native declaration : src\main\include\CAN\can_proto.h */ - public static final int CAN_STATUS_DTYPE_S = 24; - /** native declaration : src\main\include\CAN\can_proto.h */ - public static final int LM_API_POS_SET_NO_ACK = ((0x00020000 | 0x02000000 | 0x00000c00) | (11 << 6)); - /** native declaration : src\main\include\CAN\can_proto.h */ - public static final int LM_FAULT_GATE_DRIVE = 0x08; - /** native declaration : src\main\include\CAN\can_proto.h */ - public static final int CAN_STATUS_DTYPE_M = 0x1f000000; - /** native declaration : src\main\include\CAN\can_proto.h */ - public static final int LM_STATUS_LIMIT_STKY_REV = 0x20; - /** native declaration : src\main\include\CAN\can_proto.h */ - public static final int CAN_MSGID_DTYPE_ROBOT = 0x01000000; - /** native declaration : src\main\include\CAN\can_proto.h */ - public static final int CAN_API_MC_ACK = 0x00002000; - /** native declaration : src\main\include\CAN\can_proto.h */ - public static final int LM_API_VCOMP = (0x00020000 | 0x02000000 | 0x00000800); - /** native declaration : src\main\include\CAN\can_proto.h */ - public static final int LM_API_UPD_ACK = ((0x00020000 | 0x1f000000) | (4 << 6)); - /** native declaration : src\main\include\CAN\can_proto.h */ - public static final int LM_API_VCOMP_COMP_RAMP = ((0x00020000 | 0x02000000 | 0x00000800) | (4 << 6)); - /** native declaration : src\main\include\CAN\can_proto.h */ - public static final int LM_API_VCOMP_T_SET_NO_ACK = ((0x00020000 | 0x02000000 | 0x00000800) | (8 << 6)); - /** native declaration : src\main\include\CAN\can_proto.h */ - public static final int LM_API_POS = (0x00020000 | 0x02000000 | 0x00000c00); - /** native declaration : src\main\include\CAN\can_proto.h */ - public static final int CAN_MSGID_API_SYNC = 0x00000180; - /** native declaration : src\main\include\CAN\can_proto.h */ - public static final int LM_API_ICTRL_SET_NO_ACK = ((0x00020000 | 0x02000000 | 0x00001000) | (10 << 6)); - /** native declaration : src\main\include\CAN\can_proto.h */ - public static final int LM_PSTAT_CURRENT_B1 = 6; - /** native declaration : src\main\include\CAN\can_proto.h */ - public static final int LM_API_SPD = (0x00020000 | 0x02000000 | 0x00000400); - /** native declaration : src\main\include\CAN\can_proto.h */ - public static final int LM_PSTAT_CURRENT_B0 = 5; - /** native declaration : src\main\include\CAN\can_proto.h */ - public static final int CAN_MSGID_DTYPE_UPDATE = 0x1f000000; - /** native declaration : src\main\include\CAN\can_proto.h */ - public static final int LM_API_SPD_IC = ((0x00020000 | 0x02000000 | 0x00000400) | (4 << 6)); - /** native declaration : src\main\include\CAN\can_proto.h */ - public static final int LM_API_ACK = (0x00020000 | 0x02000000 | 0x00002000); - /** native declaration : src\main\include\CAN\can_proto.h */ - public static final int LM_FAULT_TEMP = 0x02; - /** native declaration : src\main\include\CAN\can_proto.h */ - public static final int LM_API_VCOMP_T_SET = ((0x00020000 | 0x02000000 | 0x00000800) | (6 << 6)); - /** native declaration : src\main\include\CAN\can_proto.h */ - public static final int LM_PSTAT_FLT_COUNT_TEMP = 25; - /** native declaration : src\main\include\CAN\can_proto.h */ - public static final int LM_API_VOLT_SET_NO_ACK = ((0x00020000 | 0x02000000 | 0x00000000) | (8 << 6)); - /** native declaration : src\main\include\CAN\can_proto.h */ - public static final int CAN_MSGID_DTYPE_GEART = 0x07000000; - /** native declaration : src\main\include\CAN\can_proto.h */ - public static final int CAN_MSGID_MFR_NI = 0x00010000; - /** native declaration : src\main\include\CAN\can_proto.h */ - public static final int LM_API_POS_T_SET = ((0x00020000 | 0x02000000 | 0x00000c00) | (8 << 6)); - /** native declaration : src\main\include\CAN\can_proto.h */ - public static final int LM_API_STATUS_STKY_FLT = ((0x00020000 | 0x02000000 | 0x00001400) | (11 << 6)); - /** native declaration : src\main\include\CAN\can_proto.h */ - public static final int LM_API_UPD_RESET = ((0x00020000 | 0x1f000000) | (3 << 6)); - /** native declaration : src\main\include\CAN\can_proto.h */ - public static final int CAN_MSGID_API_ID_M = 0x000003c0; - /** native declaration : src\main\include\CAN\can_proto.h */ - public static final int LM_API_VCOMP_T_EN = ((0x00020000 | 0x02000000 | 0x00000800) | (5 << 6)); - /** native declaration : src\main\include\CAN\can_proto.h */ - public static final int LM_STATUS_LIMIT_STKY_SFWD = 0x40; - - public static final int CAN_SEND_PERIOD_NO_REPEAT = 0; - public static final int CAN_SEND_PERIOD_STOP_REPEATING = -1; +public class CANJNI extends JNIWrapper { + /** native declaration : src\main\include\CAN\can_proto.h */ + public static final int LM_STATUS_LIMIT_REV = 0x02; + /** native declaration : src\main\include\CAN\can_proto.h */ + public static final int LM_API_CFG_MAX_VOUT = ((0x00020000 | 0x02000000 | 0x00001c00) | (7 << 6)); + /** native declaration : src\main\include\CAN\can_proto.h */ + public static final int LM_PSTAT_CANERR_B0 = 30; + /** native declaration : src\main\include\CAN\can_proto.h */ + public static final int LM_API_SPD_DIS = ((0x00020000 | 0x02000000 | 0x00000400) | (1 << 6)); + /** native declaration : src\main\include\CAN\can_proto.h */ + public static final int CAN_MSGID_DTYPE_ACCEL = 0x05000000; + /** native declaration : src\main\include\CAN\can_proto.h */ + public static final int LM_API_STATUS_FAULT = ((0x00020000 | 0x02000000 | 0x00001400) | (7 << 6)); + /** native declaration : src\main\include\CAN\can_proto.h */ + public static final int CAN_MSGID_API_FIRMVER = 0x00000200; + /** native declaration : src\main\include\CAN\can_proto.h */ + public static final int LM_API_ICTRL_EN = ((0x00020000 | 0x02000000 | 0x00001000) | (0 << 6)); + /** native declaration : src\main\include\CAN\can_proto.h */ + public static final int CAN_MSGID_API_ENUMERATE = 0x00000240; + /** native declaration : src\main\include\CAN\can_proto.h */ + public static final int LM_API_SPD_EN = ((0x00020000 | 0x02000000 | 0x00000400) | (0 << 6)); + /** native declaration : src\main\include\CAN\can_proto.h */ + public static final int LM_API_CFG_LIMIT_REV = + ((0x00020000 | 0x02000000 | 0x00001c00) | (6 << 6)); + /** native declaration : src\main\include\CAN\can_proto.h */ + public static final int LM_PSTAT_POS_B2 = 11; + /** native declaration : src\main\include\CAN\can_proto.h */ + public static final int LM_PSTAT_POS_B3 = 12; + /** native declaration : src\main\include\CAN\can_proto.h */ + public static final int LM_API_VCOMP_EN = ((0x00020000 | 0x02000000 | 0x00000800) | (0 << 6)); + /** native declaration : src\main\include\CAN\can_proto.h */ + public static final int LM_PSTAT_POS_B0 = 9; + /** native declaration : src\main\include\CAN\can_proto.h */ + public static final int LM_PSTAT_POS_B1 = 10; + /** native declaration : src\main\include\CAN\can_proto.h */ + public static final int LM_API_HWVER = ((0x00020000 | 0x1f000000) | (5 << 6)); + /** native declaration : src\main\include\CAN\can_proto.h */ + public static final int LM_STATUS_FAULT_ILIMIT = 0x01; + /** native declaration : src\main\include\CAN\can_proto.h */ + public static final int LM_API_ICTRL_DC = ((0x00020000 | 0x02000000 | 0x00001000) | (5 << 6)); + /** native declaration : src\main\include\CAN\can_proto.h */ + public static final int LM_API_VOLT = (0x00020000 | 0x02000000 | 0x00000000); + /** native declaration : src\main\include\CAN\can_proto.h */ + public static final int CAN_API_MC_VCOMP = 0x00000800; + /** native declaration : src\main\include\CAN\can_proto.h */ + public static final int LM_PSTAT_END = 0; + /** native declaration : src\main\include\CAN\can_proto.h */ + public static final int LM_API_CFG_LIMIT_FWD = + ((0x00020000 | 0x02000000 | 0x00001c00) | (5 << 6)); + /** native declaration : src\main\include\CAN\can_proto.h */ + public static final int CAN_MSGID_DTYPE_M = 0x1f000000; + /** native declaration : src\main\include\CAN\can_proto.h */ + public static final int CAN_API_MC_ICTRL = 0x00001000; + /** native declaration : src\main\include\CAN\can_proto.h */ + public static final int CAN_API_MC_CFG = 0x00001c00; + /** native declaration : src\main\include\CAN\can_proto.h */ + public static final int CAN_MSGID_MFR_DEKA = 0x00030000; + /** native declaration : src\main\include\CAN\can_proto.h */ + public static final int CAN_MSGID_API_SYSRST = 0x00000040; + /** native declaration : src\main\include\CAN\can_proto.h */ + public static final int LM_REF_QUAD_ENCODER = 0x03; + /** native declaration : src\main\include\CAN\can_proto.h */ + public static final int LM_API_SYNC_PEND_NOW = 0; + /** native declaration : src\main\include\CAN\can_proto.h */ + public static final int LM_STATUS_CMODE_CURRENT = 0x01; + /** native declaration : src\main\include\CAN\can_proto.h */ + public static final int LM_API_STATUS_TEMP = ((0x00020000 | 0x02000000 | 0x00001400) | (3 << 6)); + /** native declaration : src\main\include\CAN\can_proto.h */ + public static final int LM_API_SPD_DC = ((0x00020000 | 0x02000000 | 0x00000400) | (5 << 6)); + /** native declaration : src\main\include\CAN\can_proto.h */ + public static final int CAN_API_MC_POS = 0x00000c00; + /** native declaration : src\main\include\CAN\can_proto.h */ + public static final int LM_STATUS_LIMIT_SFWD = 0x04; + /** native declaration : src\main\include\CAN\can_proto.h */ + public static final int LM_API_ICTRL_DIS = ((0x00020000 | 0x02000000 | 0x00001000) | (1 << 6)); + /** native declaration : src\main\include\CAN\can_proto.h */ + public static final int LM_API_VOLT_SET = ((0x00020000 | 0x02000000 | 0x00000000) | (2 << 6)); + /** native declaration : src\main\include\CAN\can_proto.h */ + public static final int CAN_MSGID_API_HEARTBEAT = 0x00000140; + /** native declaration : src\main\include\CAN\can_proto.h */ + public static final int LM_FAULT_CURRENT = 0x01; + /** native declaration : src\main\include\CAN\can_proto.h */ + public static final int CAN_MSGID_DTYPE_GYRO = 0x04000000; + /** native declaration : src\main\include\CAN\can_proto.h */ + public static final int LM_STATUS_FAULT_TLIMIT = 0x02; + /** native declaration : src\main\include\CAN\can_proto.h */ + public static final int CAN_MSGID_MFR_S = 16; + /** native declaration : src\main\include\CAN\can_proto.h */ + public static final int LM_API_SPD_T_SET_NO_ACK = + ((0x00020000 | 0x02000000 | 0x00000400) | (10 << 6)); + /** native declaration : src\main\include\CAN\can_proto.h */ + public static final int CAN_MSGID_MFR_M = 0x00ff0000; + /** native declaration : src\main\include\CAN\can_proto.h */ + public static final int LM_STATUS_CMODE_POS = 0x03; + /** native declaration : src\main\include\CAN\can_proto.h */ + public static final int LM_REF_POT = 0x01; + /** native declaration : src\main\include\CAN\can_proto.h */ + public static final int LM_HWVER_UNKNOWN = 0x00; + /** native declaration : src\main\include\CAN\can_proto.h */ + public static final int LM_API_CFG_BRAKE_COAST = + ((0x00020000 | 0x02000000 | 0x00001c00) | (3 << 6)); + /** native declaration : src\main\include\CAN\can_proto.h */ + public static final int LM_HWVER_JAG_1_0 = 0x01; + /** native declaration : src\main\include\CAN\can_proto.h */ + public static final int CAN_MSGID_DEVNO_BCAST = 0x00000000; + /** native declaration : src\main\include\CAN\can_proto.h */ + public static final int LM_API_VOLT_T_SET = ((0x00020000 | 0x02000000 | 0x00000000) | (5 << 6)); + /** native declaration : src\main\include\CAN\can_proto.h */ + public static final int LM_STATUS_LIMIT_STKY_SREV = 0x80; + /** native declaration : src\main\include\CAN\can_proto.h */ + public static final int LM_API_ICTRL_IC = ((0x00020000 | 0x02000000 | 0x00001000) | (4 << 6)); + /** native declaration : src\main\include\CAN\can_proto.h */ + public static final int LM_FAULT_COMM = 0x10; + /** native declaration : src\main\include\CAN\can_proto.h */ + public static final int LM_API_ICTRL_T_SET_NO_ACK = + ((0x00020000 | 0x02000000 | 0x00001000) | (9 << 6)); + /** native declaration : src\main\include\CAN\can_proto.h */ + public static final int LM_PSTAT_SPD_B2 = 15; + /** native declaration : src\main\include\CAN\can_proto.h */ + public static final int LM_PSTAT_SPD_B1 = 14; + /** native declaration : src\main\include\CAN\can_proto.h */ + public static final int LM_PSTAT_STKY_FLT_CLR = 21; + /** native declaration : src\main\include\CAN\can_proto.h */ + public static final int LM_PSTAT_SPD_B3 = 16; + /** native declaration : src\main\include\CAN\can_proto.h */ + public static final int CAN_STATUS_MFG_S = 16; + /** native declaration : src\main\include\CAN\can_proto.h */ + public static final int LM_API_SPD_SET_NO_ACK = + ((0x00020000 | 0x02000000 | 0x00000400) | (11 << 6)); + /** native declaration : src\main\include\CAN\can_proto.h */ + public static final int LM_API_STATUS_LIMIT = ((0x00020000 | 0x02000000 | 0x00001400) | (6 << 6)); + /** native declaration : src\main\include\CAN\can_proto.h */ + public static final int LM_API_VOLT_EN = ((0x00020000 | 0x02000000 | 0x00000000) | (0 << 6)); + /** native declaration : src\main\include\CAN\can_proto.h */ + public static final int LM_API_VOLT_RAMP_DIS = 0; + /** native declaration : src\main\include\CAN\can_proto.h */ + public static final int LM_PSTAT_TEMP_B0 = 7; + /** native declaration : src\main\include\CAN\can_proto.h */ + public static final int LM_PSTAT_TEMP_B1 = 8; + /** native declaration : src\main\include\CAN\can_proto.h */ + public static final int LM_API_POS_IC = ((0x00020000 | 0x02000000 | 0x00000c00) | (4 << 6)); + /** native declaration : src\main\include\CAN\can_proto.h */ + public static final int CAN_MSGID_DTYPE_MOTOR = 0x02000000; + /** native declaration : src\main\include\CAN\can_proto.h */ + public static final int LM_API_SPD_T_EN = ((0x00020000 | 0x02000000 | 0x00000400) | (7 << 6)); + /** native declaration : src\main\include\CAN\can_proto.h */ + public static final int CAN_MSGID_DEVNO_M = 0x0000003f; + /** native declaration : src\main\include\CAN\can_proto.h */ + public static final int LM_PSTAT_VOLTBUS_B1 = 4; + /** native declaration : src\main\include\CAN\can_proto.h */ + public static final int LM_API_UPD_PING = ((0x00020000 | 0x1f000000) | (0 << 6)); + /** native declaration : src\main\include\CAN\can_proto.h */ + public static final int LM_API_POS_T_SET_NO_ACK = + ((0x00020000 | 0x02000000 | 0x00000c00) | (10 << 6)); + /** native declaration : src\main\include\CAN\can_proto.h */ + public static final int CAN_MSGID_DEVNO_S = 0; + /** native declaration : src\main\include\CAN\can_proto.h */ + public static final int LM_API_TRUST_HEARTBEAT = ((0x00020000 | 0x1f000000) | (13 << 6)); + /** native declaration : src\main\include\CAN\can_proto.h */ + public static final int LM_PSTAT_VOLTBUS_B0 = 3; + /** native declaration : src\main\include\CAN\can_proto.h */ + public static final int LM_PSTAT_SPD_B0 = 13; + /** native declaration : src\main\include\CAN\can_proto.h */ + public static final int LM_API_CFG = (0x00020000 | 0x02000000 | 0x00001c00); + /** native declaration : src\main\include\CAN\can_proto.h */ + public static final int LM_PSTAT_FLT_COUNT_COMM = 28; + /** native declaration : src\main\include\CAN\can_proto.h */ + public static final int CAN_MSGID_API_SYSHALT = 0x00000000; + /** native declaration : src\main\include\CAN\can_proto.h */ + public static final int LM_API_UPD_DOWNLOAD = ((0x00020000 | 0x1f000000) | (1 << 6)); + /** native declaration : src\main\include\CAN\can_proto.h */ + public static final int LM_API_STATUS_CMODE = ((0x00020000 | 0x02000000 | 0x00001400) | (9 << 6)); + /** native declaration : src\main\include\CAN\can_proto.h */ + public static final int LM_API_VCOMP_IN_RAMP = + ((0x00020000 | 0x02000000 | 0x00000800) | (3 << 6)); + /** native declaration : src\main\include\CAN\can_proto.h */ + public static final int LM_STATUS_FAULT_VLIMIT = 0x04; + /** native declaration : src\main\include\CAN\can_proto.h */ + public static final int LM_STATUS_LIMIT_SREV = 0x08; + /** native declaration : src\main\include\CAN\can_proto.h */ + public static final int CAN_MSGID_DTYPE_S = 24; + /** native declaration : src\main\include\CAN\can_proto.h */ + public static final int LM_PSTAT_FLT_COUNT_VOLTBUS = 26; + /** native declaration : src\main\include\CAN\can_proto.h */ + public static final int CAN_API_MC_STATUS = 0x00001400; + /** native declaration : src\main\include\CAN\can_proto.h */ + public static final int LM_API_VOLT_T_EN = ((0x00020000 | 0x02000000 | 0x00000000) | (4 << 6)); + /** native declaration : src\main\include\CAN\can_proto.h */ + public static final int LM_API_STATUS_VOLTBUS = + ((0x00020000 | 0x02000000 | 0x00001400) | (1 << 6)); + /** native declaration : src\main\include\CAN\can_proto.h */ + public static final int LM_API_UPD = (0x00020000 | 0x1f000000); + /** native declaration : src\main\include\CAN\can_proto.h */ + public static final int LM_API_UPD_REQUEST = ((0x00020000 | 0x1f000000) | (6 << 6)); + /** native declaration : src\main\include\CAN\can_proto.h */ + public static final int CAN_API_MC_VOLTAGE = 0x00000000; + /** native declaration : src\main\include\CAN\can_proto.h */ + public static final int LM_API_PSTAT_PER_EN_S3 = + ((0x00020000 | 0x02000000 | 0x00001800) | (3 << 6)); + /** native declaration : src\main\include\CAN\can_proto.h */ + public static final int LM_API_PSTAT_PER_EN_S2 = + ((0x00020000 | 0x02000000 | 0x00001800) | (2 << 6)); + /** native declaration : src\main\include\CAN\can_proto.h */ + public static final int CAN_API_MC_PSTAT = 0x00001800; + /** native declaration : src\main\include\CAN\can_proto.h */ + public static final int LM_PSTAT_CANERR_B1 = 31; + /** native declaration : src\main\include\CAN\can_proto.h */ + public static final int LM_API_PSTAT_PER_EN_S1 = + ((0x00020000 | 0x02000000 | 0x00001800) | (1 << 6)); + /** native declaration : src\main\include\CAN\can_proto.h */ + public static final int LM_REF_ENCODER = 0x00; + /** native declaration : src\main\include\CAN\can_proto.h */ + public static final int LM_API_PSTAT_PER_EN_S0 = + ((0x00020000 | 0x02000000 | 0x00001800) | (0 << 6)); + /** native declaration : src\main\include\CAN\can_proto.h */ + public static final int LM_API_STATUS_CURRENT = + ((0x00020000 | 0x02000000 | 0x00001400) | (2 << 6)); + /** native declaration : src\main\include\CAN\can_proto.h */ + public static final int LM_API_POS_SET = ((0x00020000 | 0x02000000 | 0x00000c00) | (2 << 6)); + /** native declaration : src\main\include\CAN\can_proto.h */ + public static final int LM_STATUS_LIMIT_STKY_FWD = 0x10; + /** native declaration : src\main\include\CAN\can_proto.h */ + public static final int LM_API_ICTRL = (0x00020000 | 0x02000000 | 0x00001000); + /** native declaration : src\main\include\CAN\can_proto.h */ + public static final int LM_HWVER_JAG_2_0 = 0x02; + /** native declaration : src\main\include\CAN\can_proto.h */ + public static final int CAN_STATUS_MFG_M = 0x00ff0000; + /** native declaration : src\main\include\CAN\can_proto.h */ + public static final int LM_PSTAT_LIMIT_CLR = 18; + /** native declaration : src\main\include\CAN\can_proto.h */ + public static final int LM_API_CFG_POT_TURNS = + ((0x00020000 | 0x02000000 | 0x00001c00) | (2 << 6)); + /** native declaration : src\main\include\CAN\can_proto.h */ + public static final int LM_API_POS_REF = ((0x00020000 | 0x02000000 | 0x00000c00) | (6 << 6)); + /** native declaration : src\main\include\CAN\can_proto.h */ + public static final int LM_API_SPD_PC = ((0x00020000 | 0x02000000 | 0x00000400) | (3 << 6)); + /** native declaration : src\main\include\CAN\can_proto.h */ + public static final int LM_API_STATUS_VOUT = ((0x00020000 | 0x02000000 | 0x00001400) | (10 << 6)); + /** native declaration : src\main\include\CAN\can_proto.h */ + public static final int CAN_MSGID_API_SYSRESUME = 0x00000280; + /** native declaration : src\main\include\CAN\can_proto.h */ + public static final int LM_API_UNTRUST_EN = ((0x00020000 | 0x1f000000) | (11 << 6)); + /** native declaration : src\main\include\CAN\can_proto.h */ + public static final int LM_PSTAT_CANSTS = 29; + /** native declaration : src\main\include\CAN\can_proto.h */ + public static final int LM_API_POS_DC = ((0x00020000 | 0x02000000 | 0x00000c00) | (5 << 6)); + /** native declaration : src\main\include\CAN\can_proto.h */ + public static final int LM_API_STATUS_POS = ((0x00020000 | 0x02000000 | 0x00001400) | (4 << 6)); + /** native declaration : src\main\include\CAN\can_proto.h */ + public static final int LM_API_SPD_SET = ((0x00020000 | 0x02000000 | 0x00000400) | (2 << 6)); + /** native declaration : src\main\include\CAN\can_proto.h */ + public static final int CAN_MSGID_FULL_M = 0x1fffffff; + /** native declaration : src\main\include\CAN\can_proto.h */ + public static final int LM_API_STATUS_SPD = ((0x00020000 | 0x02000000 | 0x00001400) | (5 << 6)); + /** native declaration : src\main\include\CAN\can_proto.h */ + public static final int LM_PSTAT_STKY_FLT_NCLR = 20; + /** native declaration : src\main\include\CAN\can_proto.h */ + public static final int LM_API_STATUS = (0x00020000 | 0x02000000 | 0x00001400); + /** native declaration : src\main\include\CAN\can_proto.h */ + public static final int LM_API_TRUST_EN = ((0x00020000 | 0x1f000000) | (12 << 6)); + /** native declaration : src\main\include\CAN\can_proto.h */ + public static final int LM_API_ICTRL_T_SET = ((0x00020000 | 0x02000000 | 0x00001000) | (7 << 6)); + /** native declaration : src\main\include\CAN\can_proto.h */ + public static final int CAN_STATUS_CODE_M = 0x0000ffff; + /** native declaration : src\main\include\CAN\can_proto.h */ + public static final int CAN_STATUS_CODE_S = 0; + /** native declaration : src\main\include\CAN\can_proto.h */ + public static final int LM_API_POS_T_EN = ((0x00020000 | 0x02000000 | 0x00000c00) | (7 << 6)); + /** native declaration : src\main\include\CAN\can_proto.h */ + public static final int LM_API_PSTAT = (0x00020000 | 0x02000000 | 0x00001800); + /** native declaration : src\main\include\CAN\can_proto.h */ + public static final int LM_PSTAT_FAULT = 19; + /** native declaration : src\main\include\CAN\can_proto.h */ + public static final int LM_PSTAT_FLT_COUNT_GATE = 27; + /** native declaration : src\main\include\CAN\can_proto.h */ + public static final int LM_API_ICTRL_T_EN = ((0x00020000 | 0x02000000 | 0x00001000) | (6 << 6)); + /** native declaration : src\main\include\CAN\can_proto.h */ + public static final int CAN_MSGID_API_DEVQUERY = 0x000000c0; + /** native declaration : src\main\include\CAN\can_proto.h */ + public static final int CAN_MSGID_DTYPE_USONIC = 0x06000000; + /** native declaration : src\main\include\CAN\can_proto.h */ + public static final int LM_STATUS_CMODE_VCOMP = 0x04; + /** native declaration : src\main\include\CAN\can_proto.h */ + public static final int LM_API_SPD_T_SET = ((0x00020000 | 0x02000000 | 0x00000400) | (8 << 6)); + /** native declaration : src\main\include\CAN\can_proto.h */ + public static final int LM_API_POS_EN = ((0x00020000 | 0x02000000 | 0x00000c00) | (0 << 6)); + /** native declaration : src\main\include\CAN\can_proto.h */ + public static final int LM_API_VOLT_DIS = ((0x00020000 | 0x02000000 | 0x00000000) | (1 << 6)); + /** native declaration : src\main\include\CAN\can_proto.h */ + public static final int LM_STATUS_LIMIT_FWD = 0x01; + /** native declaration : src\main\include\CAN\can_proto.h */ + public static final int LM_API_VCOMP_DIS = ((0x00020000 | 0x02000000 | 0x00000800) | (1 << 6)); + /** native declaration : src\main\include\CAN\can_proto.h */ + public static final int LM_REF_INV_ENCODER = 0x02; + /** native declaration : src\main\include\CAN\can_proto.h */ + public static final int LM_API_CFG_NUM_BRUSHES = + ((0x00020000 | 0x02000000 | 0x00001c00) | (0 << 6)); + /** native declaration : src\main\include\CAN\can_proto.h */ + public static final int CAN_MSGID_DTYPE_RELAY = 0x03000000; + /** native declaration : src\main\include\CAN\can_proto.h */ + public static final int CAN_MSGID_API_DEVASSIGN = 0x00000080; + /** native declaration : src\main\include\CAN\can_proto.h */ + public static final int LM_API_VOLT_T_SET_NO_ACK = + ((0x00020000 | 0x02000000 | 0x00000000) | (7 << 6)); + /** native declaration : src\main\include\CAN\can_proto.h */ + public static final int CAN_API_MC_SPD = 0x00000400; + /** native declaration : src\main\include\CAN\can_proto.h */ + public static final int LM_API_CFG_ENC_LINES = + ((0x00020000 | 0x02000000 | 0x00001c00) | (1 << 6)); + /** native declaration : src\main\include\CAN\can_proto.h */ + public static final int LM_REF_NONE = 0xff; + /** native declaration : src\main\include\CAN\can_proto.h */ + public static final int LM_FAULT_VBUS = 0x04; + /** native declaration : src\main\include\CAN\can_proto.h */ + public static final int LM_API_VOLT_SET_RAMP = + ((0x00020000 | 0x02000000 | 0x00000000) | (3 << 6)); + /** native declaration : src\main\include\CAN\can_proto.h */ + public static final int LM_API_SPD_REF = ((0x00020000 | 0x02000000 | 0x00000400) | (6 << 6)); + /** native declaration : src\main\include\CAN\can_proto.h */ + public static final int LM_API_STATUS_POWER = ((0x00020000 | 0x02000000 | 0x00001400) | (8 << 6)); + /** native declaration : src\main\include\CAN\can_proto.h */ + public static final int LM_PSTAT_VOLTOUT_B1 = 2; + /** native declaration : src\main\include\CAN\can_proto.h */ + public static final int LM_API_VCOMP_SET_NO_ACK = + ((0x00020000 | 0x02000000 | 0x00000800) | (9 << 6)); + /** native declaration : src\main\include\CAN\can_proto.h */ + public static final int LM_PSTAT_VOLTOUT_B0 = 1; + /** native declaration : src\main\include\CAN\can_proto.h */ + public static final int LM_API_CFG_LIMIT_MODE = + ((0x00020000 | 0x02000000 | 0x00001c00) | (4 << 6)); + /** native declaration : src\main\include\CAN\can_proto.h */ + public static final int LM_PSTAT_VOUT_B1 = 23; + /** native declaration : src\main\include\CAN\can_proto.h */ + public static final int LM_API_UPD_SEND_DATA = ((0x00020000 | 0x1f000000) | (2 << 6)); + /** native declaration : src\main\include\CAN\can_proto.h */ + public static final int LM_PSTAT_FLT_COUNT_CURRENT = 24; + /** native declaration : src\main\include\CAN\can_proto.h */ + public static final int LM_PSTAT_VOUT_B0 = 22; + /** native declaration : src\main\include\CAN\can_proto.h */ + public static final int LM_API_PSTAT_CFG_S0 = ((0x00020000 | 0x02000000 | 0x00001800) | (4 << 6)); + /** native declaration : src\main\include\CAN\can_proto.h */ + public static final int LM_PSTAT_LIMIT_NCLR = 17; + /** native declaration : src\main\include\CAN\can_proto.h */ + public static final int LM_API_PSTAT_CFG_S1 = ((0x00020000 | 0x02000000 | 0x00001800) | (5 << 6)); + /** native declaration : src\main\include\CAN\can_proto.h */ + public static final int LM_API_PSTAT_CFG_S2 = ((0x00020000 | 0x02000000 | 0x00001800) | (6 << 6)); + /** native declaration : src\main\include\CAN\can_proto.h */ + public static final int LM_API_PSTAT_CFG_S3 = ((0x00020000 | 0x02000000 | 0x00001800) | (7 << 6)); + /** native declaration : src\main\include\CAN\can_proto.h */ + public static final int LM_API_VCOMP_SET = ((0x00020000 | 0x02000000 | 0x00000800) | (2 << 6)); + /** native declaration : src\main\include\CAN\can_proto.h */ + public static final int CAN_MSGID_API_UPDATE = 0x000001c0; + /** native declaration : src\main\include\CAN\can_proto.h */ + public static final int LM_API_CFG_FAULT_TIME = + ((0x00020000 | 0x02000000 | 0x00001c00) | (8 << 6)); + /** native declaration : src\main\include\CAN\can_proto.h */ + public static final int LM_API_STATUS_VOLTOUT = + ((0x00020000 | 0x02000000 | 0x00001400) | (0 << 6)); + /** native declaration : src\main\include\CAN\can_proto.h */ + public static final int LM_API_ICTRL_SET = ((0x00020000 | 0x02000000 | 0x00001000) | (2 << 6)); + /** native declaration : src\main\include\CAN\can_proto.h */ + public static final int CAN_MSGID_API_M = 0x0000ffc0; + /** native declaration : src\main\include\CAN\can_proto.h */ + public static final int LM_STATUS_CMODE_SPEED = 0x02; + /** native declaration : src\main\include\CAN\can_proto.h */ + public static final int CAN_MSGID_API_CLASS_M = 0x0000fc00; + /** native declaration : src\main\include\CAN\can_proto.h */ + public static final int LM_API_PSTAT_DATA_S3 = + ((0x00020000 | 0x02000000 | 0x00001800) | (11 << 6)); + /** native declaration : src\main\include\CAN\can_proto.h */ + public static final int CAN_MSGID_API_S = 6; + /** native declaration : src\main\include\CAN\can_proto.h */ + public static final int LM_API_STATUS_FLT_COUNT = + ((0x00020000 | 0x02000000 | 0x00001400) | (12 << 6)); + /** native declaration : src\main\include\CAN\can_proto.h */ + public static final int LM_API_PSTAT_DATA_S2 = + ((0x00020000 | 0x02000000 | 0x00001800) | (10 << 6)); + /** native declaration : src\main\include\CAN\can_proto.h */ + public static final int LM_API_PSTAT_DATA_S1 = + ((0x00020000 | 0x02000000 | 0x00001800) | (9 << 6)); + /** native declaration : src\main\include\CAN\can_proto.h */ + public static final int LM_API_PSTAT_DATA_S0 = + ((0x00020000 | 0x02000000 | 0x00001800) | (8 << 6)); + /** native declaration : src\main\include\CAN\can_proto.h */ + public static final int LM_API_ICTRL_PC = ((0x00020000 | 0x02000000 | 0x00001000) | (3 << 6)); + /** native declaration : src\main\include\CAN\can_proto.h */ + public static final int LM_API_POS_PC = ((0x00020000 | 0x02000000 | 0x00000c00) | (3 << 6)); + /** native declaration : src\main\include\CAN\can_proto.h */ + public static final int CAN_MSGID_MFR_LM = 0x00020000; + /** native declaration : src\main\include\CAN\can_proto.h */ + public static final int LM_API_POS_DIS = ((0x00020000 | 0x02000000 | 0x00000c00) | (1 << 6)); + /** native declaration : src\main\include\CAN\can_proto.h */ + public static final int CAN_MSGID_DTYPE_BCAST = 0x00000000; + /** native declaration : src\main\include\CAN\can_proto.h */ + public static final int LM_STATUS_CMODE_VOLT = 0x00; + /** native declaration : src\main\include\CAN\can_proto.h */ + public static final int CAN_STATUS_DTYPE_S = 24; + /** native declaration : src\main\include\CAN\can_proto.h */ + public static final int LM_API_POS_SET_NO_ACK = + ((0x00020000 | 0x02000000 | 0x00000c00) | (11 << 6)); + /** native declaration : src\main\include\CAN\can_proto.h */ + public static final int LM_FAULT_GATE_DRIVE = 0x08; + /** native declaration : src\main\include\CAN\can_proto.h */ + public static final int CAN_STATUS_DTYPE_M = 0x1f000000; + /** native declaration : src\main\include\CAN\can_proto.h */ + public static final int LM_STATUS_LIMIT_STKY_REV = 0x20; + /** native declaration : src\main\include\CAN\can_proto.h */ + public static final int CAN_MSGID_DTYPE_ROBOT = 0x01000000; + /** native declaration : src\main\include\CAN\can_proto.h */ + public static final int CAN_API_MC_ACK = 0x00002000; + /** native declaration : src\main\include\CAN\can_proto.h */ + public static final int LM_API_VCOMP = (0x00020000 | 0x02000000 | 0x00000800); + /** native declaration : src\main\include\CAN\can_proto.h */ + public static final int LM_API_UPD_ACK = ((0x00020000 | 0x1f000000) | (4 << 6)); + /** native declaration : src\main\include\CAN\can_proto.h */ + public static final int LM_API_VCOMP_COMP_RAMP = + ((0x00020000 | 0x02000000 | 0x00000800) | (4 << 6)); + /** native declaration : src\main\include\CAN\can_proto.h */ + public static final int LM_API_VCOMP_T_SET_NO_ACK = + ((0x00020000 | 0x02000000 | 0x00000800) | (8 << 6)); + /** native declaration : src\main\include\CAN\can_proto.h */ + public static final int LM_API_POS = (0x00020000 | 0x02000000 | 0x00000c00); + /** native declaration : src\main\include\CAN\can_proto.h */ + public static final int CAN_MSGID_API_SYNC = 0x00000180; + /** native declaration : src\main\include\CAN\can_proto.h */ + public static final int LM_API_ICTRL_SET_NO_ACK = + ((0x00020000 | 0x02000000 | 0x00001000) | (10 << 6)); + /** native declaration : src\main\include\CAN\can_proto.h */ + public static final int LM_PSTAT_CURRENT_B1 = 6; + /** native declaration : src\main\include\CAN\can_proto.h */ + public static final int LM_API_SPD = (0x00020000 | 0x02000000 | 0x00000400); + /** native declaration : src\main\include\CAN\can_proto.h */ + public static final int LM_PSTAT_CURRENT_B0 = 5; + /** native declaration : src\main\include\CAN\can_proto.h */ + public static final int CAN_MSGID_DTYPE_UPDATE = 0x1f000000; + /** native declaration : src\main\include\CAN\can_proto.h */ + public static final int LM_API_SPD_IC = ((0x00020000 | 0x02000000 | 0x00000400) | (4 << 6)); + /** native declaration : src\main\include\CAN\can_proto.h */ + public static final int LM_API_ACK = (0x00020000 | 0x02000000 | 0x00002000); + /** native declaration : src\main\include\CAN\can_proto.h */ + public static final int LM_FAULT_TEMP = 0x02; + /** native declaration : src\main\include\CAN\can_proto.h */ + public static final int LM_API_VCOMP_T_SET = ((0x00020000 | 0x02000000 | 0x00000800) | (6 << 6)); + /** native declaration : src\main\include\CAN\can_proto.h */ + public static final int LM_PSTAT_FLT_COUNT_TEMP = 25; + /** native declaration : src\main\include\CAN\can_proto.h */ + public static final int LM_API_VOLT_SET_NO_ACK = + ((0x00020000 | 0x02000000 | 0x00000000) | (8 << 6)); + /** native declaration : src\main\include\CAN\can_proto.h */ + public static final int CAN_MSGID_DTYPE_GEART = 0x07000000; + /** native declaration : src\main\include\CAN\can_proto.h */ + public static final int CAN_MSGID_MFR_NI = 0x00010000; + /** native declaration : src\main\include\CAN\can_proto.h */ + public static final int LM_API_POS_T_SET = ((0x00020000 | 0x02000000 | 0x00000c00) | (8 << 6)); + /** native declaration : src\main\include\CAN\can_proto.h */ + public static final int LM_API_STATUS_STKY_FLT = + ((0x00020000 | 0x02000000 | 0x00001400) | (11 << 6)); + /** native declaration : src\main\include\CAN\can_proto.h */ + public static final int LM_API_UPD_RESET = ((0x00020000 | 0x1f000000) | (3 << 6)); + /** native declaration : src\main\include\CAN\can_proto.h */ + public static final int CAN_MSGID_API_ID_M = 0x000003c0; + /** native declaration : src\main\include\CAN\can_proto.h */ + public static final int LM_API_VCOMP_T_EN = ((0x00020000 | 0x02000000 | 0x00000800) | (5 << 6)); + /** native declaration : src\main\include\CAN\can_proto.h */ + public static final int LM_STATUS_LIMIT_STKY_SFWD = 0x40; - /* Flags in the upper bits of the messageID */ - public static final int CAN_IS_FRAME_REMOTE = 0x80000000; - public static final int CAN_IS_FRAME_11BIT = 0x40000000; + public static final int CAN_SEND_PERIOD_NO_REPEAT = 0; + public static final int CAN_SEND_PERIOD_STOP_REPEATING = -1; - public static native void FRCNetworkCommunicationCANSessionMuxSendMessage(int messageID, ByteBuffer data, int periodMs, IntBuffer status); - public static native ByteBuffer FRCNetworkCommunicationCANSessionMuxReceiveMessage(IntBuffer messageID, int messageIDMask, ByteBuffer timeStamp, IntBuffer status); + /* Flags in the upper bits of the messageID */ + public static final int CAN_IS_FRAME_REMOTE = 0x80000000; + public static final int CAN_IS_FRAME_11BIT = 0x40000000; + + public static native void FRCNetworkCommunicationCANSessionMuxSendMessage(int messageID, + ByteBuffer data, int periodMs, IntBuffer status); + + public static native ByteBuffer FRCNetworkCommunicationCANSessionMuxReceiveMessage( + IntBuffer messageID, int messageIDMask, ByteBuffer timeStamp, IntBuffer status); } diff --git a/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/can/CANJaguarVersionException.java b/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/can/CANJaguarVersionException.java index 4e4111584a..a50d86a6c2 100644 --- a/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/can/CANJaguarVersionException.java +++ b/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/can/CANJaguarVersionException.java @@ -1,41 +1,43 @@ /*----------------------------------------------------------------------------*/ -/* Copyright (c) FIRST 2008-2012. All Rights Reserved. */ -/* Open Source Software - may be modified and shared by FRC teams. The code */ +/* Copyright (c) FIRST 2008-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 the root directory of */ -/* the project. */ +/* the project. */ /*----------------------------------------------------------------------------*/ package edu.wpi.first.wpilibj.can; /** - * Exception indicating that the CAN driver layer has not been initialized. - * This happens when an entry-point is called before a CAN driver plugin - * has been installed. + * Exception indicating that the CAN driver layer has not been initialized. This + * happens when an entry-point is called before a CAN driver plugin has been + * installed. */ public class CANJaguarVersionException extends RuntimeException { - public static final int kMinLegalFIRSTFirmwareVersion = 101; - // 3330 was the first shipping RDK firmware version for the Jaguar - public static final int kMinRDKFirmwareVersion = 3330; + public static final int kMinLegalFIRSTFirmwareVersion = 101; + // 3330 was the first shipping RDK firmware version for the Jaguar + public static final int kMinRDKFirmwareVersion = 3330; - public CANJaguarVersionException(int deviceNumber, int fwVersion) { - super(getString(deviceNumber, fwVersion)); - System.out.println("fwVersion[" + deviceNumber + "]: " + fwVersion); - } + public CANJaguarVersionException(int deviceNumber, int fwVersion) { + super(getString(deviceNumber, fwVersion)); + System.out.println("fwVersion[" + deviceNumber + "]: " + fwVersion); + } - static String getString(int deviceNumber, int fwVersion) { - String msg; - if (fwVersion < kMinRDKFirmwareVersion) { - msg = "Jaguar " + deviceNumber + - " firmware is too old. It must be updated to at least version " + - Integer.toString(kMinLegalFIRSTFirmwareVersion) + - " of the FIRST approved firmware!"; - } else { - msg = "Jaguar " + deviceNumber + - " firmware is not FIRST approved. It must be updated to at least version " + - Integer.toString(kMinLegalFIRSTFirmwareVersion) + - " of the FIRST approved firmware!"; - } - return msg; + static String getString(int deviceNumber, int fwVersion) { + String msg; + if (fwVersion < kMinRDKFirmwareVersion) { + msg = + "Jaguar " + deviceNumber + + " firmware is too old. It must be updated to at least version " + + Integer.toString(kMinLegalFIRSTFirmwareVersion) + + " of the FIRST approved firmware!"; + } else { + msg = + "Jaguar " + deviceNumber + + " firmware is not FIRST approved. It must be updated to at least version " + + Integer.toString(kMinLegalFIRSTFirmwareVersion) + + " of the FIRST approved firmware!"; } + return msg; + } } diff --git a/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/can/CANMessageNotAllowedException.java b/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/can/CANMessageNotAllowedException.java index cdb9be2263..3ef52bd216 100644 --- a/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/can/CANMessageNotAllowedException.java +++ b/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/can/CANMessageNotAllowedException.java @@ -1,8 +1,8 @@ /*----------------------------------------------------------------------------*/ -/* Copyright (c) FIRST 2008-2012. All Rights Reserved. */ -/* Open Source Software - may be modified and shared by FRC teams. The code */ +/* Copyright (c) FIRST 2008-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 the root directory of */ -/* the project. */ +/* the project. */ /*----------------------------------------------------------------------------*/ package edu.wpi.first.wpilibj.can; @@ -12,7 +12,7 @@ package edu.wpi.first.wpilibj.can; * restricted message ID to the CAN bus. */ public class CANMessageNotAllowedException extends RuntimeException { - public CANMessageNotAllowedException(String msg) { - super(msg); - } + public CANMessageNotAllowedException(String msg) { + super(msg); + } } diff --git a/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/can/CANMessageNotFoundException.java b/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/can/CANMessageNotFoundException.java index f2483de901..8b319564a6 100644 --- a/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/can/CANMessageNotFoundException.java +++ b/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/can/CANMessageNotFoundException.java @@ -1,19 +1,19 @@ /*----------------------------------------------------------------------------*/ -/* Copyright (c) FIRST 2008-2012. All Rights Reserved. */ -/* Open Source Software - may be modified and shared by FRC teams. The code */ +/* Copyright (c) FIRST 2008-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 the root directory of */ -/* the project. */ +/* the project. */ /*----------------------------------------------------------------------------*/ package edu.wpi.first.wpilibj.can; /** * Exception indicating that a can message is not available from Network - * Communications. This usually just means we already have the most recent - * value cached locally. + * Communications. This usually just means we already have the most recent value + * cached locally. */ public class CANMessageNotFoundException extends RuntimeException { - public CANMessageNotFoundException() { - super(); - } + public CANMessageNotFoundException() { + super(); + } } diff --git a/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/can/CANNotInitializedException.java b/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/can/CANNotInitializedException.java index 18fed00ae2..e2e6a1d148 100644 --- a/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/can/CANNotInitializedException.java +++ b/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/can/CANNotInitializedException.java @@ -1,19 +1,19 @@ /*----------------------------------------------------------------------------*/ -/* Copyright (c) FIRST 2008-2012. All Rights Reserved. */ -/* Open Source Software - may be modified and shared by FRC teams. The code */ +/* Copyright (c) FIRST 2008-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 the root directory of */ -/* the project. */ +/* the project. */ /*----------------------------------------------------------------------------*/ package edu.wpi.first.wpilibj.can; /** - * Exception indicating that the CAN driver layer has not been initialized. - * This happens when an entry-point is called before a CAN driver plugin - * has been installed. + * Exception indicating that the CAN driver layer has not been initialized. This + * happens when an entry-point is called before a CAN driver plugin has been + * installed. */ public class CANNotInitializedException extends RuntimeException { - public CANNotInitializedException() { - super(); - } + public CANNotInitializedException() { + super(); + } } diff --git a/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/communication/FRCNetworkCommunicationsLibrary.java b/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/communication/FRCNetworkCommunicationsLibrary.java index 374b842983..38fb281438 100644 --- a/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/communication/FRCNetworkCommunicationsLibrary.java +++ b/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/communication/FRCNetworkCommunicationsLibrary.java @@ -5,484 +5,975 @@ import java.nio.IntBuffer; import java.nio.ShortBuffer; import edu.wpi.first.wpilibj.hal.JNIWrapper; + /** * JNA Wrapper for library FRC_NetworkCommunications
- * This file was autogenerated by JNAerator,
- * a tool written by Olivier Chafik that uses a few opensource projects..
- * For help, please visit NativeLibs4Java , Rococoa, or JNA. + * This file was autogenerated by JNAerator,
+ * a tool written by Olivier Chafik that uses a few + * opensource projects..
+ * For help, please visit NativeLibs4Java , Rococoa, or JNA. */ public class FRCNetworkCommunicationsLibrary extends JNIWrapper { - //public static final String JNA_LIBRARY_NAME = LibraryExtractor.getLibraryPath("FRC_NetworkCommunications", true, FRC_NetworkCommunicationsLibrary.class); - //public static final NativeLibrary JNA_NATIVE_LIB = NativeLibrary.getInstance(FRC_NetworkCommunicationsLibrary.JNA_LIBRARY_NAME, MangledFunctionMapper.DEFAULT_OPTIONS); - //static { - //System.loadLibrary("JNIWrappers"); - //Native.register(FRC_NetworkCommunicationsLibrary.class, FRC_NetworkCommunicationsLibrary.JNA_NATIVE_LIB); - //} - /** - * native declaration : src\main\include\NetworkCommunication\LoadOut.h
- * enum values - */ - public static interface tModuleType { - /** native declaration : src\main\include\NetworkCommunication\LoadOut.h:9 */ - public static final int kModuleType_Unknown = 0x00; - /** native declaration : src\main\include\NetworkCommunication\LoadOut.h:10 */ - public static final int kModuleType_Analog = 0x01; - /** native declaration : src\main\include\NetworkCommunication\LoadOut.h:11 */ - public static final int kModuleType_Digital = 0x02; - /** native declaration : src\main\include\NetworkCommunication\LoadOut.h:12 */ - public static final int kModuleType_Solenoid = 0x03; - }; - /** - * native declaration : src\main\include\NetworkCommunication\LoadOut.h
- * enum values - */ - public static interface tTargetClass { - /** native declaration : src\main\include\NetworkCommunication\LoadOut.h:16 */ - public static final int kTargetClass_Unknown = 0x00; - /** native declaration : src\main\include\NetworkCommunication\LoadOut.h:17 */ - public static final int kTargetClass_FRC1 = 0x10; - /** native declaration : src\main\include\NetworkCommunication\LoadOut.h:18 */ - public static final int kTargetClass_FRC2 = 0x20; - /** native declaration : src\main\include\NetworkCommunication\LoadOut.h:19 */ - public static final int kTargetClass_FRC2_Analog = (int)FRCNetworkCommunicationsLibrary.tTargetClass.kTargetClass_FRC2 | (int)FRCNetworkCommunicationsLibrary.tModuleType.kModuleType_Analog; - /** native declaration : src\main\include\NetworkCommunication\LoadOut.h:20 */ - public static final int kTargetClass_FRC2_Digital = (int)FRCNetworkCommunicationsLibrary.tTargetClass.kTargetClass_FRC2 | (int)FRCNetworkCommunicationsLibrary.tModuleType.kModuleType_Digital; - /** native declaration : src\main\include\NetworkCommunication\LoadOut.h:21 */ - public static final int kTargetClass_FRC2_Solenoid = (int)FRCNetworkCommunicationsLibrary.tTargetClass.kTargetClass_FRC2 | (int)FRCNetworkCommunicationsLibrary.tModuleType.kModuleType_Solenoid; - /** native declaration : src\main\include\NetworkCommunication\LoadOut.h:22 */ - public static final int kTargetClass_FamilyMask = 0xF0; - /** native declaration : src\main\include\NetworkCommunication\LoadOut.h:23 */ - public static final int kTargetClass_ModuleMask = 0x0F; - }; - /** - * native declaration : src\main\include\NetworkCommunication\UsageReporting.h
- * enum values - */ - public static interface tResourceType { - /** native declaration : src\main\include\NetworkCommunication\UsageReporting.h:10 */ - public static final int kResourceType_Controller = 0; - /** native declaration : src\main\include\NetworkCommunication\UsageReporting.h:11 */ - public static final int kResourceType_Module = 1; - /** native declaration : src\main\include\NetworkCommunication\UsageReporting.h:12 */ - public static final int kResourceType_Language = 2; - /** native declaration : src\main\include\NetworkCommunication\UsageReporting.h:13 */ - public static final int kResourceType_CANPlugin = 3; - /** native declaration : src\main\include\NetworkCommunication\UsageReporting.h:14 */ - public static final int kResourceType_Accelerometer = 4; - /** native declaration : src\main\include\NetworkCommunication\UsageReporting.h:15 */ - public static final int kResourceType_ADXL345 = 5; - /** native declaration : src\main\include\NetworkCommunication\UsageReporting.h:16 */ - public static final int kResourceType_AnalogChannel = 6; - /** native declaration : src\main\include\NetworkCommunication\UsageReporting.h:17 */ - public static final int kResourceType_AnalogTrigger = 7; - /** native declaration : src\main\include\NetworkCommunication\UsageReporting.h:18 */ - public static final int kResourceType_AnalogTriggerOutput = 8; - /** native declaration : src\main\include\NetworkCommunication\UsageReporting.h:19 */ - public static final int kResourceType_CANJaguar = 9; - /** native declaration : src\main\include\NetworkCommunication\UsageReporting.h:20 */ - public static final int kResourceType_Compressor = 10; - /** native declaration : src\main\include\NetworkCommunication\UsageReporting.h:21 */ - public static final int kResourceType_Counter = 11; - /** native declaration : src\main\include\NetworkCommunication\UsageReporting.h:22 */ - public static final int kResourceType_Dashboard = 12; - /** native declaration : src\main\include\NetworkCommunication\UsageReporting.h:23 */ - public static final int kResourceType_DigitalInput = 13; - /** native declaration : src\main\include\NetworkCommunication\UsageReporting.h:24 */ - public static final int kResourceType_DigitalOutput = 14; - /** native declaration : src\main\include\NetworkCommunication\UsageReporting.h:25 */ - public static final int kResourceType_DriverStationCIO = 15; - /** native declaration : src\main\include\NetworkCommunication\UsageReporting.h:26 */ - public static final int kResourceType_DriverStationEIO = 16; - /** native declaration : src\main\include\NetworkCommunication\UsageReporting.h:27 */ - public static final int kResourceType_DriverStationLCD = 17; - /** native declaration : src\main\include\NetworkCommunication\UsageReporting.h:28 */ - public static final int kResourceType_Encoder = 18; - /** native declaration : src\main\include\NetworkCommunication\UsageReporting.h:29 */ - public static final int kResourceType_GearTooth = 19; - /** native declaration : src\main\include\NetworkCommunication\UsageReporting.h:30 */ - public static final int kResourceType_Gyro = 20; - /** native declaration : src\main\include\NetworkCommunication\UsageReporting.h:31 */ - public static final int kResourceType_I2C = 21; - /** native declaration : src\main\include\NetworkCommunication\UsageReporting.h:32 */ - public static final int kResourceType_Framework = 22; - /** native declaration : src\main\include\NetworkCommunication\UsageReporting.h:33 */ - public static final int kResourceType_Jaguar = 23; - /** native declaration : src\main\include\NetworkCommunication\UsageReporting.h:34 */ - public static final int kResourceType_Joystick = 24; - /** native declaration : src\main\include\NetworkCommunication\UsageReporting.h:35 */ - public static final int kResourceType_Kinect = 25; - /** native declaration : src\main\include\NetworkCommunication\UsageReporting.h:36 */ - public static final int kResourceType_KinectStick = 26; - /** native declaration : src\main\include\NetworkCommunication\UsageReporting.h:37 */ - public static final int kResourceType_PIDController = 27; - /** native declaration : src\main\include\NetworkCommunication\UsageReporting.h:38 */ - public static final int kResourceType_Preferences = 28; - /** native declaration : src\main\include\NetworkCommunication\UsageReporting.h:39 */ - public static final int kResourceType_PWM = 29; - /** native declaration : src\main\include\NetworkCommunication\UsageReporting.h:40 */ - public static final int kResourceType_Relay = 30; - /** native declaration : src\main\include\NetworkCommunication\UsageReporting.h:41 */ - public static final int kResourceType_RobotDrive = 31; - /** native declaration : src\main\include\NetworkCommunication\UsageReporting.h:42 */ - public static final int kResourceType_SerialPort = 32; - /** native declaration : src\main\include\NetworkCommunication\UsageReporting.h:43 */ - public static final int kResourceType_Servo = 33; - /** native declaration : src\main\include\NetworkCommunication\UsageReporting.h:44 */ - public static final int kResourceType_Solenoid = 34; - /** native declaration : src\main\include\NetworkCommunication\UsageReporting.h:45 */ - public static final int kResourceType_SPI = 35; - /** native declaration : src\main\include\NetworkCommunication\UsageReporting.h:46 */ - public static final int kResourceType_Task = 36; - /** native declaration : src\main\include\NetworkCommunication\UsageReporting.h:47 */ - public static final int kResourceType_Ultrasonic = 37; - /** native declaration : src\main\include\NetworkCommunication\UsageReporting.h:48 */ - public static final int kResourceType_Victor = 38; - /** native declaration : src\main\include\NetworkCommunication\UsageReporting.h:49 */ - public static final int kResourceType_Button = 39; - /** native declaration : src\main\include\NetworkCommunication\UsageReporting.h:50 */ - public static final int kResourceType_Command = 40; - /** native declaration : src\main\include\NetworkCommunication\UsageReporting.h:51 */ - public static final int kResourceType_AxisCamera = 41; - /** native declaration : src\main\include\NetworkCommunication\UsageReporting.h:52 */ - public static final int kResourceType_PCVideoServer = 42; - /** native declaration : src\main\include\NetworkCommunication\UsageReporting.h:53 */ - public static final int kResourceType_SmartDashboard = 43; - /** native declaration : src\main\include\NetworkCommunication\UsageReporting.h:54 */ - public static final int kResourceType_Talon = 44; - /** native declaration : src\main\include\NetworkCommunication\UsageReporting.h:55 */ - public static final int kResourceType_HiTechnicColorSensor = 45; - /** native declaration : src\main\include\NetworkCommunication\UsageReporting.h:56 */ - public static final int kResourceType_HiTechnicAccel = 46; - /** native declaration : src\main\include\NetworkCommunication\UsageReporting.h:57 */ - public static final int kResourceType_HiTechnicCompass = 47; - /** native declaration : src\main\include\NetworkCommunication\UsageReporting.h:58 */ - public static final int kResourceType_SRF08 = 48; - /** native declaration : src\main\include\NetworkCommunication\UsageReporting.h:59 */ - public static final int kResourceType_AnalogOutput = 49; - /** native declaration : src\main\include\NetworkCommunication\UsageReporting.h:60 */ - public static final int kResourceType_VictorSP = 50; - /** native declaration : src\main\include\NetworkCommunication\UsageReporting.h:61 */ - public static final int kResourceType_TalonSRX = 51; - /** native declaration : src\main\include\NetworkCommunication\UsageReporting.h:62 */ - public static final int kResourceType_CANTalonSRX = 52; - }; - /** - * native declaration : src\main\include\NetworkCommunication\UsageReporting.h
- * enum values - */ - public static interface tInstances { - /** native declaration : src\main\include\NetworkCommunication\UsageReporting.h:63 */ - public static final int kLanguage_LabVIEW = 1; - /** native declaration : src\main\include\NetworkCommunication\UsageReporting.h:64 */ - public static final int kLanguage_CPlusPlus = 2; - /** native declaration : src\main\include\NetworkCommunication\UsageReporting.h:65 */ - public static final int kLanguage_Java = 3; - /** native declaration : src\main\include\NetworkCommunication\UsageReporting.h:66 */ - public static final int kLanguage_Python = 4; - /** native declaration : src\main\include\NetworkCommunication\UsageReporting.h:68 */ - public static final int kCANPlugin_BlackJagBridge = 1; - /** native declaration : src\main\include\NetworkCommunication\UsageReporting.h:69 */ - public static final int kCANPlugin_2CAN = 2; - /** native declaration : src\main\include\NetworkCommunication\UsageReporting.h:71 */ - public static final int kFramework_Iterative = 1; - /** native declaration : src\main\include\NetworkCommunication\UsageReporting.h:72 */ - public static final int kFramework_Simple = 2; - /** native declaration : src\main\include\NetworkCommunication\UsageReporting.h:74 */ - public static final int kRobotDrive_ArcadeStandard = 1; - /** native declaration : src\main\include\NetworkCommunication\UsageReporting.h:75 */ - public static final int kRobotDrive_ArcadeButtonSpin = 2; - /** native declaration : src\main\include\NetworkCommunication\UsageReporting.h:76 */ - public static final int kRobotDrive_ArcadeRatioCurve = 3; - /** native declaration : src\main\include\NetworkCommunication\UsageReporting.h:77 */ - public static final int kRobotDrive_Tank = 4; - /** native declaration : src\main\include\NetworkCommunication\UsageReporting.h:78 */ - public static final int kRobotDrive_MecanumPolar = 5; - /** native declaration : src\main\include\NetworkCommunication\UsageReporting.h:79 */ - public static final int kRobotDrive_MecanumCartesian = 6; - /** native declaration : src\main\include\NetworkCommunication\UsageReporting.h:81 */ - public static final int kDriverStationCIO_Analog = 1; - /** native declaration : src\main\include\NetworkCommunication\UsageReporting.h:82 */ - public static final int kDriverStationCIO_DigitalIn = 2; - /** native declaration : src\main\include\NetworkCommunication\UsageReporting.h:83 */ - public static final int kDriverStationCIO_DigitalOut = 3; - /** native declaration : src\main\include\NetworkCommunication\UsageReporting.h:85 */ - public static final int kDriverStationEIO_Acceleration = 1; - /** native declaration : src\main\include\NetworkCommunication\UsageReporting.h:86 */ - public static final int kDriverStationEIO_AnalogIn = 2; - /** native declaration : src\main\include\NetworkCommunication\UsageReporting.h:87 */ - public static final int kDriverStationEIO_AnalogOut = 3; - /** native declaration : src\main\include\NetworkCommunication\UsageReporting.h:88 */ - public static final int kDriverStationEIO_Button = 4; - /** native declaration : src\main\include\NetworkCommunication\UsageReporting.h:89 */ - public static final int kDriverStationEIO_LED = 5; - /** native declaration : src\main\include\NetworkCommunication\UsageReporting.h:90 */ - public static final int kDriverStationEIO_DigitalIn = 6; - /** native declaration : src\main\include\NetworkCommunication\UsageReporting.h:91 */ - public static final int kDriverStationEIO_DigitalOut = 7; - /** native declaration : src\main\include\NetworkCommunication\UsageReporting.h:92 */ - public static final int kDriverStationEIO_FixedDigitalOut = 8; - /** native declaration : src\main\include\NetworkCommunication\UsageReporting.h:93 */ - public static final int kDriverStationEIO_PWM = 9; - /** native declaration : src\main\include\NetworkCommunication\UsageReporting.h:94 */ - public static final int kDriverStationEIO_Encoder = 10; - /** native declaration : src\main\include\NetworkCommunication\UsageReporting.h:95 */ - public static final int kDriverStationEIO_TouchSlider = 11; - /** native declaration : src\main\include\NetworkCommunication\UsageReporting.h:97 */ - public static final int kADXL345_SPI = 1; - /** native declaration : src\main\include\NetworkCommunication\UsageReporting.h:98 */ - public static final int kADXL345_I2C = 2; - /** native declaration : src\main\include\NetworkCommunication\UsageReporting.h:100 */ - public static final int kCommand_Scheduler = 1; - /** native declaration : src\main\include\NetworkCommunication\UsageReporting.h:102 */ - public static final int kSmartDashboard_Instance = 1; - }; - /** native declaration : src\main\include\NetworkCommunication\FRCComm.h */ - public static final int kFRC_NetworkCommunication_DynamicType_DSEnhancedIO_Input = 17; - /** native declaration : src\main\include\NetworkCommunication\FRCComm.h */ - public static final int kFRC_NetworkCommunication_DynamicType_Kinect_Vertices1 = 21; - /** native declaration : src\main\include\NetworkCommunication\FRCComm.h */ - public static final int SYS_STATUS_DATA_SIZE = 44; - /** native declaration : src\main\include\NetworkCommunication\FRCComm.h */ - public static final int kFRC_NetworkCommunication_DynamicType_Kinect_Custom = 25; - /** native declaration : src\main\include\NetworkCommunication\FRCComm.h */ - public static final int kFRC_NetworkCommunication_DynamicType_Kinect_Vertices2 = 23; - /** native declaration : src\main\include\NetworkCommunication\FRCComm.h */ - public static final int kFRC_NetworkCommunication_DynamicType_Kinect_Header = 19; - /** native declaration : src\main\include\NetworkCommunication\FRCComm.h */ - public static final int kFRC_NetworkCommunication_DynamicType_Kinect_Joystick = 24; - /** native declaration : src\main\include\NetworkCommunication\FRCComm.h */ - public static final int IO_CONFIG_DATA_SIZE = 32; - /** native declaration : src\main\include\NetworkCommunication\LoadOut.h */ - public static final int kMaxModuleNumber = 2; - /** native declaration : src\main\include\NetworkCommunication\FRCComm.h */ - public static final int kFRC_NetworkCommunication_DynamicType_DSEnhancedIO_Output = 18; - /** native declaration : src\main\include\NetworkCommunication\FRCComm.h */ - public static final int kFRC_NetworkCommunication_DynamicType_Kinect_Extra2 = 22; - /** native declaration : src\main\include\NetworkCommunication\FRCComm.h */ - public static final int kFRC_NetworkCommunication_DynamicType_Kinect_Extra1 = 20; - /** native declaration : src\main\include\NetworkCommunication\FRCComm.h */ - public static final int USER_DS_LCD_DATA_SIZE = 128; - /** native declaration : src\main\include\NetworkCommunication\UsageReporting.h */ - public static final int kUsageReporting_version = 1; - /** native declaration : src\main\include\NetworkCommunication\FRCComm.h */ - public static final int USER_STATUS_DATA_SIZE = (984 - 32 - 44); - /** - * Original signature : uint32_t FRC_NetworkCommunication_nAICalibration_getLSBWeight(const uint32_t, const uint32_t, int32_t*)
- * native declaration : src\main\include\NetworkCommunication\AICalibration.h:7
- * @deprecated use the safer methods {@link #FRC_NetworkCommunication_nAICalibration_getLSBWeight(int, int, java.nio.IntBuffer)} and {@link #FRC_NetworkCommunication_nAICalibration_getLSBWeight(int, int, com.sun.jna.ptr.IntByReference)} instead - */ - //@Deprecated - //public static native int FRC_NetworkCommunication_nAICalibration_getLSBWeight(int aiSystemIndex, int channel, Integer status); - /** - * Original signature : uint32_t FRC_NetworkCommunication_nAICalibration_getLSBWeight(const uint32_t, const uint32_t, int32_t*)
- * native declaration : src\main\include\NetworkCommunication\AICalibration.h:7 - */ - public static native int FRCNetworkCommunicationAICalibrationGetLSBWeight(int aiSystemIndex, int channel, Integer status); - /** - * Original signature : int32_t FRC_NetworkCommunication_nAICalibration_getOffset(const uint32_t, const uint32_t, int32_t*)
- * native declaration : src\main\include\NetworkCommunication\AICalibration.h:8
- * @deprecated use the safer methods {@link #FRC_NetworkCommunication_nAICalibration_getOffset(int, int, java.nio.IntBuffer)} and {@link #FRC_NetworkCommunication_nAICalibration_getOffset(int, int, com.sun.jna.ptr.IntByReference)} instead - */ - //@Deprecated - //public static native int FRC_NetworkCommunication_nAICalibration_getOffset(int aiSystemIndex, int channel, Integer status); - /** - * Original signature : int32_t FRC_NetworkCommunication_nAICalibration_getOffset(const uint32_t, const uint32_t, int32_t*)
- * native declaration : src\main\include\NetworkCommunication\AICalibration.h:8 - */ - public static native int FRCNetworkCommunicationAICalibrationGetOffset(int aiSystemIndex, int channel, Integer status); - /** - * Original signature : tTargetClass getTargetClass()
- * native declaration : src\main\include\NetworkCommunication\LoadOut.h:25 - */ - public static native int getTargetClass(); - /** - * Original signature : uint32_t FRC_NetworkCommunication_nLoadOut_getModulePresence(uint32_t, uint8_t)
- * native declaration : src\main\include\NetworkCommunication\LoadOut.h:32 - */ - public static native int FRCNetworkCommunicationLoadOutGetModulePresence(int moduleType, byte moduleNumber); - /** - * Original signature : uint32_t FRC_NetworkCommunication_nLoadOut_getTargetClass()
- * native declaration : src\main\include\NetworkCommunication\LoadOut.h:33 - */ - public static native int FRCNetworkCommunicationLoadOutGetTargetClass(); - /** - * Original signature : STATUS moduleNameFindBySymbolName(const char*, char*)
- * @param symbol symbol name to look for
- * @param module where to return module name
- * native declaration : src\main\include\NetworkCommunication\symModuleLink.h:6
- * @deprecated use the safer methods {@link #moduleNameFindBySymbolName(java.lang.String, java.nio.ByteBuffer)} and {@link #moduleNameFindBySymbolName(com.sun.jna.Pointer, com.sun.jna.Pointer)} instead - */ - //@Deprecated - //public static native FRC_NetworkCommunicationsLibrary.STATUS moduleNameFindBySymbolName(Pointer symbol, Pointer module); - /** - * Original signature : STATUS moduleNameFindBySymbolName(const char*, char*)
- * @param symbol symbol name to look for
- * @param module where to return module name
- * native declaration : src\main\include\NetworkCommunication\symModuleLink.h:6 - */ - //public static native FRC_NetworkCommunicationsLibrary.STATUS moduleNameFindBySymbolName(String symbol, ByteBuffer module); - /** - * Report the usage of a resource of interest.
- *
- * @param resource one of the values in the tResourceType above (max value 51).
- * @param instanceNumber an index that identifies the resource instance.
- * @param context an optional additional context number for some cases (such as module number). Set to 0 to omit.
- * @param feature a string to be included describing features in use on a specific resource. Setting the same resource more than once allows you to change the feature string.
- * Original signature : uint32_t report(tResourceType, uint8_t, uint8_t, const char*)
- * native declaration : src\main\include\NetworkCommunication\UsageReporting.h:113
- * @deprecated use the safer methods {@link #report(int, byte, byte, java.lang.String)} and {@link #report(int, byte, byte, com.sun.jna.Pointer)} instead - */ - //@Deprecated - //public static native int report(int resource, byte instanceNumber, byte context, Pointer feature); - /** - * Report the usage of a resource of interest.
- *
- * @param resource one of the values in the tResourceType above (max value 51).
- * @param instanceNumber an index that identifies the resource instance.
- * @param context an optional additional context number for some cases (such as module number). Set to 0 to omit.
- * @param feature a string to be included describing features in use on a specific resource. Setting the same resource more than once allows you to change the feature string.
- * Original signature : uint32_t report(tResourceType, uint8_t, uint8_t, const char*)
- * native declaration : src\main\include\NetworkCommunication\UsageReporting.h:113 - */ - public static native int report(int resource, byte instanceNumber, byte context, String feature); - /** - * Original signature : uint32_t FRC_NetworkCommunication_nUsageReporting_report(uint8_t, uint8_t, uint8_t, const char*)
- * native declaration : src\main\include\NetworkCommunication\UsageReporting.h:120
- * @deprecated use the safer methods {@link #FRC_NetworkCommunication_nUsageReporting_report(byte, byte, byte, java.lang.String)} and {@link #FRC_NetworkCommunication_nUsageReporting_report(byte, byte, byte, com.sun.jna.Pointer)} instead - */ - //@Deprecated - //public static native int FRC_NetworkCommunication_nUsageReporting_report(byte resource, byte instanceNumber, byte context, Pointer feature); - /** - * Original signature : uint32_t FRC_NetworkCommunication_nUsageReporting_report(uint8_t, uint8_t, uint8_t, const char*)
- * native declaration : src\main\include\NetworkCommunication\UsageReporting.h:120 - */ - public static native int FRCNetworkCommunicationUsageReportingReport(byte resource, byte instanceNumber, byte context, String feature); - /** - * Original signature : void getFPGAHardwareVersion(uint16_t*, uint32_t*)
- * native declaration : src\main\include\NetworkCommunication\FRCComm.h:124
- * @deprecated use the safer methods {@link #getFPGAHardwareVersion(java.nio.ShortBuffer, java.nio.IntBuffer)} and {@link #getFPGAHardwareVersion(com.sun.jna.ptr.ShortByReference, com.sun.jna.ptr.IntByReference)} instead - */ - //@Deprecated - //public static native void getFPGAHardwareVersion(ShortByReference fpgaVersion, IntByReference fpgaRevision); - /** - * Original signature : void getFPGAHardwareVersion(uint16_t*, uint32_t*)
- * native declaration : src\main\include\NetworkCommunication\FRCComm.h:124 - */ - public static native void getFPGAHardwareVersion(ShortBuffer fpgaVersion, IntBuffer fpgaRevision); - /** - * Original signature : int setErrorData(const char*, int, int)
- * native declaration : src\main\include\NetworkCommunication\FRCComm.h:136
- * @deprecated use the safer methods {@link #setErrorData(java.lang.String, int, int)} and {@link #setErrorData(com.sun.jna.Pointer, int, int)} instead - */ - //@Deprecated - //public static native int setErrorData(Pointer errors, int errorsLength, int wait_ms); - /** - * Original signature : int setErrorData(const char*, int, int)
- * native declaration : src\main\include\NetworkCommunication\FRCComm.h:136 - */ - public static native int setErrorData(String errors, int errorsLength, int wait_ms); - /** - * Original signature : int overrideIOConfig(const char*, int)
- * native declaration : src\main\include\NetworkCommunication\FRCComm.h:138
- * @deprecated use the safer methods {@link #overrideIOConfig(java.lang.String, int)} and {@link #overrideIOConfig(com.sun.jna.Pointer, int)} instead - */ - //@Deprecated - //public static native int overrideIOConfig(String ioConfig, int wait_ms); - /** - * Original signature : int overrideIOConfig(const char*, int)
- * native declaration : src\main\include\NetworkCommunication\FRCComm.h:138 - */ - public static native int overrideIOConfig(String ioConfig, int wait_ms); - /** - * Original signature : void setNewDataSem(pthread_mutex_t*)
- * native declaration : src\main\include\NetworkCommunication\FRCComm.h:147 - */ - public static native void setNewDataSem(ByteBuffer mutexId); - /** - * Original signature : void setResyncSem(pthread_mutex_t*)
- * native declaration : src\main\include\NetworkCommunication\FRCComm.h:148 - */ - //public static native void setResyncSem(FRC_NetworkCommunicationsLibrary.pthread_mutex_t pthread_mutex_tPtr1); - /** - * Original signature : void signalResyncActionDone()
- * native declaration : src\main\include\NetworkCommunication\FRCComm.h:150 - */ - public static native void signalResyncActionDone(); - /** - * this uint32_t is really a LVRefNum
- * Original signature : void setNewDataOccurRef(uint32_t)
- * native declaration : src\main\include\NetworkCommunication\FRCComm.h:154 - */ - public static native void setNewDataOccurRef(int refnum); - /** - * Original signature : void setResyncOccurRef(uint32_t)
- * native declaration : src\main\include\NetworkCommunication\FRCComm.h:156 - */ - public static native void setResyncOccurRef(int refnum); - /** - * Original signature : void FRC_NetworkCommunication_getVersionString(char*)
- * native declaration : src\main\include\NetworkCommunication\FRCComm.h:159
- * @deprecated use the safer methods {@link #FRC_NetworkCommunication_getVersionString(java.nio.ByteBuffer)} and {@link #FRC_NetworkCommunication_getVersionString(com.sun.jna.Pointer)} instead - */ - //@Deprecated - //public static native void FRC_NetworkCommunication_getVersionString(Pointer version); - /** - * Original signature : void FRC_NetworkCommunication_getVersionString(char*)
- * native declaration : src\main\include\NetworkCommunication\FRCComm.h:159 - */ - public static native void FRCNetworkCommunicationGetVersionString(ByteBuffer version); - public static native void FRCNetworkCommunicationObserveUserProgramStarting(); - public static native void FRCNetworkCommunicationObserveUserProgramDisabled(); - public static native void FRCNetworkCommunicationObserveUserProgramAutonomous(); - public static native void FRCNetworkCommunicationObserveUserProgramTeleop(); - public static native void FRCNetworkCommunicationObserveUserProgramTest(); - public static native void FRCNetworkCommunicationReserve(); + // public static final String JNA_LIBRARY_NAME = + // LibraryExtractor.getLibraryPath("FRC_NetworkCommunications", true, + // FRC_NetworkCommunicationsLibrary.class); + // public static final NativeLibrary JNA_NATIVE_LIB = + // NativeLibrary.getInstance(FRC_NetworkCommunicationsLibrary.JNA_LIBRARY_NAME, + // MangledFunctionMapper.DEFAULT_OPTIONS); + // static { + // System.loadLibrary("JNIWrappers"); + // Native.register(FRC_NetworkCommunicationsLibrary.class, + // FRC_NetworkCommunicationsLibrary.JNA_NATIVE_LIB); + // } + /** + * native declaration : src\main\include\NetworkCommunication\LoadOut.h
+ * enum values + */ + public static interface tModuleType { + /** + * native declaration : + * src\main\include\NetworkCommunication\LoadOut.h:9 + */ + public static final int kModuleType_Unknown = 0x00; + /** + * native declaration : + * src\main\include\NetworkCommunication\LoadOut.h:10 + */ + public static final int kModuleType_Analog = 0x01; + /** + * native declaration : + * src\main\include\NetworkCommunication\LoadOut.h:11 + */ + public static final int kModuleType_Digital = 0x02; + /** + * native declaration : + * src\main\include\NetworkCommunication\LoadOut.h:12 + */ + public static final int kModuleType_Solenoid = 0x03; + }; + /** + * native declaration : src\main\include\NetworkCommunication\LoadOut.h
+ * enum values + */ + public static interface tTargetClass { + /** + * native declaration : + * src\main\include\NetworkCommunication\LoadOut.h:16 + */ + public static final int kTargetClass_Unknown = 0x00; + /** + * native declaration : + * src\main\include\NetworkCommunication\LoadOut.h:17 + */ + public static final int kTargetClass_FRC1 = 0x10; + /** + * native declaration : + * src\main\include\NetworkCommunication\LoadOut.h:18 + */ + public static final int kTargetClass_FRC2 = 0x20; + /** + * native declaration : + * src\main\include\NetworkCommunication\LoadOut.h:19 + */ + public static final int kTargetClass_FRC2_Analog = + (int) FRCNetworkCommunicationsLibrary.tTargetClass.kTargetClass_FRC2 + | (int) FRCNetworkCommunicationsLibrary.tModuleType.kModuleType_Analog; + /** + * native declaration : + * src\main\include\NetworkCommunication\LoadOut.h:20 + */ + public static final int kTargetClass_FRC2_Digital = + (int) FRCNetworkCommunicationsLibrary.tTargetClass.kTargetClass_FRC2 + | (int) FRCNetworkCommunicationsLibrary.tModuleType.kModuleType_Digital; + /** + * native declaration : + * src\main\include\NetworkCommunication\LoadOut.h:21 + */ + public static final int kTargetClass_FRC2_Solenoid = + (int) FRCNetworkCommunicationsLibrary.tTargetClass.kTargetClass_FRC2 + | (int) FRCNetworkCommunicationsLibrary.tModuleType.kModuleType_Solenoid; + /** + * native declaration : + * src\main\include\NetworkCommunication\LoadOut.h:22 + */ + public static final int kTargetClass_FamilyMask = 0xF0; + /** + * native declaration : + * src\main\include\NetworkCommunication\LoadOut.h:23 + */ + public static final int kTargetClass_ModuleMask = 0x0F; + }; + /** + * native declaration : + * src\main\include\NetworkCommunication\UsageReporting.h
+ * enum values + */ + public static interface tResourceType { + /** + * native declaration : + * src\main\include\NetworkCommunication\UsageReporting.h:10 + */ + public static final int kResourceType_Controller = 0; + /** + * native declaration : + * src\main\include\NetworkCommunication\UsageReporting.h:11 + */ + public static final int kResourceType_Module = 1; + /** + * native declaration : + * src\main\include\NetworkCommunication\UsageReporting.h:12 + */ + public static final int kResourceType_Language = 2; + /** + * native declaration : + * src\main\include\NetworkCommunication\UsageReporting.h:13 + */ + public static final int kResourceType_CANPlugin = 3; + /** + * native declaration : + * src\main\include\NetworkCommunication\UsageReporting.h:14 + */ + public static final int kResourceType_Accelerometer = 4; + /** + * native declaration : + * src\main\include\NetworkCommunication\UsageReporting.h:15 + */ + public static final int kResourceType_ADXL345 = 5; + /** + * native declaration : + * src\main\include\NetworkCommunication\UsageReporting.h:16 + */ + public static final int kResourceType_AnalogChannel = 6; + /** + * native declaration : + * src\main\include\NetworkCommunication\UsageReporting.h:17 + */ + public static final int kResourceType_AnalogTrigger = 7; + /** + * native declaration : + * src\main\include\NetworkCommunication\UsageReporting.h:18 + */ + public static final int kResourceType_AnalogTriggerOutput = 8; + /** + * native declaration : + * src\main\include\NetworkCommunication\UsageReporting.h:19 + */ + public static final int kResourceType_CANJaguar = 9; + /** + * native declaration : + * src\main\include\NetworkCommunication\UsageReporting.h:20 + */ + public static final int kResourceType_Compressor = 10; + /** + * native declaration : + * src\main\include\NetworkCommunication\UsageReporting.h:21 + */ + public static final int kResourceType_Counter = 11; + /** + * native declaration : + * src\main\include\NetworkCommunication\UsageReporting.h:22 + */ + public static final int kResourceType_Dashboard = 12; + /** + * native declaration : + * src\main\include\NetworkCommunication\UsageReporting.h:23 + */ + public static final int kResourceType_DigitalInput = 13; + /** + * native declaration : + * src\main\include\NetworkCommunication\UsageReporting.h:24 + */ + public static final int kResourceType_DigitalOutput = 14; + /** + * native declaration : + * src\main\include\NetworkCommunication\UsageReporting.h:25 + */ + public static final int kResourceType_DriverStationCIO = 15; + /** + * native declaration : + * src\main\include\NetworkCommunication\UsageReporting.h:26 + */ + public static final int kResourceType_DriverStationEIO = 16; + /** + * native declaration : + * src\main\include\NetworkCommunication\UsageReporting.h:27 + */ + public static final int kResourceType_DriverStationLCD = 17; + /** + * native declaration : + * src\main\include\NetworkCommunication\UsageReporting.h:28 + */ + public static final int kResourceType_Encoder = 18; + /** + * native declaration : + * src\main\include\NetworkCommunication\UsageReporting.h:29 + */ + public static final int kResourceType_GearTooth = 19; + /** + * native declaration : + * src\main\include\NetworkCommunication\UsageReporting.h:30 + */ + public static final int kResourceType_Gyro = 20; + /** + * native declaration : + * src\main\include\NetworkCommunication\UsageReporting.h:31 + */ + public static final int kResourceType_I2C = 21; + /** + * native declaration : + * src\main\include\NetworkCommunication\UsageReporting.h:32 + */ + public static final int kResourceType_Framework = 22; + /** + * native declaration : + * src\main\include\NetworkCommunication\UsageReporting.h:33 + */ + public static final int kResourceType_Jaguar = 23; + /** + * native declaration : + * src\main\include\NetworkCommunication\UsageReporting.h:34 + */ + public static final int kResourceType_Joystick = 24; + /** + * native declaration : + * src\main\include\NetworkCommunication\UsageReporting.h:35 + */ + public static final int kResourceType_Kinect = 25; + /** + * native declaration : + * src\main\include\NetworkCommunication\UsageReporting.h:36 + */ + public static final int kResourceType_KinectStick = 26; + /** + * native declaration : + * src\main\include\NetworkCommunication\UsageReporting.h:37 + */ + public static final int kResourceType_PIDController = 27; + /** + * native declaration : + * src\main\include\NetworkCommunication\UsageReporting.h:38 + */ + public static final int kResourceType_Preferences = 28; + /** + * native declaration : + * src\main\include\NetworkCommunication\UsageReporting.h:39 + */ + public static final int kResourceType_PWM = 29; + /** + * native declaration : + * src\main\include\NetworkCommunication\UsageReporting.h:40 + */ + public static final int kResourceType_Relay = 30; + /** + * native declaration : + * src\main\include\NetworkCommunication\UsageReporting.h:41 + */ + public static final int kResourceType_RobotDrive = 31; + /** + * native declaration : + * src\main\include\NetworkCommunication\UsageReporting.h:42 + */ + public static final int kResourceType_SerialPort = 32; + /** + * native declaration : + * src\main\include\NetworkCommunication\UsageReporting.h:43 + */ + public static final int kResourceType_Servo = 33; + /** + * native declaration : + * src\main\include\NetworkCommunication\UsageReporting.h:44 + */ + public static final int kResourceType_Solenoid = 34; + /** + * native declaration : + * src\main\include\NetworkCommunication\UsageReporting.h:45 + */ + public static final int kResourceType_SPI = 35; + /** + * native declaration : + * src\main\include\NetworkCommunication\UsageReporting.h:46 + */ + public static final int kResourceType_Task = 36; + /** + * native declaration : + * src\main\include\NetworkCommunication\UsageReporting.h:47 + */ + public static final int kResourceType_Ultrasonic = 37; + /** + * native declaration : + * src\main\include\NetworkCommunication\UsageReporting.h:48 + */ + public static final int kResourceType_Victor = 38; + /** + * native declaration : + * src\main\include\NetworkCommunication\UsageReporting.h:49 + */ + public static final int kResourceType_Button = 39; + /** + * native declaration : + * src\main\include\NetworkCommunication\UsageReporting.h:50 + */ + public static final int kResourceType_Command = 40; + /** + * native declaration : + * src\main\include\NetworkCommunication\UsageReporting.h:51 + */ + public static final int kResourceType_AxisCamera = 41; + /** + * native declaration : + * src\main\include\NetworkCommunication\UsageReporting.h:52 + */ + public static final int kResourceType_PCVideoServer = 42; + /** + * native declaration : + * src\main\include\NetworkCommunication\UsageReporting.h:53 + */ + public static final int kResourceType_SmartDashboard = 43; + /** + * native declaration : + * src\main\include\NetworkCommunication\UsageReporting.h:54 + */ + public static final int kResourceType_Talon = 44; + /** + * native declaration : + * src\main\include\NetworkCommunication\UsageReporting.h:55 + */ + public static final int kResourceType_HiTechnicColorSensor = 45; + /** + * native declaration : + * src\main\include\NetworkCommunication\UsageReporting.h:56 + */ + public static final int kResourceType_HiTechnicAccel = 46; + /** + * native declaration : + * src\main\include\NetworkCommunication\UsageReporting.h:57 + */ + public static final int kResourceType_HiTechnicCompass = 47; + /** + * native declaration : + * src\main\include\NetworkCommunication\UsageReporting.h:58 + */ + public static final int kResourceType_SRF08 = 48; + /** + * native declaration : + * src\main\include\NetworkCommunication\UsageReporting.h:59 + */ + public static final int kResourceType_AnalogOutput = 49; + /** + * native declaration : + * src\main\include\NetworkCommunication\UsageReporting.h:60 + */ + public static final int kResourceType_VictorSP = 50; + /** + * native declaration : + * src\main\include\NetworkCommunication\UsageReporting.h:61 + */ + public static final int kResourceType_TalonSRX = 51; + /** + * native declaration : + * src\main\include\NetworkCommunication\UsageReporting.h:62 + */ + public static final int kResourceType_CANTalonSRX = 52; + }; + /** + * native declaration : + * src\main\include\NetworkCommunication\UsageReporting.h
+ * enum values + */ + public static interface tInstances { + /** + * native declaration : + * src\main\include\NetworkCommunication\UsageReporting.h:63 + */ + public static final int kLanguage_LabVIEW = 1; + /** + * native declaration : + * src\main\include\NetworkCommunication\UsageReporting.h:64 + */ + public static final int kLanguage_CPlusPlus = 2; + /** + * native declaration : + * src\main\include\NetworkCommunication\UsageReporting.h:65 + */ + public static final int kLanguage_Java = 3; + /** + * native declaration : + * src\main\include\NetworkCommunication\UsageReporting.h:66 + */ + public static final int kLanguage_Python = 4; + /** + * native declaration : + * src\main\include\NetworkCommunication\UsageReporting.h:68 + */ + public static final int kCANPlugin_BlackJagBridge = 1; + /** + * native declaration : + * src\main\include\NetworkCommunication\UsageReporting.h:69 + */ + public static final int kCANPlugin_2CAN = 2; + /** + * native declaration : + * src\main\include\NetworkCommunication\UsageReporting.h:71 + */ + public static final int kFramework_Iterative = 1; + /** + * native declaration : + * src\main\include\NetworkCommunication\UsageReporting.h:72 + */ + public static final int kFramework_Simple = 2; + /** + * native declaration : + * src\main\include\NetworkCommunication\UsageReporting.h:74 + */ + public static final int kRobotDrive_ArcadeStandard = 1; + /** + * native declaration : + * src\main\include\NetworkCommunication\UsageReporting.h:75 + */ + public static final int kRobotDrive_ArcadeButtonSpin = 2; + /** + * native declaration : + * src\main\include\NetworkCommunication\UsageReporting.h:76 + */ + public static final int kRobotDrive_ArcadeRatioCurve = 3; + /** + * native declaration : + * src\main\include\NetworkCommunication\UsageReporting.h:77 + */ + public static final int kRobotDrive_Tank = 4; + /** + * native declaration : + * src\main\include\NetworkCommunication\UsageReporting.h:78 + */ + public static final int kRobotDrive_MecanumPolar = 5; + /** + * native declaration : + * src\main\include\NetworkCommunication\UsageReporting.h:79 + */ + public static final int kRobotDrive_MecanumCartesian = 6; + /** + * native declaration : + * src\main\include\NetworkCommunication\UsageReporting.h:81 + */ + public static final int kDriverStationCIO_Analog = 1; + /** + * native declaration : + * src\main\include\NetworkCommunication\UsageReporting.h:82 + */ + public static final int kDriverStationCIO_DigitalIn = 2; + /** + * native declaration : + * src\main\include\NetworkCommunication\UsageReporting.h:83 + */ + public static final int kDriverStationCIO_DigitalOut = 3; + /** + * native declaration : + * src\main\include\NetworkCommunication\UsageReporting.h:85 + */ + public static final int kDriverStationEIO_Acceleration = 1; + /** + * native declaration : + * src\main\include\NetworkCommunication\UsageReporting.h:86 + */ + public static final int kDriverStationEIO_AnalogIn = 2; + /** + * native declaration : + * src\main\include\NetworkCommunication\UsageReporting.h:87 + */ + public static final int kDriverStationEIO_AnalogOut = 3; + /** + * native declaration : + * src\main\include\NetworkCommunication\UsageReporting.h:88 + */ + public static final int kDriverStationEIO_Button = 4; + /** + * native declaration : + * src\main\include\NetworkCommunication\UsageReporting.h:89 + */ + public static final int kDriverStationEIO_LED = 5; + /** + * native declaration : + * src\main\include\NetworkCommunication\UsageReporting.h:90 + */ + public static final int kDriverStationEIO_DigitalIn = 6; + /** + * native declaration : + * src\main\include\NetworkCommunication\UsageReporting.h:91 + */ + public static final int kDriverStationEIO_DigitalOut = 7; + /** + * native declaration : + * src\main\include\NetworkCommunication\UsageReporting.h:92 + */ + public static final int kDriverStationEIO_FixedDigitalOut = 8; + /** + * native declaration : + * src\main\include\NetworkCommunication\UsageReporting.h:93 + */ + public static final int kDriverStationEIO_PWM = 9; + /** + * native declaration : + * src\main\include\NetworkCommunication\UsageReporting.h:94 + */ + public static final int kDriverStationEIO_Encoder = 10; + /** + * native declaration : + * src\main\include\NetworkCommunication\UsageReporting.h:95 + */ + public static final int kDriverStationEIO_TouchSlider = 11; + /** + * native declaration : + * src\main\include\NetworkCommunication\UsageReporting.h:97 + */ + public static final int kADXL345_SPI = 1; + /** + * native declaration : + * src\main\include\NetworkCommunication\UsageReporting.h:98 + */ + public static final int kADXL345_I2C = 2; + /** + * native declaration : + * src\main\include\NetworkCommunication\UsageReporting.h:100 + */ + public static final int kCommand_Scheduler = 1; + /** + * native declaration : + * src\main\include\NetworkCommunication\UsageReporting.h:102 + */ + public static final int kSmartDashboard_Instance = 1; + }; - private static native int NativeHALGetControlWord(); - public static HALControlWord HALGetControlWord() { - int word = NativeHALGetControlWord(); - return new HALControlWord( - (word & 1) != 0, - ((word >> 1) & 1) != 0, - ((word >> 2) & 1) != 0, - ((word >> 3) & 1) != 0, - ((word >> 4) & 1) != 0, - ((word >> 5) & 1) != 0 - ); - } + /** + * native declaration : src\main\include\NetworkCommunication\FRCComm.h + */ + public static final int kFRC_NetworkCommunication_DynamicType_DSEnhancedIO_Input = 17; + /** + * native declaration : src\main\include\NetworkCommunication\FRCComm.h + */ + public static final int kFRC_NetworkCommunication_DynamicType_Kinect_Vertices1 = 21; + /** + * native declaration : src\main\include\NetworkCommunication\FRCComm.h + */ + public static final int SYS_STATUS_DATA_SIZE = 44; + /** + * native declaration : src\main\include\NetworkCommunication\FRCComm.h + */ + public static final int kFRC_NetworkCommunication_DynamicType_Kinect_Custom = 25; + /** + * native declaration : src\main\include\NetworkCommunication\FRCComm.h + */ + public static final int kFRC_NetworkCommunication_DynamicType_Kinect_Vertices2 = 23; + /** + * native declaration : src\main\include\NetworkCommunication\FRCComm.h + */ + public static final int kFRC_NetworkCommunication_DynamicType_Kinect_Header = 19; + /** + * native declaration : src\main\include\NetworkCommunication\FRCComm.h + */ + public static final int kFRC_NetworkCommunication_DynamicType_Kinect_Joystick = 24; + /** + * native declaration : src\main\include\NetworkCommunication\FRCComm.h + */ + public static final int IO_CONFIG_DATA_SIZE = 32; + /** + * native declaration : src\main\include\NetworkCommunication\LoadOut.h + */ + public static final int kMaxModuleNumber = 2; + /** + * native declaration : src\main\include\NetworkCommunication\FRCComm.h + */ + public static final int kFRC_NetworkCommunication_DynamicType_DSEnhancedIO_Output = 18; + /** + * native declaration : src\main\include\NetworkCommunication\FRCComm.h + */ + public static final int kFRC_NetworkCommunication_DynamicType_Kinect_Extra2 = 22; + /** + * native declaration : src\main\include\NetworkCommunication\FRCComm.h + */ + public static final int kFRC_NetworkCommunication_DynamicType_Kinect_Extra1 = 20; + /** + * native declaration : src\main\include\NetworkCommunication\FRCComm.h + */ + public static final int USER_DS_LCD_DATA_SIZE = 128; + /** + * native declaration : + * src\main\include\NetworkCommunication\UsageReporting.h + */ + public static final int kUsageReporting_version = 1; + /** + * native declaration : src\main\include\NetworkCommunication\FRCComm.h + */ + public static final int USER_STATUS_DATA_SIZE = (984 - 32 - 44); - private static native int NativeHALGetAllianceStation(); - public static HALAllianceStationID HALGetAllianceStation() { - switch(NativeHALGetAllianceStation()) { - case 0: - return HALAllianceStationID.Red1; - case 1: - return HALAllianceStationID.Red2; - case 2: - return HALAllianceStationID.Red3; - case 3: - return HALAllianceStationID.Blue1; - case 4: - return HALAllianceStationID.Blue2; - case 5: - return HALAllianceStationID.Blue3; - default: - return null; - } - } + /** + * Original signature : + * uint32_t FRC_NetworkCommunication_nAICalibration_getLSBWeight(const uint32_t, const uint32_t, int32_t*) + *
+ * native declaration : + * src\main\include\NetworkCommunication\AICalibration.h:7
+ *$ + * @deprecated use the safer methods + * {@link #FRC_NetworkCommunication_nAICalibration_getLSBWeight(int, int, java.nio.IntBuffer)} + * and + * {@link #FRC_NetworkCommunication_nAICalibration_getLSBWeight(int, int, com.sun.jna.ptr.IntByReference)} + * instead + */ + // @Deprecated + // public static native int + // FRC_NetworkCommunication_nAICalibration_getLSBWeight(int aiSystemIndex, int + // channel, Integer status); + /** + * Original signature : + * uint32_t FRC_NetworkCommunication_nAICalibration_getLSBWeight(const uint32_t, const uint32_t, int32_t*) + *
+ * native declaration : + * src\main\include\NetworkCommunication\AICalibration.h:7 + */ + public static native int FRCNetworkCommunicationAICalibrationGetLSBWeight(int aiSystemIndex, + int channel, Integer status); - public static int kMaxJoystickAxes = 12; - public static int kMaxJoystickPOVs = 12; - public static native short[] HALGetJoystickAxes(byte joystickNum); - public static native short[] HALGetJoystickPOVs(byte joystickNum); - public static native int HALGetJoystickButtons(byte joystickNum, ByteBuffer count); - public static native int HALSetJoystickOutputs(byte joystickNum, int outputs, short leftRumble, short rightRumble); - public static native int HALGetJoystickIsXbox(byte joystickNum); - public static native int HALGetJoystickType(byte joystickNum); - public static native String HALGetJoystickName(byte joystickNum); - public static native float HALGetMatchTime(); - public static native boolean HALGetSystemActive(IntBuffer status); - public static native boolean HALGetBrownedOut(IntBuffer status); - - public static native int HALSetErrorData(String error); + /** + * Original signature : + * int32_t FRC_NetworkCommunication_nAICalibration_getOffset(const uint32_t, const uint32_t, int32_t*) + *
+ * native declaration : + * src\main\include\NetworkCommunication\AICalibration.h:8
+ *$ + * @deprecated use the safer methods + * {@link #FRC_NetworkCommunication_nAICalibration_getOffset(int, int, java.nio.IntBuffer)} + * and + * {@link #FRC_NetworkCommunication_nAICalibration_getOffset(int, int, com.sun.jna.ptr.IntByReference)} + * instead + */ + // @Deprecated + // public static native int + // FRC_NetworkCommunication_nAICalibration_getOffset(int aiSystemIndex, int + // channel, Integer status); + /** + * Original signature : + * int32_t FRC_NetworkCommunication_nAICalibration_getOffset(const uint32_t, const uint32_t, int32_t*) + *
+ * native declaration : + * src\main\include\NetworkCommunication\AICalibration.h:8 + */ + public static native int FRCNetworkCommunicationAICalibrationGetOffset(int aiSystemIndex, + int channel, Integer status); + + /** + * Original signature : tTargetClass getTargetClass()
+ * native declaration : + * src\main\include\NetworkCommunication\LoadOut.h:25 + */ + public static native int getTargetClass(); + + /** + * Original signature : + * uint32_t FRC_NetworkCommunication_nLoadOut_getModulePresence(uint32_t, uint8_t) + *
+ * native declaration : + * src\main\include\NetworkCommunication\LoadOut.h:32 + */ + public static native int FRCNetworkCommunicationLoadOutGetModulePresence(int moduleType, + byte moduleNumber); + + /** + * Original signature : + * uint32_t FRC_NetworkCommunication_nLoadOut_getTargetClass()
+ * native declaration : + * src\main\include\NetworkCommunication\LoadOut.h:33 + */ + public static native int FRCNetworkCommunicationLoadOutGetTargetClass(); + + /** + * Original signature : + * STATUS moduleNameFindBySymbolName(const char*, char*)
+ *$ + * @param symbol symbol name to look for
+ * @param module where to return module name
+ * native declaration : + * src\main\include\NetworkCommunication\symModuleLink.h:6
+ * @deprecated use the safer methods + * {@link #moduleNameFindBySymbolName(java.lang.String, java.nio.ByteBuffer)} + * and + * {@link #moduleNameFindBySymbolName(com.sun.jna.Pointer, com.sun.jna.Pointer)} + * instead + */ + // @Deprecated + // public static native FRC_NetworkCommunicationsLibrary.STATUS + // moduleNameFindBySymbolName(Pointer symbol, Pointer module); + /** + * Original signature : + * STATUS moduleNameFindBySymbolName(const char*, char*)
+ *$ + * @param symbol symbol name to look for
+ * @param module where to return module name
+ * native declaration : + * src\main\include\NetworkCommunication\symModuleLink.h:6 + */ + // public static native FRC_NetworkCommunicationsLibrary.STATUS + // moduleNameFindBySymbolName(String symbol, ByteBuffer module); + /** + * Report the usage of a resource of interest.
+ * + *
+ *$ + * @param resource one of the values in the tResourceType above (max value + * 51).
+ * @param instanceNumber an index that identifies the resource instance.
+ * @param context an optional additional context number for some cases (such + * as module number). Set to 0 to omit.
+ * @param feature a string to be included describing features in use on a + * specific resource. Setting the same resource more than once allows + * you to change the feature string.
+ * Original signature : + * uint32_t report(tResourceType, uint8_t, uint8_t, const char*) + *
+ * native declaration : + * src\main\include\NetworkCommunication\UsageReporting.h:113
+ * @deprecated use the safer methods + * {@link #report(int, byte, byte, java.lang.String)} and + * {@link #report(int, byte, byte, com.sun.jna.Pointer)} instead + */ + // @Deprecated + // public static native int report(int resource, byte instanceNumber, byte + // context, Pointer feature); + /** + * Report the usage of a resource of interest.
+ * + *
+ *$ + * @param resource one of the values in the tResourceType above (max value + * 51).
+ * @param instanceNumber an index that identifies the resource instance.
+ * @param context an optional additional context number for some cases (such + * as module number). Set to 0 to omit.
+ * @param feature a string to be included describing features in use on a + * specific resource. Setting the same resource more than once allows + * you to change the feature string.
+ * Original signature : + * uint32_t report(tResourceType, uint8_t, uint8_t, const char*) + *
+ * native declaration : + * src\main\include\NetworkCommunication\UsageReporting.h:113 + */ + public static native int report(int resource, byte instanceNumber, byte context, String feature); + + /** + * Original signature : + * uint32_t FRC_NetworkCommunication_nUsageReporting_report(uint8_t, uint8_t, uint8_t, const char*) + *
+ * native declaration : + * src\main\include\NetworkCommunication\UsageReporting.h:120
+ *$ + * @deprecated use the safer methods + * {@link #FRC_NetworkCommunication_nUsageReporting_report(byte, byte, byte, java.lang.String)} + * and + * {@link #FRC_NetworkCommunication_nUsageReporting_report(byte, byte, byte, com.sun.jna.Pointer)} + * instead + */ + // @Deprecated + // public static native int + // FRC_NetworkCommunication_nUsageReporting_report(byte resource, byte + // instanceNumber, byte context, Pointer feature); + /** + * Original signature : + * uint32_t FRC_NetworkCommunication_nUsageReporting_report(uint8_t, uint8_t, uint8_t, const char*) + *
+ * native declaration : + * src\main\include\NetworkCommunication\UsageReporting.h:120 + */ + public static native int FRCNetworkCommunicationUsageReportingReport(byte resource, + byte instanceNumber, byte context, String feature); + + /** + * Original signature : + * void getFPGAHardwareVersion(uint16_t*, uint32_t*)
+ * native declaration : + * src\main\include\NetworkCommunication\FRCComm.h:124
+ *$ + * @deprecated use the safer methods + * {@link #getFPGAHardwareVersion(java.nio.ShortBuffer, java.nio.IntBuffer)} + * and + * {@link #getFPGAHardwareVersion(com.sun.jna.ptr.ShortByReference, com.sun.jna.ptr.IntByReference)} + * instead + */ + // @Deprecated + // public static native void getFPGAHardwareVersion(ShortByReference + // fpgaVersion, IntByReference fpgaRevision); + /** + * Original signature : + * void getFPGAHardwareVersion(uint16_t*, uint32_t*)
+ * native declaration : + * src\main\include\NetworkCommunication\FRCComm.h:124 + */ + public static native void getFPGAHardwareVersion(ShortBuffer fpgaVersion, IntBuffer fpgaRevision); + + /** + * Original signature : int setErrorData(const char*, int, int)
+ * native declaration : + * src\main\include\NetworkCommunication\FRCComm.h:136
+ *$ + * @deprecated use the safer methods + * {@link #setErrorData(java.lang.String, int, int)} and + * {@link #setErrorData(com.sun.jna.Pointer, int, int)} instead + */ + // @Deprecated + // public static native int setErrorData(Pointer errors, int errorsLength, int + // wait_ms); + /** + * Original signature : int setErrorData(const char*, int, int)
+ * native declaration : + * src\main\include\NetworkCommunication\FRCComm.h:136 + */ + public static native int setErrorData(String errors, int errorsLength, int wait_ms); + + /** + * Original signature : int overrideIOConfig(const char*, int)
+ * native declaration : + * src\main\include\NetworkCommunication\FRCComm.h:138
+ *$ + * @deprecated use the safer methods + * {@link #overrideIOConfig(java.lang.String, int)} and + * {@link #overrideIOConfig(com.sun.jna.Pointer, int)} instead + */ + // @Deprecated + // public static native int overrideIOConfig(String ioConfig, int wait_ms); + /** + * Original signature : int overrideIOConfig(const char*, int)
+ * native declaration : + * src\main\include\NetworkCommunication\FRCComm.h:138 + */ + public static native int overrideIOConfig(String ioConfig, int wait_ms); + + /** + * Original signature : void setNewDataSem(pthread_mutex_t*)
+ * native declaration : + * src\main\include\NetworkCommunication\FRCComm.h:147 + */ + public static native void setNewDataSem(ByteBuffer mutexId); + + /** + * Original signature : void setResyncSem(pthread_mutex_t*)
+ * native declaration : + * src\main\include\NetworkCommunication\FRCComm.h:148 + */ + // public static native void + // setResyncSem(FRC_NetworkCommunicationsLibrary.pthread_mutex_t + // pthread_mutex_tPtr1); + /** + * Original signature : void signalResyncActionDone()
+ * native declaration : + * src\main\include\NetworkCommunication\FRCComm.h:150 + */ + public static native void signalResyncActionDone(); + + /** + * this uint32_t is really a LVRefNum
+ * Original signature : void setNewDataOccurRef(uint32_t)
+ * native declaration : + * src\main\include\NetworkCommunication\FRCComm.h:154 + */ + public static native void setNewDataOccurRef(int refnum); + + /** + * Original signature : void setResyncOccurRef(uint32_t)
+ * native declaration : + * src\main\include\NetworkCommunication\FRCComm.h:156 + */ + public static native void setResyncOccurRef(int refnum); + + /** + * Original signature : + * void FRC_NetworkCommunication_getVersionString(char*)
+ * native declaration : + * src\main\include\NetworkCommunication\FRCComm.h:159
+ *$ + * @deprecated use the safer methods + * {@link #FRC_NetworkCommunication_getVersionString(java.nio.ByteBuffer)} + * and + * {@link #FRC_NetworkCommunication_getVersionString(com.sun.jna.Pointer)} + * instead + */ + // @Deprecated + // public static native void FRC_NetworkCommunication_getVersionString(Pointer + // version); + /** + * Original signature : + * void FRC_NetworkCommunication_getVersionString(char*)
+ * native declaration : + * src\main\include\NetworkCommunication\FRCComm.h:159 + */ + public static native void FRCNetworkCommunicationGetVersionString(ByteBuffer version); + + public static native void FRCNetworkCommunicationObserveUserProgramStarting(); + + public static native void FRCNetworkCommunicationObserveUserProgramDisabled(); + + public static native void FRCNetworkCommunicationObserveUserProgramAutonomous(); + + public static native void FRCNetworkCommunicationObserveUserProgramTeleop(); + + public static native void FRCNetworkCommunicationObserveUserProgramTest(); + + public static native void FRCNetworkCommunicationReserve(); + + private static native int NativeHALGetControlWord(); + + public static HALControlWord HALGetControlWord() { + int word = NativeHALGetControlWord(); + return new HALControlWord((word & 1) != 0, ((word >> 1) & 1) != 0, ((word >> 2) & 1) != 0, + ((word >> 3) & 1) != 0, ((word >> 4) & 1) != 0, ((word >> 5) & 1) != 0); + } + + private static native int NativeHALGetAllianceStation(); + + public static HALAllianceStationID HALGetAllianceStation() { + switch (NativeHALGetAllianceStation()) { + case 0: + return HALAllianceStationID.Red1; + case 1: + return HALAllianceStationID.Red2; + case 2: + return HALAllianceStationID.Red3; + case 3: + return HALAllianceStationID.Blue1; + case 4: + return HALAllianceStationID.Blue2; + case 5: + return HALAllianceStationID.Blue3; + default: + return null; + } + } + + public static int kMaxJoystickAxes = 12; + public static int kMaxJoystickPOVs = 12; + + public static native short[] HALGetJoystickAxes(byte joystickNum); + + public static native short[] HALGetJoystickPOVs(byte joystickNum); + + public static native int HALGetJoystickButtons(byte joystickNum, ByteBuffer count); + + public static native int HALSetJoystickOutputs(byte joystickNum, int outputs, short leftRumble, + short rightRumble); + + public static native int HALGetJoystickIsXbox(byte joystickNum); + + public static native int HALGetJoystickType(byte joystickNum); + + public static native String HALGetJoystickName(byte joystickNum); + + public static native float HALGetMatchTime(); + + public static native boolean HALGetSystemActive(IntBuffer status); + + public static native boolean HALGetBrownedOut(IntBuffer status); + + public static native int HALSetErrorData(String error); } diff --git a/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/communication/HALAllianceStationID.java b/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/communication/HALAllianceStationID.java index 7c9748886e..58322c1353 100644 --- a/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/communication/HALAllianceStationID.java +++ b/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/communication/HALAllianceStationID.java @@ -1,10 +1,5 @@ package edu.wpi.first.wpilibj.communication; public enum HALAllianceStationID { - Red1, - Red2, - Red3, - Blue1, - Blue2, - Blue3 + Red1, Red2, Red3, Blue1, Blue2, Blue3 } diff --git a/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/communication/HALControlWord.java b/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/communication/HALControlWord.java index 715ec93409..0e21d97de7 100644 --- a/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/communication/HALControlWord.java +++ b/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/communication/HALControlWord.java @@ -4,46 +4,46 @@ package edu.wpi.first.wpilibj.communication; * A wrapper for the HALControlWord bitfield */ public class HALControlWord { - private boolean m_enabled; - private boolean m_autonomous; - private boolean m_test; - private boolean m_eStop; - private boolean m_fmsAttached; - private boolean m_dsAttached; + private boolean m_enabled; + private boolean m_autonomous; + private boolean m_test; + private boolean m_eStop; + private boolean m_fmsAttached; + private boolean m_dsAttached; - protected HALControlWord(boolean enabled, boolean autonomous, boolean test, - boolean eStop, boolean fmsAttached, boolean dsAttached) { - m_enabled = enabled; - m_autonomous = autonomous; - m_test = test; - m_eStop = eStop; - m_fmsAttached = fmsAttached; - m_dsAttached = dsAttached; - } + protected HALControlWord(boolean enabled, boolean autonomous, boolean test, boolean eStop, + boolean fmsAttached, boolean dsAttached) { + m_enabled = enabled; + m_autonomous = autonomous; + m_test = test; + m_eStop = eStop; + m_fmsAttached = fmsAttached; + m_dsAttached = dsAttached; + } - public boolean getEnabled() { - return m_enabled; - } + public boolean getEnabled() { + return m_enabled; + } - public boolean getAutonomous() { - return m_autonomous; - } + public boolean getAutonomous() { + return m_autonomous; + } - public boolean getTest() { - return m_test; - } + public boolean getTest() { + return m_test; + } - public boolean getEStop() { - return m_eStop; - } + public boolean getEStop() { + return m_eStop; + } - public boolean getFMSAttached() { - return m_fmsAttached; - } + public boolean getFMSAttached() { + return m_fmsAttached; + } - public boolean getDSAttached() { - return m_dsAttached; - } + public boolean getDSAttached() { + return m_dsAttached; + } } diff --git a/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/communication/NIRioStatus.java b/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/communication/NIRioStatus.java index f51c14239e..0652518379 100644 --- a/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/communication/NIRioStatus.java +++ b/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/communication/NIRioStatus.java @@ -1,12 +1,12 @@ package edu.wpi.first.wpilibj.communication; public class NIRioStatus { - // TODO: Should this file be auto-generated? - public static final int kRioStatusOffset = -63000; - - public static final int kRioStatusSuccess = 0; - public static final int kRIOStatusBufferInvalidSize = kRioStatusOffset - 80; - public static final int kRIOStatusOperationTimedOut = -52007; - public static final int kRIOStatusFeatureNotSupported = kRioStatusOffset - 193; - public static final int kRIOStatusResourceNotInitialized = -52010; + // TODO: Should this file be auto-generated? + public static final int kRioStatusOffset = -63000; + + public static final int kRioStatusSuccess = 0; + public static final int kRIOStatusBufferInvalidSize = kRioStatusOffset - 80; + public static final int kRIOStatusOperationTimedOut = -52007; + public static final int kRIOStatusFeatureNotSupported = kRioStatusOffset - 193; + public static final int kRIOStatusResourceNotInitialized = -52010; } diff --git a/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/communication/UsageReporting.java b/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/communication/UsageReporting.java index 6787e76280..58a0b35d5c 100644 --- a/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/communication/UsageReporting.java +++ b/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/communication/UsageReporting.java @@ -2,17 +2,17 @@ package edu.wpi.first.wpilibj.communication; public class UsageReporting { - public static void report(int resource, int instanceNumber, int i) { - report(resource, instanceNumber, i, ""); - } - - public static void report(int resource, int instanceNumber) { - report(resource, instanceNumber, 0, ""); - } + public static void report(int resource, int instanceNumber, int i) { + report(resource, instanceNumber, i, ""); + } - public static void report(int resource, int instanceNumber, int i, - String string) { - FRCNetworkCommunicationsLibrary.FRCNetworkCommunicationUsageReportingReport((byte)resource, (byte) instanceNumber, (byte) i, string); - } + public static void report(int resource, int instanceNumber) { + report(resource, instanceNumber, 0, ""); + } + + public static void report(int resource, int instanceNumber, int i, String string) { + FRCNetworkCommunicationsLibrary.FRCNetworkCommunicationUsageReportingReport((byte) resource, + (byte) instanceNumber, (byte) i, string); + } } diff --git a/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/hal/AccelerometerJNI.java b/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/hal/AccelerometerJNI.java index bfc8c15824..2c91d0e118 100644 --- a/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/hal/AccelerometerJNI.java +++ b/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/hal/AccelerometerJNI.java @@ -1,9 +1,13 @@ package edu.wpi.first.wpilibj.hal; public class AccelerometerJNI extends JNIWrapper { - public static native void setAccelerometerActive(boolean active); - public static native void setAccelerometerRange(int range); - public static native double getAccelerometerX(); - public static native double getAccelerometerY(); - public static native double getAccelerometerZ(); + public static native void setAccelerometerActive(boolean active); + + public static native void setAccelerometerRange(int range); + + public static native double getAccelerometerX(); + + public static native double getAccelerometerY(); + + public static native double getAccelerometerZ(); } diff --git a/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/hal/AnalogJNI.java b/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/hal/AnalogJNI.java index d241bcc3a6..ea0cb60450 100644 --- a/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/hal/AnalogJNI.java +++ b/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/hal/AnalogJNI.java @@ -5,56 +5,123 @@ import java.nio.ByteBuffer; import java.nio.LongBuffer; public class AnalogJNI extends JNIWrapper { - /** - * native declaration : AthenaJava\target\native\include\HAL\Analog.h:58
- * enum values - */ - public static interface AnalogTriggerType { - /** native declaration : AthenaJava\target\native\include\HAL\Analog.h:54 */ - public static final int kInWindow = 0; - /** native declaration : AthenaJava\target\native\include\HAL\Analog.h:55 */ - public static final int kState = 1; - /** native declaration : AthenaJava\target\native\include\HAL\Analog.h:56 */ - public static final int kRisingPulse = 2; - /** native declaration : AthenaJava\target\native\include\HAL\Analog.h:57 */ - public static final int kFallingPulse = 3; - }; + /** + * native declaration : + * AthenaJava\target\native\include\HAL\Analog.h:58
+ * enum values + */ + public static interface AnalogTriggerType { + /** + * native declaration : + * AthenaJava\target\native\include\HAL\Analog.h:54 + */ + public static final int kInWindow = 0; + /** + * native declaration : + * AthenaJava\target\native\include\HAL\Analog.h:55 + */ + public static final int kState = 1; + /** + * native declaration : + * AthenaJava\target\native\include\HAL\Analog.h:56 + */ + public static final int kRisingPulse = 2; + /** + * native declaration : + * AthenaJava\target\native\include\HAL\Analog.h:57 + */ + public static final int kFallingPulse = 3; + }; - public static native ByteBuffer initializeAnalogInputPort(ByteBuffer port_pointer, IntBuffer status); - public static native ByteBuffer initializeAnalogOutputPort(ByteBuffer port_pointer, IntBuffer status); - public static native byte checkAnalogModule(byte module); - public static native byte checkAnalogInputChannel(int pin); - public static native byte checkAnalogOutputChannel(int pin); - public static native void setAnalogOutput(ByteBuffer port_pointer, double voltage, IntBuffer status); - public static native double getAnalogOutput(ByteBuffer port_pointer, IntBuffer status); - public static native void setAnalogSampleRate(double samplesPerSecond, IntBuffer status); - public static native double getAnalogSampleRate(IntBuffer status); - public static native void setAnalogAverageBits(ByteBuffer analog_port_pointer, int bits, IntBuffer status); - public static native int getAnalogAverageBits(ByteBuffer analog_port_pointer, IntBuffer status); - public static native void setAnalogOversampleBits(ByteBuffer analog_port_pointer, int bits, IntBuffer status); - public static native int getAnalogOversampleBits(ByteBuffer analog_port_pointer, IntBuffer status); - public static native short getAnalogValue(ByteBuffer analog_port_pointer, IntBuffer status); - public static native int getAnalogAverageValue(ByteBuffer analog_port_pointer, IntBuffer status); - public static native int getAnalogVoltsToValue(ByteBuffer analog_port_pointer, double voltage, IntBuffer status); - public static native double getAnalogVoltage(ByteBuffer analog_port_pointer, IntBuffer status); - public static native double getAnalogAverageVoltage(ByteBuffer analog_port_pointer, IntBuffer status); - public static native int getAnalogLSBWeight(ByteBuffer analog_port_pointer, IntBuffer status); - public static native int getAnalogOffset(ByteBuffer analog_port_pointer, IntBuffer status); - public static native byte isAccumulatorChannel(ByteBuffer analog_port_pointer, IntBuffer status); - public static native void initAccumulator(ByteBuffer analog_port_pointer, IntBuffer status); - public static native void resetAccumulator(ByteBuffer analog_port_pointer, IntBuffer status); - public static native void setAccumulatorCenter(ByteBuffer analog_port_pointer, int center, IntBuffer status); - public static native void setAccumulatorDeadband(ByteBuffer analog_port_pointer, int deadband, IntBuffer status); - public static native long getAccumulatorValue(ByteBuffer analog_port_pointer, IntBuffer status); - public static native int getAccumulatorCount(ByteBuffer analog_port_pointer, IntBuffer status); - public static native void getAccumulatorOutput(ByteBuffer analog_port_pointer, LongBuffer value, IntBuffer count, IntBuffer status); - public static native ByteBuffer initializeAnalogTrigger(ByteBuffer port_pointer, IntBuffer index, IntBuffer status); - public static native void cleanAnalogTrigger(ByteBuffer analog_trigger_pointer, IntBuffer status); - public static native void setAnalogTriggerLimitsRaw(ByteBuffer analog_trigger_pointer, int lower, int upper, IntBuffer status); - public static native void setAnalogTriggerLimitsVoltage(ByteBuffer analog_trigger_pointer, double lower, double upper, IntBuffer status); - public static native void setAnalogTriggerAveraged(ByteBuffer analog_trigger_pointer, byte useAveragedValue, IntBuffer status); - public static native void setAnalogTriggerFiltered(ByteBuffer analog_trigger_pointer, byte useFilteredValue, IntBuffer status); - public static native byte getAnalogTriggerInWindow(ByteBuffer analog_trigger_pointer, IntBuffer status); - public static native byte getAnalogTriggerTriggerState(ByteBuffer analog_trigger_pointer, IntBuffer status); - public static native byte getAnalogTriggerOutput(ByteBuffer analog_trigger_pointer, int type, IntBuffer status); + public static native ByteBuffer initializeAnalogInputPort(ByteBuffer port_pointer, + IntBuffer status); + + public static native ByteBuffer initializeAnalogOutputPort(ByteBuffer port_pointer, + IntBuffer status); + + public static native byte checkAnalogModule(byte module); + + public static native byte checkAnalogInputChannel(int pin); + + public static native byte checkAnalogOutputChannel(int pin); + + public static native void setAnalogOutput(ByteBuffer port_pointer, double voltage, + IntBuffer status); + + public static native double getAnalogOutput(ByteBuffer port_pointer, IntBuffer status); + + public static native void setAnalogSampleRate(double samplesPerSecond, IntBuffer status); + + public static native double getAnalogSampleRate(IntBuffer status); + + public static native void setAnalogAverageBits(ByteBuffer analog_port_pointer, int bits, + IntBuffer status); + + public static native int getAnalogAverageBits(ByteBuffer analog_port_pointer, IntBuffer status); + + public static native void setAnalogOversampleBits(ByteBuffer analog_port_pointer, int bits, + IntBuffer status); + + public static native int getAnalogOversampleBits(ByteBuffer analog_port_pointer, IntBuffer status); + + public static native short getAnalogValue(ByteBuffer analog_port_pointer, IntBuffer status); + + public static native int getAnalogAverageValue(ByteBuffer analog_port_pointer, IntBuffer status); + + public static native int getAnalogVoltsToValue(ByteBuffer analog_port_pointer, double voltage, + IntBuffer status); + + public static native double getAnalogVoltage(ByteBuffer analog_port_pointer, IntBuffer status); + + public static native double getAnalogAverageVoltage(ByteBuffer analog_port_pointer, + IntBuffer status); + + public static native int getAnalogLSBWeight(ByteBuffer analog_port_pointer, IntBuffer status); + + public static native int getAnalogOffset(ByteBuffer analog_port_pointer, IntBuffer status); + + public static native byte isAccumulatorChannel(ByteBuffer analog_port_pointer, IntBuffer status); + + public static native void initAccumulator(ByteBuffer analog_port_pointer, IntBuffer status); + + public static native void resetAccumulator(ByteBuffer analog_port_pointer, IntBuffer status); + + public static native void setAccumulatorCenter(ByteBuffer analog_port_pointer, int center, + IntBuffer status); + + public static native void setAccumulatorDeadband(ByteBuffer analog_port_pointer, int deadband, + IntBuffer status); + + public static native long getAccumulatorValue(ByteBuffer analog_port_pointer, IntBuffer status); + + public static native int getAccumulatorCount(ByteBuffer analog_port_pointer, IntBuffer status); + + public static native void getAccumulatorOutput(ByteBuffer analog_port_pointer, LongBuffer value, + IntBuffer count, IntBuffer status); + + public static native ByteBuffer initializeAnalogTrigger(ByteBuffer port_pointer, IntBuffer index, + IntBuffer status); + + public static native void cleanAnalogTrigger(ByteBuffer analog_trigger_pointer, IntBuffer status); + + public static native void setAnalogTriggerLimitsRaw(ByteBuffer analog_trigger_pointer, int lower, + int upper, IntBuffer status); + + public static native void setAnalogTriggerLimitsVoltage(ByteBuffer analog_trigger_pointer, + double lower, double upper, IntBuffer status); + + public static native void setAnalogTriggerAveraged(ByteBuffer analog_trigger_pointer, + byte useAveragedValue, IntBuffer status); + + public static native void setAnalogTriggerFiltered(ByteBuffer analog_trigger_pointer, + byte useFilteredValue, IntBuffer status); + + public static native byte getAnalogTriggerInWindow(ByteBuffer analog_trigger_pointer, + IntBuffer status); + + public static native byte getAnalogTriggerTriggerState(ByteBuffer analog_trigger_pointer, + IntBuffer status); + + public static native byte getAnalogTriggerOutput(ByteBuffer analog_trigger_pointer, int type, + IntBuffer status); } diff --git a/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/hal/CanTalonJNI.java b/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/hal/CanTalonJNI.java index bd55d12d3f..529e48b85f 100644 --- a/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/hal/CanTalonJNI.java +++ b/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/hal/CanTalonJNI.java @@ -1,222 +1,496 @@ -/* ---------------------------------------------------------------------------- - * This file was automatically generated by SWIG (http://www.swig.org). - * Version 2.0.11 - * +/* + * ---------------------------------------------------------------------------- + * This file was automatically generated by SWIG (http://www.swig.org). Version + * 2.0.11 + *$ * Do not make changes to this file unless you know what you are doing--modify * the SWIG interface file instead. - * ----------------------------------------------------------------------------- */ + * ----------------------------------------------------------------------------- + */ package edu.wpi.first.wpilibj.hal; public class CanTalonJNI { public final static native long new_doublep(); + public final static native long copy_doublep(double jarg1); + public final static native void delete_doublep(long jarg1); + public final static native void doublep_assign(long jarg1, double jarg2); + public final static native double doublep_value(long jarg1); + public final static native long new_intp(); + public final static native long copy_intp(int jarg1); + public final static native void delete_intp(long jarg1); + public final static native void intp_assign(long jarg1, int jarg2); + public final static native int intp_value(long jarg1); + public final static native long new_uint32_tp(); + public final static native long copy_uint32_tp(long jarg1); + public final static native void delete_uint32_tp(long jarg1); + public final static native void uint32_tp_assign(long jarg1, long jarg2); + public final static native long uint32_tp_value(long jarg1); + public final static native long new_int32_tp(); + public final static native long copy_int32_tp(long jarg1); + public final static native void delete_int32_tp(long jarg1); + public final static native void int32_tp_assign(long jarg1, long jarg2); + public final static native long int32_tp_value(long jarg1); + public final static native long new_uint8_tp(); + public final static native long copy_uint8_tp(long jarg1); + public final static native void delete_uint8_tp(long jarg1); + public final static native void uint8_tp_assign(long jarg1, long jarg2); + public final static native long uint8_tp_value(long jarg1); + public final static native long new_CTR_Codep(); + public final static native long copy_CTR_Codep(long jarg1); + public final static native void delete_CTR_Codep(long jarg1); + public final static native void CTR_Codep_assign(long jarg1, long jarg2); + public final static native long CTR_Codep_value(long jarg1); + public final static native long new_floatp(); + public final static native long copy_floatp(float jarg1); + public final static native void delete_floatp(long jarg1); + public final static native void floatp_assign(long jarg1, float jarg2); + public final static native float floatp_value(long jarg1); + public final static native long new_CtreCanNode(long jarg1); + public final static native void delete_CtreCanNode(long jarg1); + public final static native long CtreCanNode_GetDeviceNumber(long jarg1, CtreCanNode jarg1_); + public final static native int CanTalonSRX_kDefaultControlPeriodMs_get(); + public final static native long new_CanTalonSRX__SWIG_0(int jarg1, int jarg2); + public final static native long new_CanTalonSRX__SWIG_1(int jarg1); + public final static native long new_CanTalonSRX__SWIG_2(); + public final static native void delete_CanTalonSRX(long jarg1); + public final static native void CanTalonSRX_Set(long jarg1, CanTalonSRX jarg1_, double jarg2); + public final static native int CanTalonSRX_kMode_DutyCycle_get(); + public final static native int CanTalonSRX_kMode_PositionCloseLoop_get(); + public final static native int CanTalonSRX_kMode_VelocityCloseLoop_get(); + public final static native int CanTalonSRX_kMode_CurrentCloseLoop_get(); + public final static native int CanTalonSRX_kMode_VoltCompen_get(); + public final static native int CanTalonSRX_kMode_SlaveFollower_get(); + public final static native int CanTalonSRX_kMode_NoDrive_get(); + public final static native int CanTalonSRX_kLimitSwitchOverride_UseDefaultsFromFlash_get(); + public final static native int CanTalonSRX_kLimitSwitchOverride_DisableFwd_DisableRev_get(); + public final static native int CanTalonSRX_kLimitSwitchOverride_DisableFwd_EnableRev_get(); + public final static native int CanTalonSRX_kLimitSwitchOverride_EnableFwd_DisableRev_get(); + public final static native int CanTalonSRX_kLimitSwitchOverride_EnableFwd_EnableRev_get(); + public final static native int CanTalonSRX_kBrakeOverride_UseDefaultsFromFlash_get(); + public final static native int CanTalonSRX_kBrakeOverride_OverrideCoast_get(); + public final static native int CanTalonSRX_kBrakeOverride_OverrideBrake_get(); + public final static native int CanTalonSRX_kFeedbackDev_DigitalQuadEnc_get(); + public final static native int CanTalonSRX_kFeedbackDev_AnalogPot_get(); + public final static native int CanTalonSRX_kFeedbackDev_AnalogEncoder_get(); + public final static native int CanTalonSRX_kFeedbackDev_CountEveryRisingEdge_get(); + public final static native int CanTalonSRX_kFeedbackDev_CountEveryFallingEdge_get(); + public final static native int CanTalonSRX_kFeedbackDev_PosIsPulseWidth_get(); + public final static native int CanTalonSRX_kProfileSlotSelect_Slot0_get(); + public final static native int CanTalonSRX_kProfileSlotSelect_Slot1_get(); + public final static native int CanTalonSRX_kStatusFrame_General_get(); + public final static native int CanTalonSRX_kStatusFrame_Feedback_get(); + public final static native int CanTalonSRX_kStatusFrame_Encoder_get(); + public final static native int CanTalonSRX_kStatusFrame_AnalogTempVbat_get(); + public final static native int CanTalonSRX_eProfileParamSlot0_P_get(); + public final static native int CanTalonSRX_eProfileParamSlot0_I_get(); + public final static native int CanTalonSRX_eProfileParamSlot0_D_get(); + public final static native int CanTalonSRX_eProfileParamSlot0_F_get(); + public final static native int CanTalonSRX_eProfileParamSlot0_IZone_get(); + public final static native int CanTalonSRX_eProfileParamSlot0_CloseLoopRampRate_get(); + public final static native int CanTalonSRX_eProfileParamSlot1_P_get(); + public final static native int CanTalonSRX_eProfileParamSlot1_I_get(); + public final static native int CanTalonSRX_eProfileParamSlot1_D_get(); + public final static native int CanTalonSRX_eProfileParamSlot1_F_get(); + public final static native int CanTalonSRX_eProfileParamSlot1_IZone_get(); + public final static native int CanTalonSRX_eProfileParamSlot1_CloseLoopRampRate_get(); + public final static native int CanTalonSRX_eProfileParamSoftLimitForThreshold_get(); + public final static native int CanTalonSRX_eProfileParamSoftLimitRevThreshold_get(); + public final static native int CanTalonSRX_eProfileParamSoftLimitForEnable_get(); + public final static native int CanTalonSRX_eProfileParamSoftLimitRevEnable_get(); + public final static native int CanTalonSRX_eOnBoot_BrakeMode_get(); + public final static native int CanTalonSRX_eOnBoot_LimitSwitch_Forward_NormallyClosed_get(); + public final static native int CanTalonSRX_eOnBoot_LimitSwitch_Reverse_NormallyClosed_get(); + public final static native int CanTalonSRX_eOnBoot_LimitSwitch_Forward_Disable_get(); + public final static native int CanTalonSRX_eOnBoot_LimitSwitch_Reverse_Disable_get(); + public final static native int CanTalonSRX_eFault_OverTemp_get(); + public final static native int CanTalonSRX_eFault_UnderVoltage_get(); + public final static native int CanTalonSRX_eFault_ForLim_get(); + public final static native int CanTalonSRX_eFault_RevLim_get(); + public final static native int CanTalonSRX_eFault_HardwareFailure_get(); + public final static native int CanTalonSRX_eFault_ForSoftLim_get(); + public final static native int CanTalonSRX_eFault_RevSoftLim_get(); + public final static native int CanTalonSRX_eStckyFault_OverTemp_get(); + public final static native int CanTalonSRX_eStckyFault_UnderVoltage_get(); + public final static native int CanTalonSRX_eStckyFault_ForLim_get(); + public final static native int CanTalonSRX_eStckyFault_RevLim_get(); + public final static native int CanTalonSRX_eStckyFault_ForSoftLim_get(); + public final static native int CanTalonSRX_eStckyFault_RevSoftLim_get(); + public final static native int CanTalonSRX_eAppliedThrottle_get(); + public final static native int CanTalonSRX_eCloseLoopErr_get(); + public final static native int CanTalonSRX_eFeedbackDeviceSelect_get(); + public final static native int CanTalonSRX_eRevMotDuringCloseLoopEn_get(); + public final static native int CanTalonSRX_eModeSelect_get(); + public final static native int CanTalonSRX_eProfileSlotSelect_get(); + public final static native int CanTalonSRX_eRampThrottle_get(); + public final static native int CanTalonSRX_eRevFeedbackSensor_get(); + public final static native int CanTalonSRX_eLimitSwitchEn_get(); + public final static native int CanTalonSRX_eLimitSwitchClosedFor_get(); + public final static native int CanTalonSRX_eLimitSwitchClosedRev_get(); + public final static native int CanTalonSRX_eSensorPosition_get(); + public final static native int CanTalonSRX_eSensorVelocity_get(); + public final static native int CanTalonSRX_eCurrent_get(); + public final static native int CanTalonSRX_eBrakeIsEnabled_get(); + public final static native int CanTalonSRX_eEncPosition_get(); + public final static native int CanTalonSRX_eEncVel_get(); + public final static native int CanTalonSRX_eEncIndexRiseEvents_get(); + public final static native int CanTalonSRX_eQuadApin_get(); + public final static native int CanTalonSRX_eQuadBpin_get(); + public final static native int CanTalonSRX_eQuadIdxpin_get(); + public final static native int CanTalonSRX_eAnalogInWithOv_get(); + public final static native int CanTalonSRX_eAnalogInVel_get(); + public final static native int CanTalonSRX_eTemp_get(); + public final static native int CanTalonSRX_eBatteryV_get(); + public final static native int CanTalonSRX_eResetCount_get(); + public final static native int CanTalonSRX_eResetFlags_get(); + public final static native int CanTalonSRX_eFirmVers_get(); + public final static native int CanTalonSRX_eSettingsChanged_get(); + public final static native int CanTalonSRX_eQuadFilterEn_get(); + public final static native int CanTalonSRX_ePidIaccum_get(); - public final static native long CanTalonSRX_SetParam(long jarg1, CanTalonSRX jarg1_, int jarg2, double jarg3); + + public final static native long CanTalonSRX_SetParam(long jarg1, CanTalonSRX jarg1_, int jarg2, + double jarg3); + public final static native long CanTalonSRX_RequestParam(long jarg1, CanTalonSRX jarg1_, int jarg2); - public final static native long CanTalonSRX_GetParamResponse(long jarg1, CanTalonSRX jarg1_, int jarg2, long jarg3); - public final static native long CanTalonSRX_GetParamResponseInt32(long jarg1, CanTalonSRX jarg1_, int jarg2, long jarg3); - public final static native long CanTalonSRX_SetPgain(long jarg1, CanTalonSRX jarg1_, long jarg2, double jarg3); - public final static native long CanTalonSRX_SetIgain(long jarg1, CanTalonSRX jarg1_, long jarg2, double jarg3); - public final static native long CanTalonSRX_SetDgain(long jarg1, CanTalonSRX jarg1_, long jarg2, double jarg3); - public final static native long CanTalonSRX_SetFgain(long jarg1, CanTalonSRX jarg1_, long jarg2, double jarg3); - public final static native long CanTalonSRX_SetIzone(long jarg1, CanTalonSRX jarg1_, long jarg2, int jarg3); - public final static native long CanTalonSRX_SetCloseLoopRampRate(long jarg1, CanTalonSRX jarg1_, long jarg2, int jarg3); - public final static native long CanTalonSRX_SetSensorPosition(long jarg1, CanTalonSRX jarg1_, int jarg2); - public final static native long CanTalonSRX_SetForwardSoftLimit(long jarg1, CanTalonSRX jarg1_, int jarg2); - public final static native long CanTalonSRX_SetReverseSoftLimit(long jarg1, CanTalonSRX jarg1_, int jarg2); - public final static native long CanTalonSRX_SetForwardSoftEnable(long jarg1, CanTalonSRX jarg1_, int jarg2); - public final static native long CanTalonSRX_SetReverseSoftEnable(long jarg1, CanTalonSRX jarg1_, int jarg2); - public final static native long CanTalonSRX_GetPgain(long jarg1, CanTalonSRX jarg1_, long jarg2, long jarg3); - public final static native long CanTalonSRX_GetIgain(long jarg1, CanTalonSRX jarg1_, long jarg2, long jarg3); - public final static native long CanTalonSRX_GetDgain(long jarg1, CanTalonSRX jarg1_, long jarg2, long jarg3); - public final static native long CanTalonSRX_GetFgain(long jarg1, CanTalonSRX jarg1_, long jarg2, long jarg3); - public final static native long CanTalonSRX_GetIzone(long jarg1, CanTalonSRX jarg1_, long jarg2, long jarg3); - public final static native long CanTalonSRX_GetCloseLoopRampRate(long jarg1, CanTalonSRX jarg1_, long jarg2, long jarg3); - public final static native long CanTalonSRX_GetForwardSoftLimit(long jarg1, CanTalonSRX jarg1_, long jarg2); - public final static native long CanTalonSRX_GetReverseSoftLimit(long jarg1, CanTalonSRX jarg1_, long jarg2); - public final static native long CanTalonSRX_GetForwardSoftEnable(long jarg1, CanTalonSRX jarg1_, long jarg2); - public final static native long CanTalonSRX_GetReverseSoftEnable(long jarg1, CanTalonSRX jarg1_, long jarg2); - public final static native long CanTalonSRX_SetStatusFrameRate(long jarg1, CanTalonSRX jarg1_, long jarg2, long jarg3); + + public final static native long CanTalonSRX_GetParamResponse(long jarg1, CanTalonSRX jarg1_, + int jarg2, long jarg3); + + public final static native long CanTalonSRX_GetParamResponseInt32(long jarg1, CanTalonSRX jarg1_, + int jarg2, long jarg3); + + public final static native long CanTalonSRX_SetPgain(long jarg1, CanTalonSRX jarg1_, long jarg2, + double jarg3); + + public final static native long CanTalonSRX_SetIgain(long jarg1, CanTalonSRX jarg1_, long jarg2, + double jarg3); + + public final static native long CanTalonSRX_SetDgain(long jarg1, CanTalonSRX jarg1_, long jarg2, + double jarg3); + + public final static native long CanTalonSRX_SetFgain(long jarg1, CanTalonSRX jarg1_, long jarg2, + double jarg3); + + public final static native long CanTalonSRX_SetIzone(long jarg1, CanTalonSRX jarg1_, long jarg2, + int jarg3); + + public final static native long CanTalonSRX_SetCloseLoopRampRate(long jarg1, CanTalonSRX jarg1_, + long jarg2, int jarg3); + + public final static native long CanTalonSRX_SetSensorPosition(long jarg1, CanTalonSRX jarg1_, + int jarg2); + + public final static native long CanTalonSRX_SetForwardSoftLimit(long jarg1, CanTalonSRX jarg1_, + int jarg2); + + public final static native long CanTalonSRX_SetReverseSoftLimit(long jarg1, CanTalonSRX jarg1_, + int jarg2); + + public final static native long CanTalonSRX_SetForwardSoftEnable(long jarg1, CanTalonSRX jarg1_, + int jarg2); + + public final static native long CanTalonSRX_SetReverseSoftEnable(long jarg1, CanTalonSRX jarg1_, + int jarg2); + + public final static native long CanTalonSRX_GetPgain(long jarg1, CanTalonSRX jarg1_, long jarg2, + long jarg3); + + public final static native long CanTalonSRX_GetIgain(long jarg1, CanTalonSRX jarg1_, long jarg2, + long jarg3); + + public final static native long CanTalonSRX_GetDgain(long jarg1, CanTalonSRX jarg1_, long jarg2, + long jarg3); + + public final static native long CanTalonSRX_GetFgain(long jarg1, CanTalonSRX jarg1_, long jarg2, + long jarg3); + + public final static native long CanTalonSRX_GetIzone(long jarg1, CanTalonSRX jarg1_, long jarg2, + long jarg3); + + public final static native long CanTalonSRX_GetCloseLoopRampRate(long jarg1, CanTalonSRX jarg1_, + long jarg2, long jarg3); + + public final static native long CanTalonSRX_GetForwardSoftLimit(long jarg1, CanTalonSRX jarg1_, + long jarg2); + + public final static native long CanTalonSRX_GetReverseSoftLimit(long jarg1, CanTalonSRX jarg1_, + long jarg2); + + public final static native long CanTalonSRX_GetForwardSoftEnable(long jarg1, CanTalonSRX jarg1_, + long jarg2); + + public final static native long CanTalonSRX_GetReverseSoftEnable(long jarg1, CanTalonSRX jarg1_, + long jarg2); + + public final static native long CanTalonSRX_SetStatusFrameRate(long jarg1, CanTalonSRX jarg1_, + long jarg2, long jarg3); + public final static native long CanTalonSRX_ClearStickyFaults(long jarg1, CanTalonSRX jarg1_); - public final static native long CanTalonSRX_GetFault_OverTemp(long jarg1, CanTalonSRX jarg1_, long jarg2); - public final static native long CanTalonSRX_GetFault_UnderVoltage(long jarg1, CanTalonSRX jarg1_, long jarg2); - public final static native long CanTalonSRX_GetFault_ForLim(long jarg1, CanTalonSRX jarg1_, long jarg2); - public final static native long CanTalonSRX_GetFault_RevLim(long jarg1, CanTalonSRX jarg1_, long jarg2); - public final static native long CanTalonSRX_GetFault_HardwareFailure(long jarg1, CanTalonSRX jarg1_, long jarg2); - public final static native long CanTalonSRX_GetFault_ForSoftLim(long jarg1, CanTalonSRX jarg1_, long jarg2); - public final static native long CanTalonSRX_GetFault_RevSoftLim(long jarg1, CanTalonSRX jarg1_, long jarg2); - public final static native long CanTalonSRX_GetStckyFault_OverTemp(long jarg1, CanTalonSRX jarg1_, long jarg2); - public final static native long CanTalonSRX_GetStckyFault_UnderVoltage(long jarg1, CanTalonSRX jarg1_, long jarg2); - public final static native long CanTalonSRX_GetStckyFault_ForLim(long jarg1, CanTalonSRX jarg1_, long jarg2); - public final static native long CanTalonSRX_GetStckyFault_RevLim(long jarg1, CanTalonSRX jarg1_, long jarg2); - public final static native long CanTalonSRX_GetStckyFault_ForSoftLim(long jarg1, CanTalonSRX jarg1_, long jarg2); - public final static native long CanTalonSRX_GetStckyFault_RevSoftLim(long jarg1, CanTalonSRX jarg1_, long jarg2); - public final static native long CanTalonSRX_GetAppliedThrottle(long jarg1, CanTalonSRX jarg1_, long jarg2); - public final static native long CanTalonSRX_GetCloseLoopErr(long jarg1, CanTalonSRX jarg1_, long jarg2); - public final static native long CanTalonSRX_GetFeedbackDeviceSelect(long jarg1, CanTalonSRX jarg1_, long jarg2); - public final static native long CanTalonSRX_GetModeSelect(long jarg1, CanTalonSRX jarg1_, long jarg2); - public final static native long CanTalonSRX_GetLimitSwitchEn(long jarg1, CanTalonSRX jarg1_, long jarg2); - public final static native long CanTalonSRX_GetLimitSwitchClosedFor(long jarg1, CanTalonSRX jarg1_, long jarg2); - public final static native long CanTalonSRX_GetLimitSwitchClosedRev(long jarg1, CanTalonSRX jarg1_, long jarg2); - public final static native long CanTalonSRX_GetSensorPosition(long jarg1, CanTalonSRX jarg1_, long jarg2); - public final static native long CanTalonSRX_GetSensorVelocity(long jarg1, CanTalonSRX jarg1_, long jarg2); + + public final static native long CanTalonSRX_GetFault_OverTemp(long jarg1, CanTalonSRX jarg1_, + long jarg2); + + public final static native long CanTalonSRX_GetFault_UnderVoltage(long jarg1, CanTalonSRX jarg1_, + long jarg2); + + public final static native long CanTalonSRX_GetFault_ForLim(long jarg1, CanTalonSRX jarg1_, + long jarg2); + + public final static native long CanTalonSRX_GetFault_RevLim(long jarg1, CanTalonSRX jarg1_, + long jarg2); + + public final static native long CanTalonSRX_GetFault_HardwareFailure(long jarg1, + CanTalonSRX jarg1_, long jarg2); + + public final static native long CanTalonSRX_GetFault_ForSoftLim(long jarg1, CanTalonSRX jarg1_, + long jarg2); + + public final static native long CanTalonSRX_GetFault_RevSoftLim(long jarg1, CanTalonSRX jarg1_, + long jarg2); + + public final static native long CanTalonSRX_GetStckyFault_OverTemp(long jarg1, + CanTalonSRX jarg1_, long jarg2); + + public final static native long CanTalonSRX_GetStckyFault_UnderVoltage(long jarg1, + CanTalonSRX jarg1_, long jarg2); + + public final static native long CanTalonSRX_GetStckyFault_ForLim(long jarg1, CanTalonSRX jarg1_, + long jarg2); + + public final static native long CanTalonSRX_GetStckyFault_RevLim(long jarg1, CanTalonSRX jarg1_, + long jarg2); + + public final static native long CanTalonSRX_GetStckyFault_ForSoftLim(long jarg1, + CanTalonSRX jarg1_, long jarg2); + + public final static native long CanTalonSRX_GetStckyFault_RevSoftLim(long jarg1, + CanTalonSRX jarg1_, long jarg2); + + public final static native long CanTalonSRX_GetAppliedThrottle(long jarg1, CanTalonSRX jarg1_, + long jarg2); + + public final static native long CanTalonSRX_GetCloseLoopErr(long jarg1, CanTalonSRX jarg1_, + long jarg2); + + public final static native long CanTalonSRX_GetFeedbackDeviceSelect(long jarg1, + CanTalonSRX jarg1_, long jarg2); + + public final static native long CanTalonSRX_GetModeSelect(long jarg1, CanTalonSRX jarg1_, + long jarg2); + + public final static native long CanTalonSRX_GetLimitSwitchEn(long jarg1, CanTalonSRX jarg1_, + long jarg2); + + public final static native long CanTalonSRX_GetLimitSwitchClosedFor(long jarg1, + CanTalonSRX jarg1_, long jarg2); + + public final static native long CanTalonSRX_GetLimitSwitchClosedRev(long jarg1, + CanTalonSRX jarg1_, long jarg2); + + public final static native long CanTalonSRX_GetSensorPosition(long jarg1, CanTalonSRX jarg1_, + long jarg2); + + public final static native long CanTalonSRX_GetSensorVelocity(long jarg1, CanTalonSRX jarg1_, + long jarg2); + public final static native long CanTalonSRX_GetCurrent(long jarg1, CanTalonSRX jarg1_, long jarg2); - public final static native long CanTalonSRX_GetBrakeIsEnabled(long jarg1, CanTalonSRX jarg1_, long jarg2); - public final static native long CanTalonSRX_GetEncPosition(long jarg1, CanTalonSRX jarg1_, long jarg2); + + public final static native long CanTalonSRX_GetBrakeIsEnabled(long jarg1, CanTalonSRX jarg1_, + long jarg2); + + public final static native long CanTalonSRX_GetEncPosition(long jarg1, CanTalonSRX jarg1_, + long jarg2); + public final static native long CanTalonSRX_GetEncVel(long jarg1, CanTalonSRX jarg1_, long jarg2); - public final static native long CanTalonSRX_GetEncIndexRiseEvents(long jarg1, CanTalonSRX jarg1_, long jarg2); + + public final static native long CanTalonSRX_GetEncIndexRiseEvents(long jarg1, CanTalonSRX jarg1_, + long jarg2); + public final static native long CanTalonSRX_GetQuadApin(long jarg1, CanTalonSRX jarg1_, long jarg2); + public final static native long CanTalonSRX_GetQuadBpin(long jarg1, CanTalonSRX jarg1_, long jarg2); - public final static native long CanTalonSRX_GetQuadIdxpin(long jarg1, CanTalonSRX jarg1_, long jarg2); - public final static native long CanTalonSRX_GetAnalogInWithOv(long jarg1, CanTalonSRX jarg1_, long jarg2); - public final static native long CanTalonSRX_GetAnalogInVel(long jarg1, CanTalonSRX jarg1_, long jarg2); + + public final static native long CanTalonSRX_GetQuadIdxpin(long jarg1, CanTalonSRX jarg1_, + long jarg2); + + public final static native long CanTalonSRX_GetAnalogInWithOv(long jarg1, CanTalonSRX jarg1_, + long jarg2); + + public final static native long CanTalonSRX_GetAnalogInVel(long jarg1, CanTalonSRX jarg1_, + long jarg2); + public final static native long CanTalonSRX_GetTemp(long jarg1, CanTalonSRX jarg1_, long jarg2); + public final static native long CanTalonSRX_GetBatteryV(long jarg1, CanTalonSRX jarg1_, long jarg2); - public final static native long CanTalonSRX_GetResetCount(long jarg1, CanTalonSRX jarg1_, long jarg2); - public final static native long CanTalonSRX_GetResetFlags(long jarg1, CanTalonSRX jarg1_, long jarg2); + + public final static native long CanTalonSRX_GetResetCount(long jarg1, CanTalonSRX jarg1_, + long jarg2); + + public final static native long CanTalonSRX_GetResetFlags(long jarg1, CanTalonSRX jarg1_, + long jarg2); + public final static native long CanTalonSRX_GetFirmVers(long jarg1, CanTalonSRX jarg1_, long jarg2); + public final static native long CanTalonSRX_SetDemand(long jarg1, CanTalonSRX jarg1_, int jarg2); - public final static native long CanTalonSRX_SetOverrideLimitSwitchEn(long jarg1, CanTalonSRX jarg1_, int jarg2); - public final static native long CanTalonSRX_SetFeedbackDeviceSelect(long jarg1, CanTalonSRX jarg1_, int jarg2); - public final static native long CanTalonSRX_SetRevMotDuringCloseLoopEn(long jarg1, CanTalonSRX jarg1_, int jarg2); - public final static native long CanTalonSRX_SetOverrideBrakeType(long jarg1, CanTalonSRX jarg1_, int jarg2); - public final static native long CanTalonSRX_SetModeSelect(long jarg1, CanTalonSRX jarg1_, int jarg2); - public final static native long CanTalonSRX_SetProfileSlotSelect(long jarg1, CanTalonSRX jarg1_, int jarg2); - public final static native long CanTalonSRX_SetRampThrottle(long jarg1, CanTalonSRX jarg1_, int jarg2); - public final static native long CanTalonSRX_SetRevFeedbackSensor(long jarg1, CanTalonSRX jarg1_, int jarg2); + + public final static native long CanTalonSRX_SetOverrideLimitSwitchEn(long jarg1, + CanTalonSRX jarg1_, int jarg2); + + public final static native long CanTalonSRX_SetFeedbackDeviceSelect(long jarg1, + CanTalonSRX jarg1_, int jarg2); + + public final static native long CanTalonSRX_SetRevMotDuringCloseLoopEn(long jarg1, + CanTalonSRX jarg1_, int jarg2); + + public final static native long CanTalonSRX_SetOverrideBrakeType(long jarg1, CanTalonSRX jarg1_, + int jarg2); + + public final static native long CanTalonSRX_SetModeSelect(long jarg1, CanTalonSRX jarg1_, + int jarg2); + + public final static native long CanTalonSRX_SetProfileSlotSelect(long jarg1, CanTalonSRX jarg1_, + int jarg2); + + public final static native long CanTalonSRX_SetRampThrottle(long jarg1, CanTalonSRX jarg1_, + int jarg2); + + public final static native long CanTalonSRX_SetRevFeedbackSensor(long jarg1, CanTalonSRX jarg1_, + int jarg2); + public final static native long CanTalonSRX_SWIGUpcast(long jarg1); } diff --git a/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/hal/CompressorJNI.java b/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/hal/CompressorJNI.java index 2838ca3baf..8a2363a046 100644 --- a/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/hal/CompressorJNI.java +++ b/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/hal/CompressorJNI.java @@ -1,25 +1,40 @@ -package edu.wpi.first.wpilibj.hal; - -import java.nio.ByteBuffer; -import java.nio.IntBuffer; - -public class CompressorJNI extends JNIWrapper { - public static native ByteBuffer initializeCompressor(byte module); - public static native boolean checkCompressorModule(byte module); - - public static native boolean getCompressor(ByteBuffer pcm_pointer, IntBuffer status); - - public static native void setClosedLoopControl(ByteBuffer pcm_pointer, boolean value, IntBuffer status); - public static native boolean getClosedLoopControl(ByteBuffer pcm_pointer, IntBuffer status); - - public static native boolean getPressureSwitch(ByteBuffer pcm_pointer, IntBuffer status); - public static native float getCompressorCurrent(ByteBuffer pcm_pointer, IntBuffer status); - - public static native boolean getCompressorCurrentTooHighFault(ByteBuffer pcm_pointer, IntBuffer status); - public static native boolean getCompressorCurrentTooHighStickyFault(ByteBuffer pcm_pointer, IntBuffer status); - public static native boolean getCompressorShortedStickyFault(ByteBuffer pcm_pointer, IntBuffer status); - public static native boolean getCompressorShortedFault(ByteBuffer pcm_pointer, IntBuffer status); - public static native boolean getCompressorNotConnectedStickyFault(ByteBuffer pcm_pointer, IntBuffer status); - public static native boolean getCompressorNotConnectedFault(ByteBuffer pcm_pointer, IntBuffer status); - public static native void clearAllPCMStickyFaults(ByteBuffer pcm_pointer, IntBuffer status); -} +package edu.wpi.first.wpilibj.hal; + +import java.nio.ByteBuffer; +import java.nio.IntBuffer; + +public class CompressorJNI extends JNIWrapper { + public static native ByteBuffer initializeCompressor(byte module); + + public static native boolean checkCompressorModule(byte module); + + public static native boolean getCompressor(ByteBuffer pcm_pointer, IntBuffer status); + + public static native void setClosedLoopControl(ByteBuffer pcm_pointer, boolean value, + IntBuffer status); + + public static native boolean getClosedLoopControl(ByteBuffer pcm_pointer, IntBuffer status); + + public static native boolean getPressureSwitch(ByteBuffer pcm_pointer, IntBuffer status); + + public static native float getCompressorCurrent(ByteBuffer pcm_pointer, IntBuffer status); + + public static native boolean getCompressorCurrentTooHighFault(ByteBuffer pcm_pointer, + IntBuffer status); + + public static native boolean getCompressorCurrentTooHighStickyFault(ByteBuffer pcm_pointer, + IntBuffer status); + + public static native boolean getCompressorShortedStickyFault(ByteBuffer pcm_pointer, + IntBuffer status); + + public static native boolean getCompressorShortedFault(ByteBuffer pcm_pointer, IntBuffer status); + + public static native boolean getCompressorNotConnectedStickyFault(ByteBuffer pcm_pointer, + IntBuffer status); + + public static native boolean getCompressorNotConnectedFault(ByteBuffer pcm_pointer, + IntBuffer status); + + public static native void clearAllPCMStickyFaults(ByteBuffer pcm_pointer, IntBuffer status); +} diff --git a/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/hal/CounterJNI.java b/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/hal/CounterJNI.java index 3baf2ede9f..b9097e62ca 100644 --- a/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/hal/CounterJNI.java +++ b/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/hal/CounterJNI.java @@ -4,27 +4,61 @@ import java.nio.IntBuffer; import java.nio.ByteBuffer; public class CounterJNI extends JNIWrapper { - public static native ByteBuffer initializeCounter(int mode, IntBuffer index, IntBuffer status); - public static native void freeCounter(ByteBuffer counter_pointer, IntBuffer status); - public static native void setCounterAverageSize(ByteBuffer counter_pointer, int size, IntBuffer status); - public static native void setCounterUpSource(ByteBuffer counter_pointer, int pin, byte analogTrigger, IntBuffer status); - public static native void setCounterUpSourceEdge(ByteBuffer counter_pointer, byte risingEdge, byte fallingEdge, IntBuffer status); - public static native void clearCounterUpSource(ByteBuffer counter_pointer, IntBuffer status); - public static native void setCounterDownSource(ByteBuffer counter_pointer, int pin, byte analogTrigger, IntBuffer status); - public static native void setCounterDownSourceEdge(ByteBuffer counter_pointer, byte risingEdge, byte fallingEdge, IntBuffer status); - public static native void clearCounterDownSource(ByteBuffer counter_pointer, IntBuffer status); - public static native void setCounterUpDownMode(ByteBuffer counter_pointer, IntBuffer status); - public static native void setCounterExternalDirectionMode(ByteBuffer counter_pointer, IntBuffer status); - public static native void setCounterSemiPeriodMode(ByteBuffer counter_pointer, byte highSemiPeriod, IntBuffer status); - public static native void setCounterPulseLengthMode(ByteBuffer counter_pointer, double threshold, IntBuffer status); - public static native int getCounterSamplesToAverage(ByteBuffer counter_pointer, IntBuffer status); - public static native void setCounterSamplesToAverage(ByteBuffer counter_pointer, int samplesToAverage, IntBuffer status); - public static native void resetCounter(ByteBuffer counter_pointer, IntBuffer status); - public static native int getCounter(ByteBuffer counter_pointer, IntBuffer status); - public static native double getCounterPeriod(ByteBuffer counter_pointer, IntBuffer status); - public static native void setCounterMaxPeriod(ByteBuffer counter_pointer, double maxPeriod, IntBuffer status); - public static native void setCounterUpdateWhenEmpty(ByteBuffer counter_pointer, byte enabled, IntBuffer status); - public static native byte getCounterStopped(ByteBuffer counter_pointer, IntBuffer status); - public static native byte getCounterDirection(ByteBuffer counter_pointer, IntBuffer status); - public static native void setCounterReverseDirection(ByteBuffer counter_pointer, byte reverseDirection, IntBuffer status); + public static native ByteBuffer initializeCounter(int mode, IntBuffer index, IntBuffer status); + + public static native void freeCounter(ByteBuffer counter_pointer, IntBuffer status); + + public static native void setCounterAverageSize(ByteBuffer counter_pointer, int size, + IntBuffer status); + + public static native void setCounterUpSource(ByteBuffer counter_pointer, int pin, + byte analogTrigger, IntBuffer status); + + public static native void setCounterUpSourceEdge(ByteBuffer counter_pointer, byte risingEdge, + byte fallingEdge, IntBuffer status); + + public static native void clearCounterUpSource(ByteBuffer counter_pointer, IntBuffer status); + + public static native void setCounterDownSource(ByteBuffer counter_pointer, int pin, + byte analogTrigger, IntBuffer status); + + public static native void setCounterDownSourceEdge(ByteBuffer counter_pointer, byte risingEdge, + byte fallingEdge, IntBuffer status); + + public static native void clearCounterDownSource(ByteBuffer counter_pointer, IntBuffer status); + + public static native void setCounterUpDownMode(ByteBuffer counter_pointer, IntBuffer status); + + public static native void setCounterExternalDirectionMode(ByteBuffer counter_pointer, + IntBuffer status); + + public static native void setCounterSemiPeriodMode(ByteBuffer counter_pointer, + byte highSemiPeriod, IntBuffer status); + + public static native void setCounterPulseLengthMode(ByteBuffer counter_pointer, double threshold, + IntBuffer status); + + public static native int getCounterSamplesToAverage(ByteBuffer counter_pointer, IntBuffer status); + + public static native void setCounterSamplesToAverage(ByteBuffer counter_pointer, + int samplesToAverage, IntBuffer status); + + public static native void resetCounter(ByteBuffer counter_pointer, IntBuffer status); + + public static native int getCounter(ByteBuffer counter_pointer, IntBuffer status); + + public static native double getCounterPeriod(ByteBuffer counter_pointer, IntBuffer status); + + public static native void setCounterMaxPeriod(ByteBuffer counter_pointer, double maxPeriod, + IntBuffer status); + + public static native void setCounterUpdateWhenEmpty(ByteBuffer counter_pointer, byte enabled, + IntBuffer status); + + public static native byte getCounterStopped(ByteBuffer counter_pointer, IntBuffer status); + + public static native byte getCounterDirection(ByteBuffer counter_pointer, IntBuffer status); + + public static native void setCounterReverseDirection(ByteBuffer counter_pointer, + byte reverseDirection, IntBuffer status); } diff --git a/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/hal/DIOJNI.java b/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/hal/DIOJNI.java index 7091e5eb36..d7bda85a23 100644 --- a/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/hal/DIOJNI.java +++ b/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/hal/DIOJNI.java @@ -4,14 +4,25 @@ import java.nio.IntBuffer; import java.nio.ByteBuffer; public class DIOJNI extends JNIWrapper { - public static native ByteBuffer initializeDigitalPort(ByteBuffer port_pointer, IntBuffer status); - public static native byte allocateDIO(ByteBuffer digital_port_pointer, byte input, IntBuffer status); - public static native void freeDIO(ByteBuffer digital_port_pointer, IntBuffer status); - public static native void setDIO(ByteBuffer digital_port_pointer, short value, IntBuffer status); - public static native byte getDIO(ByteBuffer digital_port_pointer, IntBuffer status); - public static native byte getDIODirection(ByteBuffer digital_port_pointer, IntBuffer status); - public static native void pulse(ByteBuffer digital_port_pointer, double pulseLength, IntBuffer status); - public static native byte isPulsing(ByteBuffer digital_port_pointer, IntBuffer status); - public static native byte isAnyPulsing(IntBuffer status); - public static native short getLoopTiming(IntBuffer status); + public static native ByteBuffer initializeDigitalPort(ByteBuffer port_pointer, IntBuffer status); + + public static native byte allocateDIO(ByteBuffer digital_port_pointer, byte input, + IntBuffer status); + + public static native void freeDIO(ByteBuffer digital_port_pointer, IntBuffer status); + + public static native void setDIO(ByteBuffer digital_port_pointer, short value, IntBuffer status); + + public static native byte getDIO(ByteBuffer digital_port_pointer, IntBuffer status); + + public static native byte getDIODirection(ByteBuffer digital_port_pointer, IntBuffer status); + + public static native void pulse(ByteBuffer digital_port_pointer, double pulseLength, + IntBuffer status); + + public static native byte isPulsing(ByteBuffer digital_port_pointer, IntBuffer status); + + public static native byte isAnyPulsing(IntBuffer status); + + public static native short getLoopTiming(IntBuffer status); } diff --git a/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/hal/EncoderJNI.java b/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/hal/EncoderJNI.java index 1c59301f20..45cd14772f 100644 --- a/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/hal/EncoderJNI.java +++ b/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/hal/EncoderJNI.java @@ -4,16 +4,33 @@ import java.nio.IntBuffer; import java.nio.ByteBuffer; public class EncoderJNI extends JNIWrapper { - public static native ByteBuffer initializeEncoder(byte port_a_module, int port_a_pin, byte port_a_analog_trigger, byte port_b_module, int port_b_pin, byte port_b_analog_trigger, byte reverseDirection, IntBuffer index, IntBuffer status); - public static native void freeEncoder(ByteBuffer encoder_pointer, IntBuffer status); - public static native void resetEncoder(ByteBuffer encoder_pointer, IntBuffer status); - public static native int getEncoder(ByteBuffer encoder_pointer, IntBuffer status); - public static native double getEncoderPeriod(ByteBuffer encoder_pointer, IntBuffer status); - public static native void setEncoderMaxPeriod(ByteBuffer encoder_pointer, double maxPeriod, IntBuffer status); - public static native byte getEncoderStopped(ByteBuffer encoder_pointer, IntBuffer status); - public static native byte getEncoderDirection(ByteBuffer encoder_pointer, IntBuffer status); - public static native void setEncoderReverseDirection(ByteBuffer encoder_pointer, byte reverseDirection, IntBuffer status); - public static native void setEncoderSamplesToAverage(ByteBuffer encoder_pointer, int samplesToAverage, IntBuffer status); - public static native int getEncoderSamplesToAverage(ByteBuffer encoder_pointer, IntBuffer status); - public static native void setEncoderIndexSource(ByteBuffer digital_port, int pin, boolean analogTrigger, boolean activeHigh, boolean edgeSensitive, IntBuffer status); + public static native ByteBuffer initializeEncoder(byte port_a_module, int port_a_pin, + byte port_a_analog_trigger, byte port_b_module, int port_b_pin, byte port_b_analog_trigger, + byte reverseDirection, IntBuffer index, IntBuffer status); + + public static native void freeEncoder(ByteBuffer encoder_pointer, IntBuffer status); + + public static native void resetEncoder(ByteBuffer encoder_pointer, IntBuffer status); + + public static native int getEncoder(ByteBuffer encoder_pointer, IntBuffer status); + + public static native double getEncoderPeriod(ByteBuffer encoder_pointer, IntBuffer status); + + public static native void setEncoderMaxPeriod(ByteBuffer encoder_pointer, double maxPeriod, + IntBuffer status); + + public static native byte getEncoderStopped(ByteBuffer encoder_pointer, IntBuffer status); + + public static native byte getEncoderDirection(ByteBuffer encoder_pointer, IntBuffer status); + + public static native void setEncoderReverseDirection(ByteBuffer encoder_pointer, + byte reverseDirection, IntBuffer status); + + public static native void setEncoderSamplesToAverage(ByteBuffer encoder_pointer, + int samplesToAverage, IntBuffer status); + + public static native int getEncoderSamplesToAverage(ByteBuffer encoder_pointer, IntBuffer status); + + public static native void setEncoderIndexSource(ByteBuffer digital_port, int pin, + boolean analogTrigger, boolean activeHigh, boolean edgeSensitive, IntBuffer status); } diff --git a/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/hal/HALLibrary.java b/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/hal/HALLibrary.java index a030b39c4c..c82da56d35 100644 --- a/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/hal/HALLibrary.java +++ b/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/hal/HALLibrary.java @@ -1,547 +1,767 @@ package edu.wpi.first.wpilibj.hal; -//import com.ochafik.lang.jnaerator.runtime.LibraryExtractor; -//import com.ochafik.lang.jnaerator.runtime.MangledFunctionMapper; -//import com.ochafik.lang.jnaerator.runtime.globals.GlobalDouble; -//import com.ochafik.lang.jnaerator.runtime.globals.GlobalInt; -//import com.sun.jna.Callback; -//import com.sun.jna.Library; -//import com.sun.jna.Native; -//import com.sun.jna.NativeLibrary; -//import com.sun.jna.Pointer; -//import com.sun.jna.PointerType; -//import com.sun.jna.ptr.IntByReference; -//import com.sun.jna.ptr.LongByReference; + +// import com.ochafik.lang.jnaerator.runtime.LibraryExtractor; +// import com.ochafik.lang.jnaerator.runtime.MangledFunctionMapper; +// import com.ochafik.lang.jnaerator.runtime.globals.GlobalDouble; +// import com.ochafik.lang.jnaerator.runtime.globals.GlobalInt; +// import com.sun.jna.Callback; +// import com.sun.jna.Library; +// import com.sun.jna.Native; +// import com.sun.jna.NativeLibrary; +// import com.sun.jna.Pointer; +// import com.sun.jna.PointerType; +// import com.sun.jna.ptr.IntByReference; +// import com.sun.jna.ptr.LongByReference; import java.nio.ByteBuffer; import java.nio.IntBuffer; + /** * JNA Wrapper for library HAL
- * This file was autogenerated by JNAerator,
- * a tool written by Olivier Chafik that uses a few opensource projects..
- * For help, please visit NativeLibs4Java , Rococoa, or JNA. + * This file was autogenerated by JNAerator,
+ * a tool written by Olivier Chafik that uses a few + * opensource projects..
+ * For help, please visit NativeLibs4Java , Rococoa, or JNA. */ -public class HALLibrary /* implements Library */ { - //public static final String JNA_LIBRARY_NAME = LibraryExtractor.getLibraryPath("HALAthenaJava", true, HALLibrary.class); - //public static final NativeLibrary JNA_NATIVE_LIB = NativeLibrary.getInstance(HALLibrary.JNA_LIBRARY_NAME, MangledFunctionMapper.DEFAULT_OPTIONS); - static { - System.loadLibrary("JNIWrappers"); - // Native.register(HALLibrary.class, HALLibrary.JNA_NATIVE_LIB); - } - /** - * native declaration : AthenaJava\target\native\include\HAL\Digital.h:148
- * enum values - */ - public static interface Mode { - /** native declaration : AthenaJava\target\native\include\HAL\Digital.h:144 */ - public static final int kTwoPulse = 0; - /** native declaration : AthenaJava\target\native\include\HAL\Digital.h:145 */ - public static final int kSemiperiod = 1; - /** native declaration : AthenaJava\target\native\include\HAL\Digital.h:146 */ - public static final int kPulseLength = 2; - /** native declaration : AthenaJava\target\native\include\HAL\Digital.h:147 */ - public static final int kExternalDirection = 3; - }; - /** - * native declaration : AthenaJava\target\native\include\HAL\Digital.h:235
- * enum values - */ - public static interface tSPIConstants { - /** native declaration : AthenaJava\target\native\include\HAL\Digital.h:233 */ - public static final int kReceiveFIFODepth = 512; - /** native declaration : AthenaJava\target\native\include\HAL\Digital.h:234 */ - public static final int kTransmitFIFODepth = 512; - }; - /** - * native declaration : AthenaJava\target\native\include\HAL\Digital.h:241
- * enum values - */ - public static interface tFrameMode { - /** native declaration : AthenaJava\target\native\include\HAL\Digital.h:237 */ - public static final int kChipSelect = 0; - /** native declaration : AthenaJava\target\native\include\HAL\Digital.h:238 */ - public static final int kPreLatchPulse = 1; - /** native declaration : AthenaJava\target\native\include\HAL\Digital.h:239 */ - public static final int kPostLatchPulse = 2; - /** native declaration : AthenaJava\target\native\include\HAL\Digital.h:240 */ - public static final int kPreAndPostLatchPulse = 3; - }; - /** native declaration : AthenaJava\target\native\include\HAL\Errors.h */ - public static final String NULL_PARAMETER_MESSAGE = "A pointer parameter to a method is NULL"; - /** native declaration : AthenaJava\target\native\include\HAL\Errors.h */ - public static final String NO_AVAILABLE_RESOURCES_MESSAGE = "No available resources to allocate"; - /** native declaration : AthenaJava\target\native\include\HAL\Errors.h */ - public static final String INCOMPATIBLE_STATE_MESSAGE = "Incompatible State: The operation cannot be completed"; - /** native declaration : AthenaJava\target\native\include\HAL\Errors.h */ - public static final String ANALOG_TRIGGER_PULSE_OUTPUT_ERROR_MESSAGE = "Attempted to read AnalogTrigger pulse output."; - /** native declaration : AthenaJava\target\native\include\HAL\Errors.h */ - public static final int ANALOG_TRIGGER_LIMIT_ORDER_ERROR = -10; - /** native declaration : AthenaJava\target\native\include\HAL\Errors.h */ - public static final int SPI_READ_NO_DATA = 14; - /** native declaration : AthenaJava\target\native\include\HAL\Errors.h */ - public static final String VOLTAGE_OUT_OF_RANGE_MESSAGE = "Voltage to convert to raw value is out of range [-10; 10]"; - /** native declaration : AthenaJava\target\native\include\HAL\Errors.h */ - public static final String ANALOG_TRIGGER_LIMIT_ORDER_ERROR_MESSAGE = "AnalogTrigger limits error. Lower limit > Upper Limit"; - /** native declaration : AthenaJava\target\native\include\HAL\Errors.h */ - public static final int SPI_WRITE_NO_MOSI = 12; - /** native declaration : AthenaJava\target\native\include\HAL\Errors.h */ - public static final String PARAMETER_OUT_OF_RANGE_MESSAGE = "A parameter is out of range."; - /** native declaration : AthenaJava\target\native\include\HAL\Task.h */ - public static final int OK = 0; - /** native declaration : AthenaJava\target\native\include\HAL\Task.h */ - public static final int ERROR = (-1); - /** native declaration : AthenaJava\target\native\include\HAL\Errors.h */ - public static final String SAMPLE_RATE_TOO_HIGH_MESSAGE = "Analog module sample rate is too high"; - /** native declaration : AthenaJava\target\native\include\HAL\Errors.h */ - public static final String SPI_WRITE_NO_MOSI_MESSAGE = "Cannot write to SPI port with no MOSI output"; - /** native declaration : AthenaJava\target\native\include\HAL\Errors.h */ - public static final int SPI_READ_NO_MISO = 13; - /** native declaration : AthenaJava\target\native\include\HAL\Errors.h */ - public static final String SPI_READ_NO_DATA_MESSAGE = "No data available to read from SPI"; - /** native declaration : AthenaJava\target\native\include\HAL\Errors.h */ - /** native declaration : AthenaJava\target\native\include\HAL\Errors.h */ - public static final String SPI_READ_NO_MISO_MESSAGE = "Cannot read from SPI port with no MISO input"; - /** native declaration : AthenaJava\target\native\include\HAL\Errors.h */ - public static final String LOOP_TIMING_ERROR_MESSAGE = "Digital module loop timing is not the expected value"; - /** native declaration : AthenaJava\target\native\include\HAL\Notifier.h:339 */ - //public interface initializeNotifier_ProcessQueue_callback extends Callback { - // void apply(int uint32_t1, Pointer voidPtr1); - //}; - /** native declaration : AthenaJava\target\native\include\HAL\Interrupts.h:342 */ - /** native declaration : AthenaJava\target\native\include\HAL\Task.h:409 */ - //public interface FUNCPTR extends Callback { - // int apply(Object... varargs); - //}; - /** - * Original signature : bool checkPWMChannel(void*)
- * native declaration : AthenaJava\target\native\include\HAL\Digital.h:84 - */ - //public static native byte checkPWMChannel(Pointer digital_port_pointer); - /** - * Original signature : bool checkRelayChannel(void*)
- * native declaration : AthenaJava\target\native\include\HAL\Digital.h:86 - */ - //public static native byte checkRelayChannel(Pointer digital_port_pointer); - /** - * Original signature : void* initializeNotifier(initializeNotifier_ProcessQueue_callback*, int32_t*)
- * native declaration : AthenaJava\target\native\include\HAL\Notifier.h:334
- * @deprecated use the safer methods {@link #initializeNotifier(edu.wpi.first.wpilibj.hal.HALLibrary.initializeNotifier_ProcessQueue_callback, java.nio.IntBuffer)} and {@link #initializeNotifier(edu.wpi.first.wpilibj.hal.HALLibrary.initializeNotifier_ProcessQueue_callback, com.sun.jna.ptr.IntByReference)} instead - */ - //@Deprecated - //public static native Pointer initializeNotifier(HALLibrary.initializeNotifier_ProcessQueue_callback ProcessQueue, IntByReference status); - /** - * Original signature : void* initializeNotifier(initializeNotifier_ProcessQueue_callback*, int32_t*)
- * native declaration : AthenaJava\target\native\include\HAL\Notifier.h:334 - */ - //public static native Pointer initializeNotifier(HALLibrary.initializeNotifier_ProcessQueue_callback ProcessQueue, IntBuffer status); - /** - * Original signature : void cleanNotifier(void*, int32_t*)
- * native declaration : AthenaJava\target\native\include\HAL\Notifier.h:336
- * @deprecated use the safer methods {@link #cleanNotifier(com.sun.jna.Pointer, java.nio.IntBuffer)} and {@link #cleanNotifier(com.sun.jna.Pointer, com.sun.jna.ptr.IntByReference)} instead - */ - //@Deprecated - //public static native void cleanNotifier(Pointer notifier_pointer, IntByReference status); - /** - * Original signature : void cleanNotifier(void*, int32_t*)
- * native declaration : AthenaJava\target\native\include\HAL\Notifier.h:336 - */ - //public static native void cleanNotifier(Pointer notifier_pointer, IntBuffer status); - /** - * Original signature : void updateNotifierAlarm(void*, uint32_t, int32_t*)
- * native declaration : AthenaJava\target\native\include\HAL\Notifier.h:338
- * @deprecated use the safer methods {@link #updateNotifierAlarm(com.sun.jna.Pointer, int, java.nio.IntBuffer)} and {@link #updateNotifierAlarm(com.sun.jna.Pointer, int, com.sun.jna.ptr.IntByReference)} instead - */ - //@Deprecated - //public static native void updateNotifierAlarm(Pointer notifier_pointer, int triggerTime, IntByReference status); - /** - * Original signature : void updateNotifierAlarm(void*, uint32_t, int32_t*)
- * native declaration : AthenaJava\target\native\include\HAL\Notifier.h:338 - */ - //public static native void updateNotifierAlarm(Pointer notifier_pointer, int triggerTime, IntBuffer status); - /** - * Original signature : void delayTicks(int32_t)
- * native declaration : AthenaJava\target\native\include\HAL\Utilities.h:366 - */ - public static native void delayTicks(int ticks); - /** - * Original signature : void delayMillis(double)
- * native declaration : AthenaJava\target\native\include\HAL\Utilities.h:368 - */ - public static native void delayMillis(double ms); - /** - * Original signature : void delaySeconds(double)
- * native declaration : AthenaJava\target\native\include\HAL\Utilities.h:370 - */ - public static native void delaySeconds(double s); - /** - * Original signature : MUTEX_ID initializeMutex(uint32_t)
- * native declaration : AthenaJava\target\native\include\HAL\Semaphore.h:385 - */ - public static native ByteBuffer initializeMutex(int flags); - /** - * Original signature : void deleteMutex(MUTEX_ID)
- * native declaration : AthenaJava\target\native\include\HAL\Semaphore.h:387
- * @deprecated use the safer methods {@link #deleteMutex(edu.wpi.first.wpilibj.hal.HALLibrary.MUTEX_ID)} and {@link #deleteMutex(com.sun.jna.Pointer)} instead - */ - //@Deprecated - //public static native void deleteMutex(Pointer sem); - /** - * Original signature : void deleteMutex(MUTEX_ID)
- * native declaration : AthenaJava\target\native\include\HAL\Semaphore.h:387 - */ - public static native void deleteMutex(ByteBuffer sem); - /** - * Original signature : int8_t takeMutex(MUTEX_ID, int32_t)
- * native declaration : AthenaJava\target\native\include\HAL\Semaphore.h:389
- * @deprecated use the safer methods {@link #takeMutex(edu.wpi.first.wpilibj.hal.HALLibrary.MUTEX_ID, int)} and {@link #takeMutex(com.sun.jna.Pointer, int)} instead - */ - //@Deprecated - //public static native byte takeMutex(Pointer sem, int timeout); - /** - * Original signature : int8_t takeMutex(MUTEX_ID, int32_t)
- * native declaration : AthenaJava\target\native\include\HAL\Semaphore.h:389 - */ - public static native byte takeMutex(ByteBuffer sem, int timeout); - /** - * Original signature : int8_t giveMutex(MUTEX_ID)
- * native declaration : AthenaJava\target\native\include\HAL\Semaphore.h:391
- * @deprecated use the safer methods {@link #giveMutex(edu.wpi.first.wpilibj.hal.HALLibrary.MUTEX_ID)} and {@link #giveMutex(com.sun.jna.Pointer)} instead - */ - //@Deprecated - //public static native byte giveMutex(Pointer sem); - /** - * Original signature : int8_t giveMutex(MUTEX_ID)
- * native declaration : AthenaJava\target\native\include\HAL\Semaphore.h:391 - */ - //public static native byte giveMutex(HALLibrary.MUTEX_ID sem); - /** - * Original signature : SEMAPHORE_ID initializeSemaphore(uint32_t, uint32_t)
- * native declaration : AthenaJava\target\native\include\HAL\Semaphore.h:393 - */ - //public static native HALLibrary.SEMAPHORE_ID initializeSemaphore(int flags, int initial_value); - /** - * Original signature : void deleteSemaphore(SEMAPHORE_ID)
- * native declaration : AthenaJava\target\native\include\HAL\Semaphore.h:395
- * @deprecated use the safer methods {@link #deleteSemaphore(edu.wpi.first.wpilibj.hal.HALLibrary.SEMAPHORE_ID)} and {@link #deleteSemaphore(com.sun.jna.Pointer)} instead - */ - //@Deprecated - //public static native void deleteSemaphore(Pointer sem); - /** - * Original signature : void deleteSemaphore(SEMAPHORE_ID)
- * native declaration : AthenaJava\target\native\include\HAL\Semaphore.h:395 - */ - //public static native void deleteSemaphore(HALLibrary.SEMAPHORE_ID sem); - /** - * Original signature : int8_t takeSemaphore(SEMAPHORE_ID, int32_t)
- * native declaration : AthenaJava\target\native\include\HAL\Semaphore.h:397
- * @deprecated use the safer methods {@link #takeSemaphore(edu.wpi.first.wpilibj.hal.HALLibrary.SEMAPHORE_ID, int)} and {@link #takeSemaphore(com.sun.jna.Pointer, int)} instead - */ - //@Deprecated - //public static native byte takeSemaphore(Pointer sem, int timeout); - /** - * Original signature : int8_t takeSemaphore(SEMAPHORE_ID, int32_t)
- * native declaration : AthenaJava\target\native\include\HAL\Semaphore.h:397 - */ - //public static native byte takeSemaphore(HALLibrary.SEMAPHORE_ID sem, int timeout); - /** - * Original signature : int8_t giveSemaphore(SEMAPHORE_ID)
- * native declaration : AthenaJava\target\native\include\HAL\Semaphore.h:399
- * @deprecated use the safer methods {@link #giveSemaphore(edu.wpi.first.wpilibj.hal.HALLibrary.SEMAPHORE_ID)} and {@link #giveSemaphore(com.sun.jna.Pointer)} instead - */ - //@Deprecated - //public static native byte giveSemaphore(Pointer sem); - /** - * Original signature : int8_t giveSemaphore(SEMAPHORE_ID)
- * native declaration : AthenaJava\target\native\include\HAL\Semaphore.h:399 - */ - //public static native byte giveSemaphore(HALLibrary.SEMAPHORE_ID sem); - /** - * Original signature : MULTIWAIT_ID initializeMultiWait()
- * native declaration : AthenaJava\target\native\include\HAL\Semaphore.h:401 - */ - //public static native HALLibrary.MULTIWAIT_ID initializeMultiWait(); - /** - * Original signature : void deleteMultiWait(MULTIWAIT_ID)
- * native declaration : AthenaJava\target\native\include\HAL\Semaphore.h:403
- * @deprecated use the safer methods {@link #deleteMultiWait(edu.wpi.first.wpilibj.hal.HALLibrary.MULTIWAIT_ID)} and {@link #deleteMultiWait(com.sun.jna.Pointer)} instead - */ - //@Deprecated - //public static native void deleteMultiWait(Pointer sem); - /** - * Original signature : void deleteMultiWait(MULTIWAIT_ID)
- * native declaration : AthenaJava\target\native\include\HAL\Semaphore.h:403 - */ - //public static native void deleteMultiWait(HALLibrary.MULTIWAIT_ID sem); - /** - * Original signature : int8_t takeMultiWait(MULTIWAIT_ID, int32_t)
- * native declaration : AthenaJava\target\native\include\HAL\Semaphore.h:405
- * @deprecated use the safer methods {@link #takeMultiWait(edu.wpi.first.wpilibj.hal.HALLibrary.MULTIWAIT_ID, int)} and {@link #takeMultiWait(com.sun.jna.Pointer, int)} instead - */ - //@Deprecated - //public static native byte takeMultiWait(Pointer sem, int timeout); - /** - * Original signature : int8_t takeMultiWait(MULTIWAIT_ID, int32_t)
- * native declaration : AthenaJava\target\native\include\HAL\Semaphore.h:405 - */ - //public static native byte takeMultiWait(HALLibrary.MULTIWAIT_ID sem, int timeout); - /** - * Original signature : int8_t giveMultiWait(MULTIWAIT_ID)
- * native declaration : AthenaJava\target\native\include\HAL\Semaphore.h:407
- * @deprecated use the safer methods {@link #giveMultiWait(edu.wpi.first.wpilibj.hal.HALLibrary.MULTIWAIT_ID)} and {@link #giveMultiWait(com.sun.jna.Pointer)} instead - */ - //@Deprecated - //public static native byte giveMultiWait(Pointer sem); - /** - * Original signature : int8_t giveMultiWait(MULTIWAIT_ID)
- * native declaration : AthenaJava\target\native\include\HAL\Semaphore.h:407 - */ - //public static native byte giveMultiWait(HALLibrary.MULTIWAIT_ID sem); - /** - * Original signature : TASK spawnTask(char*, int, int, int, FUNCPTR, uint32_t, uint32_t, uint32_t, uint32_t, uint32_t, uint32_t, uint32_t, uint32_t, uint32_t, uint32_t)
- * native declaration : AthenaJava\target\native\include\HAL\Task.h:420
- * @deprecated use the safer methods {@link #spawnTask(java.nio.ByteBuffer, int, int, int, edu.wpi.first.wpilibj.hal.HALLibrary.FUNCPTR, int, int, int, int, int, int, int, int, int, int)} and {@link #spawnTask(com.sun.jna.Pointer, int, int, int, edu.wpi.first.wpilibj.hal.HALLibrary.FUNCPTR, int, int, int, int, int, int, int, int, int, int)} instead - */ - //@Deprecated - //public static native HALLibrary.TASK spawnTask(Pointer name, int priority, int options, int stackSize, HALLibrary.FUNCPTR entryPt, int arg0, int arg1, int arg2, int arg3, int arg4, int arg5, int arg6, int arg7, int arg8, int arg9); - /** - * Original signature : TASK spawnTask(char*, int, int, int, FUNCPTR, uint32_t, uint32_t, uint32_t, uint32_t, uint32_t, uint32_t, uint32_t, uint32_t, uint32_t, uint32_t)
- * native declaration : AthenaJava\target\native\include\HAL\Task.h:420 - */ - //public static native HALLibrary.TASK spawnTask(ByteBuffer name, int priority, int options, int stackSize, HALLibrary.FUNCPTR entryPt, int arg0, int arg1, int arg2, int arg3, int arg4, int arg5, int arg6, int arg7, int arg8, int arg9); - /** - * Original signature : STATUS restartTask(TASK)
- * native declaration : AthenaJava\target\native\include\HAL\Task.h:422
- * @deprecated use the safer methods {@link #restartTask(edu.wpi.first.wpilibj.hal.HALLibrary.TASK)} and {@link #restartTask(com.sun.jna.Pointer)} instead - */ - //@Deprecated - //public static native int restartTask(Pointer task); - /** - * Original signature : STATUS restartTask(TASK)
- * native declaration : AthenaJava\target\native\include\HAL\Task.h:422 - */ - //public static native int restartTask(HALLibrary.TASK task); - /** - * Original signature : STATUS deleteTask(TASK)
- * native declaration : AthenaJava\target\native\include\HAL\Task.h:424
- * @deprecated use the safer methods {@link #deleteTask(edu.wpi.first.wpilibj.hal.HALLibrary.TASK)} and {@link #deleteTask(com.sun.jna.Pointer)} instead - */ - //@Deprecated - //public static native int deleteTask(Pointer task); - /** - * Original signature : STATUS deleteTask(TASK)
- * native declaration : AthenaJava\target\native\include\HAL\Task.h:424 - */ - //public static native int deleteTask(HALLibrary.TASK task); - /** - * Original signature : STATUS isTaskReady(TASK)
- * native declaration : AthenaJava\target\native\include\HAL\Task.h:426
- * @deprecated use the safer methods {@link #isTaskReady(edu.wpi.first.wpilibj.hal.HALLibrary.TASK)} and {@link #isTaskReady(com.sun.jna.Pointer)} instead - */ - //@Deprecated - //public static native int isTaskReady(Pointer task); - /** - * Original signature : STATUS isTaskReady(TASK)
- * native declaration : AthenaJava\target\native\include\HAL\Task.h:426 - */ - //public static native int isTaskReady(HALLibrary.TASK task); - /** - * Original signature : STATUS isTaskSuspended(TASK)
- * native declaration : AthenaJava\target\native\include\HAL\Task.h:428
- * @deprecated use the safer methods {@link #isTaskSuspended(edu.wpi.first.wpilibj.hal.HALLibrary.TASK)} and {@link #isTaskSuspended(com.sun.jna.Pointer)} instead - */ - //@Deprecated - //public static native int isTaskSuspended(Pointer task); - /** - * Original signature : STATUS isTaskSuspended(TASK)
- * native declaration : AthenaJava\target\native\include\HAL\Task.h:428 - */ - //public static native int isTaskSuspended(HALLibrary.TASK task); - /** - * Original signature : STATUS suspendTask(TASK)
- * native declaration : AthenaJava\target\native\include\HAL\Task.h:430
- * @deprecated use the safer methods {@link #suspendTask(edu.wpi.first.wpilibj.hal.HALLibrary.TASK)} and {@link #suspendTask(com.sun.jna.Pointer)} instead - */ - //@Deprecated - //public static native int suspendTask(Pointer task); - /** - * Original signature : STATUS suspendTask(TASK)
- * native declaration : AthenaJava\target\native\include\HAL\Task.h:430 - */ - //public static native int suspendTask(HALLibrary.TASK task); - /** - * Original signature : STATUS resumeTask(TASK)
- * native declaration : AthenaJava\target\native\include\HAL\Task.h:432
- * @deprecated use the safer methods {@link #resumeTask(edu.wpi.first.wpilibj.hal.HALLibrary.TASK)} and {@link #resumeTask(com.sun.jna.Pointer)} instead - */ - //@Deprecated - //public static native int resumeTask(Pointer task); - /** - * Original signature : STATUS resumeTask(TASK)
- * native declaration : AthenaJava\target\native\include\HAL\Task.h:432 - */ - //public static native int resumeTask(HALLibrary.TASK task); - /** - * Original signature : STATUS verifyTaskID(TASK)
- * native declaration : AthenaJava\target\native\include\HAL\Task.h:434
- * @deprecated use the safer methods {@link #verifyTaskID(edu.wpi.first.wpilibj.hal.HALLibrary.TASK)} and {@link #verifyTaskID(com.sun.jna.Pointer)} instead - */ - //@Deprecated - //public static native int verifyTaskID(Pointer task); - /** - * Original signature : STATUS verifyTaskID(TASK)
- * native declaration : AthenaJava\target\native\include\HAL\Task.h:434 - */ - //public static native int verifyTaskID(HALLibrary.TASK task); - /** - * Original signature : STATUS setTaskPriority(TASK, int)
- * native declaration : AthenaJava\target\native\include\HAL\Task.h:436
- * @deprecated use the safer methods {@link #setTaskPriority(edu.wpi.first.wpilibj.hal.HALLibrary.TASK, int)} and {@link #setTaskPriority(com.sun.jna.Pointer, int)} instead - */ - //@Deprecated - //public static native int setTaskPriority(Pointer task, int priority); - /** - * Original signature : STATUS setTaskPriority(TASK, int)
- * native declaration : AthenaJava\target\native\include\HAL\Task.h:436 - */ - //public static native int setTaskPriority(HALLibrary.TASK task, int priority); - /** - * Original signature : STATUS getTaskPriority(TASK, int*)
- * native declaration : AthenaJava\target\native\include\HAL\Task.h:438
- * @deprecated use the safer methods {@link #getTaskPriority(edu.wpi.first.wpilibj.hal.HALLibrary.TASK, java.nio.IntBuffer)} and {@link #getTaskPriority(com.sun.jna.Pointer, com.sun.jna.ptr.IntByReference)} instead - */ - //@Deprecated - //public static native int getTaskPriority(Pointer task, IntByReference priority); - /** - * Original signature : STATUS getTaskPriority(TASK, int*)
- * native declaration : AthenaJava\target\native\include\HAL\Task.h:438 - */ - //public static native int getTaskPriority(HALLibrary.TASK task, IntBuffer priority); - /** - * Original signature : void* getPort(uint8_t)
- * native declaration : AthenaJava\target\native\include\HAL\HAL.h:446 - */ - //public static native Pointer getPort(byte pin); - /** - * Original signature : uint16_t getFPGAVersion(int32_t*)
- * native declaration : AthenaJava\target\native\include\HAL\HAL.h:452
- * @deprecated use the safer methods {@link #getFPGAVersion(java.nio.IntBuffer)} and {@link #getFPGAVersion(com.sun.jna.ptr.IntByReference)} instead - */ - //@Deprecated - //public static native short getFPGAVersion(IntByReference status); - /** - * Original signature : uint16_t getFPGAVersion(int32_t*)
- * native declaration : AthenaJava\target\native\include\HAL\HAL.h:452 - */ - //public static native short getFPGAVersion(IntBuffer status); - /** - * Original signature : uint32_t getFPGARevision(int32_t*)
- * native declaration : AthenaJava\target\native\include\HAL\HAL.h:454
- * @deprecated use the safer methods {@link #getFPGARevision(java.nio.IntBuffer)} and {@link #getFPGARevision(com.sun.jna.ptr.IntByReference)} instead - */ - //@Deprecated - //public static native int getFPGARevision(IntByReference status); - /** - * Original signature : uint32_t getFPGARevision(int32_t*)
- * native declaration : AthenaJava\target\native\include\HAL\HAL.h:454 - */ - //public static native int getFPGARevision(IntBuffer status); - /** - * Original signature : uint32_t getFPGATime(int32_t*)
- * native declaration : AthenaJava\target\native\include\HAL\HAL.h:456
- * @deprecated use the safer methods {@link #getFPGATime(java.nio.IntBuffer)} and {@link #getFPGATime(com.sun.jna.ptr.IntByReference)} instead - */ - //@Deprecated - //public static native int getFPGATime(IntByReference status); - /** - * Original signature : uint32_t getFPGATime(int32_t*)
- * native declaration : AthenaJava\target\native\include\HAL\HAL.h:456 - */ - //public static native int getFPGATime(IntBuffer status); - /** - * Original signature : double testDouble(double)
- * native declaration : AthenaJava\target\native\include\HAL\HAL.h:462 - */ - public static native double testDouble(double param); - /** - * Original signature : int32_t testInt32(int32_t)
- * native declaration : AthenaJava\target\native\include\HAL\HAL.h:464 - */ - public static native int testInt32(int param); - /** - * Original signature : void NumericArrayResize()
- * native declaration : AthenaJava\target\native\include\HAL\HAL.h:470 - */ - public static native void NumericArrayResize(); - /** - * Original signature : void RTSetCleanupProc()
- * native declaration : AthenaJava\target\native\include\HAL\HAL.h:472 - */ - public static native void RTSetCleanupProc(); - /** - * Original signature : void EDVR_CreateReference()
- * native declaration : AthenaJava\target\native\include\HAL\HAL.h:474 - */ - public static native void EDVR_CreateReference(); - /** - * Original signature : void Occur()
- * native declaration : AthenaJava\target\native\include\HAL\HAL.h:476 - */ - public static native void Occur(); - /* - public static final GlobalDouble kDefaultWatchdogExpiration = new GlobalDouble(HALLibrary.JNA_NATIVE_LIB, "kDefaultWatchdogExpiration"); - public static final GlobalInt HAL_NO_WAIT = new GlobalInt(HALLibrary.JNA_NATIVE_LIB, "HAL_NO_WAIT"); - public static final GlobalInt HAL_WAIT_FOREVER = new GlobalInt(HALLibrary.JNA_NATIVE_LIB, "HAL_WAIT_FOREVER"); - public static final GlobalInt SEMAPHORE_Q_FIFO = new GlobalInt(HALLibrary.JNA_NATIVE_LIB, "SEMAPHORE_Q_FIFO"); - */ - /* - public static final GlobalInt SEMAPHORE_DELETE_SAFE = new GlobalInt(HALLibrary.JNA_NATIVE_LIB, "SEMAPHORE_DELETE_SAFE"); - public static final GlobalInt SEMAPHORE_INVERSION_SAFE = new GlobalInt(HALLibrary.JNA_NATIVE_LIB, "SEMAPHORE_INVERSION_SAFE"); - public static final GlobalInt SEMAPHORE_NO_WAIT = new GlobalInt(HALLibrary.JNA_NATIVE_LIB, "SEMAPHORE_NO_WAIT"); - */ - /* - public static final GlobalInt SEMAPHORE_EMPTY = new GlobalInt(HALLibrary.JNA_NATIVE_LIB, "SEMAPHORE_EMPTY"); - public static final GlobalInt SEMAPHORE_FULL = new GlobalInt(HALLibrary.JNA_NATIVE_LIB, "SEMAPHORE_FULL"); - public static final GlobalInt VXWORKS_FP_TASK = new GlobalInt(HALLibrary.JNA_NATIVE_LIB, "VXWORKS_FP_TASK"); - public static final GlobalInt HAL_objLib_OBJ_ID_ERROR = new GlobalInt(HALLibrary.JNA_NATIVE_LIB, "HAL_objLib_OBJ_ID_ERROR"); - public static final GlobalInt HAL_objLib_OBJ_DELETED = new GlobalInt(HALLibrary.JNA_NATIVE_LIB, "HAL_objLib_OBJ_DELETED"); - public static final GlobalInt HAL_taskLib_ILLEGAL_OPTIONS = new GlobalInt(HALLibrary.JNA_NATIVE_LIB, "HAL_taskLib_ILLEGAL_OPTIONS"); - public static final GlobalInt HAL_memLib_NOT_ENOUGH_MEMORY = new GlobalInt(HALLibrary.JNA_NATIVE_LIB, "HAL_memLib_NOT_ENOUGH_MEMORY"); - public static final GlobalInt HAL_taskLib_ILLEGAL_PRIORITY = new GlobalInt(HALLibrary.JNA_NATIVE_LIB, "HAL_taskLib_ILLEGAL_PRIORITY"); - public static final GlobalInt dio_kNumSystems = new GlobalInt(HALLibrary.JNA_NATIVE_LIB, "dio_kNumSystems"); - public static final GlobalInt solenoid_kNumDO7_0Elements = new GlobalInt(HALLibrary.JNA_NATIVE_LIB, "solenoid_kNumDO7_0Elements"); - public static final GlobalInt interrupt_kNumSystems = new GlobalInt(HALLibrary.JNA_NATIVE_LIB, "interrupt_kNumSystems"); - public static final GlobalInt kSystemClockTicksPerMicrosecond = new GlobalInt(HALLibrary.JNA_NATIVE_LIB, "kSystemClockTicksPerMicrosecond"); - */ - /* - public static class TASK extends PointerType { - public TASK(Pointer address) { - super(address); - } - public TASK() { - super(); - } - }; - public static class MUTEX_ID extends PointerType { - public MUTEX_ID(Pointer address) { - super(address); - } - public MUTEX_ID() { - super(); - } - }; - public static class MULTIWAIT_ID extends PointerType { - public MULTIWAIT_ID(Pointer address) { - super(address); - } - public MULTIWAIT_ID() { - super(); - } - }; - public static class SEMAPHORE_ID extends PointerType { - public SEMAPHORE_ID(Pointer address) { - super(address); - } - public SEMAPHORE_ID() { - super(); - } - }; - */ +public class HALLibrary /* implements Library */{ + // public static final String JNA_LIBRARY_NAME = + // LibraryExtractor.getLibraryPath("HALAthenaJava", true, HALLibrary.class); + // public static final NativeLibrary JNA_NATIVE_LIB = + // NativeLibrary.getInstance(HALLibrary.JNA_LIBRARY_NAME, + // MangledFunctionMapper.DEFAULT_OPTIONS); + static { + System.loadLibrary("JNIWrappers"); + // Native.register(HALLibrary.class, HALLibrary.JNA_NATIVE_LIB); + } + + /** + * native declaration : + * AthenaJava\target\native\include\HAL\Digital.h:148
+ * enum values + */ + public static interface Mode { + /** + * native declaration : + * AthenaJava\target\native\include\HAL\Digital.h:144 + */ + public static final int kTwoPulse = 0; + /** + * native declaration : + * AthenaJava\target\native\include\HAL\Digital.h:145 + */ + public static final int kSemiperiod = 1; + /** + * native declaration : + * AthenaJava\target\native\include\HAL\Digital.h:146 + */ + public static final int kPulseLength = 2; + /** + * native declaration : + * AthenaJava\target\native\include\HAL\Digital.h:147 + */ + public static final int kExternalDirection = 3; + }; + /** + * native declaration : + * AthenaJava\target\native\include\HAL\Digital.h:235
+ * enum values + */ + public static interface tSPIConstants { + /** + * native declaration : + * AthenaJava\target\native\include\HAL\Digital.h:233 + */ + public static final int kReceiveFIFODepth = 512; + /** + * native declaration : + * AthenaJava\target\native\include\HAL\Digital.h:234 + */ + public static final int kTransmitFIFODepth = 512; + }; + /** + * native declaration : + * AthenaJava\target\native\include\HAL\Digital.h:241
+ * enum values + */ + public static interface tFrameMode { + /** + * native declaration : + * AthenaJava\target\native\include\HAL\Digital.h:237 + */ + public static final int kChipSelect = 0; + /** + * native declaration : + * AthenaJava\target\native\include\HAL\Digital.h:238 + */ + public static final int kPreLatchPulse = 1; + /** + * native declaration : + * AthenaJava\target\native\include\HAL\Digital.h:239 + */ + public static final int kPostLatchPulse = 2; + /** + * native declaration : + * AthenaJava\target\native\include\HAL\Digital.h:240 + */ + public static final int kPreAndPostLatchPulse = 3; + }; + + /** native declaration : AthenaJava\target\native\include\HAL\Errors.h */ + public static final String NULL_PARAMETER_MESSAGE = "A pointer parameter to a method is NULL"; + /** native declaration : AthenaJava\target\native\include\HAL\Errors.h */ + public static final String NO_AVAILABLE_RESOURCES_MESSAGE = "No available resources to allocate"; + /** native declaration : AthenaJava\target\native\include\HAL\Errors.h */ + public static final String INCOMPATIBLE_STATE_MESSAGE = + "Incompatible State: The operation cannot be completed"; + /** native declaration : AthenaJava\target\native\include\HAL\Errors.h */ + public static final String ANALOG_TRIGGER_PULSE_OUTPUT_ERROR_MESSAGE = + "Attempted to read AnalogTrigger pulse output."; + /** native declaration : AthenaJava\target\native\include\HAL\Errors.h */ + public static final int ANALOG_TRIGGER_LIMIT_ORDER_ERROR = -10; + /** native declaration : AthenaJava\target\native\include\HAL\Errors.h */ + public static final int SPI_READ_NO_DATA = 14; + /** native declaration : AthenaJava\target\native\include\HAL\Errors.h */ + public static final String VOLTAGE_OUT_OF_RANGE_MESSAGE = + "Voltage to convert to raw value is out of range [-10; 10]"; + /** native declaration : AthenaJava\target\native\include\HAL\Errors.h */ + public static final String ANALOG_TRIGGER_LIMIT_ORDER_ERROR_MESSAGE = + "AnalogTrigger limits error. Lower limit > Upper Limit"; + /** native declaration : AthenaJava\target\native\include\HAL\Errors.h */ + public static final int SPI_WRITE_NO_MOSI = 12; + /** native declaration : AthenaJava\target\native\include\HAL\Errors.h */ + public static final String PARAMETER_OUT_OF_RANGE_MESSAGE = "A parameter is out of range."; + /** native declaration : AthenaJava\target\native\include\HAL\Task.h */ + public static final int OK = 0; + /** native declaration : AthenaJava\target\native\include\HAL\Task.h */ + public static final int ERROR = (-1); + /** native declaration : AthenaJava\target\native\include\HAL\Errors.h */ + public static final String SAMPLE_RATE_TOO_HIGH_MESSAGE = "Analog module sample rate is too high"; + /** native declaration : AthenaJava\target\native\include\HAL\Errors.h */ + public static final String SPI_WRITE_NO_MOSI_MESSAGE = + "Cannot write to SPI port with no MOSI output"; + /** native declaration : AthenaJava\target\native\include\HAL\Errors.h */ + public static final int SPI_READ_NO_MISO = 13; + /** native declaration : AthenaJava\target\native\include\HAL\Errors.h */ + public static final String SPI_READ_NO_DATA_MESSAGE = "No data available to read from SPI"; + /** native declaration : AthenaJava\target\native\include\HAL\Errors.h */ + /** native declaration : AthenaJava\target\native\include\HAL\Errors.h */ + public static final String SPI_READ_NO_MISO_MESSAGE = + "Cannot read from SPI port with no MISO input"; + /** native declaration : AthenaJava\target\native\include\HAL\Errors.h */ + public static final String LOOP_TIMING_ERROR_MESSAGE = + "Digital module loop timing is not the expected value"; + + /** + * native declaration : + * AthenaJava\target\native\include\HAL\Notifier.h:339 + */ + // public interface initializeNotifier_ProcessQueue_callback extends Callback + // { + // void apply(int uint32_t1, Pointer voidPtr1); + // }; + /** + * native declaration : + * AthenaJava\target\native\include\HAL\Interrupts.h:342 + */ + /** + * native declaration : AthenaJava\target\native\include\HAL\Task.h:409 + */ + // public interface FUNCPTR extends Callback { + // int apply(Object... varargs); + // }; + /** + * Original signature : bool checkPWMChannel(void*)
+ * native declaration : + * AthenaJava\target\native\include\HAL\Digital.h:84 + */ + // public static native byte checkPWMChannel(Pointer digital_port_pointer); + /** + * Original signature : bool checkRelayChannel(void*)
+ * native declaration : + * AthenaJava\target\native\include\HAL\Digital.h:86 + */ + // public static native byte checkRelayChannel(Pointer digital_port_pointer); + /** + * Original signature : + * void* initializeNotifier(initializeNotifier_ProcessQueue_callback*, int32_t*) + *
+ * native declaration : + * AthenaJava\target\native\include\HAL\Notifier.h:334
+ *$ + * @deprecated use the safer methods + * {@link #initializeNotifier(edu.wpi.first.wpilibj.hal.HALLibrary.initializeNotifier_ProcessQueue_callback, java.nio.IntBuffer)} + * and + * {@link #initializeNotifier(edu.wpi.first.wpilibj.hal.HALLibrary.initializeNotifier_ProcessQueue_callback, com.sun.jna.ptr.IntByReference)} + * instead + */ + // @Deprecated + // public static native Pointer + // initializeNotifier(HALLibrary.initializeNotifier_ProcessQueue_callback + // ProcessQueue, IntByReference status); + /** + * Original signature : + * void* initializeNotifier(initializeNotifier_ProcessQueue_callback*, int32_t*) + *
+ * native declaration : + * AthenaJava\target\native\include\HAL\Notifier.h:334 + */ + // public static native Pointer + // initializeNotifier(HALLibrary.initializeNotifier_ProcessQueue_callback + // ProcessQueue, IntBuffer status); + /** + * Original signature : void cleanNotifier(void*, int32_t*)
+ * native declaration : + * AthenaJava\target\native\include\HAL\Notifier.h:336
+ *$ + * @deprecated use the safer methods + * {@link #cleanNotifier(com.sun.jna.Pointer, java.nio.IntBuffer)} + * and + * {@link #cleanNotifier(com.sun.jna.Pointer, com.sun.jna.ptr.IntByReference)} + * instead + */ + // @Deprecated + // public static native void cleanNotifier(Pointer notifier_pointer, + // IntByReference status); + /** + * Original signature : void cleanNotifier(void*, int32_t*)
+ * native declaration : + * AthenaJava\target\native\include\HAL\Notifier.h:336 + */ + // public static native void cleanNotifier(Pointer notifier_pointer, IntBuffer + // status); + /** + * Original signature : + * void updateNotifierAlarm(void*, uint32_t, int32_t*)
+ * native declaration : + * AthenaJava\target\native\include\HAL\Notifier.h:338
+ *$ + * @deprecated use the safer methods + * {@link #updateNotifierAlarm(com.sun.jna.Pointer, int, java.nio.IntBuffer)} + * and + * {@link #updateNotifierAlarm(com.sun.jna.Pointer, int, com.sun.jna.ptr.IntByReference)} + * instead + */ + // @Deprecated + // public static native void updateNotifierAlarm(Pointer notifier_pointer, int + // triggerTime, IntByReference status); + /** + * Original signature : + * void updateNotifierAlarm(void*, uint32_t, int32_t*)
+ * native declaration : + * AthenaJava\target\native\include\HAL\Notifier.h:338 + */ + // public static native void updateNotifierAlarm(Pointer notifier_pointer, int + // triggerTime, IntBuffer status); + /** + * Original signature : void delayTicks(int32_t)
+ * native declaration : + * AthenaJava\target\native\include\HAL\Utilities.h:366 + */ + public static native void delayTicks(int ticks); + + /** + * Original signature : void delayMillis(double)
+ * native declaration : + * AthenaJava\target\native\include\HAL\Utilities.h:368 + */ + public static native void delayMillis(double ms); + + /** + * Original signature : void delaySeconds(double)
+ * native declaration : + * AthenaJava\target\native\include\HAL\Utilities.h:370 + */ + public static native void delaySeconds(double s); + + /** + * Original signature : MUTEX_ID initializeMutex(uint32_t)
+ * native declaration : + * AthenaJava\target\native\include\HAL\Semaphore.h:385 + */ + public static native ByteBuffer initializeMutex(int flags); + + /** + * Original signature : void deleteMutex(MUTEX_ID)
+ * native declaration : + * AthenaJava\target\native\include\HAL\Semaphore.h:387
+ *$ + * @deprecated use the safer methods + * {@link #deleteMutex(edu.wpi.first.wpilibj.hal.HALLibrary.MUTEX_ID)} + * and {@link #deleteMutex(com.sun.jna.Pointer)} instead + */ + // @Deprecated + // public static native void deleteMutex(Pointer sem); + /** + * Original signature : void deleteMutex(MUTEX_ID)
+ * native declaration : + * AthenaJava\target\native\include\HAL\Semaphore.h:387 + */ + public static native void deleteMutex(ByteBuffer sem); + + /** + * Original signature : int8_t takeMutex(MUTEX_ID, int32_t)
+ * native declaration : + * AthenaJava\target\native\include\HAL\Semaphore.h:389
+ *$ + * @deprecated use the safer methods + * {@link #takeMutex(edu.wpi.first.wpilibj.hal.HALLibrary.MUTEX_ID, int)} + * and {@link #takeMutex(com.sun.jna.Pointer, int)} instead + */ + // @Deprecated + // public static native byte takeMutex(Pointer sem, int timeout); + /** + * Original signature : int8_t takeMutex(MUTEX_ID, int32_t)
+ * native declaration : + * AthenaJava\target\native\include\HAL\Semaphore.h:389 + */ + public static native byte takeMutex(ByteBuffer sem, int timeout); + + /** + * Original signature : int8_t giveMutex(MUTEX_ID)
+ * native declaration : + * AthenaJava\target\native\include\HAL\Semaphore.h:391
+ *$ + * @deprecated use the safer methods + * {@link #giveMutex(edu.wpi.first.wpilibj.hal.HALLibrary.MUTEX_ID)} + * and {@link #giveMutex(com.sun.jna.Pointer)} instead + */ + // @Deprecated + // public static native byte giveMutex(Pointer sem); + /** + * Original signature : int8_t giveMutex(MUTEX_ID)
+ * native declaration : + * AthenaJava\target\native\include\HAL\Semaphore.h:391 + */ + // public static native byte giveMutex(HALLibrary.MUTEX_ID sem); + /** + * Original signature : + * SEMAPHORE_ID initializeSemaphore(uint32_t, uint32_t)
+ * native declaration : + * AthenaJava\target\native\include\HAL\Semaphore.h:393 + */ + // public static native HALLibrary.SEMAPHORE_ID initializeSemaphore(int flags, + // int initial_value); + /** + * Original signature : void deleteSemaphore(SEMAPHORE_ID)
+ * native declaration : + * AthenaJava\target\native\include\HAL\Semaphore.h:395
+ *$ + * @deprecated use the safer methods + * {@link #deleteSemaphore(edu.wpi.first.wpilibj.hal.HALLibrary.SEMAPHORE_ID)} + * and {@link #deleteSemaphore(com.sun.jna.Pointer)} instead + */ + // @Deprecated + // public static native void deleteSemaphore(Pointer sem); + /** + * Original signature : void deleteSemaphore(SEMAPHORE_ID)
+ * native declaration : + * AthenaJava\target\native\include\HAL\Semaphore.h:395 + */ + // public static native void deleteSemaphore(HALLibrary.SEMAPHORE_ID sem); + /** + * Original signature : + * int8_t takeSemaphore(SEMAPHORE_ID, int32_t)
+ * native declaration : + * AthenaJava\target\native\include\HAL\Semaphore.h:397
+ *$ + * @deprecated use the safer methods + * {@link #takeSemaphore(edu.wpi.first.wpilibj.hal.HALLibrary.SEMAPHORE_ID, int)} + * and {@link #takeSemaphore(com.sun.jna.Pointer, int)} instead + */ + // @Deprecated + // public static native byte takeSemaphore(Pointer sem, int timeout); + /** + * Original signature : + * int8_t takeSemaphore(SEMAPHORE_ID, int32_t)
+ * native declaration : + * AthenaJava\target\native\include\HAL\Semaphore.h:397 + */ + // public static native byte takeSemaphore(HALLibrary.SEMAPHORE_ID sem, int + // timeout); + /** + * Original signature : int8_t giveSemaphore(SEMAPHORE_ID)
+ * native declaration : + * AthenaJava\target\native\include\HAL\Semaphore.h:399
+ *$ + * @deprecated use the safer methods + * {@link #giveSemaphore(edu.wpi.first.wpilibj.hal.HALLibrary.SEMAPHORE_ID)} + * and {@link #giveSemaphore(com.sun.jna.Pointer)} instead + */ + // @Deprecated + // public static native byte giveSemaphore(Pointer sem); + /** + * Original signature : int8_t giveSemaphore(SEMAPHORE_ID)
+ * native declaration : + * AthenaJava\target\native\include\HAL\Semaphore.h:399 + */ + // public static native byte giveSemaphore(HALLibrary.SEMAPHORE_ID sem); + /** + * Original signature : MULTIWAIT_ID initializeMultiWait()
+ * native declaration : + * AthenaJava\target\native\include\HAL\Semaphore.h:401 + */ + // public static native HALLibrary.MULTIWAIT_ID initializeMultiWait(); + /** + * Original signature : void deleteMultiWait(MULTIWAIT_ID)
+ * native declaration : + * AthenaJava\target\native\include\HAL\Semaphore.h:403
+ *$ + * @deprecated use the safer methods + * {@link #deleteMultiWait(edu.wpi.first.wpilibj.hal.HALLibrary.MULTIWAIT_ID)} + * and {@link #deleteMultiWait(com.sun.jna.Pointer)} instead + */ + // @Deprecated + // public static native void deleteMultiWait(Pointer sem); + /** + * Original signature : void deleteMultiWait(MULTIWAIT_ID)
+ * native declaration : + * AthenaJava\target\native\include\HAL\Semaphore.h:403 + */ + // public static native void deleteMultiWait(HALLibrary.MULTIWAIT_ID sem); + /** + * Original signature : + * int8_t takeMultiWait(MULTIWAIT_ID, int32_t)
+ * native declaration : + * AthenaJava\target\native\include\HAL\Semaphore.h:405
+ *$ + * @deprecated use the safer methods + * {@link #takeMultiWait(edu.wpi.first.wpilibj.hal.HALLibrary.MULTIWAIT_ID, int)} + * and {@link #takeMultiWait(com.sun.jna.Pointer, int)} instead + */ + // @Deprecated + // public static native byte takeMultiWait(Pointer sem, int timeout); + /** + * Original signature : + * int8_t takeMultiWait(MULTIWAIT_ID, int32_t)
+ * native declaration : + * AthenaJava\target\native\include\HAL\Semaphore.h:405 + */ + // public static native byte takeMultiWait(HALLibrary.MULTIWAIT_ID sem, int + // timeout); + /** + * Original signature : int8_t giveMultiWait(MULTIWAIT_ID)
+ * native declaration : + * AthenaJava\target\native\include\HAL\Semaphore.h:407
+ *$ + * @deprecated use the safer methods + * {@link #giveMultiWait(edu.wpi.first.wpilibj.hal.HALLibrary.MULTIWAIT_ID)} + * and {@link #giveMultiWait(com.sun.jna.Pointer)} instead + */ + // @Deprecated + // public static native byte giveMultiWait(Pointer sem); + /** + * Original signature : int8_t giveMultiWait(MULTIWAIT_ID)
+ * native declaration : + * AthenaJava\target\native\include\HAL\Semaphore.h:407 + */ + // public static native byte giveMultiWait(HALLibrary.MULTIWAIT_ID sem); + /** + * Original signature : + * TASK spawnTask(char*, int, int, int, FUNCPTR, uint32_t, uint32_t, uint32_t, uint32_t, uint32_t, uint32_t, uint32_t, uint32_t, uint32_t, uint32_t) + *
+ * native declaration : AthenaJava\target\native\include\HAL\Task.h:420
+ *$ + * @deprecated use the safer methods + * {@link #spawnTask(java.nio.ByteBuffer, int, int, int, edu.wpi.first.wpilibj.hal.HALLibrary.FUNCPTR, int, int, int, int, int, int, int, int, int, int)} + * and + * {@link #spawnTask(com.sun.jna.Pointer, int, int, int, edu.wpi.first.wpilibj.hal.HALLibrary.FUNCPTR, int, int, int, int, int, int, int, int, int, int)} + * instead + */ + // @Deprecated + // public static native HALLibrary.TASK spawnTask(Pointer name, int priority, + // int options, int stackSize, HALLibrary.FUNCPTR entryPt, int arg0, int arg1, + // int arg2, int arg3, int arg4, int arg5, int arg6, int arg7, int arg8, int + // arg9); + /** + * Original signature : + * TASK spawnTask(char*, int, int, int, FUNCPTR, uint32_t, uint32_t, uint32_t, uint32_t, uint32_t, uint32_t, uint32_t, uint32_t, uint32_t, uint32_t) + *
+ * native declaration : AthenaJava\target\native\include\HAL\Task.h:420 + */ + // public static native HALLibrary.TASK spawnTask(ByteBuffer name, int + // priority, int options, int stackSize, HALLibrary.FUNCPTR entryPt, int arg0, + // int arg1, int arg2, int arg3, int arg4, int arg5, int arg6, int arg7, int + // arg8, int arg9); + /** + * Original signature : STATUS restartTask(TASK)
+ * native declaration : AthenaJava\target\native\include\HAL\Task.h:422
+ *$ + * @deprecated use the safer methods + * {@link #restartTask(edu.wpi.first.wpilibj.hal.HALLibrary.TASK)} + * and {@link #restartTask(com.sun.jna.Pointer)} instead + */ + // @Deprecated + // public static native int restartTask(Pointer task); + /** + * Original signature : STATUS restartTask(TASK)
+ * native declaration : AthenaJava\target\native\include\HAL\Task.h:422 + */ + // public static native int restartTask(HALLibrary.TASK task); + /** + * Original signature : STATUS deleteTask(TASK)
+ * native declaration : AthenaJava\target\native\include\HAL\Task.h:424
+ *$ + * @deprecated use the safer methods + * {@link #deleteTask(edu.wpi.first.wpilibj.hal.HALLibrary.TASK)} + * and {@link #deleteTask(com.sun.jna.Pointer)} instead + */ + // @Deprecated + // public static native int deleteTask(Pointer task); + /** + * Original signature : STATUS deleteTask(TASK)
+ * native declaration : AthenaJava\target\native\include\HAL\Task.h:424 + */ + // public static native int deleteTask(HALLibrary.TASK task); + /** + * Original signature : STATUS isTaskReady(TASK)
+ * native declaration : AthenaJava\target\native\include\HAL\Task.h:426
+ *$ + * @deprecated use the safer methods + * {@link #isTaskReady(edu.wpi.first.wpilibj.hal.HALLibrary.TASK)} + * and {@link #isTaskReady(com.sun.jna.Pointer)} instead + */ + // @Deprecated + // public static native int isTaskReady(Pointer task); + /** + * Original signature : STATUS isTaskReady(TASK)
+ * native declaration : AthenaJava\target\native\include\HAL\Task.h:426 + */ + // public static native int isTaskReady(HALLibrary.TASK task); + /** + * Original signature : STATUS isTaskSuspended(TASK)
+ * native declaration : AthenaJava\target\native\include\HAL\Task.h:428
+ *$ + * @deprecated use the safer methods + * {@link #isTaskSuspended(edu.wpi.first.wpilibj.hal.HALLibrary.TASK)} + * and {@link #isTaskSuspended(com.sun.jna.Pointer)} instead + */ + // @Deprecated + // public static native int isTaskSuspended(Pointer task); + /** + * Original signature : STATUS isTaskSuspended(TASK)
+ * native declaration : AthenaJava\target\native\include\HAL\Task.h:428 + */ + // public static native int isTaskSuspended(HALLibrary.TASK task); + /** + * Original signature : STATUS suspendTask(TASK)
+ * native declaration : AthenaJava\target\native\include\HAL\Task.h:430
+ *$ + * @deprecated use the safer methods + * {@link #suspendTask(edu.wpi.first.wpilibj.hal.HALLibrary.TASK)} + * and {@link #suspendTask(com.sun.jna.Pointer)} instead + */ + // @Deprecated + // public static native int suspendTask(Pointer task); + /** + * Original signature : STATUS suspendTask(TASK)
+ * native declaration : AthenaJava\target\native\include\HAL\Task.h:430 + */ + // public static native int suspendTask(HALLibrary.TASK task); + /** + * Original signature : STATUS resumeTask(TASK)
+ * native declaration : AthenaJava\target\native\include\HAL\Task.h:432
+ *$ + * @deprecated use the safer methods + * {@link #resumeTask(edu.wpi.first.wpilibj.hal.HALLibrary.TASK)} + * and {@link #resumeTask(com.sun.jna.Pointer)} instead + */ + // @Deprecated + // public static native int resumeTask(Pointer task); + /** + * Original signature : STATUS resumeTask(TASK)
+ * native declaration : AthenaJava\target\native\include\HAL\Task.h:432 + */ + // public static native int resumeTask(HALLibrary.TASK task); + /** + * Original signature : STATUS verifyTaskID(TASK)
+ * native declaration : AthenaJava\target\native\include\HAL\Task.h:434
+ *$ + * @deprecated use the safer methods + * {@link #verifyTaskID(edu.wpi.first.wpilibj.hal.HALLibrary.TASK)} + * and {@link #verifyTaskID(com.sun.jna.Pointer)} instead + */ + // @Deprecated + // public static native int verifyTaskID(Pointer task); + /** + * Original signature : STATUS verifyTaskID(TASK)
+ * native declaration : AthenaJava\target\native\include\HAL\Task.h:434 + */ + // public static native int verifyTaskID(HALLibrary.TASK task); + /** + * Original signature : STATUS setTaskPriority(TASK, int)
+ * native declaration : AthenaJava\target\native\include\HAL\Task.h:436
+ *$ + * @deprecated use the safer methods + * {@link #setTaskPriority(edu.wpi.first.wpilibj.hal.HALLibrary.TASK, int)} + * and {@link #setTaskPriority(com.sun.jna.Pointer, int)} instead + */ + // @Deprecated + // public static native int setTaskPriority(Pointer task, int priority); + /** + * Original signature : STATUS setTaskPriority(TASK, int)
+ * native declaration : AthenaJava\target\native\include\HAL\Task.h:436 + */ + // public static native int setTaskPriority(HALLibrary.TASK task, int + // priority); + /** + * Original signature : STATUS getTaskPriority(TASK, int*)
+ * native declaration : AthenaJava\target\native\include\HAL\Task.h:438
+ *$ + * @deprecated use the safer methods + * {@link #getTaskPriority(edu.wpi.first.wpilibj.hal.HALLibrary.TASK, java.nio.IntBuffer)} + * and + * {@link #getTaskPriority(com.sun.jna.Pointer, com.sun.jna.ptr.IntByReference)} + * instead + */ + // @Deprecated + // public static native int getTaskPriority(Pointer task, IntByReference + // priority); + /** + * Original signature : STATUS getTaskPriority(TASK, int*)
+ * native declaration : AthenaJava\target\native\include\HAL\Task.h:438 + */ + // public static native int getTaskPriority(HALLibrary.TASK task, IntBuffer + // priority); + /** + * Original signature : void* getPort(uint8_t)
+ * native declaration : AthenaJava\target\native\include\HAL\HAL.h:446 + */ + // public static native Pointer getPort(byte pin); + /** + * Original signature : uint16_t getFPGAVersion(int32_t*)
+ * native declaration : AthenaJava\target\native\include\HAL\HAL.h:452
+ *$ + * @deprecated use the safer methods + * {@link #getFPGAVersion(java.nio.IntBuffer)} and + * {@link #getFPGAVersion(com.sun.jna.ptr.IntByReference)} instead + */ + // @Deprecated + // public static native short getFPGAVersion(IntByReference status); + /** + * Original signature : uint16_t getFPGAVersion(int32_t*)
+ * native declaration : AthenaJava\target\native\include\HAL\HAL.h:452 + */ + // public static native short getFPGAVersion(IntBuffer status); + /** + * Original signature : uint32_t getFPGARevision(int32_t*)
+ * native declaration : AthenaJava\target\native\include\HAL\HAL.h:454
+ *$ + * @deprecated use the safer methods + * {@link #getFPGARevision(java.nio.IntBuffer)} and + * {@link #getFPGARevision(com.sun.jna.ptr.IntByReference)} + * instead + */ + // @Deprecated + // public static native int getFPGARevision(IntByReference status); + /** + * Original signature : uint32_t getFPGARevision(int32_t*)
+ * native declaration : AthenaJava\target\native\include\HAL\HAL.h:454 + */ + // public static native int getFPGARevision(IntBuffer status); + /** + * Original signature : uint32_t getFPGATime(int32_t*)
+ * native declaration : AthenaJava\target\native\include\HAL\HAL.h:456
+ *$ + * @deprecated use the safer methods {@link #getFPGATime(java.nio.IntBuffer)} + * and {@link #getFPGATime(com.sun.jna.ptr.IntByReference)} + * instead + */ + // @Deprecated + // public static native int getFPGATime(IntByReference status); + /** + * Original signature : uint32_t getFPGATime(int32_t*)
+ * native declaration : AthenaJava\target\native\include\HAL\HAL.h:456 + */ + // public static native int getFPGATime(IntBuffer status); + /** + * Original signature : double testDouble(double)
+ * native declaration : AthenaJava\target\native\include\HAL\HAL.h:462 + */ + public static native double testDouble(double param); + + /** + * Original signature : int32_t testInt32(int32_t)
+ * native declaration : AthenaJava\target\native\include\HAL\HAL.h:464 + */ + public static native int testInt32(int param); + + /** + * Original signature : void NumericArrayResize()
+ * native declaration : AthenaJava\target\native\include\HAL\HAL.h:470 + */ + public static native void NumericArrayResize(); + + /** + * Original signature : void RTSetCleanupProc()
+ * native declaration : AthenaJava\target\native\include\HAL\HAL.h:472 + */ + public static native void RTSetCleanupProc(); + + /** + * Original signature : void EDVR_CreateReference()
+ * native declaration : AthenaJava\target\native\include\HAL\HAL.h:474 + */ + public static native void EDVR_CreateReference(); + + /** + * Original signature : void Occur()
+ * native declaration : AthenaJava\target\native\include\HAL\HAL.h:476 + */ + public static native void Occur(); + /* + * public static final GlobalDouble kDefaultWatchdogExpiration = new + * GlobalDouble(HALLibrary.JNA_NATIVE_LIB, "kDefaultWatchdogExpiration"); + * public static final GlobalInt HAL_NO_WAIT = new + * GlobalInt(HALLibrary.JNA_NATIVE_LIB, "HAL_NO_WAIT"); public static final + * GlobalInt HAL_WAIT_FOREVER = new GlobalInt(HALLibrary.JNA_NATIVE_LIB, + * "HAL_WAIT_FOREVER"); public static final GlobalInt SEMAPHORE_Q_FIFO = new + * GlobalInt(HALLibrary.JNA_NATIVE_LIB, "SEMAPHORE_Q_FIFO"); + */ + /* + * public static final GlobalInt SEMAPHORE_DELETE_SAFE = new + * GlobalInt(HALLibrary.JNA_NATIVE_LIB, "SEMAPHORE_DELETE_SAFE"); public + * static final GlobalInt SEMAPHORE_INVERSION_SAFE = new + * GlobalInt(HALLibrary.JNA_NATIVE_LIB, "SEMAPHORE_INVERSION_SAFE"); public + * static final GlobalInt SEMAPHORE_NO_WAIT = new + * GlobalInt(HALLibrary.JNA_NATIVE_LIB, "SEMAPHORE_NO_WAIT"); + */ + /* + * public static final GlobalInt SEMAPHORE_EMPTY = new + * GlobalInt(HALLibrary.JNA_NATIVE_LIB, "SEMAPHORE_EMPTY"); public static + * final GlobalInt SEMAPHORE_FULL = new GlobalInt(HALLibrary.JNA_NATIVE_LIB, + * "SEMAPHORE_FULL"); public static final GlobalInt VXWORKS_FP_TASK = new + * GlobalInt(HALLibrary.JNA_NATIVE_LIB, "VXWORKS_FP_TASK"); public static + * final GlobalInt HAL_objLib_OBJ_ID_ERROR = new + * GlobalInt(HALLibrary.JNA_NATIVE_LIB, "HAL_objLib_OBJ_ID_ERROR"); public + * static final GlobalInt HAL_objLib_OBJ_DELETED = new + * GlobalInt(HALLibrary.JNA_NATIVE_LIB, "HAL_objLib_OBJ_DELETED"); public + * static final GlobalInt HAL_taskLib_ILLEGAL_OPTIONS = new + * GlobalInt(HALLibrary.JNA_NATIVE_LIB, "HAL_taskLib_ILLEGAL_OPTIONS"); public + * static final GlobalInt HAL_memLib_NOT_ENOUGH_MEMORY = new + * GlobalInt(HALLibrary.JNA_NATIVE_LIB, "HAL_memLib_NOT_ENOUGH_MEMORY"); + * public static final GlobalInt HAL_taskLib_ILLEGAL_PRIORITY = new + * GlobalInt(HALLibrary.JNA_NATIVE_LIB, "HAL_taskLib_ILLEGAL_PRIORITY"); + * public static final GlobalInt dio_kNumSystems = new + * GlobalInt(HALLibrary.JNA_NATIVE_LIB, "dio_kNumSystems"); public static + * final GlobalInt solenoid_kNumDO7_0Elements = new + * GlobalInt(HALLibrary.JNA_NATIVE_LIB, "solenoid_kNumDO7_0Elements"); public + * static final GlobalInt interrupt_kNumSystems = new + * GlobalInt(HALLibrary.JNA_NATIVE_LIB, "interrupt_kNumSystems"); public + * static final GlobalInt kSystemClockTicksPerMicrosecond = new + * GlobalInt(HALLibrary.JNA_NATIVE_LIB, "kSystemClockTicksPerMicrosecond"); + */ + /* + * public static class TASK extends PointerType { public TASK(Pointer address) + * { super(address); } public TASK() { super(); } }; public static class + * MUTEX_ID extends PointerType { public MUTEX_ID(Pointer address) { + * super(address); } public MUTEX_ID() { super(); } }; public static class + * MULTIWAIT_ID extends PointerType { public MULTIWAIT_ID(Pointer address) { + * super(address); } public MULTIWAIT_ID() { super(); } }; public static class + * SEMAPHORE_ID extends PointerType { public SEMAPHORE_ID(Pointer address) { + * super(address); } public SEMAPHORE_ID() { super(); } }; + */ } diff --git a/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/hal/HALUtil.java b/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/hal/HALUtil.java index 4f82bceb30..e1d6b8d9bf 100644 --- a/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/hal/HALUtil.java +++ b/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/hal/HALUtil.java @@ -5,52 +5,61 @@ import java.nio.IntBuffer; import edu.wpi.first.wpilibj.DriverStation; public class HALUtil extends JNIWrapper { - public static final int NULL_PARAMETER = -1005; - public static final int SAMPLE_RATE_TOO_HIGH = 1001; - public static final int VOLTAGE_OUT_OF_RANGE = 1002; - public static final int LOOP_TIMING_ERROR = 1004; - public static final int INCOMPATIBLE_STATE = 1015; - public static final int ANALOG_TRIGGER_PULSE_OUTPUT_ERROR = -1011; - public static final int NO_AVAILABLE_RESOURCES = -104; - public static final int PARAMETER_OUT_OF_RANGE = -1028; + public static final int NULL_PARAMETER = -1005; + public static final int SAMPLE_RATE_TOO_HIGH = 1001; + public static final int VOLTAGE_OUT_OF_RANGE = 1002; + public static final int LOOP_TIMING_ERROR = 1004; + public static final int INCOMPATIBLE_STATE = 1015; + public static final int ANALOG_TRIGGER_PULSE_OUTPUT_ERROR = -1011; + public static final int NO_AVAILABLE_RESOURCES = -104; + public static final int PARAMETER_OUT_OF_RANGE = -1028; - //public static final int SEMAPHORE_WAIT_FOREVER = -1; - //public static final int SEMAPHORE_Q_PRIORITY = 0x01; + // public static final int SEMAPHORE_WAIT_FOREVER = -1; + // public static final int SEMAPHORE_Q_PRIORITY = 0x01; - public static native ByteBuffer initializeMutexNormal(); - public static native void deleteMutex(ByteBuffer sem); - public static native byte takeMutex(ByteBuffer sem); - //public static native ByteBuffer initializeSemaphore(int initialValue); - //public static native void deleteSemaphore(ByteBuffer sem); - //public static native byte takeSemaphore(ByteBuffer sem, int timeout); - public static native ByteBuffer initializeMultiWait(); - public static native void deleteMultiWait(ByteBuffer sem); - public static native byte takeMultiWait(ByteBuffer sem, ByteBuffer m, int timeOut); - public static native short getFPGAVersion(IntBuffer status); - public static native int getFPGARevision(IntBuffer status); - public static native long getFPGATime(IntBuffer status); - public static native boolean getFPGAButton(IntBuffer status); + public static native ByteBuffer initializeMutexNormal(); - public static native String getHALErrorMessage(int code); + public static native void deleteMutex(ByteBuffer sem); - public static native int getHALErrno(); - public static native String getHALstrerror(int errno); - public static String getHALstrerror(){ - return getHALstrerror(getHALErrno()); - } + public static native byte takeMutex(ByteBuffer sem); - public static void checkStatus(IntBuffer status) - { - int s = status.get(0); - if (s < 0) - { - String message = getHALErrorMessage(s); - throw new RuntimeException(" Code: " + s + ". " + message); - } else if (s > 0) { - String message = getHALErrorMessage(s); - DriverStation.reportError(message, true); - } - } + // public static native ByteBuffer initializeSemaphore(int initialValue); + // public static native void deleteSemaphore(ByteBuffer sem); + // public static native byte takeSemaphore(ByteBuffer sem, int timeout); + public static native ByteBuffer initializeMultiWait(); + + public static native void deleteMultiWait(ByteBuffer sem); + + public static native byte takeMultiWait(ByteBuffer sem, ByteBuffer m, int timeOut); + + public static native short getFPGAVersion(IntBuffer status); + + public static native int getFPGARevision(IntBuffer status); + + public static native long getFPGATime(IntBuffer status); + + public static native boolean getFPGAButton(IntBuffer status); + + public static native String getHALErrorMessage(int code); + + public static native int getHALErrno(); + + public static native String getHALstrerror(int errno); + + public static String getHALstrerror() { + return getHALstrerror(getHALErrno()); + } + + public static void checkStatus(IntBuffer status) { + int s = status.get(0); + if (s < 0) { + String message = getHALErrorMessage(s); + throw new RuntimeException(" Code: " + s + ". " + message); + } else if (s > 0) { + String message = getHALErrorMessage(s); + DriverStation.reportError(message, true); + } + } public static native int pointerSize(); } diff --git a/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/hal/I2CJNI.java b/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/hal/I2CJNI.java index 6c646f5577..0a66c6da60 100644 --- a/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/hal/I2CJNI.java +++ b/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/hal/I2CJNI.java @@ -4,9 +4,15 @@ import java.nio.ByteBuffer; import java.nio.IntBuffer; public class I2CJNI extends JNIWrapper { - public static native void i2CInitialize(byte port, IntBuffer status); - public static native byte i2CTransaction(byte port, byte address, ByteBuffer dataToSend, byte sendSize, ByteBuffer dataReceived, byte receiveSize); - public static native byte i2CWrite(byte port, byte address, ByteBuffer dataToSend, byte sendSize); - public static native byte i2CRead(byte port, byte address, ByteBuffer dataRecieved, byte receiveSize); - public static native void i2CClose(byte port); + public static native void i2CInitialize(byte port, IntBuffer status); + + public static native byte i2CTransaction(byte port, byte address, ByteBuffer dataToSend, + byte sendSize, ByteBuffer dataReceived, byte receiveSize); + + public static native byte i2CWrite(byte port, byte address, ByteBuffer dataToSend, byte sendSize); + + public static native byte i2CRead(byte port, byte address, ByteBuffer dataRecieved, + byte receiveSize); + + public static native void i2CClose(byte port); } diff --git a/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/hal/InterruptJNI.java b/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/hal/InterruptJNI.java index b7a31cf7c5..8e8ac4203b 100644 --- a/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/hal/InterruptJNI.java +++ b/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/hal/InterruptJNI.java @@ -4,18 +4,34 @@ import java.nio.ByteBuffer; import java.nio.IntBuffer; public class InterruptJNI extends JNIWrapper { - public interface InterruptJNIHandlerFunction { - void apply(int interruptAssertedMask, Object param); - }; - public static native void initializeInterruptJVM(IntBuffer status); - public static native ByteBuffer initializeInterrupts(int interruptIndex, byte watcher, IntBuffer status); - public static native void cleanInterrupts(ByteBuffer interrupt_pointer, IntBuffer status); - public static native int waitForInterrupt(ByteBuffer interrupt_pointer, double timeout, boolean ignorePrevious, IntBuffer status); - public static native void enableInterrupts(ByteBuffer interrupt_pointer, IntBuffer status); - public static native void disableInterrupts(ByteBuffer interrupt_pointer, IntBuffer status); - public static native double readRisingTimestamp(ByteBuffer interrupt_pointer, IntBuffer status); - public static native double readFallingTimestamp(ByteBuffer interrupt_pointer, IntBuffer status); - public static native void requestInterrupts(ByteBuffer interrupt_pointer, byte routing_module, int routing_pin, byte routing_analog_trigger, IntBuffer status); - public static native void attachInterruptHandler(ByteBuffer interrupt_pointer, InterruptJNIHandlerFunction handler, Object param, IntBuffer status); - public static native void setInterruptUpSourceEdge(ByteBuffer interrupt_pointer, byte risingEdge, byte fallingEdge, IntBuffer status); + public interface InterruptJNIHandlerFunction { + void apply(int interruptAssertedMask, Object param); + }; + + public static native void initializeInterruptJVM(IntBuffer status); + + public static native ByteBuffer initializeInterrupts(int interruptIndex, byte watcher, + IntBuffer status); + + public static native void cleanInterrupts(ByteBuffer interrupt_pointer, IntBuffer status); + + public static native int waitForInterrupt(ByteBuffer interrupt_pointer, double timeout, + boolean ignorePrevious, IntBuffer status); + + public static native void enableInterrupts(ByteBuffer interrupt_pointer, IntBuffer status); + + public static native void disableInterrupts(ByteBuffer interrupt_pointer, IntBuffer status); + + public static native double readRisingTimestamp(ByteBuffer interrupt_pointer, IntBuffer status); + + public static native double readFallingTimestamp(ByteBuffer interrupt_pointer, IntBuffer status); + + public static native void requestInterrupts(ByteBuffer interrupt_pointer, byte routing_module, + int routing_pin, byte routing_analog_trigger, IntBuffer status); + + public static native void attachInterruptHandler(ByteBuffer interrupt_pointer, + InterruptJNIHandlerFunction handler, Object param, IntBuffer status); + + public static native void setInterruptUpSourceEdge(ByteBuffer interrupt_pointer, byte risingEdge, + byte fallingEdge, IntBuffer status); } diff --git a/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/hal/JNIWrapper.java b/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/hal/JNIWrapper.java index 5e3d3b66e1..fc77dddf10 100644 --- a/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/hal/JNIWrapper.java +++ b/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/hal/JNIWrapper.java @@ -9,55 +9,47 @@ import java.nio.ByteBuffer; // // base class for all JNI wrappers // -public class JNIWrapper -{ - static boolean libraryLoaded = false; - static File jniLibrary = null; - static - { - try - { - if( !libraryLoaded ) - { - // create temporary file - jniLibrary = File.createTempFile("libwpilibJavaJNI", ".so"); - // flag for delete on exit - jniLibrary.deleteOnExit(); +public class JNIWrapper { + static boolean libraryLoaded = false; + static File jniLibrary = null; + static { + try { + if (!libraryLoaded) { + // create temporary file + jniLibrary = File.createTempFile("libwpilibJavaJNI", ".so"); + // flag for delete on exit + jniLibrary.deleteOnExit(); - byte [] buffer = new byte[1024]; + byte[] buffer = new byte[1024]; - int readBytes; + int readBytes; - InputStream is = JNIWrapper.class.getResourceAsStream("/linux-arm/libwpilibJavaJNI.so"); + InputStream is = JNIWrapper.class.getResourceAsStream("/linux-arm/libwpilibJavaJNI.so"); - OutputStream os = new FileOutputStream(jniLibrary); + OutputStream os = new FileOutputStream(jniLibrary); - try - { - while((readBytes = is.read(buffer)) != -1 ) - { - os.write(buffer, 0, readBytes); - } + try { + while ((readBytes = is.read(buffer)) != -1) { + os.write(buffer, 0, readBytes); + } - } - finally - { - os.close(); - is.close(); - } + } finally { + os.close(); + is.close(); + } - libraryLoaded = true; - } + libraryLoaded = true; + } - System.load(jniLibrary.getAbsolutePath()); - } - catch( Exception ex ) - { - ex.printStackTrace(); - System.exit(1); - } - } - public static native ByteBuffer getPortWithModule(byte module, byte pin); - public static native ByteBuffer getPort(byte pin); + System.load(jniLibrary.getAbsolutePath()); + } catch (Exception ex) { + ex.printStackTrace(); + System.exit(1); + } + } + + public static native ByteBuffer getPortWithModule(byte module, byte pin); + + public static native ByteBuffer getPort(byte pin); } diff --git a/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/hal/NotifierJNI.java b/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/hal/NotifierJNI.java index c9c3dbc95f..7df2ce7317 100644 --- a/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/hal/NotifierJNI.java +++ b/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/hal/NotifierJNI.java @@ -17,19 +17,22 @@ public class NotifierJNI extends JNIWrapper { * * Should be called after initializeNotifierJVM(). */ - public static native ByteBuffer initializeNotifier(Runnable func, IntBuffer status); + public static native ByteBuffer initializeNotifier(Runnable func, IntBuffer status); + /** * Initializes the JVM for use by the callback. Should be called before * anything else. */ public static native void initializeNotifierJVM(IntBuffer status); + /** * Deletes the notifier object when we are done with it. */ - public static native void cleanNotifier(ByteBuffer notifierPtr, IntBuffer status); + public static native void cleanNotifier(ByteBuffer notifierPtr, IntBuffer status); + /** * Sets the notifier to call the callback in another triggerTime microseconds. */ - public static native void updateNotifierAlarm(ByteBuffer notifierPtr, - int triggerTime, IntBuffer status); + public static native void updateNotifierAlarm(ByteBuffer notifierPtr, int triggerTime, + IntBuffer status); } diff --git a/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/hal/PDPJNI.java b/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/hal/PDPJNI.java index f595e0a086..1623c0aa37 100644 --- a/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/hal/PDPJNI.java +++ b/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/hal/PDPJNI.java @@ -4,13 +4,21 @@ import java.nio.ByteBuffer; import java.nio.IntBuffer; public class PDPJNI extends JNIWrapper { - public static native void initializePDP(int module); - public static native double getPDPTemperature(IntBuffer status, int module); - public static native double getPDPVoltage(IntBuffer status, int module); - public static native double getPDPChannelCurrent(byte channel, IntBuffer status, int module); - public static native double getPDPTotalCurrent(IntBuffer status, int module); - public static native double getPDPTotalPower(IntBuffer status, int module); - public static native double getPDPTotalEnergy(IntBuffer status, int module); - public static native void resetPDPTotalEnergy(IntBuffer status, int module); - public static native void clearPDPStickyFaults(IntBuffer status, int module); -} \ No newline at end of file + public static native void initializePDP(int module); + + public static native double getPDPTemperature(IntBuffer status, int module); + + public static native double getPDPVoltage(IntBuffer status, int module); + + public static native double getPDPChannelCurrent(byte channel, IntBuffer status, int module); + + public static native double getPDPTotalCurrent(IntBuffer status, int module); + + public static native double getPDPTotalPower(IntBuffer status, int module); + + public static native double getPDPTotalEnergy(IntBuffer status, int module); + + public static native void resetPDPTotalEnergy(IntBuffer status, int module); + + public static native void clearPDPStickyFaults(IntBuffer status, int module); +} diff --git a/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/hal/PWMJNI.java b/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/hal/PWMJNI.java index a555c6adf1..f60fad8925 100644 --- a/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/hal/PWMJNI.java +++ b/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/hal/PWMJNI.java @@ -7,15 +7,27 @@ import edu.wpi.first.wpilibj.SensorBase; public class PWMJNI extends DIOJNI { - public static native boolean allocatePWMChannel(ByteBuffer digital_port_pointer, IntBuffer status); - public static native void freePWMChannel(ByteBuffer digital_port_pointer, IntBuffer status); - public static native void setPWM(ByteBuffer digital_port_pointer, short value, IntBuffer status); - public static native short getPWM(ByteBuffer digital_port_pointer, IntBuffer status); - public static native void latchPWMZero(ByteBuffer digital_port_pointer, IntBuffer status); - public static native void setPWMPeriodScale(ByteBuffer digital_port_pointer, int squelchMask, IntBuffer status); - public static native ByteBuffer allocatePWM(IntBuffer status); - public static native void freePWM(ByteBuffer pwmGenerator, IntBuffer status); - public static native void setPWMRate(double rate, IntBuffer status); - public static native void setPWMDutyCycle(ByteBuffer pwmGenerator, double dutyCycle, IntBuffer status); - public static native void setPWMOutputChannel(ByteBuffer pwmGenerator, int pin, IntBuffer status); + public static native boolean allocatePWMChannel(ByteBuffer digital_port_pointer, IntBuffer status); + + public static native void freePWMChannel(ByteBuffer digital_port_pointer, IntBuffer status); + + public static native void setPWM(ByteBuffer digital_port_pointer, short value, IntBuffer status); + + public static native short getPWM(ByteBuffer digital_port_pointer, IntBuffer status); + + public static native void latchPWMZero(ByteBuffer digital_port_pointer, IntBuffer status); + + public static native void setPWMPeriodScale(ByteBuffer digital_port_pointer, int squelchMask, + IntBuffer status); + + public static native ByteBuffer allocatePWM(IntBuffer status); + + public static native void freePWM(ByteBuffer pwmGenerator, IntBuffer status); + + public static native void setPWMRate(double rate, IntBuffer status); + + public static native void setPWMDutyCycle(ByteBuffer pwmGenerator, double dutyCycle, + IntBuffer status); + + public static native void setPWMOutputChannel(ByteBuffer pwmGenerator, int pin, IntBuffer status); } diff --git a/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/hal/PowerJNI.java b/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/hal/PowerJNI.java index 061fa18f44..4217ac0572 100644 --- a/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/hal/PowerJNI.java +++ b/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/hal/PowerJNI.java @@ -3,18 +3,31 @@ package edu.wpi.first.wpilibj.hal; import java.nio.IntBuffer; public class PowerJNI extends JNIWrapper { - public static native float getVinVoltage(IntBuffer status); - public static native float getVinCurrent(IntBuffer status); - public static native float getUserVoltage6V(IntBuffer status); - public static native float getUserCurrent6V(IntBuffer status); - public static native boolean getUserActive6V(IntBuffer status); - public static native int getUserCurrentFaults6V(IntBuffer status); - public static native float getUserVoltage5V(IntBuffer status); - public static native float getUserCurrent5V(IntBuffer status); - public static native boolean getUserActive5V(IntBuffer status); - public static native int getUserCurrentFaults5V(IntBuffer status); - public static native float getUserVoltage3V3(IntBuffer status); - public static native float getUserCurrent3V3(IntBuffer status); - public static native boolean getUserActive3V3(IntBuffer status); - public static native int getUserCurrentFaults3V3(IntBuffer status); + public static native float getVinVoltage(IntBuffer status); + + public static native float getVinCurrent(IntBuffer status); + + public static native float getUserVoltage6V(IntBuffer status); + + public static native float getUserCurrent6V(IntBuffer status); + + public static native boolean getUserActive6V(IntBuffer status); + + public static native int getUserCurrentFaults6V(IntBuffer status); + + public static native float getUserVoltage5V(IntBuffer status); + + public static native float getUserCurrent5V(IntBuffer status); + + public static native boolean getUserActive5V(IntBuffer status); + + public static native int getUserCurrentFaults5V(IntBuffer status); + + public static native float getUserVoltage3V3(IntBuffer status); + + public static native float getUserCurrent3V3(IntBuffer status); + + public static native boolean getUserActive3V3(IntBuffer status); + + public static native int getUserCurrentFaults3V3(IntBuffer status); } diff --git a/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/hal/RelayJNI.java b/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/hal/RelayJNI.java index 47b3db453f..a5f6c8553b 100644 --- a/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/hal/RelayJNI.java +++ b/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/hal/RelayJNI.java @@ -4,8 +4,13 @@ import java.nio.ByteBuffer; import java.nio.IntBuffer; public class RelayJNI extends DIOJNI { - public static native void setRelayForward(ByteBuffer digital_port_pointer, byte on, IntBuffer status); - public static native void setRelayReverse(ByteBuffer digital_port_pointer, byte on, IntBuffer status); - public static native byte getRelayForward(ByteBuffer digital_port_pointer, IntBuffer status); - public static native byte getRelayReverse(ByteBuffer digital_port_pointer, IntBuffer status); + public static native void setRelayForward(ByteBuffer digital_port_pointer, byte on, + IntBuffer status); + + public static native void setRelayReverse(ByteBuffer digital_port_pointer, byte on, + IntBuffer status); + + public static native byte getRelayForward(ByteBuffer digital_port_pointer, IntBuffer status); + + public static native byte getRelayReverse(ByteBuffer digital_port_pointer, IntBuffer status); } diff --git a/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/hal/SPIJNI.java b/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/hal/SPIJNI.java index db8dc7884c..cab32a59d2 100644 --- a/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/hal/SPIJNI.java +++ b/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/hal/SPIJNI.java @@ -4,14 +4,25 @@ import java.nio.ByteBuffer; import java.nio.IntBuffer; public class SPIJNI extends JNIWrapper { - public static native void spiInitialize(byte port, IntBuffer status); - public static native int spiTransaction(byte port, ByteBuffer dataToSend, ByteBuffer dataReceived, byte size); - public static native int spiWrite(byte port, ByteBuffer dataToSend, byte sendSize); - public static native int spiRead(byte port, ByteBuffer dataReceived, byte size); - public static native void spiClose(byte port); - public static native void spiSetSpeed(byte port, int speed); - public static native void spiSetBitsPerWord(byte port, byte bpw); - public static native void spiSetOpts(byte port, int msb_first, int sample_on_trailing, int clk_idle_high); - public static native void spiSetChipSelectActiveHigh(byte port, IntBuffer status); - public static native void spiSetChipSelectActiveLow(byte port, IntBuffer status); + public static native void spiInitialize(byte port, IntBuffer status); + + public static native int spiTransaction(byte port, ByteBuffer dataToSend, + ByteBuffer dataReceived, byte size); + + public static native int spiWrite(byte port, ByteBuffer dataToSend, byte sendSize); + + public static native int spiRead(byte port, ByteBuffer dataReceived, byte size); + + public static native void spiClose(byte port); + + public static native void spiSetSpeed(byte port, int speed); + + public static native void spiSetBitsPerWord(byte port, byte bpw); + + public static native void spiSetOpts(byte port, int msb_first, int sample_on_trailing, + int clk_idle_high); + + public static native void spiSetChipSelectActiveHigh(byte port, IntBuffer status); + + public static native void spiSetChipSelectActiveLow(byte port, IntBuffer status); } diff --git a/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/hal/SerialPortJNI.java b/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/hal/SerialPortJNI.java index 7d5252d4a0..fd1e83532f 100644 --- a/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/hal/SerialPortJNI.java +++ b/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/hal/SerialPortJNI.java @@ -1,24 +1,42 @@ package edu.wpi.first.wpilibj.hal; + import java.nio.IntBuffer; import java.nio.ByteBuffer; public class SerialPortJNI extends JNIWrapper { - public static native void serialInitializePort(byte port, IntBuffer status); - public static native void serialSetBaudRate(byte port, int baud, IntBuffer status); - public static native void serialSetDataBits(byte port, byte bits, IntBuffer status); - public static native void serialSetParity(byte port, byte parity, IntBuffer status); - public static native void serialSetStopBits(byte port, byte stopBits, IntBuffer status); - public static native void serialSetWriteMode(byte port, byte mode, IntBuffer status); - public static native void serialSetFlowControl(byte port, byte flow, IntBuffer status); - public static native void serialSetTimeout(byte port, float timeout, IntBuffer status); - public static native void serialEnableTermination(byte port, char terminator, IntBuffer status); - public static native void serialDisableTermination(byte port, IntBuffer status); - public static native void serialSetReadBufferSize(byte port, int size, IntBuffer status); - public static native void serialSetWriteBufferSize(byte port, int size, IntBuffer status); - public static native int serialGetBytesRecieved(byte port, IntBuffer status); - public static native int serialRead(byte port, ByteBuffer buffer, int count, IntBuffer status); - public static native int serialWrite(byte port, ByteBuffer buffer, int count, IntBuffer status); - public static native void serialFlush(byte port, IntBuffer status); - public static native void serialClear(byte port, IntBuffer status); - public static native void serialClose(byte port, IntBuffer status); -} \ No newline at end of file + public static native void serialInitializePort(byte port, IntBuffer status); + + public static native void serialSetBaudRate(byte port, int baud, IntBuffer status); + + public static native void serialSetDataBits(byte port, byte bits, IntBuffer status); + + public static native void serialSetParity(byte port, byte parity, IntBuffer status); + + public static native void serialSetStopBits(byte port, byte stopBits, IntBuffer status); + + public static native void serialSetWriteMode(byte port, byte mode, IntBuffer status); + + public static native void serialSetFlowControl(byte port, byte flow, IntBuffer status); + + public static native void serialSetTimeout(byte port, float timeout, IntBuffer status); + + public static native void serialEnableTermination(byte port, char terminator, IntBuffer status); + + public static native void serialDisableTermination(byte port, IntBuffer status); + + public static native void serialSetReadBufferSize(byte port, int size, IntBuffer status); + + public static native void serialSetWriteBufferSize(byte port, int size, IntBuffer status); + + public static native int serialGetBytesRecieved(byte port, IntBuffer status); + + public static native int serialRead(byte port, ByteBuffer buffer, int count, IntBuffer status); + + public static native int serialWrite(byte port, ByteBuffer buffer, int count, IntBuffer status); + + public static native void serialFlush(byte port, IntBuffer status); + + public static native void serialClear(byte port, IntBuffer status); + + public static native void serialClose(byte port, IntBuffer status); +} diff --git a/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/hal/SolenoidJNI.java b/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/hal/SolenoidJNI.java index 15b1f1db62..ee58aade41 100644 --- a/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/hal/SolenoidJNI.java +++ b/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/hal/SolenoidJNI.java @@ -1,15 +1,23 @@ package edu.wpi.first.wpilibj.hal; + import java.nio.IntBuffer; import java.nio.ByteBuffer; public class SolenoidJNI extends JNIWrapper { - public static native ByteBuffer initializeSolenoidPort(ByteBuffer portPointer, IntBuffer status); - public static native ByteBuffer getPortWithModule(byte module, byte channel); - public static native void setSolenoid(ByteBuffer port, byte on, IntBuffer status); - public static native byte getSolenoid(ByteBuffer port, IntBuffer status); + public static native ByteBuffer initializeSolenoidPort(ByteBuffer portPointer, IntBuffer status); - public static native byte getPCMSolenoidBlackList(ByteBuffer pcm_pointer, IntBuffer status); - public static native boolean getPCMSolenoidVoltageStickyFault(ByteBuffer pcm_pointer, IntBuffer status); - public static native boolean getPCMSolenoidVoltageFault(ByteBuffer pcm_pointer, IntBuffer status); - public static native void clearAllPCMStickyFaults(ByteBuffer pcm_pointer, IntBuffer status); + public static native ByteBuffer getPortWithModule(byte module, byte channel); + + public static native void setSolenoid(ByteBuffer port, byte on, IntBuffer status); + + public static native byte getSolenoid(ByteBuffer port, IntBuffer status); + + public static native byte getPCMSolenoidBlackList(ByteBuffer pcm_pointer, IntBuffer status); + + public static native boolean getPCMSolenoidVoltageStickyFault(ByteBuffer pcm_pointer, + IntBuffer status); + + public static native boolean getPCMSolenoidVoltageFault(ByteBuffer pcm_pointer, IntBuffer status); + + public static native void clearAllPCMStickyFaults(ByteBuffer pcm_pointer, IntBuffer status); } diff --git a/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/image/BinaryImage.java b/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/image/BinaryImage.java index a106d7fd60..5b1354e7a1 100644 --- a/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/image/BinaryImage.java +++ b/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/image/BinaryImage.java @@ -1,8 +1,8 @@ /*----------------------------------------------------------------------------*/ -/* Copyright (c) FIRST 2008-2012. All Rights Reserved. */ -/* Open Source Software - may be modified and shared by FRC teams. The code */ +/* Copyright (c) FIRST 2008-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 the root directory of */ -/* the project. */ +/* the project. */ /*----------------------------------------------------------------------------*/ package edu.wpi.first.wpilibj.image; @@ -16,152 +16,162 @@ import com.ni.vision.NIVision; * @author dtjones */ public class BinaryImage extends MonoImage { - private int numParticles = -1; + private int numParticles = -1; - BinaryImage() throws NIVisionException { + BinaryImage() throws NIVisionException {} + + BinaryImage(BinaryImage sourceImage) { + super(sourceImage); + } + + /** + * Returns the number of particles. + * + * @return The number of particles + */ + public int getNumberParticles() throws NIVisionException { + if (numParticles < 0) + numParticles = NIVision.imaqCountParticles(image, 1); + return numParticles; + } + + + private class ParticleSizeReport { + final int index; + final double size; + + public ParticleSizeReport(int index) throws NIVisionException { + if ((!(index < BinaryImage.this.getNumberParticles())) || index < 0) + throw new IndexOutOfBoundsException(); + this.index = index; + size = ParticleAnalysisReport.getParticleToImagePercent(BinaryImage.this, index); } - BinaryImage(BinaryImage sourceImage) { - super(sourceImage); + public ParticleAnalysisReport getParticleAnalysisReport() throws NIVisionException { + return new ParticleAnalysisReport(BinaryImage.this, index); } + } - /** - * Returns the number of particles. - * - * @return The number of particles - */ - public int getNumberParticles() throws NIVisionException { - if (numParticles < 0) - numParticles = NIVision.imaqCountParticles(image, 1); - return numParticles; + /** + * Get a particle analysis report for the particle at the given index. + * + * @param index The index of the particle to report on. + * @return The ParticleAnalysisReport for the particle at the given index + */ + public ParticleAnalysisReport getParticleAnalysisReport(int index) throws NIVisionException { + if (!(index < getNumberParticles())) + throw new IndexOutOfBoundsException(); + return new ParticleAnalysisReport(this, index); + } + + /** + * Gets all the particle analysis reports ordered from largest area to + * smallest. + * + * @param size The number of particles to return + * @return An array of ParticleReports from largest area to smallest + */ + public ParticleAnalysisReport[] getOrderedParticleAnalysisReports(int size) + throws NIVisionException { + if (size > getNumberParticles()) + size = getNumberParticles(); + ParticleSizeReport[] reports = new ParticleSizeReport[size]; + SortedVector sorter = new SortedVector(new SortedVector.Comparator() { + public int compare(Object object1, Object object2) { + ParticleSizeReport p1 = (ParticleSizeReport) object1; + ParticleSizeReport p2 = (ParticleSizeReport) object2; + if (p1.size < p2.size) + return -1; + else if (p1.size > p2.size) + return 1; + return 0; + } + }); + for (int i = 0; i < getNumberParticles(); i++) + sorter.addElement(new ParticleSizeReport(i)); + sorter.setSize(size); + sorter.copyInto(reports); + ParticleAnalysisReport[] finalReports = new ParticleAnalysisReport[reports.length]; + for (int i = 0; i < finalReports.length; i++) + finalReports[i] = reports[i].getParticleAnalysisReport(); + return finalReports; + } + + /** + * Gets all the particle analysis reports ordered from largest area to + * smallest. + * + * @return An array of ParticleReports from largest are to smallest + */ + public ParticleAnalysisReport[] getOrderedParticleAnalysisReports() throws NIVisionException { + return getOrderedParticleAnalysisReports(getNumberParticles()); + } + + + public void write(String fileName) throws NIVisionException { + NIVision.RGBValue colorTable = new NIVision.RGBValue(0, 0, 255, 0); + try { + NIVision.imaqWriteFile(image, fileName, colorTable); + } finally { + colorTable.free(); } + } + /** + * removeSmallObjects filters particles based on their size. The algorithm + * erodes the image a specified number of times and keeps the particles from + * the original image that remain in the eroded image. + * + * @param connectivity8 true to use connectivity-8 or false for connectivity-4 + * to determine whether particles are touching. For more information + * about connectivity, see Chapter 9, Binary Morphology, in the NI + * Vision Concepts manual. + * @param erosions the number of erosions to perform + * @return a BinaryImage after applying the filter + * @throws NIVisionException + */ + public BinaryImage removeSmallObjects(boolean connectivity8, int erosions) + throws NIVisionException { + BinaryImage result = new BinaryImage(); + NIVision.imaqSizeFilter(result.image, image, connectivity8 ? 1 : 0, erosions, + NIVision.SizeType.KEEP_LARGE, null); + result.free(); + return result; + } - private class ParticleSizeReport { - final int index; - final double size; + /** + * removeLargeObjects filters particles based on their size. The algorithm + * erodes the image a specified number of times and discards the particles + * from the original image that remain in the eroded image. + * + * @param connectivity8 true to use connectivity-8 or false for connectivity-4 + * to determine whether particles are touching. For more information + * about connectivity, see Chapter 9, Binary Morphology, in the NI + * Vision Concepts manual. + * @param erosions the number of erosions to perform + * @return a BinaryImage after applying the filter + * @throws NIVisionException + */ + public BinaryImage removeLargeObjects(boolean connectivity8, int erosions) + throws NIVisionException { + BinaryImage result = new BinaryImage(); + NIVision.imaqSizeFilter(result.image, image, connectivity8 ? 1 : 0, erosions, + NIVision.SizeType.KEEP_SMALL, null); + return result; + } - public ParticleSizeReport(int index) throws NIVisionException { - if ((!(index < BinaryImage.this.getNumberParticles())) || index < 0) - throw new IndexOutOfBoundsException(); - this.index = index; - size = ParticleAnalysisReport.getParticleToImagePercent(BinaryImage.this, index); - } + public BinaryImage convexHull(boolean connectivity8) throws NIVisionException { + BinaryImage result = new BinaryImage(); + NIVision.imaqConvexHull(result.image, image, connectivity8 ? 1 : 0); + return result; + } - public ParticleAnalysisReport getParticleAnalysisReport() throws NIVisionException { - return new ParticleAnalysisReport(BinaryImage.this, index); - } - } - - /** - * Get a particle analysis report for the particle at the given index. - * - * @param index The index of the particle to report on. - * @return The ParticleAnalysisReport for the particle at the given index - */ - public ParticleAnalysisReport getParticleAnalysisReport(int index) throws NIVisionException { - if (!(index < getNumberParticles())) throw new IndexOutOfBoundsException(); - return new ParticleAnalysisReport(this, index); - } - - /** - * Gets all the particle analysis reports ordered from largest area to smallest. - * - * @param size The number of particles to return - * @return An array of ParticleReports from largest area to smallest - */ - public ParticleAnalysisReport[] getOrderedParticleAnalysisReports(int size) throws NIVisionException { - if (size > getNumberParticles()) - size = getNumberParticles(); - ParticleSizeReport[] reports = new ParticleSizeReport[size]; - SortedVector sorter = new SortedVector(new SortedVector.Comparator() { - public int compare(Object object1, Object object2) { - ParticleSizeReport p1 = (ParticleSizeReport) object1; - ParticleSizeReport p2 = (ParticleSizeReport) object2; - if (p1.size < p2.size) - return -1; - else if (p1.size > p2.size) - return 1; - return 0; - } - }); - for (int i = 0; i < getNumberParticles(); i++) - sorter.addElement(new ParticleSizeReport(i)); - sorter.setSize(size); - sorter.copyInto(reports); - ParticleAnalysisReport[] finalReports = new ParticleAnalysisReport[reports.length]; - for (int i = 0; i < finalReports.length; i++) - finalReports[i] = reports[i].getParticleAnalysisReport(); - return finalReports; - } - - /** - * Gets all the particle analysis reports ordered from largest area to smallest. - * - * @return An array of ParticleReports from largest are to smallest - */ - public ParticleAnalysisReport[] getOrderedParticleAnalysisReports() throws NIVisionException { - return getOrderedParticleAnalysisReports(getNumberParticles()); - } - - - public void write(String fileName) throws NIVisionException { - NIVision.RGBValue colorTable = new NIVision.RGBValue(0, 0, 255, 0); - try { - NIVision.imaqWriteFile(image, fileName, colorTable); - } finally { - colorTable.free(); - } - } - - /** - * removeSmallObjects filters particles based on their size. - * The algorithm erodes the image a specified number of times and keeps the - * particles from the original image that remain in the eroded image. - * - * @param connectivity8 true to use connectivity-8 or false for connectivity-4 to determine - * whether particles are touching. For more information about connectivity, see Chapter 9, - * Binary Morphology, in the NI Vision Concepts manual. - * @param erosions the number of erosions to perform - * @return a BinaryImage after applying the filter - * @throws NIVisionException - */ - public BinaryImage removeSmallObjects(boolean connectivity8, int erosions) throws NIVisionException { - BinaryImage result = new BinaryImage(); - NIVision.imaqSizeFilter(result.image, image, connectivity8 ? 1 : 0, erosions, NIVision.SizeType.KEEP_LARGE, null); - result.free(); - return result; - } - - /** - * removeLargeObjects filters particles based on their size. - * The algorithm erodes the image a specified number of times and discards the - * particles from the original image that remain in the eroded image. - * - * @param connectivity8 true to use connectivity-8 or false for connectivity-4 to determine - * whether particles are touching. For more information about connectivity, see Chapter 9, - * Binary Morphology, in the NI Vision Concepts manual. - * @param erosions the number of erosions to perform - * @return a BinaryImage after applying the filter - * @throws NIVisionException - */ - public BinaryImage removeLargeObjects(boolean connectivity8, int erosions) throws NIVisionException { - BinaryImage result = new BinaryImage(); - NIVision.imaqSizeFilter(result.image, image, connectivity8 ? 1 : 0, erosions, NIVision.SizeType.KEEP_SMALL, null); - return result; - } - - public BinaryImage convexHull(boolean connectivity8) throws NIVisionException { - BinaryImage result = new BinaryImage(); - NIVision.imaqConvexHull(result.image, image, connectivity8 ? 1 : 0); - return result; - } - - public BinaryImage particleFilter(NIVision.ParticleFilterCriteria2[] criteria) throws NIVisionException { - BinaryImage result = new BinaryImage(); - NIVision.ParticleFilterOptions2 options = new NIVision.ParticleFilterOptions2(0, 0, 0, 1); - NIVision.imaqParticleFilter4(result.image, image, criteria, options, null); - options.free(); - return result; - } + public BinaryImage particleFilter(NIVision.ParticleFilterCriteria2[] criteria) + throws NIVisionException { + BinaryImage result = new BinaryImage(); + NIVision.ParticleFilterOptions2 options = new NIVision.ParticleFilterOptions2(0, 0, 0, 1); + NIVision.imaqParticleFilter4(result.image, image, criteria, options, null); + options.free(); + return result; + } } diff --git a/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/image/ColorImage.java b/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/image/ColorImage.java index ebe5f90b54..bc6441a27e 100644 --- a/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/image/ColorImage.java +++ b/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/image/ColorImage.java @@ -1,8 +1,8 @@ /*----------------------------------------------------------------------------*/ -/* Copyright (c) FIRST 2008-2012. All Rights Reserved. */ -/* Open Source Software - may be modified and shared by FRC teams. The code */ +/* Copyright (c) FIRST 2008-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 the root directory of */ -/* the project. */ +/* the project. */ /*----------------------------------------------------------------------------*/ package edu.wpi.first.wpilibj.image; @@ -15,403 +15,423 @@ import com.ni.vision.NIVision; */ public abstract class ColorImage extends ImageBase { - ColorImage(NIVision.ImageType type) throws NIVisionException { - super(type); - } + ColorImage(NIVision.ImageType type) throws NIVisionException { + super(type); + } - ColorImage(ColorImage sourceImage) { - super(sourceImage); - } + ColorImage(ColorImage sourceImage) { + super(sourceImage); + } - private BinaryImage threshold(NIVision.ColorMode colorMode, - int low1, int high1, - int low2, int high2, - int low3, int high3) throws NIVisionException { - BinaryImage res = new BinaryImage(); - NIVision.Range range1 = new NIVision.Range(low1, high1); - NIVision.Range range2 = new NIVision.Range(low2, high2); - NIVision.Range range3 = new NIVision.Range(low3, high3); - NIVision.imaqColorThreshold(res.image, image, 1, colorMode, range1, range2, range3); - res.free(); - range1.free(); - range2.free(); - range3.free(); - return res; - } + private BinaryImage threshold(NIVision.ColorMode colorMode, int low1, int high1, int low2, + int high2, int low3, int high3) throws NIVisionException { + BinaryImage res = new BinaryImage(); + NIVision.Range range1 = new NIVision.Range(low1, high1); + NIVision.Range range2 = new NIVision.Range(low2, high2); + NIVision.Range range3 = new NIVision.Range(low3, high3); + NIVision.imaqColorThreshold(res.image, image, 1, colorMode, range1, range2, range3); + res.free(); + range1.free(); + range2.free(); + range3.free(); + return res; + } - /** - * Return a mask of the areas of the image that fall within the given ranges for color values - * - * @param redLow The lower red limit. - * @param redHigh The upper red limit. - * @param greenLow The lower green limit. - * @param greenHigh The upper green limit. - * @param blueLow The lower blue limit. - * @param blueHigh The upper blue limit. - * @return A BinaryImage masking the areas which match the given thresholds. - */ - public BinaryImage thresholdRGB(int redLow, int redHigh, int greenLow, int greenHigh, int blueLow, int blueHigh) throws NIVisionException { - return threshold(NIVision.ColorMode.RGB, redLow, redHigh, greenLow, greenHigh, blueLow, blueHigh); - } + /** + * Return a mask of the areas of the image that fall within the given ranges + * for color values + * + * @param redLow The lower red limit. + * @param redHigh The upper red limit. + * @param greenLow The lower green limit. + * @param greenHigh The upper green limit. + * @param blueLow The lower blue limit. + * @param blueHigh The upper blue limit. + * @return A BinaryImage masking the areas which match the given thresholds. + */ + public BinaryImage thresholdRGB(int redLow, int redHigh, int greenLow, int greenHigh, + int blueLow, int blueHigh) throws NIVisionException { + return threshold(NIVision.ColorMode.RGB, redLow, redHigh, greenLow, greenHigh, blueLow, + blueHigh); + } - /** - * Return a mask of the areas of the image that fall within the given ranges for color values - * - * @param hueLow The lower hue limit. - * @param hueHigh The upper hue limit. - * @param saturationLow The lower saturation limit. - * @param saturationHigh The upper saturation limit. - * @param luminenceLow The lower luminence limit. - * @param luminenceHigh The upper luminence limit. - * @return A BinaryImage masking the areas which match the given thresholds. - */ - public BinaryImage thresholdHSL(int hueLow, int hueHigh, int saturationLow, int saturationHigh, int luminenceLow, int luminenceHigh) throws NIVisionException { - return threshold(NIVision.ColorMode.HSL, hueLow, hueHigh, saturationLow, saturationHigh, luminenceLow, luminenceHigh); - } + /** + * Return a mask of the areas of the image that fall within the given ranges + * for color values + * + * @param hueLow The lower hue limit. + * @param hueHigh The upper hue limit. + * @param saturationLow The lower saturation limit. + * @param saturationHigh The upper saturation limit. + * @param luminenceLow The lower luminence limit. + * @param luminenceHigh The upper luminence limit. + * @return A BinaryImage masking the areas which match the given thresholds. + */ + public BinaryImage thresholdHSL(int hueLow, int hueHigh, int saturationLow, int saturationHigh, + int luminenceLow, int luminenceHigh) throws NIVisionException { + return threshold(NIVision.ColorMode.HSL, hueLow, hueHigh, saturationLow, saturationHigh, + luminenceLow, luminenceHigh); + } - /** - * Return a mask of the areas of the image that fall within the given ranges for color values - * - * @param hueLow The lower hue limit. - * @param hueHigh The upper hue limit. - * @param saturationLow The lower saturation limit. - * @param saturationHigh The upper saturation limit. - * @param valueHigh The lower value limit. - * @param valueLow The upper value limit. - * @return A BinaryImage masking the areas which match the given thresholds. - */ - public BinaryImage thresholdHSV(int hueLow, int hueHigh, int saturationLow, int saturationHigh, int valueLow, int valueHigh) throws NIVisionException { - return threshold(NIVision.ColorMode.HSV, hueLow, hueHigh, saturationLow, saturationHigh, valueLow, valueHigh); - } + /** + * Return a mask of the areas of the image that fall within the given ranges + * for color values + * + * @param hueLow The lower hue limit. + * @param hueHigh The upper hue limit. + * @param saturationLow The lower saturation limit. + * @param saturationHigh The upper saturation limit. + * @param valueHigh The lower value limit. + * @param valueLow The upper value limit. + * @return A BinaryImage masking the areas which match the given thresholds. + */ + public BinaryImage thresholdHSV(int hueLow, int hueHigh, int saturationLow, int saturationHigh, + int valueLow, int valueHigh) throws NIVisionException { + return threshold(NIVision.ColorMode.HSV, hueLow, hueHigh, saturationLow, saturationHigh, + valueLow, valueHigh); + } - /** - * Return a mask of the areas of the image that fall within the given ranges for color values - * - * @param hueLow The lower hue limit. - * @param hueHigh The upper hue limit. - * @param saturationLow The lower saturation limit. - * @param saturationHigh The upper saturation limit. - * @param intansityLow The lower intensity limit. - * @param intensityHigh The upper intensity limit. - * @return A BinaryImage masking the areas which match the given thresholds. - */ - public BinaryImage thresholdHSI(int hueLow, int hueHigh, int saturationLow, int saturationHigh, int intansityLow, int intensityHigh) throws NIVisionException { - return threshold(NIVision.ColorMode.HSI, hueLow, hueHigh, saturationLow, saturationHigh, intansityLow, intensityHigh); - } + /** + * Return a mask of the areas of the image that fall within the given ranges + * for color values + * + * @param hueLow The lower hue limit. + * @param hueHigh The upper hue limit. + * @param saturationLow The lower saturation limit. + * @param saturationHigh The upper saturation limit. + * @param intansityLow The lower intensity limit. + * @param intensityHigh The upper intensity limit. + * @return A BinaryImage masking the areas which match the given thresholds. + */ + public BinaryImage thresholdHSI(int hueLow, int hueHigh, int saturationLow, int saturationHigh, + int intansityLow, int intensityHigh) throws NIVisionException { + return threshold(NIVision.ColorMode.HSI, hueLow, hueHigh, saturationLow, saturationHigh, + intansityLow, intensityHigh); + } - MonoImage extractFirstColorPlane(NIVision.ColorMode mode) throws NIVisionException { - MonoImage result = new MonoImage(); - NIVision.imaqExtractColorPlanes(image, mode, result.image, null, null); - result.free(); - return result; - } + MonoImage extractFirstColorPlane(NIVision.ColorMode mode) throws NIVisionException { + MonoImage result = new MonoImage(); + NIVision.imaqExtractColorPlanes(image, mode, result.image, null, null); + result.free(); + return result; + } - MonoImage extractSecondColorPlane(NIVision.ColorMode mode) throws NIVisionException { - MonoImage result = new MonoImage(); - NIVision.imaqExtractColorPlanes(image, mode, null, result.image, null); - result.free(); - return result; - } + MonoImage extractSecondColorPlane(NIVision.ColorMode mode) throws NIVisionException { + MonoImage result = new MonoImage(); + NIVision.imaqExtractColorPlanes(image, mode, null, result.image, null); + result.free(); + return result; + } - MonoImage extractThirdColorPlane(NIVision.ColorMode mode) throws NIVisionException { - MonoImage result = new MonoImage(); - NIVision.imaqExtractColorPlanes(image, mode, null, null, result.image); - result.free(); - return result; - } + MonoImage extractThirdColorPlane(NIVision.ColorMode mode) throws NIVisionException { + MonoImage result = new MonoImage(); + NIVision.imaqExtractColorPlanes(image, mode, null, null, result.image); + result.free(); + return result; + } - /** - * Get the red color plane from the image when represented in RGB color space. - * - * @return The red color plane from the image. - */ - public MonoImage getRedPlane() throws NIVisionException { - return extractFirstColorPlane(NIVision.ColorMode.RGB); - } + /** + * Get the red color plane from the image when represented in RGB color space. + * + * @return The red color plane from the image. + */ + public MonoImage getRedPlane() throws NIVisionException { + return extractFirstColorPlane(NIVision.ColorMode.RGB); + } - /** - * Get the green color plane from the image when represented in RGB color space. - * - * @return The green color plane from the image. - */ - public MonoImage getGreenPlane() throws NIVisionException { - return extractSecondColorPlane(NIVision.ColorMode.RGB); - } + /** + * Get the green color plane from the image when represented in RGB color + * space. + * + * @return The green color plane from the image. + */ + public MonoImage getGreenPlane() throws NIVisionException { + return extractSecondColorPlane(NIVision.ColorMode.RGB); + } - /** - * Get the blue color plane from the image when represented in RGB color space. - * - * @return The blue color plane from the image. - */ - public MonoImage getBluePlane() throws NIVisionException { - return extractThirdColorPlane(NIVision.ColorMode.RGB); - } + /** + * Get the blue color plane from the image when represented in RGB color + * space. + * + * @return The blue color plane from the image. + */ + public MonoImage getBluePlane() throws NIVisionException { + return extractThirdColorPlane(NIVision.ColorMode.RGB); + } - /** - * Get the hue color plane from the image when represented in HSL color space. - * - * @return The hue color plane from the image. - */ - public MonoImage getHSLHuePlane() throws NIVisionException { - return extractFirstColorPlane(NIVision.ColorMode.HSL); - } + /** + * Get the hue color plane from the image when represented in HSL color space. + * + * @return The hue color plane from the image. + */ + public MonoImage getHSLHuePlane() throws NIVisionException { + return extractFirstColorPlane(NIVision.ColorMode.HSL); + } - /** - * Get the hue color plane from the image when represented in HSV color space. - * - * @return The hue color plane from the image. - */ - public MonoImage getHSVHuePlane() throws NIVisionException { - return extractFirstColorPlane(NIVision.ColorMode.HSV); - } + /** + * Get the hue color plane from the image when represented in HSV color space. + * + * @return The hue color plane from the image. + */ + public MonoImage getHSVHuePlane() throws NIVisionException { + return extractFirstColorPlane(NIVision.ColorMode.HSV); + } - /** - * Get the hue color plane from the image when represented in HSI color space. - * - * @return The hue color plane from the image. - */ - public MonoImage getHSIHuePlane() throws NIVisionException { - return extractFirstColorPlane(NIVision.ColorMode.HSI); - } + /** + * Get the hue color plane from the image when represented in HSI color space. + * + * @return The hue color plane from the image. + */ + public MonoImage getHSIHuePlane() throws NIVisionException { + return extractFirstColorPlane(NIVision.ColorMode.HSI); + } - /** - * Get the saturation color plane from the image when represented in HSL color space. - * - * @return The saturation color plane from the image. - */ - public MonoImage getHSLSaturationPlane() throws NIVisionException { - return extractSecondColorPlane(NIVision.ColorMode.HSL); - } + /** + * Get the saturation color plane from the image when represented in HSL color + * space. + * + * @return The saturation color plane from the image. + */ + public MonoImage getHSLSaturationPlane() throws NIVisionException { + return extractSecondColorPlane(NIVision.ColorMode.HSL); + } - /** - * Get the saturation color plane from the image when represented in HSV color space. - * - * @return The saturation color plane from the image. - */ - public MonoImage getHSVSaturationPlane() throws NIVisionException { - return extractSecondColorPlane(NIVision.ColorMode.HSV); - } + /** + * Get the saturation color plane from the image when represented in HSV color + * space. + * + * @return The saturation color plane from the image. + */ + public MonoImage getHSVSaturationPlane() throws NIVisionException { + return extractSecondColorPlane(NIVision.ColorMode.HSV); + } - /** - * Get the saturation color plane from the image when represented in HSI color space. - * - * @return The saturation color plane from the image. - */ - public MonoImage getHSISaturationPlane() throws NIVisionException { - return extractSecondColorPlane(NIVision.ColorMode.HSI); - } + /** + * Get the saturation color plane from the image when represented in HSI color + * space. + * + * @return The saturation color plane from the image. + */ + public MonoImage getHSISaturationPlane() throws NIVisionException { + return extractSecondColorPlane(NIVision.ColorMode.HSI); + } - /** - * Get the luminance color plane from the image when represented in HSL color space. - * - * @return The luminance color plane from the image. - */ - public MonoImage getLuminancePlane() throws NIVisionException { - return extractThirdColorPlane(NIVision.ColorMode.HSL); - } + /** + * Get the luminance color plane from the image when represented in HSL color + * space. + * + * @return The luminance color plane from the image. + */ + public MonoImage getLuminancePlane() throws NIVisionException { + return extractThirdColorPlane(NIVision.ColorMode.HSL); + } - /** - * Get the value color plane from the image when represented in HSV color space. - * - * @return The value color plane from the image. - */ - public MonoImage getValuePlane() throws NIVisionException { - return extractThirdColorPlane(NIVision.ColorMode.HSV); - } + /** + * Get the value color plane from the image when represented in HSV color + * space. + * + * @return The value color plane from the image. + */ + public MonoImage getValuePlane() throws NIVisionException { + return extractThirdColorPlane(NIVision.ColorMode.HSV); + } - /** - * Get the intensity color plane from the image when represented in HSI color space. - * - * @return The intensity color plane from the image. - */ - public MonoImage getIntensityPlane() throws NIVisionException { - return extractThirdColorPlane(NIVision.ColorMode.HSI); - } + /** + * Get the intensity color plane from the image when represented in HSI color + * space. + * + * @return The intensity color plane from the image. + */ + public MonoImage getIntensityPlane() throws NIVisionException { + return extractThirdColorPlane(NIVision.ColorMode.HSI); + } - ColorImage replaceFirstColorPlane(NIVision.ColorMode mode, MonoImage plane) throws NIVisionException { - NIVision.imaqReplaceColorPlanes(image, image, mode, plane.image, null, null); - return this; - } + ColorImage replaceFirstColorPlane(NIVision.ColorMode mode, MonoImage plane) + throws NIVisionException { + NIVision.imaqReplaceColorPlanes(image, image, mode, plane.image, null, null); + return this; + } - ColorImage replaceSecondColorPlane(NIVision.ColorMode mode, MonoImage plane) throws NIVisionException { - NIVision.imaqReplaceColorPlanes(image, image, mode, null, plane.image, null); - return this; - } + ColorImage replaceSecondColorPlane(NIVision.ColorMode mode, MonoImage plane) + throws NIVisionException { + NIVision.imaqReplaceColorPlanes(image, image, mode, null, plane.image, null); + return this; + } - ColorImage replaceThirdColorPlane(NIVision.ColorMode mode, MonoImage plane) throws NIVisionException { - NIVision.imaqReplaceColorPlanes(image, image, mode, null, null, plane.image); - return this; - } + ColorImage replaceThirdColorPlane(NIVision.ColorMode mode, MonoImage plane) + throws NIVisionException { + NIVision.imaqReplaceColorPlanes(image, image, mode, null, null, plane.image); + return this; + } - /** - * Set the red color plane from the image when represented in RGB color space. - * This does not create a new image, but modifies this one instead. Create a - * copy before hand if you need to continue using the original. - * - * @param plane The MonoImage representing the new color plane. - * @return The resulting image. - */ - public ColorImage replaceRedPlane(MonoImage plane) throws NIVisionException { - return replaceFirstColorPlane(NIVision.ColorMode.RGB, plane); - } + /** + * Set the red color plane from the image when represented in RGB color space. + * This does not create a new image, but modifies this one instead. Create a + * copy before hand if you need to continue using the original. + * + * @param plane The MonoImage representing the new color plane. + * @return The resulting image. + */ + public ColorImage replaceRedPlane(MonoImage plane) throws NIVisionException { + return replaceFirstColorPlane(NIVision.ColorMode.RGB, plane); + } - /** - * Set the green color plane from the image when represented in RGB color space. - * This does not create a new image, but modifies this one instead. Create a - * copy before hand if you need to continue using the original. - * - * @param plane The MonoImage representing the new color plane. - * @return The resulting image. - */ - public ColorImage replaceGreenPlane(MonoImage plane) throws NIVisionException { - return replaceSecondColorPlane(NIVision.ColorMode.RGB, plane); - } + /** + * Set the green color plane from the image when represented in RGB color + * space. This does not create a new image, but modifies this one instead. + * Create a copy before hand if you need to continue using the original. + * + * @param plane The MonoImage representing the new color plane. + * @return The resulting image. + */ + public ColorImage replaceGreenPlane(MonoImage plane) throws NIVisionException { + return replaceSecondColorPlane(NIVision.ColorMode.RGB, plane); + } - /** - * Set the blue color plane from the image when represented in RGB color space. - * This does not create a new image, but modifies this one instead. Create a - * copy before hand if you need to continue using the original. - * - * @param plane The MonoImage representing the new color plane. - * @return The resulting image. - */ - public ColorImage replaceBluePlane(MonoImage plane) throws NIVisionException { - return replaceThirdColorPlane(NIVision.ColorMode.RGB, plane); - } + /** + * Set the blue color plane from the image when represented in RGB color + * space. This does not create a new image, but modifies this one instead. + * Create a copy before hand if you need to continue using the original. + * + * @param plane The MonoImage representing the new color plane. + * @return The resulting image. + */ + public ColorImage replaceBluePlane(MonoImage plane) throws NIVisionException { + return replaceThirdColorPlane(NIVision.ColorMode.RGB, plane); + } - /** - * Set the hue color plane from the image when represented in HSL color space. - * This does not create a new image, but modifies this one instead. Create a - * copy before hand if you need to continue using the original. - * - * @param plane The MonoImage representing the new color plane. - * @return The resulting image. - */ - public ColorImage replaceHSLHuePlane(MonoImage plane) throws NIVisionException { - return replaceFirstColorPlane(NIVision.ColorMode.HSL, plane); - } + /** + * Set the hue color plane from the image when represented in HSL color space. + * This does not create a new image, but modifies this one instead. Create a + * copy before hand if you need to continue using the original. + * + * @param plane The MonoImage representing the new color plane. + * @return The resulting image. + */ + public ColorImage replaceHSLHuePlane(MonoImage plane) throws NIVisionException { + return replaceFirstColorPlane(NIVision.ColorMode.HSL, plane); + } - /** - * Set the hue color plane from the image when represented in HSV color space. - * This does not create a new image, but modifies this one instead. Create a - * copy before hand if you need to continue using the original. - * - * @param plane The MonoImage representing the new color plane. - * @return The resulting image. - */ - public ColorImage replaceHSVHuePlane(MonoImage plane) throws NIVisionException { - return replaceFirstColorPlane(NIVision.ColorMode.HSV, plane); - } + /** + * Set the hue color plane from the image when represented in HSV color space. + * This does not create a new image, but modifies this one instead. Create a + * copy before hand if you need to continue using the original. + * + * @param plane The MonoImage representing the new color plane. + * @return The resulting image. + */ + public ColorImage replaceHSVHuePlane(MonoImage plane) throws NIVisionException { + return replaceFirstColorPlane(NIVision.ColorMode.HSV, plane); + } - /** - * Set the hue color plane from the image when represented in HSI color space. - * This does not create a new image, but modifies this one instead. Create a - * copy before hand if you need to continue using the original. - * - * @param plane The MonoImage representing the new color plane. - * @return The resulting image. - */ - public ColorImage replaceHSIHuePlane(MonoImage plane) throws NIVisionException { - return replaceFirstColorPlane(NIVision.ColorMode.HSI, plane); - } + /** + * Set the hue color plane from the image when represented in HSI color space. + * This does not create a new image, but modifies this one instead. Create a + * copy before hand if you need to continue using the original. + * + * @param plane The MonoImage representing the new color plane. + * @return The resulting image. + */ + public ColorImage replaceHSIHuePlane(MonoImage plane) throws NIVisionException { + return replaceFirstColorPlane(NIVision.ColorMode.HSI, plane); + } - /** - * Set the saturation color plane from the image when represented in HSL color space. - * This does not create a new image, but modifies this one instead. Create a - * copy before hand if you need to continue using the original. - * - * @param plane The MonoImage representing the new color plane. - * @return The resulting image. - */ - public ColorImage replaceHSLSaturationPlane(MonoImage plane) throws NIVisionException { - return replaceSecondColorPlane(NIVision.ColorMode.HSL, plane); - } + /** + * Set the saturation color plane from the image when represented in HSL color + * space. This does not create a new image, but modifies this one instead. + * Create a copy before hand if you need to continue using the original. + * + * @param plane The MonoImage representing the new color plane. + * @return The resulting image. + */ + public ColorImage replaceHSLSaturationPlane(MonoImage plane) throws NIVisionException { + return replaceSecondColorPlane(NIVision.ColorMode.HSL, plane); + } - /** - * Set the saturation color plane from the image when represented in HSV color space. - * This does not create a new image, but modifies this one instead. Create a - * copy before hand if you need to continue using the original. - * - * @param plane The MonoImage representing the new color plane. - * @return The resulting image. - */ - public ColorImage replaceHSVSaturationPlane(MonoImage plane) throws NIVisionException { - return replaceSecondColorPlane(NIVision.ColorMode.HSV, plane); - } + /** + * Set the saturation color plane from the image when represented in HSV color + * space. This does not create a new image, but modifies this one instead. + * Create a copy before hand if you need to continue using the original. + * + * @param plane The MonoImage representing the new color plane. + * @return The resulting image. + */ + public ColorImage replaceHSVSaturationPlane(MonoImage plane) throws NIVisionException { + return replaceSecondColorPlane(NIVision.ColorMode.HSV, plane); + } - /** - * Set the saturation color plane from the image when represented in HSI color space. - * This does not create a new image, but modifies this one instead. Create a - * copy before hand if you need to continue using the original. - * - * @param plane The MonoImage representing the new color plane. - * @return The resulting image. - */ - public ColorImage replaceHSISaturationPlane(MonoImage plane) throws NIVisionException { - return replaceSecondColorPlane(NIVision.ColorMode.HSI, plane); - } + /** + * Set the saturation color plane from the image when represented in HSI color + * space. This does not create a new image, but modifies this one instead. + * Create a copy before hand if you need to continue using the original. + * + * @param plane The MonoImage representing the new color plane. + * @return The resulting image. + */ + public ColorImage replaceHSISaturationPlane(MonoImage plane) throws NIVisionException { + return replaceSecondColorPlane(NIVision.ColorMode.HSI, plane); + } - /** - * Set the luminance color plane from the image when represented in HSL color space. - * This does not create a new image, but modifies this one instead. Create a - * copy before hand if you need to continue using the original. - * - * @param plane The MonoImage representing the new color plane. - * @return The resulting image. - */ - public ColorImage replaceLuminancePlane(MonoImage plane) throws NIVisionException { - return replaceThirdColorPlane(NIVision.ColorMode.HSL, plane); - } + /** + * Set the luminance color plane from the image when represented in HSL color + * space. This does not create a new image, but modifies this one instead. + * Create a copy before hand if you need to continue using the original. + * + * @param plane The MonoImage representing the new color plane. + * @return The resulting image. + */ + public ColorImage replaceLuminancePlane(MonoImage plane) throws NIVisionException { + return replaceThirdColorPlane(NIVision.ColorMode.HSL, plane); + } - /** - * Set the value color plane from the image when represented in HSV color space. - * This does not create a new image, but modifies this one instead. Create a - * copy before hand if you need to continue using the original. - * - * @param plane The MonoImage representing the new color plane. - * @return The resulting image. - */ - public ColorImage replaceValuePlane(MonoImage plane) throws NIVisionException { - return replaceThirdColorPlane(NIVision.ColorMode.HSV, plane); - } + /** + * Set the value color plane from the image when represented in HSV color + * space. This does not create a new image, but modifies this one instead. + * Create a copy before hand if you need to continue using the original. + * + * @param plane The MonoImage representing the new color plane. + * @return The resulting image. + */ + public ColorImage replaceValuePlane(MonoImage plane) throws NIVisionException { + return replaceThirdColorPlane(NIVision.ColorMode.HSV, plane); + } - /** - * Set the intensity color plane from the image when represented in HSI color space. - * This does not create a new image, but modifies this one instead. Create a - * copy before hand if you need to continue using the original. - * - * @param plane The MonoImage representing the new color plane. - * @return The resulting image. - */ - public ColorImage replaceIntensityPlane(MonoImage plane) throws NIVisionException { - return replaceThirdColorPlane(NIVision.ColorMode.HSI, plane); - } + /** + * Set the intensity color plane from the image when represented in HSI color + * space. This does not create a new image, but modifies this one instead. + * Create a copy before hand if you need to continue using the original. + * + * @param plane The MonoImage representing the new color plane. + * @return The resulting image. + */ + public ColorImage replaceIntensityPlane(MonoImage plane) throws NIVisionException { + return replaceThirdColorPlane(NIVision.ColorMode.HSI, plane); + } - /** - * Calculates the histogram of each plane of a color image and redistributes - * pixel values across the desired range while maintaining pixel value - * groupings. - * This does not create a new image, but modifies this one instead. Create a - * copy before hand if you need to continue using the original. - * - * @return The modified image. - */ - public ColorImage colorEqualize() throws NIVisionException { - NIVision.imaqColorEqualize(image, image, 1); - return this; - } + /** + * Calculates the histogram of each plane of a color image and redistributes + * pixel values across the desired range while maintaining pixel value + * groupings. This does not create a new image, but modifies this one instead. + * Create a copy before hand if you need to continue using the original. + * + * @return The modified image. + */ + public ColorImage colorEqualize() throws NIVisionException { + NIVision.imaqColorEqualize(image, image, 1); + return this; + } - /** - * Calculates the histogram of each plane of a color image and redistributes - * pixel values across the desired range while maintaining pixel value - * groupings for the Luminance plane only. - * This does not create a new image, but modifies this one instead. Create a - * copy before hand if you need to continue using the original. - * - * @return The modified image. - */ - public ColorImage luminanceEqualize() throws NIVisionException { - NIVision.imaqColorEqualize(image, image, 0); - return this; - } + /** + * Calculates the histogram of each plane of a color image and redistributes + * pixel values across the desired range while maintaining pixel value + * groupings for the Luminance plane only. This does not create a new image, + * but modifies this one instead. Create a copy before hand if you need to + * continue using the original. + * + * @return The modified image. + */ + public ColorImage luminanceEqualize() throws NIVisionException { + NIVision.imaqColorEqualize(image, image, 0); + return this; + } } diff --git a/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/image/HSLImage.java b/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/image/HSLImage.java index f335c35922..00fc319dd9 100644 --- a/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/image/HSLImage.java +++ b/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/image/HSLImage.java @@ -1,8 +1,8 @@ /*----------------------------------------------------------------------------*/ -/* Copyright (c) FIRST 2008-2012. All Rights Reserved. */ -/* Open Source Software - may be modified and shared by FRC teams. The code */ +/* Copyright (c) FIRST 2008-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 the root directory of */ -/* the project. */ +/* the project. */ /*----------------------------------------------------------------------------*/ package edu.wpi.first.wpilibj.image; @@ -10,27 +10,29 @@ import com.ni.vision.NIVision; /** * A color image represented in HSL color space at 3 bytes per pixel. + *$ * @author dtjones */ public class HSLImage extends ColorImage { - /** - * Create a new 0x0 image. - */ - public HSLImage() throws NIVisionException { - super(NIVision.ImageType.IMAGE_HSL); - } + /** + * Create a new 0x0 image. + */ + public HSLImage() throws NIVisionException { + super(NIVision.ImageType.IMAGE_HSL); + } - HSLImage(HSLImage sourceImage) { - super(sourceImage); - } + HSLImage(HSLImage sourceImage) { + super(sourceImage); + } - /** - * Create a new image by loading a file. - * @param fileName The path of the file to load. - */ - public HSLImage(String fileName) throws NIVisionException { - super(NIVision.ImageType.IMAGE_HSL); - NIVision.imaqReadFile(image, fileName); - } + /** + * Create a new image by loading a file. + *$ + * @param fileName The path of the file to load. + */ + public HSLImage(String fileName) throws NIVisionException { + super(NIVision.ImageType.IMAGE_HSL); + NIVision.imaqReadFile(image, fileName); + } } diff --git a/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/image/ImageBase.java b/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/image/ImageBase.java index b404d7db49..319d83451c 100644 --- a/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/image/ImageBase.java +++ b/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/image/ImageBase.java @@ -1,8 +1,8 @@ /*----------------------------------------------------------------------------*/ -/* Copyright (c) FIRST 2008-2012. All Rights Reserved. */ -/* Open Source Software - may be modified and shared by FRC teams. The code */ +/* Copyright (c) FIRST 2008-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 the root directory of */ -/* the project. */ +/* the project. */ /*----------------------------------------------------------------------------*/ package edu.wpi.first.wpilibj.image; @@ -11,69 +11,68 @@ import com.ni.vision.NIVision.Image; /** * Class representing a generic image. + *$ * @author dtjones */ public abstract class ImageBase { - /** - * Pointer to the image memory - */ - public final Image image; - static final int DEFAULT_BORDER_SIZE = 3; + /** + * Pointer to the image memory + */ + public final Image image; + static final int DEFAULT_BORDER_SIZE = 3; - ImageBase(NIVision.ImageType type) throws NIVisionException { - image = NIVision.imaqCreateImage(type, DEFAULT_BORDER_SIZE); - } + ImageBase(NIVision.ImageType type) throws NIVisionException { + image = NIVision.imaqCreateImage(type, DEFAULT_BORDER_SIZE); + } - /** - * Creates a new image pointing to the same data as the source image. The - * imgae data is not copied, it is just referenced by both objects. Freeing - * one will free both. - * @param sourceImage The image to reference - */ - ImageBase(ImageBase sourceImage) { - image = sourceImage.image; - } + /** + * Creates a new image pointing to the same data as the source image. The + * imgae data is not copied, it is just referenced by both objects. Freeing + * one will free both. + *$ + * @param sourceImage The image to reference + */ + ImageBase(ImageBase sourceImage) { + image = sourceImage.image; + } - /** - * Write the image to a file. - * - * Supported extensions: - * .aipd or .apd AIPD - * .bmp BMP - * .jpg or .jpeg JPEG - * .jp2 JPEG2000 - * .png PNG - * .tif or .tiff TIFF - * - * @param fileName The path to write the image to. - */ - public void write(String fileName) throws NIVisionException { - NIVision.RGBValue value = new NIVision.RGBValue(); - NIVision.imaqWriteFile(image, fileName, value); - value.free(); - } + /** + * Write the image to a file. + * + * Supported extensions: .aipd or .apd AIPD .bmp BMP .jpg or .jpeg JPEG .jp2 + * JPEG2000 .png PNG .tif or .tiff TIFF + * + * @param fileName The path to write the image to. + */ + public void write(String fileName) throws NIVisionException { + NIVision.RGBValue value = new NIVision.RGBValue(); + NIVision.imaqWriteFile(image, fileName, value); + value.free(); + } - /** - * Release the memory associated with an image. - */ - public void free() throws NIVisionException { - image.free(); - } + /** + * Release the memory associated with an image. + */ + public void free() throws NIVisionException { + image.free(); + } - /** - * Get the height of the image in pixels. - * @return The height of the image. - */ - public int getHeight() throws NIVisionException { - return NIVision.imaqGetImageSize(image).height; - } + /** + * Get the height of the image in pixels. + *$ + * @return The height of the image. + */ + public int getHeight() throws NIVisionException { + return NIVision.imaqGetImageSize(image).height; + } - /** - * Get the width of the image in pixels. - * @return The width of the image. - */ - public int getWidth() throws NIVisionException { - return NIVision.imaqGetImageSize(image).width; - } + /** + * Get the width of the image in pixels. + *$ + * @return The width of the image. + */ + public int getWidth() throws NIVisionException { + return NIVision.imaqGetImageSize(image).width; + } } diff --git a/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/image/MonoImage.java b/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/image/MonoImage.java index 86c9562990..8cfb85e3f9 100644 --- a/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/image/MonoImage.java +++ b/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/image/MonoImage.java @@ -1,8 +1,8 @@ /*----------------------------------------------------------------------------*/ -/* Copyright (c) FIRST 2008-2012. All Rights Reserved. */ -/* Open Source Software - may be modified and shared by FRC teams. The code */ +/* Copyright (c) FIRST 2008-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 the root directory of */ -/* the project. */ +/* the project. */ /*----------------------------------------------------------------------------*/ package edu.wpi.first.wpilibj.image; @@ -15,29 +15,31 @@ import com.ni.vision.NIVision.DetectEllipsesResult; /** * A grey scale image represented at a byte per pixel. + *$ * @author dtjones */ public class MonoImage extends ImageBase { - /** - * Create a new 0x0 image. - */ - public MonoImage() throws NIVisionException { - super(NIVision.ImageType.IMAGE_U8); - } + /** + * Create a new 0x0 image. + */ + public MonoImage() throws NIVisionException { + super(NIVision.ImageType.IMAGE_U8); + } - MonoImage(MonoImage sourceImage) { - super(sourceImage); - } + MonoImage(MonoImage sourceImage) { + super(sourceImage); + } - public DetectEllipsesResult detectEllipses(EllipseDescriptor ellipseDescriptor, - CurveOptions curveOptions, ShapeDetectionOptions shapeDetectionOptions, - ROI roi) throws NIVisionException { - return NIVision.imaqDetectEllipses(image, ellipseDescriptor, curveOptions, shapeDetectionOptions, roi); - } + public DetectEllipsesResult detectEllipses(EllipseDescriptor ellipseDescriptor, + CurveOptions curveOptions, ShapeDetectionOptions shapeDetectionOptions, ROI roi) + throws NIVisionException { + return NIVision.imaqDetectEllipses(image, ellipseDescriptor, curveOptions, + shapeDetectionOptions, roi); + } - public DetectEllipsesResult detectEllipses(EllipseDescriptor ellipseDescriptor) - throws NIVisionException { - return NIVision.imaqDetectEllipses(image, ellipseDescriptor, null, null, null); - } + public DetectEllipsesResult detectEllipses(EllipseDescriptor ellipseDescriptor) + throws NIVisionException { + return NIVision.imaqDetectEllipses(image, ellipseDescriptor, null, null, null); + } } diff --git a/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/image/NIVisionException.java b/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/image/NIVisionException.java index 806119ea76..ddf096cc8e 100644 --- a/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/image/NIVisionException.java +++ b/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/image/NIVisionException.java @@ -1,1194 +1,1199 @@ /*----------------------------------------------------------------------------*/ -/* Copyright (c) FIRST 2008-2012. All Rights Reserved. */ -/* Open Source Software - may be modified and shared by FRC teams. The code */ +/* Copyright (c) FIRST 2008-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 the root directory of */ -/* the project. */ +/* the project. */ /*----------------------------------------------------------------------------*/ package edu.wpi.first.wpilibj.image; /** * Exception class which looks up nivision error codes + *$ * @author dtjones */ public class NIVisionException extends Exception { - /** - * Create a new NIVisionException. - * @param msg The message to pass with the exception describing what caused it. - */ - public NIVisionException(String msg) { - super(msg); - } + /** + * Create a new NIVisionException. + *$ + * @param msg The message to pass with the exception describing what caused + * it. + */ + public NIVisionException(String msg) { + super(msg); + } - /** - * Create a new vision exception - * @param errorCode the bad status code - */ - public NIVisionException(int errorCode) { - super(lookUpCode(errorCode)); - } - private static String lookUpCode(int errorCode) { + /** + * Create a new vision exception + *$ + * @param errorCode the bad status code + */ + public NIVisionException(int errorCode) { + super(lookUpCode(errorCode)); + } - switch (errorCode) { - case 0: - return "No error."; - case -1074396160: - return "System error."; - case -1074396159: - return "Not enough memory for requested operation."; - case -1074396158: - return "Memory error."; - case -1074396157: - return "Unlicensed copy of NI Vision."; - case -1074396156: - return "The function requires an NI Vision 5.0 Advanced license."; - case -1074396155: - return "NI Vision did not initialize properly."; - case -1074396154: - return "The image is not large enough for the operation."; - case -1074396153: - return "The barcode is not a valid Codabar barcode."; - case -1074396152: - return "The barcode is not a valid Code 3 of 9 barcode."; - case -1074396151: - return "The barcode is not a valid Code93 barcode."; - case -1074396150: - return "The barcode is not a valid Code128 barcode."; - case -1074396149: - return "The barcode is not a valid EAN8 barcode."; - case -1074396148: - return "The barcode is not a valid EAN13 barcode."; - case -1074396147: - return "The barcode is not a valid Interleaved 2 of 5 barcode."; - case -1074396146: - return "The barcode is not a valid MSI barcode."; - case -1074396145: - return "The barcode is not a valid UPCA barcode."; - case -1074396144: - return "The Code93 barcode contains invalid shift encoding."; - case -1074396143: - return "The barcode type is invalid."; - case -1074396142: - return "The image does not represent a valid linear barcode."; - case -1074396141: - return "The FNC value in the Code128 barcode is not located before the first data value."; - case -1074396140: - return "The starting code set in the Code128 barcode is not valid."; - case -1074396139: - return "Not enough reserved memory in the timed environment for the requested operation."; - case -1074396138: - return "The function is not supported when a time limit is active."; - case -1074396137: - return "Quartz.dll not found. Install DirectX 8.1 or later."; - case -1074396136: - return "The filter quality you provided is invalid. Valid quality values range from -1 to 1000."; - case -1074396135: - return "Invalid button label."; - case -1074396134: - return "Could not execute the function in the separate thread because the thread has not completed initialization."; - case -1074396133: - return "Could not execute the function in the separate thread because the thread could not initialize."; - case -1074396132: - return "The mask must be the same size as the template."; - case -1074396130: - return "The ROI must only have either a single Rectangle contour or a single Rotated Rectangle contour."; - case -1074396129: - return "During timed execution, you must use the preallocated version of this operation."; - case -1074396128: - return "An image being modified by one process cannot be requested by another process while a time limit is active."; - case -1074396127: - return "An image with pattern matching, calibration, or overlay information cannot be manipulated while a time limit is active."; - case -1074396126: - return "An image created before a time limit is started cannot be resized while a time limit is active."; - case -1074396125: - return "Invalid contrast threshold. The threshold value must be greater than 0. "; - case -1074396124: - return "NI Vision does not support the calibration ROI mode you supplied."; - case -1074396123: - return "NI Vision does not support the calibration mode you supplied."; - case -1074396122: - return "Set the foreground and background text colors to grayscale to draw on a U8 image."; - case -1074396121: - return "The value of the saturation threshold must be from 0 to 255."; - case -1074396120: - return "Not an image."; - case -1074396119: - return "They custom data key you supplied is invalid. The only valid character values are decimal 32-126 and 161-255. There must also be no repeated, leading, or trailing spaces."; - case -1074396118: - return "Step size must be greater than zero."; - case -1074396117: - return "Invalid matrix size in the structuring element."; - case -1074396116: - return "Insufficient number of calibration feature points."; - case -1074396115: - return "The operation is invalid in a corrected image."; - case -1074396114: - return "The ROI contains an invalid contour type or is not contained in the ROI learned for calibration."; - case -1074396113: - return "The source/input image has not been calibrated."; - case -1074396112: - return "The number of pixel and real-world coordinates must be equal."; - case -1074396111: - return "Unable to automatically detect grid because the image is too distorted."; - case -1074396110: - return "Invalid calibration information version."; - case -1074396109: - return "Invalid calibration scaling factor."; - case -1074396108: - return "The calibration error map cannot be computed."; - case -1074396107: - return "Invalid calibration template image."; - case -1074396106: - return "Invalid calibration template image."; - case -1074396105: - return "Invalid calibration template image."; - case -1074396104: - return "Invalid calibration template image."; - case -1074396103: - return "Invalid calibration template image."; - case -1074396102: - return "Invalid calibration template image."; - case -1074396101: - return "Invalid calibration template image."; - case -1074396100: - return "Invalid calibration template image."; - case -1074396099: - return "Invalid calibration template image."; - case -1074396098: - return "You must pass NULL for the reserved parameter."; - case -1074396097: - return "You entered an invalid selection in the particle parameter."; - case -1074396096: - return "Not an object."; - case -1074396095: - return "The reference points passed are inconsistent. At least two similar pixel coordinates correspond to different real-world coordinates."; - case -1074396094: - return "A resource conflict occurred in the timed environment. Two processes cannot manage the same resource and be time bounded."; - case -1074396093: - return "A resource conflict occurred in the timed environment. Two processes cannot access the same resource and be time bounded."; - case -1074396092: - return "Multiple timed environments are not supported."; - case -1074396091: - return "A time limit cannot be started until the timed environment is initialized."; - case -1074396090: - return "Multiple timed environments are not supported."; - case -1074396089: - return "The timed environment is already initialized."; - case -1074396088: - return "The results of the operation exceeded the size limits on the output data arrays."; - case -1074396087: - return "No time limit is available to stop."; - case -1074396086: - return "A time limit could not be set."; - case -1074396085: - return "The timed environment could not be initialized."; - case -1074396084: - return "No initialized timed environment is available to close."; - case -1074396083: - return "The time limit has expired."; - case -1074396082: - return "Only 8-bit images support the use of palettes. Either do not use a palette, or convert your image to an 8-bit image before using a palette."; - case -1074396081: - return "Incorrect password."; - case -1074396080: - return "Invalid image type."; - case -1074396079: - return "Invalid metafile handle."; - case -1074396077: - return "Incompatible image type."; - case -1074396076: - return "Unable to fit a line for the primary axis."; - case -1074396075: - return "Unable to fit a line for the secondary axis."; - case -1074396074: - return "Incompatible image size."; - case -1074396073: - return "When the mask's offset was applied, the mask was entirely outside of the image."; - case -1074396072: - return "Invalid image border."; - case -1074396071: - return "Invalid scan direction."; - case -1074396070: - return "Unsupported function."; - case -1074396069: - return "NI Vision does not support the color mode you specified."; - case -1074396068: - return "The function does not support the requested action."; - case -1074396067: - return "The source image and destination image must be different."; - case -1074396066: - return "Invalid point symbol."; - case -1074396065: - return "Cannot resize an image in an acquisition buffer."; - case -1074396064: - return "This operation is not supported for images in an acquisition buffer."; - case -1074396063: - return "The external buffer must be aligned on a 4-byte boundary. The line width and border pixels must be 4-byte aligned, as well."; - case -1074396062: - return "The tolerance parameter must be greater than or equal to 0."; - case -1074396061: - return "The size of each dimension of the window must be greater than 2 and less than or equal to the size of the image in the corresponding dimension."; - case -1074396060: - return "Lossless compression cannot be used with the floating point wavelet transform mode. Either set the wavelet transform mode to integer, or use lossy compression."; - case -1074396059: - return "Invalid maximum number of iterations. Maximum number of iterations must be greater than zero."; - case -1074396058: - return "Invalid rotation mode."; - case -1074396057: - return "Invalid search vector width. The width must be an odd number greater than zero."; - case -1074396056: - return "Invalid matrix mirror mode."; - case -1074396055: - return "Invalid aspect ratio. Valid aspect ratios must be greater than or equal to zero."; - case -1074396054: - return "Invalid cell fill type."; - case -1074396053: - return "Invalid border integrity. Valid values range from 0 to 100."; - case -1074396052: - return "Invalid demodulation mode."; - case -1074396051: - return "Invalid cell filter mode."; - case -1074396050: - return "Invalid ECC type."; - case -1074396049: - return "Invalid matrix polarity."; - case -1074396048: - return "Invalid cell sample size."; - case -1074396047: - return "Invalid linear average mode."; - case -1074396046: - return "When using a region of interest that is not a rectangle, you must specify the contrast mode of the barcode as either black on white or white on black."; - case -1074396045: - return "Invalid 2-D barcode Data Matrix subtype."; - case -1074396044: - return "Invalid 2-D barcode shape."; - case -1074396043: - return "Invalid 2-D barcode cell shape."; - case -1074396042: - return "Invalid 2-D barcode contrast."; - case -1074396041: - return "Invalid 2-D barcode type."; - case -1074396040: - return "Cannot access NI-IMAQ driver."; - case -1074396039: - return "I/O error."; - case -1074396038: - return "When searching for a coordinate system, the number of lines to fit must be 1."; - case -1074396037: - return "Trigger timeout."; - case -1074396036: - return "The Skeleton mode you specified is invalid."; - case -1074396035: - return "The template image does not contain enough information for learning the aggressive search strategy."; - case -1074396034: - return "The template image does not contain enough edge information for the sample size(s) requested."; - case -1074396033: - return "Invalid template descriptor."; - case -1074396032: - return "The template descriptor does not contain data required for the requested search strategy in rotation-invariant matching."; - case -1074396026: - return "Invalid process type for edge detection."; - case -1074396025: - return "Angle range value should be equal to or greater than zero."; - case -1074396024: - return "Minimum coverage value should be greater than zero."; - case -1074396023: - return "The angle tolerance should be equal to or greater than 0.001."; - case -1074396022: - return "Invalid search mode for detecting straight edges"; - case -1074396021: - return "Invalid kernel size for edge detection. The minimum kernel size is 3, the maximum kernel size is 1073741823 and the kernel size must be odd."; - case -1074396020: - return "Invalid grading mode."; - case -1074396019: - return "Invalid threshold percentage. Valid values range from 0 to 100."; - case -1074396018: - return "Invalid edge polarity search mode."; - case -1074396017: - return "The AIM grading data attached to the image you tried to open was created with a newer version of NI Vision. Upgrade to the latest version of NI Vision to read this file."; - case -1074396016: - return "No video driver is installed."; - case -1074396015: - return "Unable to establish network connection with remote system."; - case -1074396014: - return "RT Video Out does not support displaying the supplied image type at the selected color depth."; - case -1074396013: - return "Invalid video mode."; - case -1074396012: - return "Unable to display remote image on network connection."; - case -1074396011: - return "Unable to establish network connection."; - case -1074396010: - return "Invalid frame number."; - case -1074396009: - return "An internal DirectX error has occurred. Try upgrading to the latest version of DirectX."; - case -1074396008: - return "An appropriate DirectX filter to process this file could not be found. Install the filter that was used to create this AVI. Upgrading to the latest version of DirectX may correct this error. NI Vision requires DirectX 8.1 or higher."; - case -1074396007: - return "Incompatible compression filter."; - case -1074396006: - return "Unknown compression filter."; - case -1074396005: - return "Invalid AVI session."; - case -1074396004: - return "A software key is restricting the use of this compression filter."; - case -1074396003: - return "The data for this frame exceeds the data buffer size specified when creating the AVI file."; - case -1074396002: - return "Invalid line gauge method."; - case -1074396001: - return "There are too many AVI sessions open. You must close a session before you can open another one."; - case -1074396000: - return "Invalid file header."; - case -1074395999: - return "Invalid file type."; - case -1074395998: - return "Invalid color table."; - case -1074395997: - return "Invalid parameter."; - case -1074395996: - return "File is already open for writing."; - case -1074395995: - return "File not found."; - case -1074395994: - return "Too many files open."; - case -1074395993: - return "File I/O error."; - case -1074395992: - return "File access denied."; - case -1074395991: - return "NI Vision does not support the file type you specified."; - case -1074395990: - return "Could not read Vision info from file."; - case -1074395989: - return "Unable to read data."; - case -1074395988: - return "Unable to write data."; - case -1074395987: - return "Premature end of file."; - case -1074395986: - return "Invalid file format."; - case -1074395985: - return "Invalid file operation."; - case -1074395984: - return "NI Vision does not support the file data type you specified."; - case -1074395983: - return "Disk full."; - case -1074395982: - return "The frames per second in an AVI must be greater than zero."; - case -1074395981: - return "The buffer that was passed in is not big enough to hold all of the data."; - case -1074395980: - return "Error initializing COM."; - case -1074395979: - return "The image has invalid particle information. Call imaqCountParticles on the image to create particle information."; - case -1074395978: - return "Invalid particle number."; - case -1074395977: - return "The AVI file was created in a newer version of NI Vision. Upgrade to the latest version of NI Vision to read this AVI file."; - case -1074395976: - return "The color palette must have exactly 0 or 256 entries."; - case -1074395975: - return "DirectX has timed out reading or writing the AVI file. When closing an AVI file, try adding an additional delay. When reading an AVI file, try reducing CPU and disk load."; - case -1074395974: - return "NI Vision does not support reading JPEG2000 files with this colorspace method."; - case -1074395973: - return "NI Vision does not support reading JPEG2000 files with more than one layer."; - case -1074395972: - return "DirectX is unable to enumerate the compression filters. This is caused by a third-party compression filter that is either improperly installed or is preventing itself from being enumerated. Remove any recently installed compression filters and try again."; - case -1074395971: - return "The offset you specified must be size 2."; - case -1074395960: - return "Initialization error."; - case -1074395959: - return "Unable to create window."; - case -1074395958: - return "Invalid window ID."; - case -1074395957: - return "The array sizes are not compatible."; - case -1074395956: - return "The quality you provided is invalid. Valid quality values range from -1 to 1000."; - case -1074395955: - return "Invalid maximum wavelet transform level. Valid values range from 0 to 255."; - case -1074395954: - return "The quantization step size must be greater than or equal to 0."; - case -1074395953: - return "Invalid wavelet transform mode."; - case -1074395920: - return "Invalid number of classes."; - case -1074395880: - return "Invalid particle."; - case -1074395879: - return "Invalid measure number."; - case -1074395878: - return "The ImageBase Display control does not support writing this property node."; - case -1074395877: - return "The specified color mode requires the use of imaqChangeColorSpace2."; - case -1074395876: - return "This function does not currently support the color mode you specified."; - case -1074395875: - return "The barcode is not a valid Pharmacode symbol"; - case -1074395840: - return "Invalid handle table index."; - case -1074395837: - return "The compression ratio must be greater than or equal to 1."; - case -1074395801: - return "The ROI contains too many contours."; - case -1074395800: - return "Protection error."; - case -1074395799: - return "Internal error."; - case -1074395798: - return "The size of the feature vector in the custom sample must match the size of those you have already added."; - case -1074395797: - return "Not a valid classifier session."; - case -1074395796: - return "You requested an invalid Nearest Neighbor classifier method."; - case -1074395795: - return "The k parameter must be greater than two."; - case -1074395794: - return "The k parameter must be <= the number of samples in each class."; - case -1074395793: - return "This classifier session is compact. Only the Classify and Dispose functions may be called on a compact classifier session."; - case -1074395792: - return "This classifier session is not trained. You may only call this function on a trained classifier session."; - case -1074395791: - return "This classifier function cannot be called on this type of classifier session."; - case -1074395790: - return "You requested an invalid distance metric."; - case -1074395789: - return "The classifier session you tried to open was created with a newer version of NI Vision. Upgrade to the latest version of NI Vision to read this file."; - case -1074395788: - return "This operation cannot be performed because you have not added any samples."; - case -1074395787: - return "You requested an invalid classifier type."; - case -1074395786: - return "The sum of Scale Dependence and Symmetry Dependence must be less than 1000."; - case -1074395785: - return "The image yielded no particles."; - case -1074395784: - return "The limits you supplied are not valid."; - case -1074395783: - return "The Sample Index fell outside the range of Samples."; - case -1074395782: - return "The description must be <= 255 characters."; - case -1074395781: - return "The engine for this classifier session does not support this operation."; - case -1074395780: - return "You requested an invalid particle type."; - case -1074395779: - return "You may only save a session in compact form if it is trained."; - case -1074395778: - return "The Kernel size must be smaller than the image size."; - case -1074395777: - return "The session you read from file must be the same type as the session you passed in."; - case -1074395776: - return "You can not use a compact classification file with read options other than Read All."; - case -1074395775: - return "The ROI you passed in may only contain closed contours."; - case -1074395774: - return "You must pass in a label."; - case -1074395773: - return "You must provide a destination image."; - case -1074395772: - return "You provided an invalid registration method."; - case -1074395771: - return "The golden template you tried to open was created with a newer version of NI Vision. Upgrade to the latest version of NI Vision to read this file."; - case -1074395770: - return "Invalid golden template."; - case -1074395769: - return "Edge Thickness to Ignore must be greater than zero."; - case -1074395768: - return "Scale must be greater than zero."; - case -1074395767: - return "The supplied scale is invalid for your template."; - case -1074395766: - return "This backwards-compatibility function can not be used with this session. Use newer, supported functions instead."; - case -1074395763: - return "You must provide a valid normalization method."; - case -1074395762: - return "The deviation factor for Niblack local threshold must be between 0 and 1."; - case -1074395760: - return "Board not found."; - case -1074395758: - return "Board not opened."; - case -1074395757: - return "DLL not found."; - case -1074395756: - return "DLL function not found."; - case -1074395754: - return "Trigger timeout."; - case -1074395728: - return "NI Vision does not support the search mode you provided."; - case -1074395727: - return "NI Vision does not support the search mode you provided for the type of 2D barcode for which you are searching."; - case -1074395726: - return "matchFactor has been obsoleted. Instead, set the initialMatchListLength and matchListReductionFactor in the MatchPatternAdvancedOptions structure."; - case -1074395725: - return "The data was stored with a newer version of NI Vision. Upgrade to the latest version of NI Vision to read this data."; - case -1074395724: - return "The size you specified is out of the valid range."; - case -1074395723: - return "The key you specified cannot be found in the image."; - case -1074395722: - return "Custom classifier sessions only classify feature vectors. They do not support classifying images."; - case -1074395721: - return "NI Vision does not support the bit depth you supplied for the image you supplied."; - case -1074395720: - return "Invalid ROI."; - case -1074395719: - return "Invalid ROI global rectangle."; - case -1074395718: - return "The version of LabVIEW or BridgeVIEW you are running does not support this operation."; - case -1074395717: - return "The range you supplied is invalid."; - case -1074395716: - return "NI Vision does not support the scaling method you provided."; - case -1074395715: - return "NI Vision does not support the calibration unit you supplied."; - case -1074395714: - return "NI Vision does not support the axis orientation you supplied."; - case -1074395713: - return "Value not in enumeration."; - case -1074395712: - return "You selected a region that is not of the right type."; - case -1074395711: - return "You specified a viewer that does not contain enough regions."; - case -1074395710: - return "The image has too many particles for this process."; - case -1074395709: - return "The AVI session has not been opened."; - case -1074395708: - return "The AVI session is a write session, but this operation requires a read session."; - case -1074395707: - return "The AVI session is a read session, but this operation requires a write session."; - case -1074395706: - return "This AVI session is already open. You must close it before calling the Create or Open functions."; - case -1074395705: - return "The data is corrupted and cannot be read."; - case -1074395704: - return "Invalid compression type."; - case -1074395703: - return "Invalid type of flatten."; - case -1074395702: - return "The length of the edge detection line must be greater than zero."; - case -1074395701: - return "The maximum Data Matrix barcode size must be equal to or greater than the minimum Data Matrix barcode size."; - case -1074395700: - return "The function requires the operating system to be Microsoft Windows 2000 or newer."; - case -1074395656: - return "You must specify the same value for the smooth contours advanced match option for all templates you want to match."; - case -1074395655: - return "You must specify the same value for the enable calibration support advanced match option for all templates you want to match."; - case -1074395654: - return "The source image does not contain grading information. You must prepare the source image for grading when reading the Data Matrix, and you cannot change the contents of the source image between reading and grading the Data Matrix."; - case -1074395653: - return "The multiple geometric matching template you tried to open was created with a newer version of NI Vision. Upgrade to the latest version of NI Vision to read this file."; - case -1074395652: - return "The geometric matching template you tried to open was created with a newer version of NI Vision. Upgrade to the latest version of NI Vision to read this file."; - case -1074395651: - return "You must specify the same edge filter size for all the templates you want to match."; - case -1074395650: - return "You must specify the same curve extraction mode for all the templates you want to match."; - case -1074395649: - return "The geometric feature type specified is invalid."; - case -1074395648: - return "You supplied a template that was not learned."; - case -1074395647: - return "Invalid multiple geometric template."; - case -1074395646: - return "Need at least one template to learn."; - case -1074395645: - return "You supplied an invalid number of labels."; - case -1074395644: - return "Labels must be <= 255 characters."; - case -1074395643: - return "You supplied an invalid number of match options."; - case -1074395642: - return "Cannot find a label that matches the one you specified."; - case -1074395641: - return "Duplicate labels are not allowed."; - case -1074395640: - return "The number of zones found exceeded the capacity of the algorithm."; - case -1074395639: - return "The hatch style for the window background is invalid."; - case -1074395638: - return "The fill style for the window background is invalid."; - case -1074395637: - return "Your hardware is not supported by DirectX and cannot be put into NonTearing mode."; - case -1074395636: - return "DirectX is required for this feature. Please install the latest version.."; - case -1074395635: - return "The passed shape descriptor is invalid."; - case -1074395634: - return "Invalid max match overlap. Values must be between -1 and 100."; - case -1074395633: - return "Invalid minimum match separation scale. Values must be greater than or equal to -1."; - case -1074395632: - return "Invalid minimum match separation angle. Values must be between -1 and 360."; - case -1074395631: - return "Invalid minimum match separation distance. Values must be greater than or equal to -1."; - case -1074395630: - return "Invalid maximum number of features learn. Values must be integers greater than zero."; - case -1074395629: - return "Invalid maximum pixel distance from line. Values must be positive real numbers."; - case -1074395628: - return "Invalid geometric matching template image."; - case -1074395627: - return "The template does not contain enough features for geometric matching."; - case -1074395626: - return "The template does not contain enough features for geometric matching."; - case -1074395625: - return "You specified an invalid value for the match constraint value of the range settings."; - case -1074395624: - return "Invalid occlusion range. Valid values for the bounds range from 0 to 100 and the upper bound must be greater than or equal to the lower bound."; - case -1074395623: - return "Invalid scale range. Values for the lower bound must be a positive real numbers and the upper bound must be greater than or equal to the lower bound."; - case -1074395622: - return "Invalid match geometric pattern setup data."; - case -1074395621: - return "Invalid learn geometric pattern setup data."; - case -1074395620: - return "Invalid curve extraction mode."; - case -1074395619: - return "You can specify only one occlusion range."; - case -1074395618: - return "You can specify only one scale range."; - case -1074395617: - return "The minimum number of features must be less than or equal to the maximum number of features."; - case -1074395616: - return "Invalid edge filter size."; - case -1074395615: - return "Invalid minimum strength for features. Values must be positive real numbers."; - case -1074395614: - return "Invalid aspect ratio for rectangular features. Values must be positive real numbers in the range 0.01 to 1.0."; - case -1074395613: - return "Invalid minimum length for linear features. Values must be integers greater than 0."; - case -1074395612: - return "Invalid minimum radius for circular features. Values must be integers greater than 0."; - case -1074395611: - return "Invalid minimum rectangle dimension. Values must be integers greater than 0."; - case -1074395610: - return "Invalid initial match list length. Values must be integers greater than 5."; - case -1074395609: - return "Invalid subpixel tolerance. Values must be positive real numbers."; - case -1074395608: - return "Invalid number of subpixel iterations. Values must be integers greater 10."; - case -1074395607: - return "Invalid maximum number of features used per match. Values must be integers greater than or equal to zero."; - case -1074395606: - return "Invalid minimum number of features used for matching. Values must be integers greater than zero."; - case -1074395605: - return "Invalid maximum end point gap. Valid values range from 0 to 32767."; - case -1074395604: - return "Invalid column step. Valid range is 1 to 255."; - case -1074395603: - return "Invalid row step. Valid range is 1 to 255."; - case -1074395602: - return "Invalid minimum length. Valid values must be greater than or equal to zero."; - case -1074395601: - return "Invalid edge threshold. Valid values range from 1 to 360."; - case -1074395600: - return "You must provide information about the subimage within the browser."; - case -1074395598: - return "The acceptance level is outside the valid range of 0 to 1000."; - case -1074395597: - return "Not a valid OCR session."; - case -1074395596: - return "Invalid character size. Character size must be >= 1."; - case -1074395595: - return "Invalid threshold mode value."; - case -1074395594: - return "Invalid substitution character. Valid substitution characters are ASCII values that range from 1 to 254."; - case -1074395593: - return "Invalid number of blocks. Number of blocks must be >= 4 and <= 50."; - case -1074395592: - return "Invalid read strategy."; - case -1074395591: - return "Invalid character index."; - case -1074395590: - return "Invalid number of character positions. Valid values range from 0 to 255."; - case -1074395589: - return "Invalid low threshold value. Valid threshold values range from 0 to 255."; - case -1074395588: - return "Invalid high threshold value. Valid threshold values range from 0 to 255."; - case -1074395587: - return "The low threshold must be less than the high threshold."; - case -1074395586: - return "Invalid lower threshold limit. Valid lower threshold limits range from 0 to 255."; - case -1074395585: - return "Invalid upper threshold limit. Valid upper threshold limits range from 0 to 255."; - case -1074395584: - return "The lower threshold limit must be less than the upper threshold limit."; - case -1074395583: - return "Invalid minimum character spacing value. Character spacing must be >= 0 pixels."; - case -1074395582: - return "Invalid maximum horizontal element spacing value. Maximum horizontal element spacing must be >= 0."; - case -1074395581: - return "Invalid maximum vertical element spacing value. Maximum vertical element spacing must be >= 0."; - case -1074395580: - return "Invalid minimum bounding rectangle width. Minimum bounding rectangle width must be >= 1."; - case -1074395579: - return "Invalid aspect ratio value. The aspect ratio must be zero or >= 100."; - case -1074395578: - return "Invalid or corrupt character set file."; - case -1074395577: - return "The character value must not be an empty string."; - case -1074395576: - return "Character values must be <=255 characters."; - case -1074395575: - return "Invalid number of erosions. The number of erosions must be >= 0."; - case -1074395574: - return "The character set description must be <=255 characters."; - case -1074395573: - return "The character set file was created by a newer version of NI Vision. Upgrade to the latest version of NI Vision to read the character set file."; - case -1074395572: - return "You must specify characters for a string. A string cannot contain integers."; - case -1074395571: - return "This attribute is read-only."; - case -1074395570: - return "This attribute requires a Boolean value."; - case -1074395569: - return "Invalid attribute."; - case -1074395568: - return "This attribute requires integer values."; - case -1074395567: - return "String values are invalid for this attribute. Enter a boolean value."; - case -1074395566: - return "Boolean values are not valid for this attribute. Enter an integer value."; - case -1074395565: - return "Requires a single-character string."; - case -1074395564: - return "Invalid predefined character value."; - case -1074395563: - return "This copy of NI OCR is unlicensed."; - case -1074395562: - return "String values are not valid for this attribute. Enter a Boolean value."; - case -1074395561: - return "The number of characters in the character value must match the number of objects in the image."; - case -1074395560: - return "Invalid object index."; - case -1074395559: - return "Invalid read option."; - case -1074395558: - return "The minimum character size must be less than the maximum character size."; - case -1074395557: - return "The minimum character bounding rectangle width must be less than the maximum character bounding rectangle width."; - case -1074395556: - return "The minimum character bounding rectangle height must be less than the maximum character bounding rectangle height."; - case -1074395555: - return "The maximum horizontal element spacing value must not exceed the minimum character spacing value."; - case -1074395554: - return "Invalid read resolution."; - case -1074395553: - return "Invalid minimum bounding rectangle height. The minimum bounding rectangle height must be >= 1."; - case -1074395552: - return "Not a valid character set."; - case -1074395551: - return "A trained OCR character cannot be renamed while it is a reference character."; - case -1074395550: - return "A character cannot have an ASCII value of 255."; - case -1074395549: - return "The number of objects found does not match the number of expected characters or patterns to verify."; - case -1074395410: - return "NI Vision does not support less than one icon per line."; - case -1074395409: - return "Invalid subpixel divisions."; - case -1074395408: - return "Invalid detection mode."; - case -1074395407: - return "Invalid contrast value. Valid contrast values range from 0 to 255."; - case -1074395406: - return "The coordinate system could not be found on this image."; - case -1074395405: - return "NI Vision does not support the text orientation value you supplied."; - case -1074395404: - return "UnwrapImage does not support the interpolation method value you supplied. Valid interpolation methods are zero order and bilinear. "; - case -1074395403: - return "The image was created in a newer version of NI Vision. Upgrade to the latest version of NI Vision to use this image."; - case -1074395402: - return "The function does not support the maximum number of points that you specified."; - case -1074395401: - return "The function does not support the matchFactor that you specified."; - case -1074395400: - return "The operation you have given Multicore Options is invalid. Please see the available enumeration values for Multicore Operation."; - case -1074395399: - return "You have given Multicore Options an invalid argument."; - case -1074395397: - return "A complex image is required."; - case -1074395395: - return "The input image must be a color image."; - case -1074395394: - return "The color mask removes too much color information."; - case -1074395393: - return "The color template image is too small."; - case -1074395392: - return "The color template image is too large."; - case -1074395391: - return "The contrast in the hue plane of the image is too low for learning shape features."; - case -1074395390: - return "The contrast in the luminance plane of the image is too low to learn shape features."; - case -1074395389: - return "Invalid color learn setup data."; - case -1074395388: - return "Invalid color learn setup data."; - case -1074395387: - return "Invalid color match setup data."; - case -1074395386: - return "Invalid color match setup data."; - case -1074395385: - return "Rotation-invariant color pattern matching requires a feature mode including shape."; - case -1074395384: - return "Invalid color template image."; - case -1074395383: - return "Invalid color template image."; - case -1074395382: - return "Invalid color template image."; - case -1074395381: - return "Invalid color template image."; - case -1074395380: - return "Invalid color template image."; - case -1074395379: - return "Invalid color template image."; - case -1074395378: - return "Invalid color template image."; - case -1074395377: - return "Invalid color template image."; - case -1074395376: - return "The color template image does not contain data required for shift-invariant color matching."; - case -1074395375: - return "Invalid color template image."; - case -1074395374: - return "Invalid color template image."; - case -1074395373: - return "Invalid color template image."; - case -1074395372: - return "The color template image does not contain data required for rotation-invariant color matching."; - case -1074395371: - return "Invalid color template image."; - case -1074395370: - return "Invalid color template image."; - case -1074395369: - return "Invalid color template image."; - case -1074395368: - return "Invalid color template image."; - case -1074395367: - return "Invalid color template image."; - case -1074395366: - return "The color template image does not contain data required for color matching in shape feature mode."; - case -1074395365: - return "The color template image does not contain data required for color matching in color feature mode."; - case -1074395364: - return "The ignore color spectra array is invalid."; - case -1074395363: - return "Invalid subsampling ratio."; - case -1074395362: - return "Invalid pixel width."; - case -1074395361: - return "Invalid steepness."; - case -1074395360: - return "Invalid complex plane."; - case -1074395357: - return "Invalid color ignore mode."; - case -1074395356: - return "Invalid minimum match score. Acceptable values range from 0 to 1000."; - case -1074395355: - return "Invalid number of matches requested. You must request a minimum of one match."; - case -1074395354: - return "Invalid color weight. Acceptable values range from 0 to 1000."; - case -1074395353: - return "Invalid search strategy."; - case -1074395352: - return "Invalid feature mode."; - case -1074395351: - return "NI Vision does not support rectangles with negative widths or negative heights."; - case -1074395350: - return "NI Vision does not support the vision information type you supplied."; - case -1074395349: - return "NI Vision does not support the SkeletonMethod value you supplied."; - case -1074395348: - return "NI Vision does not support the 3DPlane value you supplied."; - case -1074395347: - return "NI Vision does not support the 3DDirection value you supplied."; - case -1074395346: - return "imaqRotate does not support the InterpolationMethod value you supplied."; - case -1074395345: - return "NI Vision does not support the axis of symmetry you supplied."; - case -1074395343: - return "You must pass a valid file name. Do not pass in NULL."; - case -1074395340: - return "NI Vision does not support the SizeType value you supplied."; - case -1074395336: - return "You specified the dispatch status of an unknown algorithm."; - case -1074395335: - return "You are attempting to set the same algorithm to dispatch and to not dispatch. Remove one of the conflicting settings."; - case -1074395334: - return "NI Vision does not support the Conversion Method value you supplied."; - case -1074395333: - return "NI Vision does not support the VerticalTextAlignment value you supplied."; - case -1074395332: - return "NI Vision does not support the CompareFunction value you supplied."; - case -1074395331: - return "NI Vision does not support the BorderMethod value you supplied."; - case -1074395330: - return "Invalid border size. Acceptable values range from 0 to 50."; - case -1074395329: - return "NI Vision does not support the OutlineMethod value you supplied."; - case -1074395328: - return "NI Vision does not support the InterpolationMethod value you supplied."; - case -1074395327: - return "NI Vision does not support the ScalingMode value you supplied."; - case -1074395326: - return "imaqDrawLineOnImage does not support the DrawMode value you supplied."; - case -1074395325: - return "NI Vision does not support the DrawMode value you supplied."; - case -1074395324: - return "NI Vision does not support the ShapeMode value you supplied."; - case -1074395323: - return "NI Vision does not support the FontColor value you supplied."; - case -1074395322: - return "NI Vision does not support the TextAlignment value you supplied."; - case -1074395321: - return "NI Vision does not support the MorphologyMethod value you supplied."; - case -1074395320: - return "The template image is empty."; - case -1074395319: - return "NI Vision does not support the interpolation type you supplied."; - case -1074395318: - return "You supplied an insufficient number of points to perform this operation."; - case -1074395317: - return "You specified a point that lies outside the image."; - case -1074395316: - return "Invalid kernel code."; - case -1074395313: - return "Writing files is not supported on this device."; - case -1074395312: - return "The input image does not seem to be a valid LCD or LED calibration image."; - case -1074395311: - return "The color spectrum array you provided does not contain enough elements or contains an element set to not-a-number (NaN)."; - case -1074395310: - return "NI Vision does not support the PaletteType value you supplied."; - case -1074395309: - return "NI Vision does not support the WindowThreadPolicy value you supplied."; - case -1074395308: - return "NI Vision does not support the ColorSensitivity value you supplied."; - case -1074395307: - return "The precision parameter must be greater than 0."; - case -1074395306: - return "NI Vision does not support the Tool value you supplied."; - case -1074395305: - return "NI Vision does not support the ReferenceMode value you supplied."; - case -1074395304: - return "NI Vision does not support the MathTransformMethod value you supplied."; - case -1074395303: - return "Invalid number of classes for auto threshold. Acceptable values range from 2 to 256."; - case -1074395302: - return "NI Vision does not support the threshold method value you supplied."; - case -1074395301: - return "The ROI you passed into imaqGetMeterArc must consist of two lines."; - case -1074395300: - return "NI Vision does not support the MeterArcMode value you supplied."; - case -1074395299: - return "NI Vision does not support the ComplexPlane value you supplied."; - case -1074395298: - return "You can perform this operation on a real or an imaginary ComplexPlane only."; - case -1074395297: - return "NI Vision does not support the ParticleInfoMode value you supplied."; - case -1074395296: - return "NI Vision does not support the BarcodeType value you supplied."; - case -1074395295: - return "imaqInterpolatePoints does not support the InterpolationMethod value you supplied."; - case -1074395294: - return "The contour index you supplied is larger than the number of contours in the ROI."; - case -1074395293: - return "The supplied ContourID did not correlate to a contour inside the ROI."; - case -1074395292: - return "Do not supply collinear points for this operation."; - case -1074395291: - return "Shape Match requires the image to contain only pixel values of 0 or 1."; - case -1074395290: - return "The template you supplied for ShapeMatch contains no shape information."; - case -1074395287: - return "The line you provided contains two identical points, or one of the coordinate locations for the line is not a number (NaN)."; - case -1074395286: - return "Invalid concentric rake direction."; - case -1074395285: - return "Invalid spoke direction."; - case -1074395284: - return "Invalid edge process."; - case -1074395283: - return "Invalid rake direction."; - case -1074395282: - return "Unable to draw to viewer. You must have the latest version of the control."; - case -1074395281: - return "Your image must be larger than its border size for this operation."; - case -1074395280: - return "The ROI must only have a single Rectangle contour."; - case -1074395279: - return "ROI is not a polygon."; - case -1074395278: - return "LCD image is not a number."; - case -1074395277: - return "The decoded barcode information did not pass the checksum test."; - case -1074395276: - return "You specified parallel lines for the meter ROI."; - case -1074395275: - return "Invalid browser image."; - case -1074395270: - return "Cannot divide by zero."; - case -1074395269: - return "Null pointer."; - case -1074395268: - return "The linear equations are not independent."; - case -1074395267: - return "The roots of the equation are complex."; - case -1074395265: - return "The barcode does not match the type you specified."; - case -1074395263: - return "No lit segment."; - case -1074395262: - return "The LCD does not form a known digit."; - case -1074395261: - return "An internal error occurred while attempting to access an invalid coordinate on an image."; - case -1074395260: - return "An internal memory error occurred."; - case -1074395258: - return "The filter width must be odd for the Canny operator."; - case -1074395257: - return "You supplied an invalid edge direction in the Canny operator."; - case -1074395256: - return "The window size must be odd for the Canny operator. "; - case -1074395253: - return "Invalid learn mode."; - case -1074395252: - return "Invalid learn setup data."; - case -1074395251: - return "Invalid match mode."; - case -1074395250: - return "Invalid match setup data."; - case -1074395249: - return "At least one range in the array of rotation angle ranges exceeds 360 degrees."; - case -1074395248: - return "The array of rotation angle ranges contains too many ranges."; - case -1074395247: - return "Invalid template descriptor."; - case -1074395246: - return "Invalid template descriptor."; - case -1074395245: - return "Invalid template descriptor."; - case -1074395244: - return "Invalid template descriptor."; - case -1074395243: - return "The template descriptor was created with a newer version of NI Vision. Upgrade to the latest version of NI Vision to use this template."; - case -1074395242: - return "Invalid template descriptor."; - case -1074395241: - return "The template descriptor does not contain data required for rotation-invariant matching."; - case -1074395240: - return "Invalid template descriptor."; - case -1074395239: - return "Invalid template descriptor."; - case -1074395238: - return "The template descriptor does not contain data required for shift-invariant matching."; - case -1074395237: - return "Invalid template descriptor."; - case -1074395235: - return "The template image does not contain enough contrast."; - case -1074395234: - return "The template image is too small."; - case -1074395233: - return "The template image is too large."; - case -1074395212: - return "The size of the template string must match the size of the string you are trying to correct."; - case -1074395211: - return "The supplied text template contains nonstandard characters that cannot be generated by OCR."; - case -1074395210: - return "At least one character in the text template was of a lexical class that did not match the supplied character reports."; - case -1074395203: - return "The OCR library cannot be initialized correctly."; - case -1074395201: - return "There was a failure when loading one of the internal OCR engine or LabView libraries."; - case -1074395200: - return "One of the parameters supplied to the OCR function that generated this error is invalid."; - case -1074395179: - return "The OCR engine failed during the preprocessing stage."; - case -1074395178: - return "The OCR engine failed during the recognition stage."; - case -1074395175: - return "The provided filename is not valid user dictionary filename."; - case -1074395174: - return "NI Vision does not support the AutoOrientMode value you supplied."; - case -1074395173: - return "NI Vision does not support the Language value you supplied."; - case -1074395172: - return "NI Vision does not support the CharacterSet value you supplied."; - case -1074395171: - return "The system could not locate the initialization file required for OCR initialization."; - case -1074395170: - return "NI Vision does not support the CharacterType value you supplied."; - case -1074395169: - return "NI Vision does not support the RecognitionMode value you supplied."; - case -1074395168: - return "NI Vision does not support the AutoCorrectionMode value you supplied."; - case -1074395167: - return "NI Vision does not support the OutputDelimiter value you supplied."; - case -1074395166: - return "The system could not locate the OCR binary directory required for OCR initialization."; - case -1074395165: - return "The system could not locate the OCR weights directory required for OCR initialization."; - case -1074395164: - return "The supplied word could not be added to the user dictionary."; - case -1074395163: - return "NI Vision does not support the CharacterPreference value you supplied."; - case -1074395162: - return "NI Vision does not support the CorrectionMethod value you supplied."; - case -1074395161: - return "NI Vision does not support the CorrectionLevel value you supplied."; - case -1074395160: - return "NI Vision does not support the maximum point size you supplied. Valid values range from 4 to 72."; - case -1074395159: - return "NI Vision does not support the tolerance value you supplied. Valid values are non-negative."; - case -1074395158: - return "NI Vision does not support the ContrastMode value you supplied."; - case -1074395156: - return "The OCR attempted to detected the text skew and failed."; - case -1074395155: - return "The OCR attempted to detected the text orientation and failed."; - case -1074395153: - return "Invalid font file format."; - case -1074395152: - return "Font file not found."; - case -1074395151: - return "The OCR engine failed during the correction stage."; - case -1074395150: - return "NI Vision does not support the RoundingMode value you supplied."; - case -1074395149: - return "Found a duplicate transform type in the properties array. Each properties array may only contain one behavior for each transform type."; - case -1074395148: - return "Overlay Group Not Found."; - case -1074395147: - return "The barcode is not a valid RSS Limited symbol"; - case -1074395146: - return "Couldn't determine the correct version of the QR code."; - case -1074395145: - return "Invalid read of the QR code."; - case -1074395144: - return "The barcode that was read contains invalid parameters."; - case -1074395143: - return "The data stream that was demodulated could not be read because the mode was not detected."; - case -1074395142: - return "Couldn't determine the correct model of the QR code."; - case -1074395141: - return "The OCR engine could not find any text in the supplied region."; - case -1074395140: - return "One of the character reports is no longer usable by the system."; - case -1074395139: - return "Invalid Dimensions."; - case -1074395138: - return "The OCR region provided was too small to have contained any characters."; - default: - return "Error code not found"; - } + private static String lookUpCode(int errorCode) { + + switch (errorCode) { + case 0: + return "No error."; + case -1074396160: + return "System error."; + case -1074396159: + return "Not enough memory for requested operation."; + case -1074396158: + return "Memory error."; + case -1074396157: + return "Unlicensed copy of NI Vision."; + case -1074396156: + return "The function requires an NI Vision 5.0 Advanced license."; + case -1074396155: + return "NI Vision did not initialize properly."; + case -1074396154: + return "The image is not large enough for the operation."; + case -1074396153: + return "The barcode is not a valid Codabar barcode."; + case -1074396152: + return "The barcode is not a valid Code 3 of 9 barcode."; + case -1074396151: + return "The barcode is not a valid Code93 barcode."; + case -1074396150: + return "The barcode is not a valid Code128 barcode."; + case -1074396149: + return "The barcode is not a valid EAN8 barcode."; + case -1074396148: + return "The barcode is not a valid EAN13 barcode."; + case -1074396147: + return "The barcode is not a valid Interleaved 2 of 5 barcode."; + case -1074396146: + return "The barcode is not a valid MSI barcode."; + case -1074396145: + return "The barcode is not a valid UPCA barcode."; + case -1074396144: + return "The Code93 barcode contains invalid shift encoding."; + case -1074396143: + return "The barcode type is invalid."; + case -1074396142: + return "The image does not represent a valid linear barcode."; + case -1074396141: + return "The FNC value in the Code128 barcode is not located before the first data value."; + case -1074396140: + return "The starting code set in the Code128 barcode is not valid."; + case -1074396139: + return "Not enough reserved memory in the timed environment for the requested operation."; + case -1074396138: + return "The function is not supported when a time limit is active."; + case -1074396137: + return "Quartz.dll not found. Install DirectX 8.1 or later."; + case -1074396136: + return "The filter quality you provided is invalid. Valid quality values range from -1 to 1000."; + case -1074396135: + return "Invalid button label."; + case -1074396134: + return "Could not execute the function in the separate thread because the thread has not completed initialization."; + case -1074396133: + return "Could not execute the function in the separate thread because the thread could not initialize."; + case -1074396132: + return "The mask must be the same size as the template."; + case -1074396130: + return "The ROI must only have either a single Rectangle contour or a single Rotated Rectangle contour."; + case -1074396129: + return "During timed execution, you must use the preallocated version of this operation."; + case -1074396128: + return "An image being modified by one process cannot be requested by another process while a time limit is active."; + case -1074396127: + return "An image with pattern matching, calibration, or overlay information cannot be manipulated while a time limit is active."; + case -1074396126: + return "An image created before a time limit is started cannot be resized while a time limit is active."; + case -1074396125: + return "Invalid contrast threshold. The threshold value must be greater than 0. "; + case -1074396124: + return "NI Vision does not support the calibration ROI mode you supplied."; + case -1074396123: + return "NI Vision does not support the calibration mode you supplied."; + case -1074396122: + return "Set the foreground and background text colors to grayscale to draw on a U8 image."; + case -1074396121: + return "The value of the saturation threshold must be from 0 to 255."; + case -1074396120: + return "Not an image."; + case -1074396119: + return "They custom data key you supplied is invalid. The only valid character values are decimal 32-126 and 161-255. There must also be no repeated, leading, or trailing spaces."; + case -1074396118: + return "Step size must be greater than zero."; + case -1074396117: + return "Invalid matrix size in the structuring element."; + case -1074396116: + return "Insufficient number of calibration feature points."; + case -1074396115: + return "The operation is invalid in a corrected image."; + case -1074396114: + return "The ROI contains an invalid contour type or is not contained in the ROI learned for calibration."; + case -1074396113: + return "The source/input image has not been calibrated."; + case -1074396112: + return "The number of pixel and real-world coordinates must be equal."; + case -1074396111: + return "Unable to automatically detect grid because the image is too distorted."; + case -1074396110: + return "Invalid calibration information version."; + case -1074396109: + return "Invalid calibration scaling factor."; + case -1074396108: + return "The calibration error map cannot be computed."; + case -1074396107: + return "Invalid calibration template image."; + case -1074396106: + return "Invalid calibration template image."; + case -1074396105: + return "Invalid calibration template image."; + case -1074396104: + return "Invalid calibration template image."; + case -1074396103: + return "Invalid calibration template image."; + case -1074396102: + return "Invalid calibration template image."; + case -1074396101: + return "Invalid calibration template image."; + case -1074396100: + return "Invalid calibration template image."; + case -1074396099: + return "Invalid calibration template image."; + case -1074396098: + return "You must pass NULL for the reserved parameter."; + case -1074396097: + return "You entered an invalid selection in the particle parameter."; + case -1074396096: + return "Not an object."; + case -1074396095: + return "The reference points passed are inconsistent. At least two similar pixel coordinates correspond to different real-world coordinates."; + case -1074396094: + return "A resource conflict occurred in the timed environment. Two processes cannot manage the same resource and be time bounded."; + case -1074396093: + return "A resource conflict occurred in the timed environment. Two processes cannot access the same resource and be time bounded."; + case -1074396092: + return "Multiple timed environments are not supported."; + case -1074396091: + return "A time limit cannot be started until the timed environment is initialized."; + case -1074396090: + return "Multiple timed environments are not supported."; + case -1074396089: + return "The timed environment is already initialized."; + case -1074396088: + return "The results of the operation exceeded the size limits on the output data arrays."; + case -1074396087: + return "No time limit is available to stop."; + case -1074396086: + return "A time limit could not be set."; + case -1074396085: + return "The timed environment could not be initialized."; + case -1074396084: + return "No initialized timed environment is available to close."; + case -1074396083: + return "The time limit has expired."; + case -1074396082: + return "Only 8-bit images support the use of palettes. Either do not use a palette, or convert your image to an 8-bit image before using a palette."; + case -1074396081: + return "Incorrect password."; + case -1074396080: + return "Invalid image type."; + case -1074396079: + return "Invalid metafile handle."; + case -1074396077: + return "Incompatible image type."; + case -1074396076: + return "Unable to fit a line for the primary axis."; + case -1074396075: + return "Unable to fit a line for the secondary axis."; + case -1074396074: + return "Incompatible image size."; + case -1074396073: + return "When the mask's offset was applied, the mask was entirely outside of the image."; + case -1074396072: + return "Invalid image border."; + case -1074396071: + return "Invalid scan direction."; + case -1074396070: + return "Unsupported function."; + case -1074396069: + return "NI Vision does not support the color mode you specified."; + case -1074396068: + return "The function does not support the requested action."; + case -1074396067: + return "The source image and destination image must be different."; + case -1074396066: + return "Invalid point symbol."; + case -1074396065: + return "Cannot resize an image in an acquisition buffer."; + case -1074396064: + return "This operation is not supported for images in an acquisition buffer."; + case -1074396063: + return "The external buffer must be aligned on a 4-byte boundary. The line width and border pixels must be 4-byte aligned, as well."; + case -1074396062: + return "The tolerance parameter must be greater than or equal to 0."; + case -1074396061: + return "The size of each dimension of the window must be greater than 2 and less than or equal to the size of the image in the corresponding dimension."; + case -1074396060: + return "Lossless compression cannot be used with the floating point wavelet transform mode. Either set the wavelet transform mode to integer, or use lossy compression."; + case -1074396059: + return "Invalid maximum number of iterations. Maximum number of iterations must be greater than zero."; + case -1074396058: + return "Invalid rotation mode."; + case -1074396057: + return "Invalid search vector width. The width must be an odd number greater than zero."; + case -1074396056: + return "Invalid matrix mirror mode."; + case -1074396055: + return "Invalid aspect ratio. Valid aspect ratios must be greater than or equal to zero."; + case -1074396054: + return "Invalid cell fill type."; + case -1074396053: + return "Invalid border integrity. Valid values range from 0 to 100."; + case -1074396052: + return "Invalid demodulation mode."; + case -1074396051: + return "Invalid cell filter mode."; + case -1074396050: + return "Invalid ECC type."; + case -1074396049: + return "Invalid matrix polarity."; + case -1074396048: + return "Invalid cell sample size."; + case -1074396047: + return "Invalid linear average mode."; + case -1074396046: + return "When using a region of interest that is not a rectangle, you must specify the contrast mode of the barcode as either black on white or white on black."; + case -1074396045: + return "Invalid 2-D barcode Data Matrix subtype."; + case -1074396044: + return "Invalid 2-D barcode shape."; + case -1074396043: + return "Invalid 2-D barcode cell shape."; + case -1074396042: + return "Invalid 2-D barcode contrast."; + case -1074396041: + return "Invalid 2-D barcode type."; + case -1074396040: + return "Cannot access NI-IMAQ driver."; + case -1074396039: + return "I/O error."; + case -1074396038: + return "When searching for a coordinate system, the number of lines to fit must be 1."; + case -1074396037: + return "Trigger timeout."; + case -1074396036: + return "The Skeleton mode you specified is invalid."; + case -1074396035: + return "The template image does not contain enough information for learning the aggressive search strategy."; + case -1074396034: + return "The template image does not contain enough edge information for the sample size(s) requested."; + case -1074396033: + return "Invalid template descriptor."; + case -1074396032: + return "The template descriptor does not contain data required for the requested search strategy in rotation-invariant matching."; + case -1074396026: + return "Invalid process type for edge detection."; + case -1074396025: + return "Angle range value should be equal to or greater than zero."; + case -1074396024: + return "Minimum coverage value should be greater than zero."; + case -1074396023: + return "The angle tolerance should be equal to or greater than 0.001."; + case -1074396022: + return "Invalid search mode for detecting straight edges"; + case -1074396021: + return "Invalid kernel size for edge detection. The minimum kernel size is 3, the maximum kernel size is 1073741823 and the kernel size must be odd."; + case -1074396020: + return "Invalid grading mode."; + case -1074396019: + return "Invalid threshold percentage. Valid values range from 0 to 100."; + case -1074396018: + return "Invalid edge polarity search mode."; + case -1074396017: + return "The AIM grading data attached to the image you tried to open was created with a newer version of NI Vision. Upgrade to the latest version of NI Vision to read this file."; + case -1074396016: + return "No video driver is installed."; + case -1074396015: + return "Unable to establish network connection with remote system."; + case -1074396014: + return "RT Video Out does not support displaying the supplied image type at the selected color depth."; + case -1074396013: + return "Invalid video mode."; + case -1074396012: + return "Unable to display remote image on network connection."; + case -1074396011: + return "Unable to establish network connection."; + case -1074396010: + return "Invalid frame number."; + case -1074396009: + return "An internal DirectX error has occurred. Try upgrading to the latest version of DirectX."; + case -1074396008: + return "An appropriate DirectX filter to process this file could not be found. Install the filter that was used to create this AVI. Upgrading to the latest version of DirectX may correct this error. NI Vision requires DirectX 8.1 or higher."; + case -1074396007: + return "Incompatible compression filter."; + case -1074396006: + return "Unknown compression filter."; + case -1074396005: + return "Invalid AVI session."; + case -1074396004: + return "A software key is restricting the use of this compression filter."; + case -1074396003: + return "The data for this frame exceeds the data buffer size specified when creating the AVI file."; + case -1074396002: + return "Invalid line gauge method."; + case -1074396001: + return "There are too many AVI sessions open. You must close a session before you can open another one."; + case -1074396000: + return "Invalid file header."; + case -1074395999: + return "Invalid file type."; + case -1074395998: + return "Invalid color table."; + case -1074395997: + return "Invalid parameter."; + case -1074395996: + return "File is already open for writing."; + case -1074395995: + return "File not found."; + case -1074395994: + return "Too many files open."; + case -1074395993: + return "File I/O error."; + case -1074395992: + return "File access denied."; + case -1074395991: + return "NI Vision does not support the file type you specified."; + case -1074395990: + return "Could not read Vision info from file."; + case -1074395989: + return "Unable to read data."; + case -1074395988: + return "Unable to write data."; + case -1074395987: + return "Premature end of file."; + case -1074395986: + return "Invalid file format."; + case -1074395985: + return "Invalid file operation."; + case -1074395984: + return "NI Vision does not support the file data type you specified."; + case -1074395983: + return "Disk full."; + case -1074395982: + return "The frames per second in an AVI must be greater than zero."; + case -1074395981: + return "The buffer that was passed in is not big enough to hold all of the data."; + case -1074395980: + return "Error initializing COM."; + case -1074395979: + return "The image has invalid particle information. Call imaqCountParticles on the image to create particle information."; + case -1074395978: + return "Invalid particle number."; + case -1074395977: + return "The AVI file was created in a newer version of NI Vision. Upgrade to the latest version of NI Vision to read this AVI file."; + case -1074395976: + return "The color palette must have exactly 0 or 256 entries."; + case -1074395975: + return "DirectX has timed out reading or writing the AVI file. When closing an AVI file, try adding an additional delay. When reading an AVI file, try reducing CPU and disk load."; + case -1074395974: + return "NI Vision does not support reading JPEG2000 files with this colorspace method."; + case -1074395973: + return "NI Vision does not support reading JPEG2000 files with more than one layer."; + case -1074395972: + return "DirectX is unable to enumerate the compression filters. This is caused by a third-party compression filter that is either improperly installed or is preventing itself from being enumerated. Remove any recently installed compression filters and try again."; + case -1074395971: + return "The offset you specified must be size 2."; + case -1074395960: + return "Initialization error."; + case -1074395959: + return "Unable to create window."; + case -1074395958: + return "Invalid window ID."; + case -1074395957: + return "The array sizes are not compatible."; + case -1074395956: + return "The quality you provided is invalid. Valid quality values range from -1 to 1000."; + case -1074395955: + return "Invalid maximum wavelet transform level. Valid values range from 0 to 255."; + case -1074395954: + return "The quantization step size must be greater than or equal to 0."; + case -1074395953: + return "Invalid wavelet transform mode."; + case -1074395920: + return "Invalid number of classes."; + case -1074395880: + return "Invalid particle."; + case -1074395879: + return "Invalid measure number."; + case -1074395878: + return "The ImageBase Display control does not support writing this property node."; + case -1074395877: + return "The specified color mode requires the use of imaqChangeColorSpace2."; + case -1074395876: + return "This function does not currently support the color mode you specified."; + case -1074395875: + return "The barcode is not a valid Pharmacode symbol"; + case -1074395840: + return "Invalid handle table index."; + case -1074395837: + return "The compression ratio must be greater than or equal to 1."; + case -1074395801: + return "The ROI contains too many contours."; + case -1074395800: + return "Protection error."; + case -1074395799: + return "Internal error."; + case -1074395798: + return "The size of the feature vector in the custom sample must match the size of those you have already added."; + case -1074395797: + return "Not a valid classifier session."; + case -1074395796: + return "You requested an invalid Nearest Neighbor classifier method."; + case -1074395795: + return "The k parameter must be greater than two."; + case -1074395794: + return "The k parameter must be <= the number of samples in each class."; + case -1074395793: + return "This classifier session is compact. Only the Classify and Dispose functions may be called on a compact classifier session."; + case -1074395792: + return "This classifier session is not trained. You may only call this function on a trained classifier session."; + case -1074395791: + return "This classifier function cannot be called on this type of classifier session."; + case -1074395790: + return "You requested an invalid distance metric."; + case -1074395789: + return "The classifier session you tried to open was created with a newer version of NI Vision. Upgrade to the latest version of NI Vision to read this file."; + case -1074395788: + return "This operation cannot be performed because you have not added any samples."; + case -1074395787: + return "You requested an invalid classifier type."; + case -1074395786: + return "The sum of Scale Dependence and Symmetry Dependence must be less than 1000."; + case -1074395785: + return "The image yielded no particles."; + case -1074395784: + return "The limits you supplied are not valid."; + case -1074395783: + return "The Sample Index fell outside the range of Samples."; + case -1074395782: + return "The description must be <= 255 characters."; + case -1074395781: + return "The engine for this classifier session does not support this operation."; + case -1074395780: + return "You requested an invalid particle type."; + case -1074395779: + return "You may only save a session in compact form if it is trained."; + case -1074395778: + return "The Kernel size must be smaller than the image size."; + case -1074395777: + return "The session you read from file must be the same type as the session you passed in."; + case -1074395776: + return "You can not use a compact classification file with read options other than Read All."; + case -1074395775: + return "The ROI you passed in may only contain closed contours."; + case -1074395774: + return "You must pass in a label."; + case -1074395773: + return "You must provide a destination image."; + case -1074395772: + return "You provided an invalid registration method."; + case -1074395771: + return "The golden template you tried to open was created with a newer version of NI Vision. Upgrade to the latest version of NI Vision to read this file."; + case -1074395770: + return "Invalid golden template."; + case -1074395769: + return "Edge Thickness to Ignore must be greater than zero."; + case -1074395768: + return "Scale must be greater than zero."; + case -1074395767: + return "The supplied scale is invalid for your template."; + case -1074395766: + return "This backwards-compatibility function can not be used with this session. Use newer, supported functions instead."; + case -1074395763: + return "You must provide a valid normalization method."; + case -1074395762: + return "The deviation factor for Niblack local threshold must be between 0 and 1."; + case -1074395760: + return "Board not found."; + case -1074395758: + return "Board not opened."; + case -1074395757: + return "DLL not found."; + case -1074395756: + return "DLL function not found."; + case -1074395754: + return "Trigger timeout."; + case -1074395728: + return "NI Vision does not support the search mode you provided."; + case -1074395727: + return "NI Vision does not support the search mode you provided for the type of 2D barcode for which you are searching."; + case -1074395726: + return "matchFactor has been obsoleted. Instead, set the initialMatchListLength and matchListReductionFactor in the MatchPatternAdvancedOptions structure."; + case -1074395725: + return "The data was stored with a newer version of NI Vision. Upgrade to the latest version of NI Vision to read this data."; + case -1074395724: + return "The size you specified is out of the valid range."; + case -1074395723: + return "The key you specified cannot be found in the image."; + case -1074395722: + return "Custom classifier sessions only classify feature vectors. They do not support classifying images."; + case -1074395721: + return "NI Vision does not support the bit depth you supplied for the image you supplied."; + case -1074395720: + return "Invalid ROI."; + case -1074395719: + return "Invalid ROI global rectangle."; + case -1074395718: + return "The version of LabVIEW or BridgeVIEW you are running does not support this operation."; + case -1074395717: + return "The range you supplied is invalid."; + case -1074395716: + return "NI Vision does not support the scaling method you provided."; + case -1074395715: + return "NI Vision does not support the calibration unit you supplied."; + case -1074395714: + return "NI Vision does not support the axis orientation you supplied."; + case -1074395713: + return "Value not in enumeration."; + case -1074395712: + return "You selected a region that is not of the right type."; + case -1074395711: + return "You specified a viewer that does not contain enough regions."; + case -1074395710: + return "The image has too many particles for this process."; + case -1074395709: + return "The AVI session has not been opened."; + case -1074395708: + return "The AVI session is a write session, but this operation requires a read session."; + case -1074395707: + return "The AVI session is a read session, but this operation requires a write session."; + case -1074395706: + return "This AVI session is already open. You must close it before calling the Create or Open functions."; + case -1074395705: + return "The data is corrupted and cannot be read."; + case -1074395704: + return "Invalid compression type."; + case -1074395703: + return "Invalid type of flatten."; + case -1074395702: + return "The length of the edge detection line must be greater than zero."; + case -1074395701: + return "The maximum Data Matrix barcode size must be equal to or greater than the minimum Data Matrix barcode size."; + case -1074395700: + return "The function requires the operating system to be Microsoft Windows 2000 or newer."; + case -1074395656: + return "You must specify the same value for the smooth contours advanced match option for all templates you want to match."; + case -1074395655: + return "You must specify the same value for the enable calibration support advanced match option for all templates you want to match."; + case -1074395654: + return "The source image does not contain grading information. You must prepare the source image for grading when reading the Data Matrix, and you cannot change the contents of the source image between reading and grading the Data Matrix."; + case -1074395653: + return "The multiple geometric matching template you tried to open was created with a newer version of NI Vision. Upgrade to the latest version of NI Vision to read this file."; + case -1074395652: + return "The geometric matching template you tried to open was created with a newer version of NI Vision. Upgrade to the latest version of NI Vision to read this file."; + case -1074395651: + return "You must specify the same edge filter size for all the templates you want to match."; + case -1074395650: + return "You must specify the same curve extraction mode for all the templates you want to match."; + case -1074395649: + return "The geometric feature type specified is invalid."; + case -1074395648: + return "You supplied a template that was not learned."; + case -1074395647: + return "Invalid multiple geometric template."; + case -1074395646: + return "Need at least one template to learn."; + case -1074395645: + return "You supplied an invalid number of labels."; + case -1074395644: + return "Labels must be <= 255 characters."; + case -1074395643: + return "You supplied an invalid number of match options."; + case -1074395642: + return "Cannot find a label that matches the one you specified."; + case -1074395641: + return "Duplicate labels are not allowed."; + case -1074395640: + return "The number of zones found exceeded the capacity of the algorithm."; + case -1074395639: + return "The hatch style for the window background is invalid."; + case -1074395638: + return "The fill style for the window background is invalid."; + case -1074395637: + return "Your hardware is not supported by DirectX and cannot be put into NonTearing mode."; + case -1074395636: + return "DirectX is required for this feature. Please install the latest version.."; + case -1074395635: + return "The passed shape descriptor is invalid."; + case -1074395634: + return "Invalid max match overlap. Values must be between -1 and 100."; + case -1074395633: + return "Invalid minimum match separation scale. Values must be greater than or equal to -1."; + case -1074395632: + return "Invalid minimum match separation angle. Values must be between -1 and 360."; + case -1074395631: + return "Invalid minimum match separation distance. Values must be greater than or equal to -1."; + case -1074395630: + return "Invalid maximum number of features learn. Values must be integers greater than zero."; + case -1074395629: + return "Invalid maximum pixel distance from line. Values must be positive real numbers."; + case -1074395628: + return "Invalid geometric matching template image."; + case -1074395627: + return "The template does not contain enough features for geometric matching."; + case -1074395626: + return "The template does not contain enough features for geometric matching."; + case -1074395625: + return "You specified an invalid value for the match constraint value of the range settings."; + case -1074395624: + return "Invalid occlusion range. Valid values for the bounds range from 0 to 100 and the upper bound must be greater than or equal to the lower bound."; + case -1074395623: + return "Invalid scale range. Values for the lower bound must be a positive real numbers and the upper bound must be greater than or equal to the lower bound."; + case -1074395622: + return "Invalid match geometric pattern setup data."; + case -1074395621: + return "Invalid learn geometric pattern setup data."; + case -1074395620: + return "Invalid curve extraction mode."; + case -1074395619: + return "You can specify only one occlusion range."; + case -1074395618: + return "You can specify only one scale range."; + case -1074395617: + return "The minimum number of features must be less than or equal to the maximum number of features."; + case -1074395616: + return "Invalid edge filter size."; + case -1074395615: + return "Invalid minimum strength for features. Values must be positive real numbers."; + case -1074395614: + return "Invalid aspect ratio for rectangular features. Values must be positive real numbers in the range 0.01 to 1.0."; + case -1074395613: + return "Invalid minimum length for linear features. Values must be integers greater than 0."; + case -1074395612: + return "Invalid minimum radius for circular features. Values must be integers greater than 0."; + case -1074395611: + return "Invalid minimum rectangle dimension. Values must be integers greater than 0."; + case -1074395610: + return "Invalid initial match list length. Values must be integers greater than 5."; + case -1074395609: + return "Invalid subpixel tolerance. Values must be positive real numbers."; + case -1074395608: + return "Invalid number of subpixel iterations. Values must be integers greater 10."; + case -1074395607: + return "Invalid maximum number of features used per match. Values must be integers greater than or equal to zero."; + case -1074395606: + return "Invalid minimum number of features used for matching. Values must be integers greater than zero."; + case -1074395605: + return "Invalid maximum end point gap. Valid values range from 0 to 32767."; + case -1074395604: + return "Invalid column step. Valid range is 1 to 255."; + case -1074395603: + return "Invalid row step. Valid range is 1 to 255."; + case -1074395602: + return "Invalid minimum length. Valid values must be greater than or equal to zero."; + case -1074395601: + return "Invalid edge threshold. Valid values range from 1 to 360."; + case -1074395600: + return "You must provide information about the subimage within the browser."; + case -1074395598: + return "The acceptance level is outside the valid range of 0 to 1000."; + case -1074395597: + return "Not a valid OCR session."; + case -1074395596: + return "Invalid character size. Character size must be >= 1."; + case -1074395595: + return "Invalid threshold mode value."; + case -1074395594: + return "Invalid substitution character. Valid substitution characters are ASCII values that range from 1 to 254."; + case -1074395593: + return "Invalid number of blocks. Number of blocks must be >= 4 and <= 50."; + case -1074395592: + return "Invalid read strategy."; + case -1074395591: + return "Invalid character index."; + case -1074395590: + return "Invalid number of character positions. Valid values range from 0 to 255."; + case -1074395589: + return "Invalid low threshold value. Valid threshold values range from 0 to 255."; + case -1074395588: + return "Invalid high threshold value. Valid threshold values range from 0 to 255."; + case -1074395587: + return "The low threshold must be less than the high threshold."; + case -1074395586: + return "Invalid lower threshold limit. Valid lower threshold limits range from 0 to 255."; + case -1074395585: + return "Invalid upper threshold limit. Valid upper threshold limits range from 0 to 255."; + case -1074395584: + return "The lower threshold limit must be less than the upper threshold limit."; + case -1074395583: + return "Invalid minimum character spacing value. Character spacing must be >= 0 pixels."; + case -1074395582: + return "Invalid maximum horizontal element spacing value. Maximum horizontal element spacing must be >= 0."; + case -1074395581: + return "Invalid maximum vertical element spacing value. Maximum vertical element spacing must be >= 0."; + case -1074395580: + return "Invalid minimum bounding rectangle width. Minimum bounding rectangle width must be >= 1."; + case -1074395579: + return "Invalid aspect ratio value. The aspect ratio must be zero or >= 100."; + case -1074395578: + return "Invalid or corrupt character set file."; + case -1074395577: + return "The character value must not be an empty string."; + case -1074395576: + return "Character values must be <=255 characters."; + case -1074395575: + return "Invalid number of erosions. The number of erosions must be >= 0."; + case -1074395574: + return "The character set description must be <=255 characters."; + case -1074395573: + return "The character set file was created by a newer version of NI Vision. Upgrade to the latest version of NI Vision to read the character set file."; + case -1074395572: + return "You must specify characters for a string. A string cannot contain integers."; + case -1074395571: + return "This attribute is read-only."; + case -1074395570: + return "This attribute requires a Boolean value."; + case -1074395569: + return "Invalid attribute."; + case -1074395568: + return "This attribute requires integer values."; + case -1074395567: + return "String values are invalid for this attribute. Enter a boolean value."; + case -1074395566: + return "Boolean values are not valid for this attribute. Enter an integer value."; + case -1074395565: + return "Requires a single-character string."; + case -1074395564: + return "Invalid predefined character value."; + case -1074395563: + return "This copy of NI OCR is unlicensed."; + case -1074395562: + return "String values are not valid for this attribute. Enter a Boolean value."; + case -1074395561: + return "The number of characters in the character value must match the number of objects in the image."; + case -1074395560: + return "Invalid object index."; + case -1074395559: + return "Invalid read option."; + case -1074395558: + return "The minimum character size must be less than the maximum character size."; + case -1074395557: + return "The minimum character bounding rectangle width must be less than the maximum character bounding rectangle width."; + case -1074395556: + return "The minimum character bounding rectangle height must be less than the maximum character bounding rectangle height."; + case -1074395555: + return "The maximum horizontal element spacing value must not exceed the minimum character spacing value."; + case -1074395554: + return "Invalid read resolution."; + case -1074395553: + return "Invalid minimum bounding rectangle height. The minimum bounding rectangle height must be >= 1."; + case -1074395552: + return "Not a valid character set."; + case -1074395551: + return "A trained OCR character cannot be renamed while it is a reference character."; + case -1074395550: + return "A character cannot have an ASCII value of 255."; + case -1074395549: + return "The number of objects found does not match the number of expected characters or patterns to verify."; + case -1074395410: + return "NI Vision does not support less than one icon per line."; + case -1074395409: + return "Invalid subpixel divisions."; + case -1074395408: + return "Invalid detection mode."; + case -1074395407: + return "Invalid contrast value. Valid contrast values range from 0 to 255."; + case -1074395406: + return "The coordinate system could not be found on this image."; + case -1074395405: + return "NI Vision does not support the text orientation value you supplied."; + case -1074395404: + return "UnwrapImage does not support the interpolation method value you supplied. Valid interpolation methods are zero order and bilinear. "; + case -1074395403: + return "The image was created in a newer version of NI Vision. Upgrade to the latest version of NI Vision to use this image."; + case -1074395402: + return "The function does not support the maximum number of points that you specified."; + case -1074395401: + return "The function does not support the matchFactor that you specified."; + case -1074395400: + return "The operation you have given Multicore Options is invalid. Please see the available enumeration values for Multicore Operation."; + case -1074395399: + return "You have given Multicore Options an invalid argument."; + case -1074395397: + return "A complex image is required."; + case -1074395395: + return "The input image must be a color image."; + case -1074395394: + return "The color mask removes too much color information."; + case -1074395393: + return "The color template image is too small."; + case -1074395392: + return "The color template image is too large."; + case -1074395391: + return "The contrast in the hue plane of the image is too low for learning shape features."; + case -1074395390: + return "The contrast in the luminance plane of the image is too low to learn shape features."; + case -1074395389: + return "Invalid color learn setup data."; + case -1074395388: + return "Invalid color learn setup data."; + case -1074395387: + return "Invalid color match setup data."; + case -1074395386: + return "Invalid color match setup data."; + case -1074395385: + return "Rotation-invariant color pattern matching requires a feature mode including shape."; + case -1074395384: + return "Invalid color template image."; + case -1074395383: + return "Invalid color template image."; + case -1074395382: + return "Invalid color template image."; + case -1074395381: + return "Invalid color template image."; + case -1074395380: + return "Invalid color template image."; + case -1074395379: + return "Invalid color template image."; + case -1074395378: + return "Invalid color template image."; + case -1074395377: + return "Invalid color template image."; + case -1074395376: + return "The color template image does not contain data required for shift-invariant color matching."; + case -1074395375: + return "Invalid color template image."; + case -1074395374: + return "Invalid color template image."; + case -1074395373: + return "Invalid color template image."; + case -1074395372: + return "The color template image does not contain data required for rotation-invariant color matching."; + case -1074395371: + return "Invalid color template image."; + case -1074395370: + return "Invalid color template image."; + case -1074395369: + return "Invalid color template image."; + case -1074395368: + return "Invalid color template image."; + case -1074395367: + return "Invalid color template image."; + case -1074395366: + return "The color template image does not contain data required for color matching in shape feature mode."; + case -1074395365: + return "The color template image does not contain data required for color matching in color feature mode."; + case -1074395364: + return "The ignore color spectra array is invalid."; + case -1074395363: + return "Invalid subsampling ratio."; + case -1074395362: + return "Invalid pixel width."; + case -1074395361: + return "Invalid steepness."; + case -1074395360: + return "Invalid complex plane."; + case -1074395357: + return "Invalid color ignore mode."; + case -1074395356: + return "Invalid minimum match score. Acceptable values range from 0 to 1000."; + case -1074395355: + return "Invalid number of matches requested. You must request a minimum of one match."; + case -1074395354: + return "Invalid color weight. Acceptable values range from 0 to 1000."; + case -1074395353: + return "Invalid search strategy."; + case -1074395352: + return "Invalid feature mode."; + case -1074395351: + return "NI Vision does not support rectangles with negative widths or negative heights."; + case -1074395350: + return "NI Vision does not support the vision information type you supplied."; + case -1074395349: + return "NI Vision does not support the SkeletonMethod value you supplied."; + case -1074395348: + return "NI Vision does not support the 3DPlane value you supplied."; + case -1074395347: + return "NI Vision does not support the 3DDirection value you supplied."; + case -1074395346: + return "imaqRotate does not support the InterpolationMethod value you supplied."; + case -1074395345: + return "NI Vision does not support the axis of symmetry you supplied."; + case -1074395343: + return "You must pass a valid file name. Do not pass in NULL."; + case -1074395340: + return "NI Vision does not support the SizeType value you supplied."; + case -1074395336: + return "You specified the dispatch status of an unknown algorithm."; + case -1074395335: + return "You are attempting to set the same algorithm to dispatch and to not dispatch. Remove one of the conflicting settings."; + case -1074395334: + return "NI Vision does not support the Conversion Method value you supplied."; + case -1074395333: + return "NI Vision does not support the VerticalTextAlignment value you supplied."; + case -1074395332: + return "NI Vision does not support the CompareFunction value you supplied."; + case -1074395331: + return "NI Vision does not support the BorderMethod value you supplied."; + case -1074395330: + return "Invalid border size. Acceptable values range from 0 to 50."; + case -1074395329: + return "NI Vision does not support the OutlineMethod value you supplied."; + case -1074395328: + return "NI Vision does not support the InterpolationMethod value you supplied."; + case -1074395327: + return "NI Vision does not support the ScalingMode value you supplied."; + case -1074395326: + return "imaqDrawLineOnImage does not support the DrawMode value you supplied."; + case -1074395325: + return "NI Vision does not support the DrawMode value you supplied."; + case -1074395324: + return "NI Vision does not support the ShapeMode value you supplied."; + case -1074395323: + return "NI Vision does not support the FontColor value you supplied."; + case -1074395322: + return "NI Vision does not support the TextAlignment value you supplied."; + case -1074395321: + return "NI Vision does not support the MorphologyMethod value you supplied."; + case -1074395320: + return "The template image is empty."; + case -1074395319: + return "NI Vision does not support the interpolation type you supplied."; + case -1074395318: + return "You supplied an insufficient number of points to perform this operation."; + case -1074395317: + return "You specified a point that lies outside the image."; + case -1074395316: + return "Invalid kernel code."; + case -1074395313: + return "Writing files is not supported on this device."; + case -1074395312: + return "The input image does not seem to be a valid LCD or LED calibration image."; + case -1074395311: + return "The color spectrum array you provided does not contain enough elements or contains an element set to not-a-number (NaN)."; + case -1074395310: + return "NI Vision does not support the PaletteType value you supplied."; + case -1074395309: + return "NI Vision does not support the WindowThreadPolicy value you supplied."; + case -1074395308: + return "NI Vision does not support the ColorSensitivity value you supplied."; + case -1074395307: + return "The precision parameter must be greater than 0."; + case -1074395306: + return "NI Vision does not support the Tool value you supplied."; + case -1074395305: + return "NI Vision does not support the ReferenceMode value you supplied."; + case -1074395304: + return "NI Vision does not support the MathTransformMethod value you supplied."; + case -1074395303: + return "Invalid number of classes for auto threshold. Acceptable values range from 2 to 256."; + case -1074395302: + return "NI Vision does not support the threshold method value you supplied."; + case -1074395301: + return "The ROI you passed into imaqGetMeterArc must consist of two lines."; + case -1074395300: + return "NI Vision does not support the MeterArcMode value you supplied."; + case -1074395299: + return "NI Vision does not support the ComplexPlane value you supplied."; + case -1074395298: + return "You can perform this operation on a real or an imaginary ComplexPlane only."; + case -1074395297: + return "NI Vision does not support the ParticleInfoMode value you supplied."; + case -1074395296: + return "NI Vision does not support the BarcodeType value you supplied."; + case -1074395295: + return "imaqInterpolatePoints does not support the InterpolationMethod value you supplied."; + case -1074395294: + return "The contour index you supplied is larger than the number of contours in the ROI."; + case -1074395293: + return "The supplied ContourID did not correlate to a contour inside the ROI."; + case -1074395292: + return "Do not supply collinear points for this operation."; + case -1074395291: + return "Shape Match requires the image to contain only pixel values of 0 or 1."; + case -1074395290: + return "The template you supplied for ShapeMatch contains no shape information."; + case -1074395287: + return "The line you provided contains two identical points, or one of the coordinate locations for the line is not a number (NaN)."; + case -1074395286: + return "Invalid concentric rake direction."; + case -1074395285: + return "Invalid spoke direction."; + case -1074395284: + return "Invalid edge process."; + case -1074395283: + return "Invalid rake direction."; + case -1074395282: + return "Unable to draw to viewer. You must have the latest version of the control."; + case -1074395281: + return "Your image must be larger than its border size for this operation."; + case -1074395280: + return "The ROI must only have a single Rectangle contour."; + case -1074395279: + return "ROI is not a polygon."; + case -1074395278: + return "LCD image is not a number."; + case -1074395277: + return "The decoded barcode information did not pass the checksum test."; + case -1074395276: + return "You specified parallel lines for the meter ROI."; + case -1074395275: + return "Invalid browser image."; + case -1074395270: + return "Cannot divide by zero."; + case -1074395269: + return "Null pointer."; + case -1074395268: + return "The linear equations are not independent."; + case -1074395267: + return "The roots of the equation are complex."; + case -1074395265: + return "The barcode does not match the type you specified."; + case -1074395263: + return "No lit segment."; + case -1074395262: + return "The LCD does not form a known digit."; + case -1074395261: + return "An internal error occurred while attempting to access an invalid coordinate on an image."; + case -1074395260: + return "An internal memory error occurred."; + case -1074395258: + return "The filter width must be odd for the Canny operator."; + case -1074395257: + return "You supplied an invalid edge direction in the Canny operator."; + case -1074395256: + return "The window size must be odd for the Canny operator. "; + case -1074395253: + return "Invalid learn mode."; + case -1074395252: + return "Invalid learn setup data."; + case -1074395251: + return "Invalid match mode."; + case -1074395250: + return "Invalid match setup data."; + case -1074395249: + return "At least one range in the array of rotation angle ranges exceeds 360 degrees."; + case -1074395248: + return "The array of rotation angle ranges contains too many ranges."; + case -1074395247: + return "Invalid template descriptor."; + case -1074395246: + return "Invalid template descriptor."; + case -1074395245: + return "Invalid template descriptor."; + case -1074395244: + return "Invalid template descriptor."; + case -1074395243: + return "The template descriptor was created with a newer version of NI Vision. Upgrade to the latest version of NI Vision to use this template."; + case -1074395242: + return "Invalid template descriptor."; + case -1074395241: + return "The template descriptor does not contain data required for rotation-invariant matching."; + case -1074395240: + return "Invalid template descriptor."; + case -1074395239: + return "Invalid template descriptor."; + case -1074395238: + return "The template descriptor does not contain data required for shift-invariant matching."; + case -1074395237: + return "Invalid template descriptor."; + case -1074395235: + return "The template image does not contain enough contrast."; + case -1074395234: + return "The template image is too small."; + case -1074395233: + return "The template image is too large."; + case -1074395212: + return "The size of the template string must match the size of the string you are trying to correct."; + case -1074395211: + return "The supplied text template contains nonstandard characters that cannot be generated by OCR."; + case -1074395210: + return "At least one character in the text template was of a lexical class that did not match the supplied character reports."; + case -1074395203: + return "The OCR library cannot be initialized correctly."; + case -1074395201: + return "There was a failure when loading one of the internal OCR engine or LabView libraries."; + case -1074395200: + return "One of the parameters supplied to the OCR function that generated this error is invalid."; + case -1074395179: + return "The OCR engine failed during the preprocessing stage."; + case -1074395178: + return "The OCR engine failed during the recognition stage."; + case -1074395175: + return "The provided filename is not valid user dictionary filename."; + case -1074395174: + return "NI Vision does not support the AutoOrientMode value you supplied."; + case -1074395173: + return "NI Vision does not support the Language value you supplied."; + case -1074395172: + return "NI Vision does not support the CharacterSet value you supplied."; + case -1074395171: + return "The system could not locate the initialization file required for OCR initialization."; + case -1074395170: + return "NI Vision does not support the CharacterType value you supplied."; + case -1074395169: + return "NI Vision does not support the RecognitionMode value you supplied."; + case -1074395168: + return "NI Vision does not support the AutoCorrectionMode value you supplied."; + case -1074395167: + return "NI Vision does not support the OutputDelimiter value you supplied."; + case -1074395166: + return "The system could not locate the OCR binary directory required for OCR initialization."; + case -1074395165: + return "The system could not locate the OCR weights directory required for OCR initialization."; + case -1074395164: + return "The supplied word could not be added to the user dictionary."; + case -1074395163: + return "NI Vision does not support the CharacterPreference value you supplied."; + case -1074395162: + return "NI Vision does not support the CorrectionMethod value you supplied."; + case -1074395161: + return "NI Vision does not support the CorrectionLevel value you supplied."; + case -1074395160: + return "NI Vision does not support the maximum point size you supplied. Valid values range from 4 to 72."; + case -1074395159: + return "NI Vision does not support the tolerance value you supplied. Valid values are non-negative."; + case -1074395158: + return "NI Vision does not support the ContrastMode value you supplied."; + case -1074395156: + return "The OCR attempted to detected the text skew and failed."; + case -1074395155: + return "The OCR attempted to detected the text orientation and failed."; + case -1074395153: + return "Invalid font file format."; + case -1074395152: + return "Font file not found."; + case -1074395151: + return "The OCR engine failed during the correction stage."; + case -1074395150: + return "NI Vision does not support the RoundingMode value you supplied."; + case -1074395149: + return "Found a duplicate transform type in the properties array. Each properties array may only contain one behavior for each transform type."; + case -1074395148: + return "Overlay Group Not Found."; + case -1074395147: + return "The barcode is not a valid RSS Limited symbol"; + case -1074395146: + return "Couldn't determine the correct version of the QR code."; + case -1074395145: + return "Invalid read of the QR code."; + case -1074395144: + return "The barcode that was read contains invalid parameters."; + case -1074395143: + return "The data stream that was demodulated could not be read because the mode was not detected."; + case -1074395142: + return "Couldn't determine the correct model of the QR code."; + case -1074395141: + return "The OCR engine could not find any text in the supplied region."; + case -1074395140: + return "One of the character reports is no longer usable by the system."; + case -1074395139: + return "Invalid Dimensions."; + case -1074395138: + return "The OCR region provided was too small to have contained any characters."; + default: + return "Error code not found"; } + } } diff --git a/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/image/ParticleAnalysisReport.java b/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/image/ParticleAnalysisReport.java index 2f435bccd5..7cb4d2e21b 100644 --- a/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/image/ParticleAnalysisReport.java +++ b/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/image/ParticleAnalysisReport.java @@ -1,8 +1,8 @@ /*----------------------------------------------------------------------------*/ -/* Copyright (c) FIRST 2008-2012. All Rights Reserved. */ -/* Open Source Software - may be modified and shared by FRC teams. The code */ +/* Copyright (c) FIRST 2008-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 the root directory of */ -/* the project. */ +/* the project. */ /*----------------------------------------------------------------------------*/ package edu.wpi.first.wpilibj.image; @@ -10,80 +10,105 @@ import com.ni.vision.NIVision; /** * Class to store commonly used information about a particle. + *$ * @author dtjones */ public class ParticleAnalysisReport { - /** - * The height of the image in pixels. - */ - public final int imageHeight; - /** - * The width of the image in pixels. - */ - public final int imageWidth; - /** X-coordinate of the point representing the average position of the - * total particle mass, assuming every point in the particle has a constant density */ - public final int center_mass_x; // MeasurementType: IMAQ_MT_CENTER_OF_MASS_X - /** Y-coordinate of the point representing the average position of the - * total particle mass, assuming every point in the particle has a constant density */ - public final int center_mass_y; // MeasurementType: IMAQ_MT_CENTER_OF_MASS_Y - /** - * Center of mass x value normalized to -1.0 to +1.0 range. - */ - public final double center_mass_x_normalized; - /** - * Center of mass y value normalized to -1.0 to +1.0 range. - */ - public final double center_mass_y_normalized; - /** Area of the particle */ - public final double particleArea; // MeasurementType: IMAQ_MT_AREA - /** Bounding Rectangle */ - public final int boundingRectLeft; // left/top/width/height - /** Bounding Rectangle */ - public final int boundingRectTop; - /** Bounding Rectangle */ - public final int boundingRectWidth; - /** Bounding Rectangle */ - public final int boundingRectHeight; - /** Percentage of the particle Area covering the Image Area. */ - public final double particleToImagePercent; // MeasurementType: IMAQ_MT_AREA_BY_IMAGE_AREA - /** Percentage of the particle Area in relation to its Particle and Holes Area */ - public final double particleQuality; // MeasurementType: IMAQ_MT_AREA_BY_PARTICLE_AND_HOLES_AREA + /** + * The height of the image in pixels. + */ + public final int imageHeight; + /** + * The width of the image in pixels. + */ + public final int imageWidth; + /** + * X-coordinate of the point representing the average position of the total + * particle mass, assuming every point in the particle has a constant density + */ + public final int center_mass_x; // MeasurementType: IMAQ_MT_CENTER_OF_MASS_X + /** + * Y-coordinate of the point representing the average position of the total + * particle mass, assuming every point in the particle has a constant density + */ + public final int center_mass_y; // MeasurementType: IMAQ_MT_CENTER_OF_MASS_Y + /** + * Center of mass x value normalized to -1.0 to +1.0 range. + */ + public final double center_mass_x_normalized; + /** + * Center of mass y value normalized to -1.0 to +1.0 range. + */ + public final double center_mass_y_normalized; + /** Area of the particle */ + public final double particleArea; // MeasurementType: IMAQ_MT_AREA + /** Bounding Rectangle */ + public final int boundingRectLeft; // left/top/width/height + /** Bounding Rectangle */ + public final int boundingRectTop; + /** Bounding Rectangle */ + public final int boundingRectWidth; + /** Bounding Rectangle */ + public final int boundingRectHeight; + /** Percentage of the particle Area covering the Image Area. */ + public final double particleToImagePercent; // MeasurementType: + // IMAQ_MT_AREA_BY_IMAGE_AREA + /** Percentage of the particle Area in relation to its Particle and Holes Area */ + public final double particleQuality; // MeasurementType: + // IMAQ_MT_AREA_BY_PARTICLE_AND_HOLES_AREA - ParticleAnalysisReport(BinaryImage image, int index) throws NIVisionException { - imageHeight = image.getHeight(); - imageWidth = image.getWidth(); - center_mass_x = (int) NIVision.imaqMeasureParticle(image.image, index, 0, NIVision.MeasurementType.MT_CENTER_OF_MASS_X); - center_mass_y = (int) NIVision.imaqMeasureParticle(image.image, index, 0, NIVision.MeasurementType.MT_CENTER_OF_MASS_Y); - center_mass_x_normalized = (2.0 * center_mass_x / imageWidth) - 1.0; - center_mass_y_normalized = (2.0 * center_mass_y / imageHeight) - 1.0; - particleArea = NIVision.imaqMeasureParticle(image.image, index, 0, NIVision.MeasurementType.MT_AREA); - boundingRectLeft = (int) NIVision.imaqMeasureParticle(image.image, index, 0, NIVision.MeasurementType.MT_BOUNDING_RECT_LEFT); - boundingRectTop = (int) NIVision.imaqMeasureParticle(image.image, index, 0, NIVision.MeasurementType.MT_BOUNDING_RECT_TOP); - boundingRectWidth = (int) NIVision.imaqMeasureParticle(image.image, index, 0, NIVision.MeasurementType.MT_BOUNDING_RECT_WIDTH); - boundingRectHeight = (int) NIVision.imaqMeasureParticle(image.image, index, 0, NIVision.MeasurementType.MT_BOUNDING_RECT_HEIGHT); - particleToImagePercent = NIVision.imaqMeasureParticle(image.image, index, 0, NIVision.MeasurementType.MT_AREA_BY_IMAGE_AREA); - particleQuality = NIVision.imaqMeasureParticle(image.image, index, 0, NIVision.MeasurementType.MT_AREA_BY_PARTICLE_AND_HOLES_AREA); - } + ParticleAnalysisReport(BinaryImage image, int index) throws NIVisionException { + imageHeight = image.getHeight(); + imageWidth = image.getWidth(); + center_mass_x = + (int) NIVision.imaqMeasureParticle(image.image, index, 0, + NIVision.MeasurementType.MT_CENTER_OF_MASS_X); + center_mass_y = + (int) NIVision.imaqMeasureParticle(image.image, index, 0, + NIVision.MeasurementType.MT_CENTER_OF_MASS_Y); + center_mass_x_normalized = (2.0 * center_mass_x / imageWidth) - 1.0; + center_mass_y_normalized = (2.0 * center_mass_y / imageHeight) - 1.0; + particleArea = + NIVision.imaqMeasureParticle(image.image, index, 0, NIVision.MeasurementType.MT_AREA); + boundingRectLeft = + (int) NIVision.imaqMeasureParticle(image.image, index, 0, + NIVision.MeasurementType.MT_BOUNDING_RECT_LEFT); + boundingRectTop = + (int) NIVision.imaqMeasureParticle(image.image, index, 0, + NIVision.MeasurementType.MT_BOUNDING_RECT_TOP); + boundingRectWidth = + (int) NIVision.imaqMeasureParticle(image.image, index, 0, + NIVision.MeasurementType.MT_BOUNDING_RECT_WIDTH); + boundingRectHeight = + (int) NIVision.imaqMeasureParticle(image.image, index, 0, + NIVision.MeasurementType.MT_BOUNDING_RECT_HEIGHT); + particleToImagePercent = + NIVision.imaqMeasureParticle(image.image, index, 0, + NIVision.MeasurementType.MT_AREA_BY_IMAGE_AREA); + particleQuality = + NIVision.imaqMeasureParticle(image.image, index, 0, + NIVision.MeasurementType.MT_AREA_BY_PARTICLE_AND_HOLES_AREA); + } - static double getParticleToImagePercent(BinaryImage image, int index) throws NIVisionException { - return NIVision.imaqMeasureParticle(image.image, index, 0, NIVision.MeasurementType.MT_AREA_BY_IMAGE_AREA); - } + static double getParticleToImagePercent(BinaryImage image, int index) throws NIVisionException { + return NIVision.imaqMeasureParticle(image.image, index, 0, + NIVision.MeasurementType.MT_AREA_BY_IMAGE_AREA); + } - /** - * Get string representation of the particle analysis report. - * @return A string representation of the particle analysis report. - */ - public String toString() { - return "Particle Report: \n" + - " Image Height : " + imageHeight + "\n" + - " Image Width : " + imageWidth + "\n" + - " Center of mass : ( " + center_mass_x + " , " + center_mass_y + " )\n" + - " normalized : ( " + center_mass_x_normalized + " , " + center_mass_y_normalized + " )\n" + - " Area : " + particleArea + "\n" + - " percent : " + particleToImagePercent + "\n" + - " Bounding Rect : ( " + boundingRectLeft + " , " + boundingRectTop + " ) " + boundingRectWidth + "*" + boundingRectHeight + "\n" + - " Quality : " + particleQuality + "\n"; - } + /** + * Get string representation of the particle analysis report. + *$ + * @return A string representation of the particle analysis report. + */ + public String toString() { + return "Particle Report: \n" + " Image Height : " + imageHeight + "\n" + + " Image Width : " + imageWidth + "\n" + " Center of mass : ( " + center_mass_x + + " , " + center_mass_y + " )\n" + " normalized : ( " + center_mass_x_normalized + + " , " + center_mass_y_normalized + " )\n" + " Area : " + particleArea + + "\n" + " percent : " + particleToImagePercent + "\n" + + " Bounding Rect : ( " + boundingRectLeft + " , " + boundingRectTop + " ) " + + boundingRectWidth + "*" + boundingRectHeight + "\n" + " Quality : " + + particleQuality + "\n"; + } } diff --git a/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/image/RGBImage.java b/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/image/RGBImage.java index 642e01a498..b69b1bfbd7 100644 --- a/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/image/RGBImage.java +++ b/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/image/RGBImage.java @@ -1,8 +1,8 @@ /*----------------------------------------------------------------------------*/ -/* Copyright (c) FIRST 2008-2012. All Rights Reserved. */ -/* Open Source Software - may be modified and shared by FRC teams. The code */ +/* Copyright (c) FIRST 2008-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 the root directory of */ -/* the project. */ +/* the project. */ /*----------------------------------------------------------------------------*/ package edu.wpi.first.wpilibj.image; @@ -11,27 +11,29 @@ import com.ni.vision.NIVision; /** * A color image represented in RGB color space at 3 bytes per pixel. + *$ * @author dtjones */ public class RGBImage extends ColorImage { - /** - * Create a new 0x0 image. - */ - public RGBImage() throws NIVisionException { - super(NIVision.ImageType.IMAGE_RGB); - } + /** + * Create a new 0x0 image. + */ + public RGBImage() throws NIVisionException { + super(NIVision.ImageType.IMAGE_RGB); + } - RGBImage(RGBImage sourceImage) { - super(sourceImage); - } + RGBImage(RGBImage sourceImage) { + super(sourceImage); + } - /** - * Create a new image by loading a file. - * @param fileName The path of the file to load. - */ - public RGBImage(String fileName) throws NIVisionException { - super(NIVision.ImageType.IMAGE_RGB); - NIVision.imaqReadFile(image, fileName); - } + /** + * Create a new image by loading a file. + *$ + * @param fileName The path of the file to load. + */ + public RGBImage(String fileName) throws NIVisionException { + super(NIVision.ImageType.IMAGE_RGB); + NIVision.imaqReadFile(image, fileName); + } } diff --git a/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/internal/HardwareHLUsageReporting.java b/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/internal/HardwareHLUsageReporting.java index 02eba2c256..0cc81d4db2 100644 --- a/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/internal/HardwareHLUsageReporting.java +++ b/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/internal/HardwareHLUsageReporting.java @@ -6,18 +6,18 @@ import edu.wpi.first.wpilibj.communication.FRCNetworkCommunicationsLibrary.tReso import edu.wpi.first.wpilibj.communication.UsageReporting; public class HardwareHLUsageReporting implements HLUsageReporting.Interface { - @Override - public void reportScheduler() { - UsageReporting.report(tResourceType.kResourceType_Command, tInstances.kCommand_Scheduler); - } + @Override + public void reportScheduler() { + UsageReporting.report(tResourceType.kResourceType_Command, tInstances.kCommand_Scheduler); + } - @Override - public void reportPIDController(int num) { - UsageReporting.report(tResourceType.kResourceType_PIDController, num); - } + @Override + public void reportPIDController(int num) { + UsageReporting.report(tResourceType.kResourceType_PIDController, num); + } - @Override - public void reportSmartDashboard() { - UsageReporting.report(tResourceType.kResourceType_SmartDashboard, 0); - } + @Override + public void reportSmartDashboard() { + UsageReporting.report(tResourceType.kResourceType_SmartDashboard, 0); + } } diff --git a/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/internal/HardwareTimer.java b/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/internal/HardwareTimer.java index e0e83e5e15..78205106a2 100644 --- a/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/internal/HardwareTimer.java +++ b/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/internal/HardwareTimer.java @@ -1,8 +1,8 @@ /*----------------------------------------------------------------------------*/ -/* Copyright (c) FIRST 2008-2012. All Rights Reserved. */ -/* Open Source Software - may be modified and shared by FRC teams. The code */ +/* Copyright (c) FIRST 2008-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 the root directory of */ -/* the project. */ +/* the project. */ /*----------------------------------------------------------------------------*/ package edu.wpi.first.wpilibj.internal; @@ -12,131 +12,130 @@ import edu.wpi.first.wpilibj.Timer; import edu.wpi.first.wpilibj.Utility; /** - * Timer objects measure accumulated time in milliseconds. - * The timer object functions like a stopwatch. It can be started, stopped, and cleared. When the - * timer is running its value counts up in milliseconds. 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. + * Timer objects measure accumulated time in milliseconds. The timer object + * functions like a stopwatch. It can be started, stopped, and cleared. When the + * timer is running its value counts up in milliseconds. 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. */ public class HardwareTimer implements Timer.StaticInterface { + /** + * Pause the thread for a specified time. Pause the execution of the thread + * for a specified period of time given in seconds. Motors will continue to + * run at their last assigned values, and sensors will continue to update. + * Only the task containing the wait will pause until the wait time is + * expired. + * + * @param seconds Length of time to pause + */ + @Override + public void delay(final double seconds) { + try { + Thread.sleep((long) (seconds * 1e3)); + } catch (final InterruptedException e) { + } + } + + /** + * Return the system clock time in seconds. Return the time from the FPGA + * hardware clock in seconds since the FPGA started. + * + * @return Robot running time in seconds. + */ + @Override + public double getFPGATimestamp() { + return Utility.getFPGATime() / 1000000.0; + } + + @Override + public double getMatchTime() { + return DriverStation.getInstance().getMatchTime(); + } + + @Override + public Timer.Interface newTimer() { + return new TimerImpl(); + } + + class TimerImpl implements Timer.Interface { + private long m_startTime; + private double m_accumulatedTime; + private boolean m_running; + /** - * Pause the thread for a specified time. Pause the execution of the - * thread for a specified period of time given in seconds. Motors will - * continue to run at their last assigned values, and sensors will continue - * to update. Only the task containing the wait will pause until the wait - * time is expired. - * - * @param seconds Length of time to pause + * Create a new timer object. Create a new timer object and reset the time + * to zero. The timer is initially not running and must be started. */ - @Override - public void delay(final double seconds) { - try { - Thread.sleep((long) (seconds * 1e3)); - } catch (final InterruptedException e) { - } + public TimerImpl() { + reset(); + } + + private long getMsClock() { + return Utility.getFPGATime() / 1000; } /** - * Return the system clock time in seconds. Return the time from the - * FPGA hardware clock in seconds since the FPGA started. + * Get the current time from the timer. If the clock is running it is + * derived from the current system clock the start time stored in the timer + * class. If the clock is not running, then return the time when it was last + * stopped. * - * @return Robot running time in seconds. + * @return Current time value for this timer in seconds */ - @Override - public double getFPGATimestamp() { - return Utility.getFPGATime() / 1000000.0; + public synchronized double get() { + if (m_running) { + return ((double) ((getMsClock() - m_startTime) + m_accumulatedTime)) / 1000.0; + } else { + return m_accumulatedTime; + } } - @Override - public double getMatchTime() { - return DriverStation.getInstance().getMatchTime(); - } - - @Override - public Timer.Interface newTimer() { - return new TimerImpl(); - } - - class TimerImpl implements Timer.Interface { - private long m_startTime; - private double m_accumulatedTime; - private boolean m_running; - - /** - * Create a new timer object. - * Create a new timer object and reset the time to zero. The timer is initially not running and - * must be started. - */ - public TimerImpl() { - reset(); - } - - private long getMsClock() { - return Utility.getFPGATime() / 1000; - } - - /** - * Get the current time from the timer. If the clock is running it is derived from - * the current system clock the start time stored in the timer class. If the clock - * is not running, then return the time when it was last stopped. - * - * @return Current time value for this timer in seconds - */ - public synchronized double get() { - if (m_running) { - return ((double) ((getMsClock() - m_startTime) + m_accumulatedTime)) / 1000.0; - } else { - return m_accumulatedTime; - } - } - - /** - * Reset the timer by setting the time to 0. - * Make the timer startTime the current time so new requests will be relative now - */ - public synchronized void reset() { - m_accumulatedTime = 0; - m_startTime = getMsClock(); - } - - /** - * Start the timer running. - * Just set the running flag to true indicating that all time requests should be - * relative to the system clock. - */ - public synchronized void start() { - m_startTime = getMsClock(); - m_running = true; - } - - /** - * Stop the timer. - * This computes the time as of now and clears the running flag, causing all - * subsequent time requests to be read from the accumulated time rather than - * looking at the system clock. - */ - public synchronized void stop() { - final double temp = get(); - m_accumulatedTime = temp; - m_running = false; - } - - /** - * Check if the period specified has passed and if it has, advance the start - * time by that period. This is useful to decide if it's time to do periodic - * work without drifting later by the time it took to get around to checking. - * - * @param period The period to check for (in seconds). - * @return If the period has passed. - */ - public synchronized boolean hasPeriodPassed(double period) { - if (get() > period) { - // Advance the start time by the period. - // Don't set it to the current time... we want to avoid drift. - m_startTime += period * 1000; - return true; - } - return false; - } + /** + * Reset the timer by setting the time to 0. Make the timer startTime the + * current time so new requests will be relative now + */ + public synchronized void reset() { + m_accumulatedTime = 0; + m_startTime = getMsClock(); } + + /** + * Start the timer running. Just set the running flag to true indicating + * that all time requests should be relative to the system clock. + */ + public synchronized void start() { + m_startTime = getMsClock(); + m_running = true; + } + + /** + * Stop the timer. This computes the time as of now and clears the running + * flag, causing all subsequent time requests to be read from the + * accumulated time rather than looking at the system clock. + */ + public synchronized void stop() { + final double temp = get(); + m_accumulatedTime = temp; + m_running = false; + } + + /** + * Check if the period specified has passed and if it has, advance the start + * time by that period. This is useful to decide if it's time to do periodic + * work without drifting later by the time it took to get around to + * checking. + * + * @param period The period to check for (in seconds). + * @return If the period has passed. + */ + public synchronized boolean hasPeriodPassed(double period) { + if (get() > period) { + // Advance the start time by the period. + // Don't set it to the current time... we want to avoid drift. + m_startTime += period * 1000; + return true; + } + return false; + } + } } diff --git a/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/vision/AxisCamera.java b/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/vision/AxisCamera.java index c69ff5c981..230667559d 100644 --- a/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/vision/AxisCamera.java +++ b/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/vision/AxisCamera.java @@ -1,8 +1,8 @@ /*----------------------------------------------------------------------------*/ -/* Copyright (c) FIRST 2014. All Rights Reserved. */ -/* Open Source Software - may be modified and shared by FRC teams. The code */ +/* Copyright (c) FIRST 2014. All Rights Reserved. */ +/* Open Source Software - may be modified and shared by FRC teams. The code */ /* must be accompanied by the FIRST BSD license file in the root directory of */ -/* the project. */ +/* the project. */ /*----------------------------------------------------------------------------*/ package edu.wpi.first.wpilibj.vision; @@ -26,531 +26,516 @@ import static edu.wpi.first.wpilibj.Timer.delay; * Axis M1011 network camera */ public class AxisCamera { - public enum WhiteBalance { - kAutomatic, - kHold, - kFixedOutdoor1, - kFixedOutdoor2, - kFixedIndoor, - kFixedFluorescent1, - kFixedFluorescent2, + public enum WhiteBalance { + kAutomatic, kHold, kFixedOutdoor1, kFixedOutdoor2, kFixedIndoor, kFixedFluorescent1, kFixedFluorescent2, + } + + public enum ExposureControl { + kAutomatic, kHold, kFlickerFree50Hz, kFlickerFree60Hz, + } + + public enum Resolution { + k640x480, k480x360, k320x240, k240x180, k176x144, k160x120, + } + + public enum Rotation { + k0, k180 + } + + private static final String[] kWhiteBalanceStrings = {"auto", "hold", "fixed_outdoor1", + "fixed_outdoor2", "fixed_indoor", "fixed_fluor1", "fixed_fluor2",}; + + private static final String[] kExposureControlStrings = {"auto", "hold", "flickerfree50", + "flickerfree60",}; + + private static final String[] kResolutionStrings = {"640x480", "480x360", "320x240", "240x180", + "176x144", "160x120",}; + + private static final String[] kRotationStrings = {"0", "180",}; + + private final static int kImageBufferAllocationIncrement = 1000; + + private String m_cameraHost; + private Socket m_cameraSocket; + + private ByteBuffer m_imageData = ByteBuffer.allocate(5000); + private final Object m_imageDataLock = new Object(); + private boolean m_freshImage = false; + + private int m_brightness = 50; + private WhiteBalance m_whiteBalance = WhiteBalance.kAutomatic; + private int m_colorLevel = 50; + private ExposureControl m_exposureControl = ExposureControl.kAutomatic; + private int m_exposurePriority = 50; + private int m_maxFPS = 0; + private Resolution m_resolution = Resolution.k640x480; + private int m_compression = 50; + private Rotation m_rotation = Rotation.k0; + private final Object m_parametersLock = new Object(); + private boolean m_parametersDirty = true; + private boolean m_streamDirty = true; + + private boolean m_done = false; + + /** + * AxisCamera constructor + * + * @param cameraHost The host to find the camera at, typically an IP address + */ + public AxisCamera(String cameraHost) { + m_cameraHost = cameraHost; + m_captureThread.start(); + } + + /** + * Return true if the latest image from the camera has not been retrieved by + * calling GetImage() yet. + *$ + * @return true if the image has not been retrieved yet. + */ + public boolean isFreshImage() { + return m_freshImage; + } + + /** + * Get an image from the camera and store it in the provided image. + * + * @param image The imaq image to store the result in. This must be an HSL or + * RGB image. + * @return true upon success, false on a failure + */ + public boolean getImage(Image image) { + if (m_imageData.limit() == 0) { + return false; } - public enum ExposureControl { - kAutomatic, - kHold, - kFlickerFree50Hz, - kFlickerFree60Hz, + synchronized (m_imageDataLock) { + Priv_ReadJPEGString_C(image, m_imageData.array()); } - public enum Resolution { - k640x480, - k480x360, - k320x240, - k240x180, - k176x144, - k160x120, + m_freshImage = false; + + return true; + } + + /** + * Get an image from the camera and store it in the provided image. + * + * @param image The image to store the result in. This must be an HSL or RGB + * image + * @return true upon success, false on a failure + */ + public boolean getImage(ColorImage image) { + return this.getImage(image.image); + } + + /** + * Instantiate a new image object and fill it with the latest image from the + * camera. + * + * @return a pointer to an HSLImage object + */ + public HSLImage getImage() throws NIVisionException { + HSLImage image = new HSLImage(); + this.getImage(image); + return image; + } + + /** + * Request a change in the brightness of the camera images. + * + * @param brightness valid values 0 .. 100 + */ + public void writeBrightness(int brightness) { + if (brightness < 0 || brightness > 100) { + throw new IllegalArgumentException("Brightness must be from 0 to 100"); } - public enum Rotation { - k0, k180 + synchronized (m_parametersLock) { + if (m_brightness != brightness) { + m_brightness = brightness; + m_parametersDirty = true; + } + } + } + + /** + * @return The configured brightness of the camera images + */ + public int getBrightness() { + synchronized (m_parametersLock) { + return m_brightness; + } + } + + /** + * Request a change in the white balance on the camera. + * + * @param whiteBalance Valid values from the WhiteBalance enum. + */ + public void writeWhiteBalance(WhiteBalance whiteBalance) { + synchronized (m_parametersLock) { + if (m_whiteBalance != whiteBalance) { + m_whiteBalance = whiteBalance; + m_parametersDirty = true; + } + } + } + + /** + * @return The configured white balances of the camera images + */ + public WhiteBalance getWhiteBalance() { + synchronized (m_parametersLock) { + return m_whiteBalance; + } + } + + /** + * Request a change in the color level of the camera images. + * + * @param colorLevel valid values are 0 .. 100 + */ + public void writeColorLevel(int colorLevel) { + if (colorLevel < 0 || colorLevel > 100) { + throw new IllegalArgumentException("Color level must be from 0 to 100"); } - private static final String[] kWhiteBalanceStrings = - {"auto", "hold", "fixed_outdoor1", "fixed_outdoor2", "fixed_indoor", - "fixed_fluor1", "fixed_fluor2",}; + synchronized (m_parametersLock) { + if (m_colorLevel != colorLevel) { + m_colorLevel = colorLevel; + m_parametersDirty = true; + } + } + } - private static final String[] kExposureControlStrings = - {"auto", "hold", "flickerfree50", "flickerfree60",}; + /** + * @return The configured color level of the camera images + */ + public int getColorLevel() { + synchronized (m_parametersLock) { + return m_colorLevel; + } + } - private static final String[] kResolutionStrings = - {"640x480", "480x360", "320x240", "240x180", "176x144", "160x120",}; + /** + * Request a change in the camera's exposure mode. + * + * @param exposureControl A mode to write in the Exposure enum. + */ + public void writeExposureControl(ExposureControl exposureControl) { + synchronized (m_parametersLock) { + if (m_exposureControl != exposureControl) { + m_exposureControl = exposureControl; + m_parametersDirty = true; + } + } + } - private static final String[] kRotationStrings = - {"0", "180",}; + /** + * @return The configured exposure control mode of the camera + */ + public ExposureControl getExposureControl() { + synchronized (m_parametersLock) { + return m_exposureControl; + } + } - private final static int kImageBufferAllocationIncrement = 1000; - - private String m_cameraHost; - private Socket m_cameraSocket; - - private ByteBuffer m_imageData = ByteBuffer.allocate(5000); - private final Object m_imageDataLock = new Object(); - private boolean m_freshImage = false; - - private int m_brightness = 50; - private WhiteBalance m_whiteBalance = WhiteBalance.kAutomatic; - private int m_colorLevel = 50; - private ExposureControl m_exposureControl = ExposureControl.kAutomatic; - private int m_exposurePriority = 50; - private int m_maxFPS = 0; - private Resolution m_resolution = Resolution.k640x480; - private int m_compression = 50; - private Rotation m_rotation = Rotation.k0; - private final Object m_parametersLock = new Object(); - private boolean m_parametersDirty = true; - private boolean m_streamDirty = true; - - private boolean m_done = false; - - /** - * AxisCamera constructor - * - * @param cameraHost The host to find the camera at, typically an IP address - */ - public AxisCamera(String cameraHost) { - m_cameraHost = cameraHost; - m_captureThread.start(); + /** + * Request a change in the exposure priority of the camera. + * + * @param exposurePriority Valid values are 0, 50, 100. 0 = Prioritize image + * quality 50 = None 100 = Prioritize frame rate + */ + public void writeExposurePriority(int exposurePriority) { + if (exposurePriority != 0 && exposurePriority != 50 && exposurePriority != 100) { + throw new IllegalArgumentException("Exposure priority must be 0, 50, or 100"); } - /** - * Return true if the latest image from the camera has not been retrieved by calling GetImage() yet. - * @return true if the image has not been retrieved yet. - */ - public boolean isFreshImage() { - return m_freshImage; + synchronized (m_parametersLock) { + if (m_exposurePriority != exposurePriority) { + m_exposurePriority = exposurePriority; + m_parametersDirty = true; + } + } + } + + /** + * @return The configured exposure priority of the camera + */ + public int getExposurePriority() { + synchronized (m_parametersLock) { + return m_exposurePriority; + } + } + + /** + * Write the maximum frames per second that the camera should send Write 0 to + * send as many as possible. + * + * @param maxFPS The number of frames the camera should send in a second, + * exposure permitting. + */ + public void writeMaxFPS(int maxFPS) { + synchronized (m_parametersLock) { + if (m_maxFPS != maxFPS) { + m_maxFPS = maxFPS; + m_parametersDirty = true; + m_streamDirty = true; + } + } + } + + /** + * @return The configured maximum FPS of the camera + */ + public int getMaxFPS() { + synchronized (m_parametersLock) { + return m_maxFPS; + } + } + + /** + * Write resolution value to camera. + * + * @param resolution The camera resolution value to write to the camera. + */ + public void writeResolution(Resolution resolution) { + synchronized (m_parametersLock) { + if (m_resolution != resolution) { + m_resolution = resolution; + m_parametersDirty = true; + m_streamDirty = true; + } + } + } + + /** + * @return The configured resolution of the camera (not necessarily the same + * resolution as the most recent image, if it was changed recently.) + */ + public Resolution getResolution() { + synchronized (m_parametersLock) { + return m_resolution; + } + } + + /** + * Write the compression value to the camera. + * + * @param compression Values between 0 and 100. + */ + public void writeCompression(int compression) { + if (compression < 0 || compression > 100) { + throw new IllegalArgumentException("Compression must be from 0 to 100"); } - /** - * Get an image from the camera and store it in the provided image. - * - * @param image The imaq image to store the result in. This must be an HSL or RGB image. - * @return true upon success, false on a failure - */ - public boolean getImage(Image image) { - if (m_imageData.limit() == 0) { - return false; + synchronized (m_parametersLock) { + if (m_compression != compression) { + m_compression = compression; + m_parametersDirty = true; + m_streamDirty = true; + } + } + } + + /** + * @return The configured compression level of the camera images + */ + public int getCompression() { + synchronized (m_parametersLock) { + return m_compression; + } + } + + /** + * Write the rotation value to the camera. If you mount your camera upside + * down, use this to adjust the image for you. + * + * @param rotation A value from the {@link Rotation} enum + */ + public void writeRotation(Rotation rotation) { + synchronized (m_parametersLock) { + if (m_rotation != rotation) { + m_rotation = rotation; + m_parametersDirty = true; + m_streamDirty = true; + } + } + } + + /** + * @return The configured rotation mode of the camera + */ + public Rotation getRotation() { + synchronized (m_parametersLock) { + return m_rotation; + } + } + + /** + * Thread spawned by AxisCamera constructor to receive images from cam + */ + private Thread m_captureThread = new Thread(new Runnable() { + @Override + public void run() { + int consecutiveErrors = 0; + + // Loop on trying to setup the camera connection. This happens in a + // background + // thread so it shouldn't effect the operation of user programs. + while (!m_done) { + String requestString = + "GET /mjpg/video.mjpg HTTP/1.1\n" + "User-Agent: HTTPStreamClient\n" + + "Connection: Keep-Alive\n" + "Cache-Control: no-cache\n" + + "Authorization: Basic RlJDOkZSQw==\n\n"; + + try { + m_cameraSocket = AxisCamera.this.createCameraSocket(requestString); + AxisCamera.this.readImagesFromCamera(); + consecutiveErrors = 0; + } catch (IOException e) { + consecutiveErrors++; + + if (consecutiveErrors > 5) { + e.printStackTrace(); + } } + delay(0.5); + } + } + }); + + /** + * This function actually reads the images from the camera. + */ + private void readImagesFromCamera() throws IOException { + DataInputStream cameraInputStream = new DataInputStream(m_cameraSocket.getInputStream()); + + while (!m_done) { + String line = cameraInputStream.readLine(); + + if (line.startsWith("Content-Length: ")) { + int contentLength = Integer.valueOf(line.substring(16)); + + /* Skip the next blank line */ + cameraInputStream.readLine(); + contentLength -= 4; + + /* The next four bytes are the JPEG magic number */ + byte[] data = new byte[contentLength]; + cameraInputStream.readFully(data); + synchronized (m_imageDataLock) { - Priv_ReadJPEGString_C(image, m_imageData.array()); + if (m_imageData.capacity() < data.length) { + m_imageData = ByteBuffer.allocate(data.length + kImageBufferAllocationIncrement); + } + + m_imageData.clear(); + m_imageData.limit(contentLength); + m_imageData.put(data); + + m_freshImage = true; } - m_freshImage = false; + if (this.writeParameters()) { + break; + } - return true; + /* Skip the boundary and Content-Type header */ + cameraInputStream.readLine(); + cameraInputStream.readLine(); + } } - /** - * Get an image from the camera and store it in the provided image. - * - * @param image The image to store the result in. This must be an HSL or RGB image - * @return true upon success, false on a failure - */ - public boolean getImage(ColorImage image) { - return this.getImage(image.image); - } + m_cameraSocket.close(); + } - /** - * Instantiate a new image object and fill it with the latest image from the camera. - * - * @return a pointer to an HSLImage object - */ - public HSLImage getImage() throws NIVisionException { - HSLImage image = new HSLImage(); - this.getImage(image); - return image; - } + /** + * Send a request to the camera to set all of the parameters. This is called + * in the capture thread between each frame. This strategy avoids making lots + * of redundant HTTP requests, accounts for failed initial requests, and + * avoids blocking calls in the main thread unless necessary. + *

+ * This method does nothing if no parameters have been modified since it last + * completely successfully. + * + * @return true if the stream should be restarted due to a + * parameter changing. + */ + private boolean writeParameters() { + if (m_parametersDirty) { + String request = "GET /axis-cgi/admin/param.cgi?action=update"; - /** - * Request a change in the brightness of the camera images. - * - * @param brightness valid values 0 .. 100 - */ - public void writeBrightness(int brightness) { - if (brightness < 0 || brightness > 100) { - throw new IllegalArgumentException("Brightness must be from 0 to 100"); + synchronized (m_parametersLock) { + request += "&ImageSource.I0.Sensor.Brightness=" + m_brightness; + request += + "&ImageSource.I0.Sensor.WhiteBalance=" + kWhiteBalanceStrings[m_whiteBalance.ordinal()]; + request += "&ImageSource.I0.Sensor.ColorLevel=" + m_colorLevel; + request += + "&ImageSource.I0.Sensor.Exposure=" + + kExposureControlStrings[m_exposureControl.ordinal()]; + request += "&ImageSource.I0.Sensor.ExposurePriority=" + m_exposurePriority; + request += "&Image.I0.Stream.FPS=" + m_maxFPS; + request += "&Image.I0.Appearance.Resolution=" + kResolutionStrings[m_resolution.ordinal()]; + request += "&Image.I0.Appearance.Compression=" + m_compression; + request += "&Image.I0.Appearance.Rotation=" + kRotationStrings[m_rotation.ordinal()]; + } + + request += " HTTP/1.1\n"; + request += "User-Agent: HTTPStreamClient\n"; + request += "Connection: Keep-Alive\n"; + request += "Cache-Control: no-cache\n"; + request += "Authorization: Basic RlJDOkZSQw==\n\n"; + + try { + Socket socket = this.createCameraSocket(request); + socket.close(); + + m_parametersDirty = false; + + if (m_streamDirty) { + m_streamDirty = false; + return true; + } else { + return false; } - - synchronized (m_parametersLock) { - if (m_brightness != brightness) { - m_brightness = brightness; - m_parametersDirty = true; - } - } - } - - /** - * @return The configured brightness of the camera images - */ - public int getBrightness() { - synchronized (m_parametersLock) { - return m_brightness; - } - } - - /** - * Request a change in the white balance on the camera. - * - * @param whiteBalance Valid values from the WhiteBalance enum. - */ - public void writeWhiteBalance(WhiteBalance whiteBalance) { - synchronized (m_parametersLock) { - if (m_whiteBalance != whiteBalance) { - m_whiteBalance = whiteBalance; - m_parametersDirty = true; - } - } - } - - /** - * @return The configured white balances of the camera images - */ - public WhiteBalance getWhiteBalance() { - synchronized (m_parametersLock) { - return m_whiteBalance; - } - } - - /** - * Request a change in the color level of the camera images. - * - * @param colorLevel valid values are 0 .. 100 - */ - public void writeColorLevel(int colorLevel) { - if (colorLevel < 0 || colorLevel > 100) { - throw new IllegalArgumentException("Color level must be from 0 to 100"); - } - - synchronized (m_parametersLock) { - if (m_colorLevel != colorLevel) { - m_colorLevel = colorLevel; - m_parametersDirty = true; - } - } - } - - /** - * @return The configured color level of the camera images - */ - public int getColorLevel() { - synchronized (m_parametersLock) { - return m_colorLevel; - } - } - - /** - * Request a change in the camera's exposure mode. - * - * @param exposureControl A mode to write in the Exposure enum. - */ - public void writeExposureControl(ExposureControl exposureControl) { - synchronized (m_parametersLock) { - if (m_exposureControl != exposureControl) { - m_exposureControl = exposureControl; - m_parametersDirty = true; - } - } - } - - /** - * @return The configured exposure control mode of the camera - */ - public ExposureControl getExposureControl() { - synchronized (m_parametersLock) { - return m_exposureControl; - } - } - - /** - * Request a change in the exposure priority of the camera. - * - * @param exposurePriority Valid values are 0, 50, 100. - * 0 = Prioritize image quality - * 50 = None - * 100 = Prioritize frame rate - */ - public void writeExposurePriority(int exposurePriority) { - if (exposurePriority != 0 && exposurePriority != 50 && exposurePriority != 100) { - throw new IllegalArgumentException("Exposure priority must be 0, 50, or 100"); - } - - synchronized (m_parametersLock) { - if (m_exposurePriority != exposurePriority) { - m_exposurePriority = exposurePriority; - m_parametersDirty = true; - } - } - } - - /** - * @return The configured exposure priority of the camera - */ - public int getExposurePriority() { - synchronized (m_parametersLock) { - return m_exposurePriority; - } - } - - /** - * Write the maximum frames per second that the camera should send - * Write 0 to send as many as possible. - * - * @param maxFPS The number of frames the camera should send in a second, exposure permitting. - */ - public void writeMaxFPS(int maxFPS) { - synchronized (m_parametersLock) { - if (m_maxFPS != maxFPS) { - m_maxFPS = maxFPS; - m_parametersDirty = true; - m_streamDirty = true; - } - } - } - - /** - * @return The configured maximum FPS of the camera - */ - public int getMaxFPS() { - synchronized (m_parametersLock) { - return m_maxFPS; - } - } - - /** - * Write resolution value to camera. - * - * @param resolution The camera resolution value to write to the camera. - */ - public void writeResolution(Resolution resolution) { - synchronized (m_parametersLock) { - if (m_resolution != resolution) { - m_resolution = resolution; - m_parametersDirty = true; - m_streamDirty = true; - } - } - } - - /** - * @return The configured resolution of the camera (not necessarily the same - * resolution as the most recent image, if it was changed recently.) - */ - public Resolution getResolution() { - synchronized (m_parametersLock) { - return m_resolution; - } - } - - /** - * Write the compression value to the camera. - * - * @param compression Values between 0 and 100. - */ - public void writeCompression(int compression) { - if (compression < 0 || compression > 100) { - throw new IllegalArgumentException("Compression must be from 0 to 100"); - } - - synchronized (m_parametersLock) { - if (m_compression != compression) { - m_compression = compression; - m_parametersDirty = true; - m_streamDirty = true; - } - } - } - - /** - * @return The configured compression level of the camera images - */ - public int getCompression() { - synchronized (m_parametersLock) { - return m_compression; - } - } - - /** - * Write the rotation value to the camera. - * If you mount your camera upside down, use this to adjust the image for you. - * - * @param rotation A value from the {@link Rotation} enum - */ - public void writeRotation(Rotation rotation) { - synchronized (m_parametersLock) { - if (m_rotation != rotation) { - m_rotation = rotation; - m_parametersDirty = true; - m_streamDirty = true; - } - } - } - - /** - * @return The configured rotation mode of the camera - */ - public Rotation getRotation() { - synchronized (m_parametersLock) { - return m_rotation; - } - } - - /** - * Thread spawned by AxisCamera constructor to receive images from cam - */ - private Thread m_captureThread = new Thread(new Runnable() { - @Override - public void run() { - int consecutiveErrors = 0; - - // Loop on trying to setup the camera connection. This happens in a background - // thread so it shouldn't effect the operation of user programs. - while (!m_done) { - String requestString = "GET /mjpg/video.mjpg HTTP/1.1\n" + - "User-Agent: HTTPStreamClient\n" + - "Connection: Keep-Alive\n" + - "Cache-Control: no-cache\n" + - "Authorization: Basic RlJDOkZSQw==\n\n"; - - try { - m_cameraSocket = AxisCamera.this.createCameraSocket(requestString); - AxisCamera.this.readImagesFromCamera(); - consecutiveErrors = 0; - } catch (IOException e) { - consecutiveErrors++; - - if (consecutiveErrors > 5) { - e.printStackTrace(); - } - } - - delay(0.5); - } - } - }); - - /** - * This function actually reads the images from the camera. - */ - private void readImagesFromCamera() throws IOException { - DataInputStream cameraInputStream = new DataInputStream(m_cameraSocket.getInputStream()); - - while (!m_done) { - String line = cameraInputStream.readLine(); - - if (line.startsWith("Content-Length: ")) { - int contentLength = Integer.valueOf(line.substring(16)); - - /* Skip the next blank line */ - cameraInputStream.readLine(); - contentLength -= 4; - - /* The next four bytes are the JPEG magic number */ - byte[] data = new byte[contentLength]; - cameraInputStream.readFully(data); - - synchronized (m_imageDataLock) { - if (m_imageData.capacity() < data.length) { - m_imageData = ByteBuffer.allocate(data.length + kImageBufferAllocationIncrement); - } - - m_imageData.clear(); - m_imageData.limit(contentLength); - m_imageData.put(data); - - m_freshImage = true; - } - - if (this.writeParameters()) { - break; - } - - /* Skip the boundary and Content-Type header */ - cameraInputStream.readLine(); - cameraInputStream.readLine(); - } - } - - m_cameraSocket.close(); - } - - /** - * Send a request to the camera to set all of the parameters. This is called - * in the capture thread between each frame. This strategy avoids making lots - * of redundant HTTP requests, accounts for failed initial requests, and - * avoids blocking calls in the main thread unless necessary. - *

- * This method does nothing if no parameters have been modified since it last - * completely successfully. - * - * @return true if the stream should be restarted due to a - * parameter changing. - */ - private boolean writeParameters() { - if (m_parametersDirty) { - String request = "GET /axis-cgi/admin/param.cgi?action=update"; - - synchronized (m_parametersLock) { - request += "&ImageSource.I0.Sensor.Brightness=" + m_brightness; - request += "&ImageSource.I0.Sensor.WhiteBalance=" + kWhiteBalanceStrings[m_whiteBalance.ordinal()]; - request += "&ImageSource.I0.Sensor.ColorLevel=" + m_colorLevel; - request += "&ImageSource.I0.Sensor.Exposure=" + kExposureControlStrings[m_exposureControl.ordinal()]; - request += "&ImageSource.I0.Sensor.ExposurePriority=" + m_exposurePriority; - request += "&Image.I0.Stream.FPS=" + m_maxFPS; - request += "&Image.I0.Appearance.Resolution=" + kResolutionStrings[m_resolution.ordinal()]; - request += "&Image.I0.Appearance.Compression=" + m_compression; - request += "&Image.I0.Appearance.Rotation=" + kRotationStrings[m_rotation.ordinal()]; - } - - request += " HTTP/1.1\n"; - request += "User-Agent: HTTPStreamClient\n"; - request += "Connection: Keep-Alive\n"; - request += "Cache-Control: no-cache\n"; - request += "Authorization: Basic RlJDOkZSQw==\n\n"; - - try { - Socket socket = this.createCameraSocket(request); - socket.close(); - - m_parametersDirty = false; - - if (m_streamDirty) { - m_streamDirty = false; - return true; - } else { - return false; - } - } catch (IOException | NullPointerException e) { - return false; - } - - } - + } catch (IOException | NullPointerException e) { return false; + } + } - /** - * Create a socket connected to camera - * Used to create a connection for reading images and setting parameters - * - * @param requestString The initial request string to send upon successful connection. - * @return The created socket - */ - private Socket createCameraSocket(String requestString) throws IOException { - /* Connect to the server */ - Socket socket = new Socket(); - socket.connect(new InetSocketAddress(m_cameraHost, 80), 5000); + return false; + } - /* Send the HTTP headers */ - OutputStream socketOutputStream = socket.getOutputStream(); - socketOutputStream.write(requestString.getBytes()); + /** + * Create a socket connected to camera Used to create a connection for reading + * images and setting parameters + * + * @param requestString The initial request string to send upon successful + * connection. + * @return The created socket + */ + private Socket createCameraSocket(String requestString) throws IOException { + /* Connect to the server */ + Socket socket = new Socket(); + socket.connect(new InetSocketAddress(m_cameraHost, 80), 5000); - return socket; - } + /* Send the HTTP headers */ + OutputStream socketOutputStream = socket.getOutputStream(); + socketOutputStream.write(requestString.getBytes()); - @Override - public String toString() { - return "AxisCamera{" + - "FreshImage=" + isFreshImage() + - ", Brightness=" + getBrightness() + - ", WhiteBalance=" + getWhiteBalance() + - ", ColorLevel=" + getColorLevel() + - ", ExposureControl=" + getExposureControl() + - ", ExposurePriority=" + getExposurePriority() + - ", MaxFPS=" + getMaxFPS() + - ", Resolution=" + getResolution() + - ", Compression=" + getCompression() + - ", Rotation=" + getRotation() + - '}'; - } + return socket; + } + + @Override + public String toString() { + return "AxisCamera{" + "FreshImage=" + isFreshImage() + ", Brightness=" + getBrightness() + + ", WhiteBalance=" + getWhiteBalance() + ", ColorLevel=" + getColorLevel() + + ", ExposureControl=" + getExposureControl() + ", ExposurePriority=" + + getExposurePriority() + ", MaxFPS=" + getMaxFPS() + ", Resolution=" + getResolution() + + ", Compression=" + getCompression() + ", Rotation=" + getRotation() + '}'; + } } diff --git a/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/vision/USBCamera.java b/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/vision/USBCamera.java index 6f5d606f79..8d1c364f29 100644 --- a/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/vision/USBCamera.java +++ b/wpilibj/wpilibJavaDevices/src/main/java/edu/wpi/first/wpilibj/vision/USBCamera.java @@ -11,290 +11,296 @@ import static com.ni.vision.NIVision.Image; import static edu.wpi.first.wpilibj.Timer.delay; public class USBCamera { - public static String kDefaultCameraName = "cam0"; + public static String kDefaultCameraName = "cam0"; - private static String ATTR_VIDEO_MODE = "AcquisitionAttributes::VideoMode"; - private static String ATTR_WB_MODE = "CameraAttributes::WhiteBalance::Mode"; - private static String ATTR_WB_VALUE = "CameraAttributes::WhiteBalance::Value"; - private static String ATTR_EX_MODE = "CameraAttributes::Exposure::Mode"; - private static String ATTR_EX_VALUE = "CameraAttributes::Exposure::Value"; - private static String ATTR_BR_MODE = "CameraAttributes::Brightness::Mode"; - private static String ATTR_BR_VALUE = "CameraAttributes::Brightness::Value"; + private static String ATTR_VIDEO_MODE = "AcquisitionAttributes::VideoMode"; + private static String ATTR_WB_MODE = "CameraAttributes::WhiteBalance::Mode"; + private static String ATTR_WB_VALUE = "CameraAttributes::WhiteBalance::Value"; + private static String ATTR_EX_MODE = "CameraAttributes::Exposure::Mode"; + private static String ATTR_EX_VALUE = "CameraAttributes::Exposure::Value"; + private static String ATTR_BR_MODE = "CameraAttributes::Brightness::Mode"; + private static String ATTR_BR_VALUE = "CameraAttributes::Brightness::Value"; - public class WhiteBalance { - public static final int kFixedIndoor = 3000; - public static final int kFixedOutdoor1 = 4000; - public static final int kFixedOutdoor2 = 5000; - public static final int kFixedFluorescent1 = 5100; - public static final int kFixedFlourescent2 = 5200; - } + public class WhiteBalance { + public static final int kFixedIndoor = 3000; + public static final int kFixedOutdoor1 = 4000; + public static final int kFixedOutdoor2 = 5000; + public static final int kFixedFluorescent1 = 5100; + public static final int kFixedFlourescent2 = 5200; + } - private Pattern m_reMode = Pattern.compile("(?[0-9]+)\\s*x\\s*(?[0-9]+)\\s+(?.*?)\\s+(?[0-9.]+)\\s*fps"); + private Pattern m_reMode = + Pattern + .compile("(?[0-9]+)\\s*x\\s*(?[0-9]+)\\s+(?.*?)\\s+(?[0-9.]+)\\s*fps"); - private String m_name = kDefaultCameraName; - private int m_id = -1; - private boolean m_active = false; - private boolean m_useJpeg = true; - private int m_width = 320; - private int m_height = 240; - private int m_fps = 30; - private String m_whiteBalance = "auto"; - private int m_whiteBalanceValue = -1; - private String m_exposure = "auto"; - private int m_exposureValue = -1; - private int m_brightness = 50; - private boolean m_needSettingsUpdate = true; + private String m_name = kDefaultCameraName; + private int m_id = -1; + private boolean m_active = false; + private boolean m_useJpeg = true; + private int m_width = 320; + private int m_height = 240; + private int m_fps = 30; + private String m_whiteBalance = "auto"; + private int m_whiteBalanceValue = -1; + private String m_exposure = "auto"; + private int m_exposureValue = -1; + private int m_brightness = 50; + private boolean m_needSettingsUpdate = true; - public USBCamera() { - openCamera(); - } + public USBCamera() { + openCamera(); + } - public USBCamera(String name) { - m_name = name; - openCamera(); - } + public USBCamera(String name) { + m_name = name; + openCamera(); + } - public synchronized void openCamera() { - if (m_id != -1) return; // Camera is already open - for (int i=0; i<3; i++) { - try { - m_id = NIVision.IMAQdxOpenCamera(m_name, - NIVision.IMAQdxCameraControlMode.CameraControlModeController); - } catch (VisionException e) { - if (i == 2) - throw e; - delay(2.0); - continue; - } - break; - } - } + public synchronized void openCamera() { + if (m_id != -1) + return; // Camera is already open + for (int i = 0; i < 3; i++) { + try { + m_id = + NIVision.IMAQdxOpenCamera(m_name, + NIVision.IMAQdxCameraControlMode.CameraControlModeController); + } catch (VisionException e) { + if (i == 2) + throw e; + delay(2.0); + continue; + } + break; + } + } - public synchronized void closeCamera() { - if (m_id == -1) - return; - NIVision.IMAQdxCloseCamera(m_id); - m_id = -1; - } + public synchronized void closeCamera() { + if (m_id == -1) + return; + NIVision.IMAQdxCloseCamera(m_id); + m_id = -1; + } - public synchronized void startCapture() { - if (m_id == -1 || m_active) - return; - NIVision.IMAQdxConfigureGrab(m_id); - NIVision.IMAQdxStartAcquisition(m_id); - m_active = true; - } + public synchronized void startCapture() { + if (m_id == -1 || m_active) + return; + NIVision.IMAQdxConfigureGrab(m_id); + NIVision.IMAQdxStartAcquisition(m_id); + m_active = true; + } - public synchronized void stopCapture() { - if (m_id == -1 || !m_active) - return; - NIVision.IMAQdxStopAcquisition(m_id); - NIVision.IMAQdxUnconfigureAcquisition(m_id); - m_active = false; - } + public synchronized void stopCapture() { + if (m_id == -1 || !m_active) + return; + NIVision.IMAQdxStopAcquisition(m_id); + NIVision.IMAQdxUnconfigureAcquisition(m_id); + m_active = false; + } - public synchronized void updateSettings() { - boolean wasActive = m_active; - // Stop acquistion, close and reopen camera - if (wasActive) - stopCapture(); - if (m_id != -1) - closeCamera(); - openCamera(); + public synchronized void updateSettings() { + boolean wasActive = m_active; + // Stop acquistion, close and reopen camera + if (wasActive) + stopCapture(); + if (m_id != -1) + closeCamera(); + openCamera(); - // Video Mode - NIVision.dxEnumerateVideoModesResult enumerated = NIVision.IMAQdxEnumerateVideoModes(m_id); - NIVision.IMAQdxEnumItem foundMode = null; - int foundFps = 1000; - for (NIVision.IMAQdxEnumItem mode : enumerated.videoModeArray) { - Matcher m = m_reMode.matcher(mode.Name); - if (!m.matches()) - continue; - if (Integer.parseInt(m.group("width")) != m_width) - continue; - if (Integer.parseInt(m.group("height")) != m_height) - continue; - double fps = Double.parseDouble(m.group("fps")); - if (fps < m_fps) - continue; - if (fps > foundFps) - continue; - String format = m.group("format"); - boolean isJpeg = format.equals("jpeg") || format.equals("JPEG"); - if ((m_useJpeg && !isJpeg) || (!m_useJpeg && isJpeg)) - continue; - foundMode = mode; - foundFps = (int)fps; - } - if (foundMode != null) { - System.out.println("found mode " + foundMode.Value + ": " + foundMode.Name); - if (foundMode.Value != enumerated.currentMode) - NIVision.IMAQdxSetAttributeU32(m_id, ATTR_VIDEO_MODE, foundMode.Value); - } + // Video Mode + NIVision.dxEnumerateVideoModesResult enumerated = NIVision.IMAQdxEnumerateVideoModes(m_id); + NIVision.IMAQdxEnumItem foundMode = null; + int foundFps = 1000; + for (NIVision.IMAQdxEnumItem mode : enumerated.videoModeArray) { + Matcher m = m_reMode.matcher(mode.Name); + if (!m.matches()) + continue; + if (Integer.parseInt(m.group("width")) != m_width) + continue; + if (Integer.parseInt(m.group("height")) != m_height) + continue; + double fps = Double.parseDouble(m.group("fps")); + if (fps < m_fps) + continue; + if (fps > foundFps) + continue; + String format = m.group("format"); + boolean isJpeg = format.equals("jpeg") || format.equals("JPEG"); + if ((m_useJpeg && !isJpeg) || (!m_useJpeg && isJpeg)) + continue; + foundMode = mode; + foundFps = (int) fps; + } + if (foundMode != null) { + System.out.println("found mode " + foundMode.Value + ": " + foundMode.Name); + if (foundMode.Value != enumerated.currentMode) + NIVision.IMAQdxSetAttributeU32(m_id, ATTR_VIDEO_MODE, foundMode.Value); + } - // White Balance - if (m_whiteBalance == "auto") - NIVision.IMAQdxSetAttributeString(m_id, ATTR_WB_MODE, "Auto"); - else { - NIVision.IMAQdxSetAttributeString(m_id, ATTR_WB_MODE, "Manual"); - if (m_whiteBalanceValue != -1) - NIVision.IMAQdxSetAttributeI64(m_id, ATTR_WB_VALUE, m_whiteBalanceValue); - } + // White Balance + if (m_whiteBalance == "auto") + NIVision.IMAQdxSetAttributeString(m_id, ATTR_WB_MODE, "Auto"); + else { + NIVision.IMAQdxSetAttributeString(m_id, ATTR_WB_MODE, "Manual"); + if (m_whiteBalanceValue != -1) + NIVision.IMAQdxSetAttributeI64(m_id, ATTR_WB_VALUE, m_whiteBalanceValue); + } - // Exposure - if (m_exposure == "auto") - NIVision.IMAQdxSetAttributeString(m_id, ATTR_EX_MODE, "AutoAperaturePriority"); - else { - NIVision.IMAQdxSetAttributeString(m_id, ATTR_EX_MODE, "Manual"); - if (m_exposureValue != -1) { - long minv = NIVision.IMAQdxGetAttributeMinimumI64(m_id, ATTR_EX_VALUE); - long maxv = NIVision.IMAQdxGetAttributeMaximumI64(m_id, ATTR_EX_VALUE); - long val = minv + (long)(((double)(maxv - minv)) * (((double)m_exposureValue) / 100.0)); - NIVision.IMAQdxSetAttributeI64(m_id, ATTR_EX_VALUE, val); - } - } + // Exposure + if (m_exposure == "auto") + NIVision.IMAQdxSetAttributeString(m_id, ATTR_EX_MODE, "AutoAperaturePriority"); + else { + NIVision.IMAQdxSetAttributeString(m_id, ATTR_EX_MODE, "Manual"); + if (m_exposureValue != -1) { + long minv = NIVision.IMAQdxGetAttributeMinimumI64(m_id, ATTR_EX_VALUE); + long maxv = NIVision.IMAQdxGetAttributeMaximumI64(m_id, ATTR_EX_VALUE); + long val = minv + (long) (((double) (maxv - minv)) * (((double) m_exposureValue) / 100.0)); + NIVision.IMAQdxSetAttributeI64(m_id, ATTR_EX_VALUE, val); + } + } - // Brightness - NIVision.IMAQdxSetAttributeString(m_id, ATTR_BR_MODE, "Manual"); - long minv = NIVision.IMAQdxGetAttributeMinimumI64(m_id, ATTR_BR_VALUE); - long maxv = NIVision.IMAQdxGetAttributeMaximumI64(m_id, ATTR_BR_VALUE); - long val = minv + (long)(((double)(maxv - minv)) * (((double)m_brightness) / 100.0)); - NIVision.IMAQdxSetAttributeI64(m_id, ATTR_BR_VALUE, val); + // Brightness + NIVision.IMAQdxSetAttributeString(m_id, ATTR_BR_MODE, "Manual"); + long minv = NIVision.IMAQdxGetAttributeMinimumI64(m_id, ATTR_BR_VALUE); + long maxv = NIVision.IMAQdxGetAttributeMaximumI64(m_id, ATTR_BR_VALUE); + long val = minv + (long) (((double) (maxv - minv)) * (((double) m_brightness) / 100.0)); + NIVision.IMAQdxSetAttributeI64(m_id, ATTR_BR_VALUE, val); - // Restart acquisition - if (wasActive) - startCapture(); - } + // Restart acquisition + if (wasActive) + startCapture(); + } - public synchronized void setFPS(int fps) { - if (fps != m_fps) { - m_needSettingsUpdate = true; - m_fps = fps; - } - } + public synchronized void setFPS(int fps) { + if (fps != m_fps) { + m_needSettingsUpdate = true; + m_fps = fps; + } + } - public synchronized void setSize(int width, int height) { - if (width != m_width || height != m_height) { - m_needSettingsUpdate = true; - m_width = width; - m_height = height; - } - } + public synchronized void setSize(int width, int height) { + if (width != m_width || height != m_height) { + m_needSettingsUpdate = true; + m_width = width; + m_height = height; + } + } - /** Set the brightness, as a percentage (0-100). */ - public synchronized void setBrightness(int brightness) { - if (brightness > 100) - m_brightness = 100; - else if (brightness < 0) - m_brightness = 0; - else - m_brightness = brightness; - m_needSettingsUpdate = true; - } + /** Set the brightness, as a percentage (0-100). */ + public synchronized void setBrightness(int brightness) { + if (brightness > 100) + m_brightness = 100; + else if (brightness < 0) + m_brightness = 0; + else + m_brightness = brightness; + m_needSettingsUpdate = true; + } - /** Get the brightness, as a percentage (0-100). */ - public synchronized int getBrightness() { - return m_brightness; - } + /** Get the brightness, as a percentage (0-100). */ + public synchronized int getBrightness() { + return m_brightness; + } - /** Set the white balance to auto. */ - public synchronized void setWhiteBalanceAuto() { - m_whiteBalance = "auto"; - m_whiteBalanceValue = -1; - m_needSettingsUpdate = true; - } + /** Set the white balance to auto. */ + public synchronized void setWhiteBalanceAuto() { + m_whiteBalance = "auto"; + m_whiteBalanceValue = -1; + m_needSettingsUpdate = true; + } - /** Set the white balance to hold current. */ - public synchronized void setWhiteBalanceHoldCurrent() { - m_whiteBalance = "manual"; - m_whiteBalanceValue = -1; - m_needSettingsUpdate = true; - } + /** Set the white balance to hold current. */ + public synchronized void setWhiteBalanceHoldCurrent() { + m_whiteBalance = "manual"; + m_whiteBalanceValue = -1; + m_needSettingsUpdate = true; + } - /** Set the white balance to manual, with specified color temperature. */ - public synchronized void setWhiteBalanceManual(int value) { - m_whiteBalance = "manual"; - m_whiteBalanceValue = value; - m_needSettingsUpdate = true; - } + /** Set the white balance to manual, with specified color temperature. */ + public synchronized void setWhiteBalanceManual(int value) { + m_whiteBalance = "manual"; + m_whiteBalanceValue = value; + m_needSettingsUpdate = true; + } - /** Set the exposure to auto aperature. */ - public synchronized void setExposureAuto() { - m_exposure = "auto"; - m_exposureValue = -1; - m_needSettingsUpdate = true; - } + /** Set the exposure to auto aperature. */ + public synchronized void setExposureAuto() { + m_exposure = "auto"; + m_exposureValue = -1; + m_needSettingsUpdate = true; + } - /** Set the exposure to hold current. */ - public synchronized void setExposureHoldCurrent() { - m_exposure = "manual"; - m_exposureValue = -1; - m_needSettingsUpdate = true; - } + /** Set the exposure to hold current. */ + public synchronized void setExposureHoldCurrent() { + m_exposure = "manual"; + m_exposureValue = -1; + m_needSettingsUpdate = true; + } - /** Set the exposure to manual, as a percentage (0-100). */ - public synchronized void setExposureManual(int value) { - m_exposure = "manual"; - if (value > 100) - m_exposureValue = 100; - else if (value < 0) - m_exposureValue = 0; - else - m_exposureValue = value; - m_needSettingsUpdate = true; - } + /** Set the exposure to manual, as a percentage (0-100). */ + public synchronized void setExposureManual(int value) { + m_exposure = "manual"; + if (value > 100) + m_exposureValue = 100; + else if (value < 0) + m_exposureValue = 0; + else + m_exposureValue = value; + m_needSettingsUpdate = true; + } - public synchronized void getImage(Image image) { - if (m_needSettingsUpdate || m_useJpeg) { - m_needSettingsUpdate = false; - m_useJpeg = false; - updateSettings(); - } + public synchronized void getImage(Image image) { + if (m_needSettingsUpdate || m_useJpeg) { + m_needSettingsUpdate = false; + m_useJpeg = false; + updateSettings(); + } - NIVision.IMAQdxGrab(m_id, image, 1); - } + NIVision.IMAQdxGrab(m_id, image, 1); + } - public synchronized void getImageData(ByteBuffer data) { - if (m_needSettingsUpdate || !m_useJpeg) { - m_needSettingsUpdate = false; - m_useJpeg = true; - updateSettings(); - } + public synchronized void getImageData(ByteBuffer data) { + if (m_needSettingsUpdate || !m_useJpeg) { + m_needSettingsUpdate = false; + m_useJpeg = true; + updateSettings(); + } - NIVision.IMAQdxGetImageData(m_id, data, NIVision.IMAQdxBufferNumberMode.BufferNumberModeLast, 0); - data.limit(data.capacity() - 1); - data.limit(getJpegSize(data)); - } + NIVision + .IMAQdxGetImageData(m_id, data, NIVision.IMAQdxBufferNumberMode.BufferNumberModeLast, 0); + data.limit(data.capacity() - 1); + data.limit(getJpegSize(data)); + } - private static int getJpegSize(ByteBuffer data) { - if (data.get(0) != (byte) 0xff || data.get(1) != (byte) 0xd8) - throw new VisionException("invalid image"); - int pos = 2; - while (true) { - try { - byte b = data.get(pos); - if (b != (byte) 0xff) - throw new VisionException("invalid image at pos " + pos + " (" + data.get(pos) + ")"); - b = data.get(pos+1); - if (b == (byte) 0x01 || (b >= (byte) 0xd0 && b <= (byte) 0xd7)) // various - pos += 2; - else if (b == (byte) 0xd9) // EOI - return pos + 2; - else if (b == (byte) 0xd8) // SOI - throw new VisionException("invalid image"); - else if (b == (byte) 0xda) { // SOS - int len = ((data.get(pos+2) & 0xff) << 8) | (data.get(pos+3) & 0xff); - pos += len + 2; - // Find next marker. Skip over escaped and RST markers. - while (data.get(pos) != (byte) 0xff || data.get(pos+1) == (byte) 0x00 || (data.get(pos+1) >= (byte) 0xd0 && data.get(pos+1) <= (byte) 0xd7)) - pos += 1; - } else { // various - int len = ((data.get(pos+2) & 0xff) << 8) | (data.get(pos+3) & 0xff); - pos += len + 2; - } - } catch (IndexOutOfBoundsException ex) { - throw new VisionException("invalid image: could not find jpeg end " + ex.getMessage()); - } - } - } + private static int getJpegSize(ByteBuffer data) { + if (data.get(0) != (byte) 0xff || data.get(1) != (byte) 0xd8) + throw new VisionException("invalid image"); + int pos = 2; + while (true) { + try { + byte b = data.get(pos); + if (b != (byte) 0xff) + throw new VisionException("invalid image at pos " + pos + " (" + data.get(pos) + ")"); + b = data.get(pos + 1); + if (b == (byte) 0x01 || (b >= (byte) 0xd0 && b <= (byte) 0xd7)) // various + pos += 2; + else if (b == (byte) 0xd9) // EOI + return pos + 2; + else if (b == (byte) 0xd8) // SOI + throw new VisionException("invalid image"); + else if (b == (byte) 0xda) { // SOS + int len = ((data.get(pos + 2) & 0xff) << 8) | (data.get(pos + 3) & 0xff); + pos += len + 2; + // Find next marker. Skip over escaped and RST markers. + while (data.get(pos) != (byte) 0xff || data.get(pos + 1) == (byte) 0x00 + || (data.get(pos + 1) >= (byte) 0xd0 && data.get(pos + 1) <= (byte) 0xd7)) + pos += 1; + } else { // various + int len = ((data.get(pos + 2) & 0xff) << 8) | (data.get(pos + 3) & 0xff); + pos += len + 2; + } + } catch (IndexOutOfBoundsException ex) { + throw new VisionException("invalid image: could not find jpeg end " + ex.getMessage()); + } + } + } } diff --git a/wpilibj/wpilibJavaDevices/src/test/java/edu/wpi/first/wpilibj/ExampleTest.java b/wpilibj/wpilibJavaDevices/src/test/java/edu/wpi/first/wpilibj/ExampleTest.java index 42901580c0..e3c1adef59 100644 --- a/wpilibj/wpilibJavaDevices/src/test/java/edu/wpi/first/wpilibj/ExampleTest.java +++ b/wpilibj/wpilibJavaDevices/src/test/java/edu/wpi/first/wpilibj/ExampleTest.java @@ -1,8 +1,8 @@ /*----------------------------------------------------------------------------*/ -/* Copyright (c) FIRST 2008-2012. All Rights Reserved. */ -/* Open Source Software - may be modified and shared by FRC teams. The code */ +/* Copyright (c) FIRST 2008-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 the root directory of */ -/* the project. */ +/* the project. */ /*----------------------------------------------------------------------------*/ package edu.wpi.first.wpilibj; @@ -15,32 +15,32 @@ import org.junit.Test; * mocks that you create should be put in the same package as the class you are * mocking. Unit tests MUST not depend on any specific hardware platform, so any * dependencies must be mocked out. - * + *$ * * Tests are written in with standard JUnit syntax, and are executed with Junit * 4. Tests should be named the same as the unit under test, with "Test" * appended. So a test on the Jaguar class would be called JaguarTest. - * + *$ * @author Fredric Silberberg */ public class ExampleTest { - /** - * Individual tests should be documented, and naming should be - * "name of thing (unit/function) being tested" + "Test". So a test ensuring - * that an input called "motor" is null-checked correctly would be called - * motorNullCheckTest. - */ - @Test - public void additionTest() { - assertEquals(2 + 2, 4); - } + /** + * Individual tests should be documented, and naming should be + * "name of thing (unit/function) being tested" + "Test". So a test ensuring + * that an input called "motor" is null-checked correctly would be called + * motorNullCheckTest. + */ + @Test + public void additionTest() { + assertEquals(2 + 2, 4); + } - /** - * Tests that expect exceptions should use standard junit expected syntax - */ - @Test(expected = Exception.class) - public void exceptionTest() throws Exception { - throw new Exception("This is expected"); - } -} \ No newline at end of file + /** + * Tests that expect exceptions should use standard junit expected syntax + */ + @Test(expected = Exception.class) + public void exceptionTest() throws Exception { + throw new Exception("This is expected"); + } +} diff --git a/wpilibj/wpilibJavaDevices/src/test/java/edu/wpi/first/wpilibj/ResourceTest.java b/wpilibj/wpilibJavaDevices/src/test/java/edu/wpi/first/wpilibj/ResourceTest.java index 6f4815f781..9eb9850645 100644 --- a/wpilibj/wpilibJavaDevices/src/test/java/edu/wpi/first/wpilibj/ResourceTest.java +++ b/wpilibj/wpilibJavaDevices/src/test/java/edu/wpi/first/wpilibj/ResourceTest.java @@ -1,8 +1,8 @@ /*----------------------------------------------------------------------------*/ -/* Copyright (c) FIRST 2008-2014. All Rights Reserved. */ -/* Open Source Software - may be modified and shared by FRC teams. The code */ +/* Copyright (c) FIRST 2008-2014. All Rights Reserved. */ +/* Open Source Software - may be modified and shared by FRC teams. The code */ /* must be accompanied by the FIRST BSD license file in the root directory of */ -/* the project. */ +/* the project. */ /*----------------------------------------------------------------------------*/ package edu.wpi.first.wpilibj; @@ -16,116 +16,127 @@ import edu.wpi.first.wpilibj.util.CheckedAllocationException; /** * Test covers the possible uses of the resource class. + *$ * @author jonathanleitschuh * */ public class ResourceTest { - private Resource testResource; - private static final int RESOURCE_MAX_SIZE = 5; + private Resource testResource; + private static final int RESOURCE_MAX_SIZE = 5; - /** - * @throws java.lang.Exception - */ - @Before - public void setUp() throws Exception { - testResource = new Resource(RESOURCE_MAX_SIZE); - } - - /** - * @throws java.lang.Exception - */ - @After - public void tearDown() throws Exception{ - Resource.restartProgram(); - } + /** + * @throws java.lang.Exception + */ + @Before + public void setUp() throws Exception { + testResource = new Resource(RESOURCE_MAX_SIZE); + } + + /** + * @throws java.lang.Exception + */ + @After + public void tearDown() throws Exception { + Resource.restartProgram(); + } - /** - * Checks that allocating a resource above the range of resources will cause an exception - * @throws CheckedAllocationException - */ - @Test(expected = CheckedAllocationException.class) - public void testAllocateAboveRange() throws CheckedAllocationException { - testResource.allocate(RESOURCE_MAX_SIZE); - } - - /** - * Checks that allocating a negative resource value will cause an exception - * @throws CheckedAllocationException - */ - @Test(expected = CheckedAllocationException.class) - public void testAllocateBelowRange() throws CheckedAllocationException { - testResource.allocate(-1); - } - - /** - * Checks that allocating the same resource twice causes an exception - * @throws CheckedAllocationException - */ - @Test(expected = CheckedAllocationException.class) - public void testAlocateAlreadyAllocatedResource() throws CheckedAllocationException{ - testResource.allocate(0); - testResource.allocate(0); - } - - /** - * Checks that all valid resources can be allocated without exception. - * @throws CheckedAllocationException - */ - @Test - public void testAllocateValidResource() throws CheckedAllocationException{ - for(int i = 0; i < RESOURCE_MAX_SIZE; i++){ - testResource.allocate(i); - } - //Should complete without errors - } - - /** - * Checks that freeing an resource that has been allocated allows it to be allocated again. - * @throws CheckedAllocationException - */ - @Test - public void testAllocateFreedResource() throws CheckedAllocationException{ - for(int i = 0; i < RESOURCE_MAX_SIZE; i++){ - testResource.allocate(i); - } - for(int i = 0; i < RESOURCE_MAX_SIZE; i++){ - testResource.free(i); - } - for(int i = 0; i < RESOURCE_MAX_SIZE; i++){ - testResource.allocate(i); - } - //Should complete without errors - } - - /** - * Checks that asking for the next valid allocated resource will cause it to skip an already allocated resource. - * @throws CheckedAllocationException - */ - @Test - public void testAllocateNextValidResource() throws CheckedAllocationException{ - testResource.allocate(3); - int allocatedValue = testResource.allocate(); - assertEquals(0, allocatedValue); - allocatedValue = testResource.allocate(); - assertEquals(1, allocatedValue); - allocatedValue = testResource.allocate(); - assertEquals(2, allocatedValue); - //Three should be skipped because it is already allocated. - allocatedValue = testResource.allocate(); - assertEquals(4, allocatedValue); - } - - /** - * Attempts to allocate a resource with no remaining resources available. - * @throws CheckedAllocationException - */ - @Test(expected = CheckedAllocationException.class) - public void testAllocateWithNoRemainingResources() throws CheckedAllocationException{ - for(int i = 0; i < RESOURCE_MAX_SIZE; i++){ - testResource.allocate(i); - } - testResource.allocate(); - } + /** + * Checks that allocating a resource above the range of resources will cause + * an exception + *$ + * @throws CheckedAllocationException + */ + @Test(expected = CheckedAllocationException.class) + public void testAllocateAboveRange() throws CheckedAllocationException { + testResource.allocate(RESOURCE_MAX_SIZE); + } + + /** + * Checks that allocating a negative resource value will cause an exception + *$ + * @throws CheckedAllocationException + */ + @Test(expected = CheckedAllocationException.class) + public void testAllocateBelowRange() throws CheckedAllocationException { + testResource.allocate(-1); + } + + /** + * Checks that allocating the same resource twice causes an exception + *$ + * @throws CheckedAllocationException + */ + @Test(expected = CheckedAllocationException.class) + public void testAlocateAlreadyAllocatedResource() throws CheckedAllocationException { + testResource.allocate(0); + testResource.allocate(0); + } + + /** + * Checks that all valid resources can be allocated without exception. + *$ + * @throws CheckedAllocationException + */ + @Test + public void testAllocateValidResource() throws CheckedAllocationException { + for (int i = 0; i < RESOURCE_MAX_SIZE; i++) { + testResource.allocate(i); + } + // Should complete without errors + } + + /** + * Checks that freeing an resource that has been allocated allows it to be + * allocated again. + *$ + * @throws CheckedAllocationException + */ + @Test + public void testAllocateFreedResource() throws CheckedAllocationException { + for (int i = 0; i < RESOURCE_MAX_SIZE; i++) { + testResource.allocate(i); + } + for (int i = 0; i < RESOURCE_MAX_SIZE; i++) { + testResource.free(i); + } + for (int i = 0; i < RESOURCE_MAX_SIZE; i++) { + testResource.allocate(i); + } + // Should complete without errors + } + + /** + * Checks that asking for the next valid allocated resource will cause it to + * skip an already allocated resource. + *$ + * @throws CheckedAllocationException + */ + @Test + public void testAllocateNextValidResource() throws CheckedAllocationException { + testResource.allocate(3); + int allocatedValue = testResource.allocate(); + assertEquals(0, allocatedValue); + allocatedValue = testResource.allocate(); + assertEquals(1, allocatedValue); + allocatedValue = testResource.allocate(); + assertEquals(2, allocatedValue); + // Three should be skipped because it is already allocated. + allocatedValue = testResource.allocate(); + assertEquals(4, allocatedValue); + } + + /** + * Attempts to allocate a resource with no remaining resources available. + *$ + * @throws CheckedAllocationException + */ + @Test(expected = CheckedAllocationException.class) + public void testAllocateWithNoRemainingResources() throws CheckedAllocationException { + for (int i = 0; i < RESOURCE_MAX_SIZE; i++) { + testResource.allocate(i); + } + testResource.allocate(); + } } diff --git a/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/AbstractInterruptTest.java b/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/AbstractInterruptTest.java index 18ea60264f..c8a581d139 100644 --- a/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/AbstractInterruptTest.java +++ b/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/AbstractInterruptTest.java @@ -1,8 +1,8 @@ /*----------------------------------------------------------------------------*/ -/* Copyright (c) FIRST 2008-2014. All Rights Reserved. */ -/* Open Source Software - may be modified and shared by FRC teams. The code */ +/* Copyright (c) FIRST 2008-2014. All Rights Reserved. */ +/* Open Source Software - may be modified and shared by FRC teams. The code */ /* must be accompanied by the FIRST BSD license file in the root directory of */ -/* the project. */ +/* the project. */ /*----------------------------------------------------------------------------*/ package edu.wpi.first.wpilibj; @@ -23,217 +23,233 @@ import org.junit.Test; import edu.wpi.first.wpilibj.test.AbstractComsSetup; /** - * This class should not be run as a test explicitly. Instead it should be extended by tests that use the InterruptableSensorBase + * This class should not be run as a test explicitly. Instead it should be + * extended by tests that use the InterruptableSensorBase * * @author jonathanleitschuh * */ public abstract class AbstractInterruptTest extends AbstractComsSetup { - private InterruptableSensorBase interruptable = null; + private InterruptableSensorBase interruptable = null; - private InterruptableSensorBase getInterruptable(){ - if(interruptable == null){ - interruptable = giveInterruptableSensorBase(); - } - return interruptable; - } + private InterruptableSensorBase getInterruptable() { + if (interruptable == null) { + interruptable = giveInterruptableSensorBase(); + } + return interruptable; + } - @After - public void interruptTeardown(){ - if(interruptable != null){ - freeInterruptableSensorBase(); - interruptable = null; - } - } + @After + public void interruptTeardown() { + if (interruptable != null) { + freeInterruptableSensorBase(); + interruptable = null; + } + } - /** - * Give the interruptible sensor base that interrupts can be attached to. - * @return - */ - abstract InterruptableSensorBase giveInterruptableSensorBase(); - /** - * Cleans up the interruptible sensor base. This is only called if {@link #giveInterruptableSensorBase()} is called. - */ - abstract void freeInterruptableSensorBase(); - /** - * Perform whatever action is required to set the interrupt high. - */ - abstract void setInterruptHigh(); - /** - * Perform whatever action is required to set the interrupt low. - */ - abstract void setInterruptLow(); + /** + * Give the interruptible sensor base that interrupts can be attached to. + *$ + * @return + */ + abstract InterruptableSensorBase giveInterruptableSensorBase(); + + /** + * Cleans up the interruptible sensor base. This is only called if + * {@link #giveInterruptableSensorBase()} is called. + */ + abstract void freeInterruptableSensorBase(); + + /** + * Perform whatever action is required to set the interrupt high. + */ + abstract void setInterruptHigh(); + + /** + * Perform whatever action is required to set the interrupt low. + */ + abstract void setInterruptLow(); - private class InterruptCounter{ - private final AtomicInteger count = new AtomicInteger(); - void increment(){ - count.addAndGet(1); - } + private class InterruptCounter { + private final AtomicInteger count = new AtomicInteger(); - int getCount(){ - return count.get(); - } - }; + void increment() { + count.addAndGet(1); + } - private class TestInterruptHandlerFunction extends InterruptHandlerFunction{ - protected final AtomicBoolean exceptionThrown = new AtomicBoolean(false); - /** Stores the time that the interrupt fires */ - final AtomicLong interruptFireTime = new AtomicLong(); - /** Stores if the interrupt has completed at least once */ - final AtomicBoolean interruptComplete = new AtomicBoolean(false); - protected Exception ex; - final InterruptCounter counter; + int getCount() { + return count.get(); + } + }; - TestInterruptHandlerFunction(InterruptCounter counter){ - this.counter = counter; - } + private class TestInterruptHandlerFunction extends InterruptHandlerFunction { + protected final AtomicBoolean exceptionThrown = new AtomicBoolean(false); + /** Stores the time that the interrupt fires */ + final AtomicLong interruptFireTime = new AtomicLong(); + /** Stores if the interrupt has completed at least once */ + final AtomicBoolean interruptComplete = new AtomicBoolean(false); + protected Exception ex; + final InterruptCounter counter; - @Override - public void interruptFired(int interruptAssertedMask, InterruptCounter param) { - interruptFireTime.set(Utility.getFPGATime()); - counter.increment(); - try{ - //This won't cause the test to fail - assertSame(counter, param); - } catch (Exception ex){ - //So we must throw the exception within the test - exceptionThrown.set(true); - this.ex = ex; - } - interruptComplete.set(true); - }; + TestInterruptHandlerFunction(InterruptCounter counter) { + this.counter = counter; + } - @Override - public InterruptCounter overridableParameter(){ - return counter; - } - }; + @Override + public void interruptFired(int interruptAssertedMask, InterruptCounter param) { + interruptFireTime.set(Utility.getFPGATime()); + counter.increment(); + try { + // This won't cause the test to fail + assertSame(counter, param); + } catch (Exception ex) { + // So we must throw the exception within the test + exceptionThrown.set(true); + this.ex = ex; + } + interruptComplete.set(true); + }; - @Test(timeout = 1000) - public void testSingleInterruptsTriggering() throws Exception{ - //Given - final InterruptCounter counter = new InterruptCounter(); - TestInterruptHandlerFunction function = new TestInterruptHandlerFunction(counter); + @Override + public InterruptCounter overridableParameter() { + return counter; + } + }; - //When - getInterruptable().requestInterrupts(function); - getInterruptable().enableInterrupts(); + @Test(timeout = 1000) + public void testSingleInterruptsTriggering() throws Exception { + // Given + final InterruptCounter counter = new InterruptCounter(); + TestInterruptHandlerFunction function = new TestInterruptHandlerFunction(counter); - setInterruptLow(); - Timer.delay(0.01); - //Note: Utility.getFPGATime() is used because double values can turn over after the robot has been running for a long time - final long interruptTriggerTime = Utility.getFPGATime(); - setInterruptHigh(); + // When + getInterruptable().requestInterrupts(function); + getInterruptable().enableInterrupts(); - //Delay until the interrupt is complete - while(!function.interruptComplete.get()){ - Timer.delay(.005); - } + setInterruptLow(); + Timer.delay(0.01); + // Note: Utility.getFPGATime() is used because double values can turn over + // after the robot has been running for a long time + final long interruptTriggerTime = Utility.getFPGATime(); + setInterruptHigh(); + + // Delay until the interrupt is complete + while (!function.interruptComplete.get()) { + Timer.delay(.005); + } - //Then - assertEquals("The interrupt did not fire the expected number of times", 1, counter.getCount()); - //If the test within the interrupt failed - if(function.exceptionThrown.get()){ - throw function.ex; - } - final long range = 10000; //in microseconds - assertThat("The interrupt did not fire within the expected time period (values in milliseconds)", - function.interruptFireTime.get(), both(greaterThan(interruptTriggerTime - range)) - .and(lessThan(interruptTriggerTime + range))); - assertThat("The readRisingTimestamp() did not return the correct value (values in seconds)", - getInterruptable().readRisingTimestamp(), both(greaterThan((interruptTriggerTime - range)/1e6)) - .and(lessThan((interruptTriggerTime + range)/1e6))); - } + // Then + assertEquals("The interrupt did not fire the expected number of times", 1, counter.getCount()); + // If the test within the interrupt failed + if (function.exceptionThrown.get()) { + throw function.ex; + } + final long range = 10000; // in microseconds + assertThat( + "The interrupt did not fire within the expected time period (values in milliseconds)", + function.interruptFireTime.get(), + both(greaterThan(interruptTriggerTime - range)).and(lessThan(interruptTriggerTime + range))); + assertThat( + "The readRisingTimestamp() did not return the correct value (values in seconds)", + getInterruptable().readRisingTimestamp(), + both(greaterThan((interruptTriggerTime - range) / 1e6)).and( + lessThan((interruptTriggerTime + range) / 1e6))); + } - @Test(timeout = 1000) - public void testMultipleInterruptsTriggering() throws Exception{ - //Given - final InterruptCounter counter = new InterruptCounter(); - TestInterruptHandlerFunction function = new TestInterruptHandlerFunction(counter); + @Test(timeout = 1000) + public void testMultipleInterruptsTriggering() throws Exception { + // Given + final InterruptCounter counter = new InterruptCounter(); + TestInterruptHandlerFunction function = new TestInterruptHandlerFunction(counter); - //When - getInterruptable().requestInterrupts(function); - getInterruptable().enableInterrupts(); + // When + getInterruptable().requestInterrupts(function); + getInterruptable().enableInterrupts(); - final int fireCount = 50; - for(int i = 0; i < fireCount; i ++){ - setInterruptLow(); - setInterruptHigh(); - //Wait for the interrupt to complete before moving on - while(!function.interruptComplete.getAndSet(false)){ - Timer.delay(.005); - } - } - //Then - assertEquals("The interrupt did not fire the expected number of times", fireCount, counter.getCount()); - } + final int fireCount = 50; + for (int i = 0; i < fireCount; i++) { + setInterruptLow(); + setInterruptHigh(); + // Wait for the interrupt to complete before moving on + while (!function.interruptComplete.getAndSet(false)) { + Timer.delay(.005); + } + } + // Then + assertEquals("The interrupt did not fire the expected number of times", fireCount, + counter.getCount()); + } - /** The timeout length for this test in seconds */ - private static final int synchronousTimeout = 5; - @Test(timeout = (long)(synchronousTimeout*1e3)) - public void testSynchronousInterruptsTriggering(){ - //Given - getInterruptable().requestInterrupts(); + /** The timeout length for this test in seconds */ + private static final int synchronousTimeout = 5; - final double synchronousDelay = synchronousTimeout/2.; - Runnable r = new Runnable(){ - @Override - public void run() { - Timer.delay(synchronousDelay); - setInterruptLow(); - setInterruptHigh(); - } - }; + @Test(timeout = (long) (synchronousTimeout * 1e3)) + public void testSynchronousInterruptsTriggering() { + // Given + getInterruptable().requestInterrupts(); - //When + final double synchronousDelay = synchronousTimeout / 2.; + Runnable r = new Runnable() { + @Override + public void run() { + Timer.delay(synchronousDelay); + setInterruptLow(); + setInterruptHigh(); + } + }; - //Note: the long time value is used because doubles can flip if the robot is left running for long enough - final long startTimeStamp = Utility.getFPGATime(); - new Thread(r).start(); - //Delay for twice as long as the timeout so the test should fail first - getInterruptable().waitForInterrupt(synchronousTimeout * 2); - final long stopTimeStamp = Utility.getFPGATime(); + // When - //Then - //The test will not have timed out and: - final double interruptRunTime = (stopTimeStamp - startTimeStamp)*1e-6; - assertEquals("The interrupt did not run for the expected amount of time (units in seconds)", synchronousDelay, interruptRunTime, .1); - } + // Note: the long time value is used because doubles can flip if the robot + // is left running for long enough + final long startTimeStamp = Utility.getFPGATime(); + new Thread(r).start(); + // Delay for twice as long as the timeout so the test should fail first + getInterruptable().waitForInterrupt(synchronousTimeout * 2); + final long stopTimeStamp = Utility.getFPGATime(); + + // Then + // The test will not have timed out and: + final double interruptRunTime = (stopTimeStamp - startTimeStamp) * 1e-6; + assertEquals("The interrupt did not run for the expected amount of time (units in seconds)", + synchronousDelay, interruptRunTime, .1); + } - @Test(timeout = 2000) - public void testDisableStopsInterruptFiring(){ - final InterruptCounter counter = new InterruptCounter(); - TestInterruptHandlerFunction function = new TestInterruptHandlerFunction(counter); + @Test(timeout = 2000) + public void testDisableStopsInterruptFiring() { + final InterruptCounter counter = new InterruptCounter(); + TestInterruptHandlerFunction function = new TestInterruptHandlerFunction(counter); - //When - getInterruptable().requestInterrupts(function); - getInterruptable().enableInterrupts(); + // When + getInterruptable().requestInterrupts(function); + getInterruptable().enableInterrupts(); - final int fireCount = 50; - for(int i = 0; i < fireCount; i ++){ - setInterruptLow(); - setInterruptHigh(); - //Wait for the interrupt to complete before moving on - while(!function.interruptComplete.getAndSet(false)){ - Timer.delay(.005); - } - } - getInterruptable().disableInterrupts(); - //TestBench.out().println("Finished disabling the robot"); + final int fireCount = 50; + for (int i = 0; i < fireCount; i++) { + setInterruptLow(); + setInterruptHigh(); + // Wait for the interrupt to complete before moving on + while (!function.interruptComplete.getAndSet(false)) { + Timer.delay(.005); + } + } + getInterruptable().disableInterrupts(); + // TestBench.out().println("Finished disabling the robot"); - for(int i = 0; i < fireCount; i ++){ - setInterruptLow(); - setInterruptHigh(); - //Just wait because the interrupt should not fire - Timer.delay(.005); - } + for (int i = 0; i < fireCount; i++) { + setInterruptLow(); + setInterruptHigh(); + // Just wait because the interrupt should not fire + Timer.delay(.005); + } - //Then - assertEquals("The interrupt did not fire the expected number of times", fireCount, counter.getCount()); - } + // Then + assertEquals("The interrupt did not fire the expected number of times", fireCount, + counter.getCount()); + } } diff --git a/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/AnalogCrossConnectTest.java b/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/AnalogCrossConnectTest.java index 89c82f05ea..2415bdc9d8 100644 --- a/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/AnalogCrossConnectTest.java +++ b/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/AnalogCrossConnectTest.java @@ -1,8 +1,8 @@ /*----------------------------------------------------------------------------*/ -/* Copyright (c) FIRST 2008-2014. All Rights Reserved. */ -/* Open Source Software - may be modified and shared by FRC teams. The code */ +/* Copyright (c) FIRST 2008-2014. All Rights Reserved. */ +/* Open Source Software - may be modified and shared by FRC teams. The code */ /* must be accompanied by the FIRST BSD license file in the root directory of */ -/* the project. */ +/* the project. */ /*----------------------------------------------------------------------------*/ package edu.wpi.first.wpilibj; @@ -27,175 +27,184 @@ import edu.wpi.first.wpilibj.test.TestBench; * */ public class AnalogCrossConnectTest extends AbstractInterruptTest { - private static final Logger logger = Logger.getLogger(AnalogCrossConnectTest.class.getName()); + private static final Logger logger = Logger.getLogger(AnalogCrossConnectTest.class.getName()); - private static AnalogCrossConnectFixture analogIO; + private static AnalogCrossConnectFixture analogIO; - static final double kDelayTime = 0.01; + static final double kDelayTime = 0.01; - @Override - protected Logger getClassLogger() { - return logger; - } + @Override + protected Logger getClassLogger() { + return logger; + } - /** - * @throws java.lang.Exception - */ - @BeforeClass - public static void setUpBeforeClass() throws Exception { - analogIO = TestBench.getAnalogCrossConnectFixture(); - } + /** + * @throws java.lang.Exception + */ + @BeforeClass + public static void setUpBeforeClass() throws Exception { + analogIO = TestBench.getAnalogCrossConnectFixture(); + } - /** - * @throws java.lang.Exception - */ - @AfterClass - public static void tearDownAfterClass() throws Exception { - analogIO.teardown(); - analogIO=null; - } + /** + * @throws java.lang.Exception + */ + @AfterClass + public static void tearDownAfterClass() throws Exception { + analogIO.teardown(); + analogIO = null; + } - /** - * @throws java.lang.Exception - */ - @Before - public void setUp() throws Exception { - analogIO.setup(); - } + /** + * @throws java.lang.Exception + */ + @Before + public void setUp() throws Exception { + analogIO.setup(); + } - /** - * @throws java.lang.Exception - */ - @After - public void tearDown() throws Exception { - } + /** + * @throws java.lang.Exception + */ + @After + public void tearDown() throws Exception {} - @Test - public void testAnalogOuput() { - for(int i = 0; i < 50; i++) { - analogIO.getOutput().setVoltage(i / 10.0f); - Timer.delay(kDelayTime); - assertEquals(analogIO.getOutput().getVoltage(), analogIO.getInput().getVoltage(), 0.01); - } - } + @Test + public void testAnalogOuput() { + for (int i = 0; i < 50; i++) { + analogIO.getOutput().setVoltage(i / 10.0f); + Timer.delay(kDelayTime); + assertEquals(analogIO.getOutput().getVoltage(), analogIO.getInput().getVoltage(), 0.01); + } + } - @Test - public void testAnalogTriggerBelowWindow() { - // Given - AnalogTrigger trigger = new AnalogTrigger(analogIO.getInput()); - trigger.setLimitsVoltage(2.0f, 3.0f); + @Test + public void testAnalogTriggerBelowWindow() { + // Given + AnalogTrigger trigger = new AnalogTrigger(analogIO.getInput()); + trigger.setLimitsVoltage(2.0f, 3.0f); - // When the output voltage is than less the lower limit - analogIO.getOutput().setVoltage(1.0f); - Timer.delay(kDelayTime); + // When the output voltage is than less the lower limit + analogIO.getOutput().setVoltage(1.0f); + Timer.delay(kDelayTime); - // Then the analog trigger is not in the window and the trigger state is off - assertFalse("Analog trigger is in the window (2V, 3V)", trigger.getInWindow()); - assertFalse("Analog trigger is on", trigger.getTriggerState()); + // Then the analog trigger is not in the window and the trigger state is off + assertFalse("Analog trigger is in the window (2V, 3V)", trigger.getInWindow()); + assertFalse("Analog trigger is on", trigger.getTriggerState()); - trigger.free(); - } + trigger.free(); + } - @Test - public void testAnalogTriggerInWindow() { - // Given - AnalogTrigger trigger = new AnalogTrigger(analogIO.getInput()); - trigger.setLimitsVoltage(2.0f, 3.0f); + @Test + public void testAnalogTriggerInWindow() { + // Given + AnalogTrigger trigger = new AnalogTrigger(analogIO.getInput()); + trigger.setLimitsVoltage(2.0f, 3.0f); - // When the output voltage is within the lower and upper limits - analogIO.getOutput().setVoltage(2.5f); - Timer.delay(kDelayTime); + // When the output voltage is within the lower and upper limits + analogIO.getOutput().setVoltage(2.5f); + Timer.delay(kDelayTime); - // Then the analog trigger is in the window and the trigger state is off - assertTrue("Analog trigger is not in the window (2V, 3V)", trigger.getInWindow()); - assertFalse("Analog trigger is on", trigger.getTriggerState()); + // Then the analog trigger is in the window and the trigger state is off + assertTrue("Analog trigger is not in the window (2V, 3V)", trigger.getInWindow()); + assertFalse("Analog trigger is on", trigger.getTriggerState()); - trigger.free(); - } + trigger.free(); + } - @Test - public void testAnalogTriggerAboveWindow() { - // Given - AnalogTrigger trigger = new AnalogTrigger(analogIO.getInput()); - trigger.setLimitsVoltage(2.0f, 3.0f); + @Test + public void testAnalogTriggerAboveWindow() { + // Given + AnalogTrigger trigger = new AnalogTrigger(analogIO.getInput()); + trigger.setLimitsVoltage(2.0f, 3.0f); - // When the output voltage is greater than the upper limit - analogIO.getOutput().setVoltage(4.0f); - Timer.delay(kDelayTime); + // When the output voltage is greater than the upper limit + analogIO.getOutput().setVoltage(4.0f); + Timer.delay(kDelayTime); - // Then the analog trigger is not in the window and the trigger state is on - assertFalse("Analog trigger is in the window (2V, 3V)", trigger.getInWindow()); - assertTrue("Analog trigger is not on", trigger.getTriggerState()); + // Then the analog trigger is not in the window and the trigger state is on + assertFalse("Analog trigger is in the window (2V, 3V)", trigger.getInWindow()); + assertTrue("Analog trigger is not on", trigger.getTriggerState()); - trigger.free(); - } + trigger.free(); + } - @Test - public void testAnalogTriggerCounter() { - // Given - AnalogTrigger trigger = new AnalogTrigger(analogIO.getInput()); - trigger.setLimitsVoltage(2.0f, 3.0f); - Counter counter = new Counter(trigger); + @Test + public void testAnalogTriggerCounter() { + // Given + AnalogTrigger trigger = new AnalogTrigger(analogIO.getInput()); + trigger.setLimitsVoltage(2.0f, 3.0f); + Counter counter = new Counter(trigger); - // When the analog output is turned low and high 50 times - for(int i = 0; i < 50; i++) { - analogIO.getOutput().setVoltage(1.0); - Timer.delay(kDelayTime); - analogIO.getOutput().setVoltage(4.0); - Timer.delay(kDelayTime); - } + // When the analog output is turned low and high 50 times + for (int i = 0; i < 50; i++) { + analogIO.getOutput().setVoltage(1.0); + Timer.delay(kDelayTime); + analogIO.getOutput().setVoltage(4.0); + Timer.delay(kDelayTime); + } - // Then the counter should be at 50 - assertEquals("Analog trigger counter did not count 50 ticks", 50, counter.get()); - } + // Then the counter should be at 50 + assertEquals("Analog trigger counter did not count 50 ticks", 50, counter.get()); + } - @Test(expected=RuntimeException.class) - public void testRuntimeExceptionOnInvalidAccumulatorPort(){ - analogIO.getInput().getAccumulatorCount(); - } + @Test(expected = RuntimeException.class) + public void testRuntimeExceptionOnInvalidAccumulatorPort() { + analogIO.getInput().getAccumulatorCount(); + } - private AnalogTrigger interruptTrigger; - private AnalogTriggerOutput interruptTriggerOutput; - - /* (non-Javadoc) - * @see edu.wpi.first.wpilibj.AbstractInterruptTest#giveInterruptableSensorBase() - */ - @Override - InterruptableSensorBase giveInterruptableSensorBase() { - interruptTrigger = new AnalogTrigger(analogIO.getInput()); - interruptTrigger.setLimitsVoltage(2.0f, 3.0f); - interruptTriggerOutput = new AnalogTriggerOutput(interruptTrigger, AnalogTriggerType.kState); - return interruptTriggerOutput; - } + private AnalogTrigger interruptTrigger; + private AnalogTriggerOutput interruptTriggerOutput; + + /* + * (non-Javadoc) + *$ + * @see + * edu.wpi.first.wpilibj.AbstractInterruptTest#giveInterruptableSensorBase() + */ + @Override + InterruptableSensorBase giveInterruptableSensorBase() { + interruptTrigger = new AnalogTrigger(analogIO.getInput()); + interruptTrigger.setLimitsVoltage(2.0f, 3.0f); + interruptTriggerOutput = new AnalogTriggerOutput(interruptTrigger, AnalogTriggerType.kState); + return interruptTriggerOutput; + } - /* (non-Javadoc) - * @see edu.wpi.first.wpilibj.AbstractInterruptTest#freeInterruptableSensorBase() - */ - @Override - void freeInterruptableSensorBase() { - interruptTriggerOutput.cancelInterrupts(); - interruptTriggerOutput.free(); - interruptTriggerOutput = null; - interruptTrigger.free(); - interruptTrigger = null; - } + /* + * (non-Javadoc) + *$ + * @see + * edu.wpi.first.wpilibj.AbstractInterruptTest#freeInterruptableSensorBase() + */ + @Override + void freeInterruptableSensorBase() { + interruptTriggerOutput.cancelInterrupts(); + interruptTriggerOutput.free(); + interruptTriggerOutput = null; + interruptTrigger.free(); + interruptTrigger = null; + } - /* (non-Javadoc) - * @see edu.wpi.first.wpilibj.AbstractInterruptTest#setInterruptHigh() - */ - @Override - void setInterruptHigh() { - analogIO.getOutput().setVoltage(4.0); - } + /* + * (non-Javadoc) + *$ + * @see edu.wpi.first.wpilibj.AbstractInterruptTest#setInterruptHigh() + */ + @Override + void setInterruptHigh() { + analogIO.getOutput().setVoltage(4.0); + } - /* (non-Javadoc) - * @see edu.wpi.first.wpilibj.AbstractInterruptTest#setInterruptLow() - */ - @Override - void setInterruptLow() { - analogIO.getOutput().setVoltage(1.0); - } + /* + * (non-Javadoc) + *$ + * @see edu.wpi.first.wpilibj.AbstractInterruptTest#setInterruptLow() + */ + @Override + void setInterruptLow() { + analogIO.getOutput().setVoltage(1.0); + } } diff --git a/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/AnalogPotentiometerTest.java b/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/AnalogPotentiometerTest.java index 4130b69f1c..5c57512d1a 100644 --- a/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/AnalogPotentiometerTest.java +++ b/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/AnalogPotentiometerTest.java @@ -1,8 +1,8 @@ /*----------------------------------------------------------------------------*/ -/* Copyright (c) FIRST 2008-2014. All Rights Reserved. */ -/* Open Source Software - may be modified and shared by FRC teams. The code */ +/* Copyright (c) FIRST 2008-2014. All Rights Reserved. */ +/* Open Source Software - may be modified and shared by FRC teams. The code */ /* must be accompanied by the FIRST BSD license file in the root directory of */ -/* the project. */ +/* the project. */ /*----------------------------------------------------------------------------*/ package edu.wpi.first.wpilibj; @@ -24,53 +24,53 @@ import edu.wpi.first.wpilibj.test.TestBench; * */ public class AnalogPotentiometerTest extends AbstractComsSetup { - private static final Logger logger = Logger.getLogger(AnalogPotentiometerTest.class.getName()); - private AnalogCrossConnectFixture analogIO; - private FakePotentiometerSource potSource; - private AnalogPotentiometer pot; - - private static final double DOUBLE_COMPARISON_DELTA = 2.0; + private static final Logger logger = Logger.getLogger(AnalogPotentiometerTest.class.getName()); + private AnalogCrossConnectFixture analogIO; + private FakePotentiometerSource potSource; + private AnalogPotentiometer pot; - /** - * @throws java.lang.Exception - */ - @Before - public void setUp() throws Exception { - analogIO = TestBench.getAnalogCrossConnectFixture(); - potSource = new FakePotentiometerSource(analogIO.getOutput(), 360); - pot = new AnalogPotentiometer(analogIO.getInput(), 360.0, 0); - - } + private static final double DOUBLE_COMPARISON_DELTA = 2.0; - /** - * @throws java.lang.Exception - */ - @After - public void tearDown() throws Exception { - potSource.reset(); - pot.free(); - analogIO.teardown(); - } - - @Override - protected Logger getClassLogger() { - return logger; - } - - @Test - public void testInitialSettings(){ - assertEquals(0, pot.get(), DOUBLE_COMPARISON_DELTA); - } - - @Test - public void testRangeValues(){ - for(double i = 0.0; i < 360.0; i = i+1.0){ - potSource.setAngle(i); - potSource.setMaxVoltage(ControllerPower.getVoltage5V()); - Timer.delay(.02); - assertEquals(i, pot.get(), DOUBLE_COMPARISON_DELTA); - } - } + /** + * @throws java.lang.Exception + */ + @Before + public void setUp() throws Exception { + analogIO = TestBench.getAnalogCrossConnectFixture(); + potSource = new FakePotentiometerSource(analogIO.getOutput(), 360); + pot = new AnalogPotentiometer(analogIO.getInput(), 360.0, 0); + + } + + /** + * @throws java.lang.Exception + */ + @After + public void tearDown() throws Exception { + potSource.reset(); + pot.free(); + analogIO.teardown(); + } + + @Override + protected Logger getClassLogger() { + return logger; + } + + @Test + public void testInitialSettings() { + assertEquals(0, pot.get(), DOUBLE_COMPARISON_DELTA); + } + + @Test + public void testRangeValues() { + for (double i = 0.0; i < 360.0; i = i + 1.0) { + potSource.setAngle(i); + potSource.setMaxVoltage(ControllerPower.getVoltage5V()); + Timer.delay(.02); + assertEquals(i, pot.get(), DOUBLE_COMPARISON_DELTA); + } + } } diff --git a/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/BuiltInAccelerometerTest.java b/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/BuiltInAccelerometerTest.java index 4f23b25ff4..a222a78cb8 100644 --- a/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/BuiltInAccelerometerTest.java +++ b/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/BuiltInAccelerometerTest.java @@ -1,8 +1,8 @@ /*----------------------------------------------------------------------------*/ -/* Copyright (c) FIRST 2014. All Rights Reserved. */ -/* Open Source Software - may be modified and shared by FRC teams. The code */ +/* Copyright (c) FIRST 2014. All Rights Reserved. */ +/* Open Source Software - may be modified and shared by FRC teams. The code */ /* must be accompanied by the FIRST BSD license file in the root directory of */ -/* the project. */ +/* the project. */ /*----------------------------------------------------------------------------*/ package edu.wpi.first.wpilibj; @@ -23,49 +23,46 @@ import edu.wpi.first.wpilibj.test.AbstractComsSetup; @RunWith(Parameterized.class) public class BuiltInAccelerometerTest extends AbstractComsSetup { - private static final Logger logger = Logger.getLogger(BuiltInAccelerometerTest.class.getName()); - private static final double kAccelerationTolerance = 0.1; - private final BuiltInAccelerometer m_accelerometer; + private static final Logger logger = Logger.getLogger(BuiltInAccelerometerTest.class.getName()); + private static final double kAccelerationTolerance = 0.1; + private final BuiltInAccelerometer m_accelerometer; - public BuiltInAccelerometerTest(Accelerometer.Range range) { - m_accelerometer = new BuiltInAccelerometer(range); - } + public BuiltInAccelerometerTest(Accelerometer.Range range) { + m_accelerometer = new BuiltInAccelerometer(range); + } - @BeforeClass - public static void waitASecond() { - /* The testbench sometimes shakes a little from a previous test. Give - it some time. */ - Timer.delay(1.0); - } + @BeforeClass + public static void waitASecond() { + /* + * The testbench sometimes shakes a little from a previous test. Give it + * some time. + */ + Timer.delay(1.0); + } - /** - * Test with all valid ranges to make sure unpacking is always done - * correctly. - */ - @Parameters - public static Collection generateData() { - return Arrays.asList(new Accelerometer.Range[][] { - { Accelerometer.Range.k2G }, - { Accelerometer.Range.k4G }, - { Accelerometer.Range.k8G }, - }); - } + /** + * Test with all valid ranges to make sure unpacking is always done correctly. + */ + @Parameters + public static Collection generateData() { + return Arrays.asList(new Accelerometer.Range[][] { {Accelerometer.Range.k2G}, + {Accelerometer.Range.k4G}, {Accelerometer.Range.k8G},}); + } - @Override - protected Logger getClassLogger(){ - return logger; - } + @Override + protected Logger getClassLogger() { + return logger; + } - /** - * There's not much we can automatically test with the on-board - * accelerometer, but checking for gravity is probably good enough to tell - * that it's working. - */ - @Test - public void testAccelerometer() { - assertEquals(0.0, m_accelerometer.getX(), kAccelerationTolerance); - assertEquals(1.0, m_accelerometer.getY(), kAccelerationTolerance); - assertEquals(0.0, m_accelerometer.getZ(), kAccelerationTolerance); - } + /** + * There's not much we can automatically test with the on-board accelerometer, + * but checking for gravity is probably good enough to tell that it's working. + */ + @Test + public void testAccelerometer() { + assertEquals(0.0, m_accelerometer.getX(), kAccelerationTolerance); + assertEquals(1.0, m_accelerometer.getY(), kAccelerationTolerance); + assertEquals(0.0, m_accelerometer.getZ(), kAccelerationTolerance); + } } diff --git a/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/CANTalonTest.java b/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/CANTalonTest.java index 506fdb708d..bc14f4bbc7 100644 --- a/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/CANTalonTest.java +++ b/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/CANTalonTest.java @@ -1,8 +1,8 @@ /*----------------------------------------------------------------------------*/ -/* Copyright (c) FIRST 2008-2014. All Rights Reserved. */ -/* Open Source Software - may be modified and shared by FRC teams. The code */ +/* Copyright (c) FIRST 2008-2014. All Rights Reserved. */ +/* Open Source Software - may be modified and shared by FRC teams. The code */ /* must be accompanied by the FIRST BSD license file in the root directory of */ -/* the project. */ +/* the project. */ /*----------------------------------------------------------------------------*/ package edu.wpi.first.wpilibj; @@ -26,31 +26,31 @@ import edu.wpi.first.wpilibj.hal.SWIGTYPE_p_double; * Basic test (borrowed straight from SampleTest) for running the CAN TalonSRX. */ public class CANTalonTest extends AbstractComsSetup { - private static final Logger logger = Logger.getLogger(SampleTest.class.getName()); + private static final Logger logger = Logger.getLogger(SampleTest.class.getName()); - static SampleFixture fixture = new SampleFixture(); + static SampleFixture fixture = new SampleFixture(); - protected Logger getClassLogger(){ - return logger; - } + protected Logger getClassLogger() { + return logger; + } - @BeforeClass - public static void classSetup() { - // Set up the fixture before the test is created - fixture.setup(); - } + @BeforeClass + public static void classSetup() { + // Set up the fixture before the test is created + fixture.setup(); + } - @Before - public void setUp() { - // Reset the fixture elements before every test - fixture.reset(); - } + @Before + public void setUp() { + // Reset the fixture elements before every test + fixture.reset(); + } - @AfterClass - public static void tearDown() { - // Clean up the fixture after the test - fixture.teardown(); - } + @AfterClass + public static void tearDown() { + // Clean up the fixture after the test + fixture.teardown(); + } private String errorMessage(double actual, double expected) { String start = "Actual value was: "; @@ -60,11 +60,11 @@ public class CANTalonTest extends AbstractComsSetup { return start; } - /** + /** * Briefly run a CAN Talon and assert true. - */ - @Test - public void throttle() { + */ + @Test + public void throttle() { double throttle = 0.1; CANTalon tal = new CANTalon(0); tal.set(throttle); @@ -82,22 +82,23 @@ public class CANTalonTest extends AbstractComsSetup { tal.disable(); Timer.delay(0.2); assertTrue(errorMessage(tal.get(), 0.0), Math.abs(tal.get()) < 1e-10); - } + } @Test public void SetGetPID() { CANTalon talon = new CANTalon(0); talon.changeControlMode(CANTalon.TalonControlMode.Position); double p = 0.05, i = 0.098, d = 1.23; - talon.setPID(p, i , d); + talon.setPID(p, i, d); assertTrue(errorMessage(talon.getP(), p), Math.abs(p - talon.getP()) < 1e-5); assertTrue(errorMessage(talon.getI(), i), Math.abs(i - talon.getI()) < 1e-5); assertTrue(errorMessage(talon.getD(), d), Math.abs(d - talon.getD()) < 1e-5); - // Test with new values in case the talon was already set to the previous ones. + // Test with new values in case the talon was already set to the previous + // ones. p = 0.15; i = 0.198; d = 1.03; - talon.setPID(p, i , d); + talon.setPID(p, i, d); assertTrue(errorMessage(talon.getP(), p), Math.abs(p - talon.getP()) < 1e-5); assertTrue(errorMessage(talon.getI(), i), Math.abs(i - talon.getI()) < 1e-5); assertTrue(errorMessage(talon.getD(), d), Math.abs(d - talon.getD()) < 1e-5); @@ -110,12 +111,13 @@ public class CANTalonTest extends AbstractComsSetup { talon.setFeedbackDevice(CANTalon.FeedbackDevice.AnalogPot); Timer.delay(0.2); double p = 1.0, i = 0.0, d = 0.00; - talon.setPID(p, i , d); + talon.setPID(p, i, d); talon.set(100); Timer.delay(5.0); talon.reverseOutput(true); Timer.delay(5.0); - //assertTrue(errorMessage(talon.get(), 100), Math.abs(100 - talon.get()) < 10); + // assertTrue(errorMessage(talon.get(), 100), Math.abs(100 - talon.get()) < + // 10); assertTrue(true); } diff --git a/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/CounterTest.java b/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/CounterTest.java index 4005a9e4d1..3049686571 100644 --- a/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/CounterTest.java +++ b/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/CounterTest.java @@ -1,8 +1,8 @@ /*----------------------------------------------------------------------------*/ -/* Copyright (c) FIRST 2008-2014. All Rights Reserved. */ -/* Open Source Software - may be modified and shared by FRC teams. The code */ +/* Copyright (c) FIRST 2008-2014. All Rights Reserved. */ +/* Open Source Software - may be modified and shared by FRC teams. The code */ /* must be accompanied by the FIRST BSD license file in the root directory of */ -/* the project. */ +/* the project. */ /*----------------------------------------------------------------------------*/ package edu.wpi.first.wpilibj; @@ -25,99 +25,101 @@ import edu.wpi.first.wpilibj.test.TestBench; /** * Tests to see if the Counter is working properly - * + *$ * @author Jonathan Leitschuh * */ @RunWith(Parameterized.class) public class CounterTest extends AbstractComsSetup { - private static FakeCounterFixture counter = null; - private static final Logger logger = Logger.getLogger(CounterTest.class.getName()); - - Integer input; - Integer output; - - @Override - protected Logger getClassLogger(){ - return logger; - } - - /** - * Constructs a Counter Test with the given inputs - * @param input The input Port - * @param output The output Port - */ - public CounterTest(Integer input, Integer output){ - assert input != null; - assert output != null; - - this.input = input; - this.output = output; - //System.out.println("Counter Test: Input: " + input + " Output: " + output); - if(counter != null) counter.teardown(); - counter = new FakeCounterFixture(input, output); - } - - /** - * Test data generator. This method is called the the JUnit - * parameterized test runner and returns a Collection of Arrays. For each - * Array in the Collection, each array element corresponds to a parameter - * in the constructor. - */ - @Parameters - public static Collection generateData() { - // In this example, the parameter generator returns a List of - // arrays. Each array has two elements: { Digital input port, Digital output port}. - // These data are hard-coded into the class, but they could be - // generated or loaded in any way you like. - return TestBench.getInstance().getDIOCrossConnectCollection(); - } - - + private static FakeCounterFixture counter = null; + private static final Logger logger = Logger.getLogger(CounterTest.class.getName()); - /** - * @throws java.lang.Exception - */ - @BeforeClass - public static void setUpBeforeClass() throws Exception { - } + Integer input; + Integer output; - /** - * @throws java.lang.Exception - */ - @AfterClass - public static void tearDownAfterClass() throws Exception { - counter.teardown(); - counter=null; - } + @Override + protected Logger getClassLogger() { + return logger; + } - /** - * @throws java.lang.Exception - */ - @Before - public void setUp() throws Exception { - counter.setup(); - } - - /** - * Tests the default state of the counter immediately after reset - */ - @Test - public void testDefault(){ - assertTrue("Counter did not reset to 0", counter.getCounter().get() == 0); - } + /** + * Constructs a Counter Test with the given inputs + *$ + * @param input The input Port + * @param output The output Port + */ + public CounterTest(Integer input, Integer output) { + assert input != null; + assert output != null; - @Test (timeout = 5000) - public void testCount() { - int goal = 100; - counter.getFakeCounterSource().setCount(goal); - counter.getFakeCounterSource().execute(); - - int count = counter.getCounter().get(); - - assertTrue("Fake Counter, Input: " + input + ", Output: " + output + - ", did not return " + goal + " instead got: " + count, - count == goal); - } + this.input = input; + this.output = output; + // System.out.println("Counter Test: Input: " + input + " Output: " + + // output); + if (counter != null) + counter.teardown(); + counter = new FakeCounterFixture(input, output); + } + + /** + * Test data generator. This method is called the the JUnit parameterized test + * runner and returns a Collection of Arrays. For each Array in the + * Collection, each array element corresponds to a parameter in the + * constructor. + */ + @Parameters + public static Collection generateData() { + // In this example, the parameter generator returns a List of + // arrays. Each array has two elements: { Digital input port, Digital output + // port}. + // These data are hard-coded into the class, but they could be + // generated or loaded in any way you like. + return TestBench.getInstance().getDIOCrossConnectCollection(); + } + + + + /** + * @throws java.lang.Exception + */ + @BeforeClass + public static void setUpBeforeClass() throws Exception {} + + /** + * @throws java.lang.Exception + */ + @AfterClass + public static void tearDownAfterClass() throws Exception { + counter.teardown(); + counter = null; + } + + /** + * @throws java.lang.Exception + */ + @Before + public void setUp() throws Exception { + counter.setup(); + } + + /** + * Tests the default state of the counter immediately after reset + */ + @Test + public void testDefault() { + assertTrue("Counter did not reset to 0", counter.getCounter().get() == 0); + } + + @Test(timeout = 5000) + public void testCount() { + int goal = 100; + counter.getFakeCounterSource().setCount(goal); + counter.getFakeCounterSource().execute(); + + int count = counter.getCounter().get(); + + assertTrue("Fake Counter, Input: " + input + ", Output: " + output + ", did not return " + goal + + " instead got: " + count, count == goal); + } } diff --git a/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/DIOCrossConnectTest.java b/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/DIOCrossConnectTest.java index 7db61ca3fe..83da79d5c0 100644 --- a/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/DIOCrossConnectTest.java +++ b/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/DIOCrossConnectTest.java @@ -1,8 +1,8 @@ /*----------------------------------------------------------------------------*/ -/* Copyright (c) FIRST 2008-2014. All Rights Reserved. */ -/* Open Source Software - may be modified and shared by FRC teams. The code */ +/* Copyright (c) FIRST 2008-2014. All Rights Reserved. */ +/* Open Source Software - may be modified and shared by FRC teams. The code */ /* must be accompanied by the FIRST BSD license file in the root directory of */ -/* the project. */ +/* the project. */ /*----------------------------------------------------------------------------*/ package edu.wpi.first.wpilibj; @@ -24,117 +24,130 @@ import edu.wpi.first.wpilibj.test.TestBench; /** * Tests to see if the Digital ports are working properly + *$ * @author jonathanleitschuh */ @RunWith(Parameterized.class) public class DIOCrossConnectTest extends AbstractInterruptTest { - private static final Logger logger = Logger.getLogger(DIOCrossConnectTest.class.getName()); + private static final Logger logger = Logger.getLogger(DIOCrossConnectTest.class.getName()); - private static DIOCrossConnectFixture dio = null; - - @Override - protected Logger getClassLogger(){ - return logger; - } + private static DIOCrossConnectFixture dio = null; - /** - * Default constructor for the DIOCrossConnectTest - * This test is parameterized in order to allow it to be tested using a variety of different input/output pairs - * without duplicate code.
- * This class takes Integer port values instead of DigitalClasses because it would force them to be instantiated - * at the same time which could (untested) cause port binding errors. - * - * @param input The port for the input wire - * @param output The port for the output wire - */ - public DIOCrossConnectTest(Integer input, Integer output) { - if(dio != null){ - dio.teardown(); - } - dio = new DIOCrossConnectFixture(input, output); - } - - + @Override + protected Logger getClassLogger() { + return logger; + } - /** - * Test data generator. This method is called the the JUnit - * parameterized test runner and returns a Collection of Arrays. For each - * Array in the Collection, each array element corresponds to a parameter - * in the constructor. - */ - @Parameters(name= "{index}: Input Port: {0} Output Port: {1}") - public static Collection generateData() { - // In this example, the parameter generator returns a List of - // arrays. Each array has two elements: { Digital input port, Digital output port}. - // These data are hard-coded into the class, but they could be - // generated or loaded in any way you like. - return TestBench.getInstance().getDIOCrossConnectCollection(); - } + /** + * Default constructor for the DIOCrossConnectTest This test is parameterized + * in order to allow it to be tested using a variety of different input/output + * pairs without duplicate code.
+ * This class takes Integer port values instead of DigitalClasses because it + * would force them to be instantiated at the same time which could (untested) + * cause port binding errors. + *$ + * @param input The port for the input wire + * @param output The port for the output wire + */ + public DIOCrossConnectTest(Integer input, Integer output) { + if (dio != null) { + dio.teardown(); + } + dio = new DIOCrossConnectFixture(input, output); + } - @AfterClass - public static void tearDownAfterClass() throws Exception { - dio.teardown(); - dio=null; - } - @After - public void tearDown() throws Exception { - dio.reset(); - } - /** - * Tests to see if the DIO can create and recognize a high value - */ - @Test - public void testSetHigh() { - dio.getOutput().set(true); - assertTrue("DIO Not High after no delay", dio.getInput().get()); - Timer.delay(.02); - assertTrue("DIO Not High after .05s delay", dio.getInput().get()); - } - - /** - * Tests to see if the DIO can create and recognize a low value - */ - @Test - public void testSetLow() { - dio.getOutput().set(false); - assertFalse("DIO Not Low after no delay", dio.getInput().get()); - Timer.delay(.02); - assertFalse("DIO Not Low after .05s delay", dio.getInput().get()); - } + /** + * Test data generator. This method is called the the JUnit parameterized test + * runner and returns a Collection of Arrays. For each Array in the + * Collection, each array element corresponds to a parameter in the + * constructor. + */ + @Parameters(name = "{index}: Input Port: {0} Output Port: {1}") + public static Collection generateData() { + // In this example, the parameter generator returns a List of + // arrays. Each array has two elements: { Digital input port, Digital output + // port}. + // These data are hard-coded into the class, but they could be + // generated or loaded in any way you like. + return TestBench.getInstance().getDIOCrossConnectCollection(); + } - /* (non-Javadoc) - * @see edu.wpi.first.wpilibj.AbstractInterruptTest#giveInterruptableSensorBase() - */ - @Override - InterruptableSensorBase giveInterruptableSensorBase() { - return dio.getInput(); - } + @AfterClass + public static void tearDownAfterClass() throws Exception { + dio.teardown(); + dio = null; + } - /* (non-Javadoc) - * @see edu.wpi.first.wpilibj.AbstractInterruptTest#freeInterruptableSensorBase() - */ - @Override - void freeInterruptableSensorBase() { - // Handled in the fixture - } + @After + public void tearDown() throws Exception { + dio.reset(); + } - /* (non-Javadoc) - * @see edu.wpi.first.wpilibj.AbstractInterruptTest#setInterruptHigh() - */ - @Override - void setInterruptHigh() { - dio.getOutput().set(true); - } + /** + * Tests to see if the DIO can create and recognize a high value + */ + @Test + public void testSetHigh() { + dio.getOutput().set(true); + assertTrue("DIO Not High after no delay", dio.getInput().get()); + Timer.delay(.02); + assertTrue("DIO Not High after .05s delay", dio.getInput().get()); + } + + /** + * Tests to see if the DIO can create and recognize a low value + */ + @Test + public void testSetLow() { + dio.getOutput().set(false); + assertFalse("DIO Not Low after no delay", dio.getInput().get()); + Timer.delay(.02); + assertFalse("DIO Not Low after .05s delay", dio.getInput().get()); + } + + /* + * (non-Javadoc) + *$ + * @see + * edu.wpi.first.wpilibj.AbstractInterruptTest#giveInterruptableSensorBase() + */ + @Override + InterruptableSensorBase giveInterruptableSensorBase() { + return dio.getInput(); + } + + /* + * (non-Javadoc) + *$ + * @see + * edu.wpi.first.wpilibj.AbstractInterruptTest#freeInterruptableSensorBase() + */ + @Override + void freeInterruptableSensorBase() { + // Handled in the fixture + } + + /* + * (non-Javadoc) + *$ + * @see edu.wpi.first.wpilibj.AbstractInterruptTest#setInterruptHigh() + */ + @Override + void setInterruptHigh() { + dio.getOutput().set(true); + } + + /* + * (non-Javadoc) + *$ + * @see edu.wpi.first.wpilibj.AbstractInterruptTest#setInterruptLow() + */ + @Override + void setInterruptLow() { + dio.getOutput().set(false); + + } - /* (non-Javadoc) - * @see edu.wpi.first.wpilibj.AbstractInterruptTest#setInterruptLow() - */ - @Override - void setInterruptLow() { - dio.getOutput().set(false); - - } - } diff --git a/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/EncoderTest.java b/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/EncoderTest.java index 242234f674..f70dd2ae20 100644 --- a/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/EncoderTest.java +++ b/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/EncoderTest.java @@ -1,8 +1,8 @@ /*----------------------------------------------------------------------------*/ -/* Copyright (c) FIRST 2008-2014. All Rights Reserved. */ -/* Open Source Software - may be modified and shared by FRC teams. The code */ +/* Copyright (c) FIRST 2008-2014. All Rights Reserved. */ +/* Open Source Software - may be modified and shared by FRC teams. The code */ /* must be accompanied by the FIRST BSD license file in the root directory of */ -/* the project. */ +/* the project. */ /*----------------------------------------------------------------------------*/ package edu.wpi.first.wpilibj; @@ -26,127 +26,137 @@ import edu.wpi.first.wpilibj.test.TestBench; /** * Test to see if the FPGA properly recognizes a mock Encoder input - * + *$ * @author Jonathan Leitschuh * */ @RunWith(Parameterized.class) public class EncoderTest extends AbstractComsSetup { - private static final Logger logger = Logger.getLogger(EncoderTest.class.getName()); - private static FakeEncoderFixture encoder = null; - - private final boolean flip; //Does this test need to flip the inputs - private final int inputA; - private final int inputB; - private final int outputA; - private final int outputB; - - @Override - protected Logger getClassLogger(){ - return logger; - } - - /** - * Test data generator. This method is called the the JUnit - * parameterized test runner and returns a Collection of Arrays. For each - * Array in the Collection, each array element corresponds to a parameter - * in the constructor. - */ - @Parameters - public static Collection generateData() { - return TestBench.getInstance().getEncoderDIOCrossConnectCollection(); - } - - /** - * Constructs a parameterized Encoder Test - * @param inputA The port number for inputA - * @param outputA The port number for outputA - * @param inputB The port number for inputB - * @param outputB The port number for outputB - * @param flip whether or not these set of values require the encoder to be reversed (0 or 1) - */ - public EncoderTest(int inputA, int outputA, int inputB, int outputB, int flip){ - this.inputA = inputA; - this.inputB = inputB; - this.outputA = outputA; - this.outputB = outputB; - - //If the encoder from a previous test is allocated then we must free its members - if(encoder != null) encoder.teardown(); - this.flip = flip==0; - encoder = new FakeEncoderFixture(inputA, outputA, inputB, outputB); - } + private static final Logger logger = Logger.getLogger(EncoderTest.class.getName()); + private static FakeEncoderFixture encoder = null; - /** - * @throws java.lang.Exception - */ - @AfterClass - public static void tearDownAfterClass() throws Exception { - encoder.teardown(); - encoder=null; - } + private final boolean flip; // Does this test need to flip the inputs + private final int inputA; + private final int inputB; + private final int outputA; + private final int outputB; - /** - * Sets up the test and verifies that the test was reset to the default state - * @throws java.lang.Exception - */ - @Before - public void setUp() throws Exception { - encoder.setup(); - testDefaultState(); - } + @Override + protected Logger getClassLogger() { + return logger; + } - /** - * @throws java.lang.Exception - */ - @After - public void tearDown() throws Exception { - encoder.reset(); - } - - /** - * Tests to see if Encoders initialize to zero - */ - @Test - public void testDefaultState(){ - int value = encoder.getEncoder().get(); - assertTrue(errorMessage(0, value), value == 0); - } + /** + * Test data generator. This method is called the the JUnit parameterized test + * runner and returns a Collection of Arrays. For each Array in the + * Collection, each array element corresponds to a parameter in the + * constructor. + */ + @Parameters + public static Collection generateData() { + return TestBench.getInstance().getEncoderDIOCrossConnectCollection(); + } - /** - * Tests to see if Encoders can count up sucsessfully - */ - @Test - public void testCountUp() { - int goal = 100; - encoder.getFakeEncoderSource().setCount(goal); - encoder.getFakeEncoderSource().setForward(flip); - encoder.getFakeEncoderSource().execute(); - int value = encoder.getEncoder().get(); - assertTrue(errorMessage(goal, value), value == goal); - - } - /** - * Tests to see if Encoders can count down sucsessfully - */ - @Test - public void testCountDown() { - int goal = -100; - encoder.getFakeEncoderSource().setCount(goal); //Goal has to be positive - encoder.getFakeEncoderSource().setForward(!flip); - encoder.getFakeEncoderSource().execute(); - int value = encoder.getEncoder().get(); - assertTrue(errorMessage(goal, value), value == goal); - - } - - /** - * Creates a simple message with the error that was encounterd for the Encoders - * @param goal The goal that was trying to be reached - * @param trueValue The actual value that was reached by the test - * @return A fully constructed message with data about where and why the the test failed - */ - private String errorMessage(int goal, int trueValue){ - return "Encoder ({In,Out}): {" + inputA + ", " + outputA + "},{" + inputB + ", " + outputB + "} Returned: " + trueValue + ", Wanted: " + goal; - } + /** + * Constructs a parameterized Encoder Test + *$ + * @param inputA The port number for inputA + * @param outputA The port number for outputA + * @param inputB The port number for inputB + * @param outputB The port number for outputB + * @param flip whether or not these set of values require the encoder to be + * reversed (0 or 1) + */ + public EncoderTest(int inputA, int outputA, int inputB, int outputB, int flip) { + this.inputA = inputA; + this.inputB = inputB; + this.outputA = outputA; + this.outputB = outputB; + + // If the encoder from a previous test is allocated then we must free its + // members + if (encoder != null) + encoder.teardown(); + this.flip = flip == 0; + encoder = new FakeEncoderFixture(inputA, outputA, inputB, outputB); + } + + /** + * @throws java.lang.Exception + */ + @AfterClass + public static void tearDownAfterClass() throws Exception { + encoder.teardown(); + encoder = null; + } + + /** + * Sets up the test and verifies that the test was reset to the default state + *$ + * @throws java.lang.Exception + */ + @Before + public void setUp() throws Exception { + encoder.setup(); + testDefaultState(); + } + + /** + * @throws java.lang.Exception + */ + @After + public void tearDown() throws Exception { + encoder.reset(); + } + + /** + * Tests to see if Encoders initialize to zero + */ + @Test + public void testDefaultState() { + int value = encoder.getEncoder().get(); + assertTrue(errorMessage(0, value), value == 0); + } + + /** + * Tests to see if Encoders can count up sucsessfully + */ + @Test + public void testCountUp() { + int goal = 100; + encoder.getFakeEncoderSource().setCount(goal); + encoder.getFakeEncoderSource().setForward(flip); + encoder.getFakeEncoderSource().execute(); + int value = encoder.getEncoder().get(); + assertTrue(errorMessage(goal, value), value == goal); + + } + + /** + * Tests to see if Encoders can count down sucsessfully + */ + @Test + public void testCountDown() { + int goal = -100; + encoder.getFakeEncoderSource().setCount(goal); // Goal has to be positive + encoder.getFakeEncoderSource().setForward(!flip); + encoder.getFakeEncoderSource().execute(); + int value = encoder.getEncoder().get(); + assertTrue(errorMessage(goal, value), value == goal); + + } + + /** + * Creates a simple message with the error that was encounterd for the + * Encoders + *$ + * @param goal The goal that was trying to be reached + * @param trueValue The actual value that was reached by the test + * @return A fully constructed message with data about where and why the the + * test failed + */ + private String errorMessage(int goal, int trueValue) { + return "Encoder ({In,Out}): {" + inputA + ", " + outputA + "},{" + inputB + ", " + outputB + + "} Returned: " + trueValue + ", Wanted: " + goal; + } } diff --git a/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/GyroTest.java b/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/GyroTest.java index 3ee2b626c3..7dd41228b4 100644 --- a/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/GyroTest.java +++ b/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/GyroTest.java @@ -1,8 +1,8 @@ /*----------------------------------------------------------------------------*/ -/* Copyright (c) FIRST 2008-2014. All Rights Reserved. */ -/* Open Source Software - may be modified and shared by FRC teams. The code */ +/* Copyright (c) FIRST 2008-2014. All Rights Reserved. */ +/* Open Source Software - may be modified and shared by FRC teams. The code */ /* must be accompanied by the FIRST BSD license file in the root directory of */ -/* the project. */ +/* the project. */ /*----------------------------------------------------------------------------*/ package edu.wpi.first.wpilibj; @@ -20,86 +20,86 @@ import edu.wpi.first.wpilibj.test.TestBench; public class GyroTest extends AbstractComsSetup { - private static final Logger logger = Logger.getLogger(GyroTest.class.getName()); + private static final Logger logger = Logger.getLogger(GyroTest.class.getName()); - public static final double TEST_ANGLE = 90.0; + public static final double TEST_ANGLE = 90.0; - private TiltPanCameraFixture tpcam; + private TiltPanCameraFixture tpcam; - @Override - protected Logger getClassLogger() { - return logger; + @Override + protected Logger getClassLogger() { + return logger; + } + + @Before + public void setUp() throws Exception { + logger.fine("Setup: TiltPan camera"); + tpcam = TestBench.getInstance().getTiltPanCam(); + tpcam.setup(); + } + + @After + public void tearDown() throws Exception { + tpcam.reset(); + tpcam.teardown(); + } + + @Test + public void testInitial() { + double angle = tpcam.getGyro().getAngle(); + assertEquals(errorMessage(angle, 0), 0, angle, .5); + } + + /** + * Test to see if the Servo and the gyroscope is turning 90 degrees Note servo + * on TestBench is not the same type of servo that servo class was designed + * for so setAngle is significantly off. This has been calibrated for the + * servo on the rig. + */ + @Test + public void testGyroAngle() { + // Set angle + for (int i = 0; i < 5; i++) { + tpcam.getPan().set(0); + Timer.delay(.1); } - @Before - public void setUp() throws Exception { - logger.fine("Setup: TiltPan camera"); - tpcam = TestBench.getInstance().getTiltPanCam(); - tpcam.setup(); + Timer.delay(0.5); + // Reset for setup + tpcam.getGyro().reset(); + Timer.delay(0.5); + + // Perform test + for (int i = 0; i < 53; i++) { + tpcam.getPan().set(i / 100.0); + Timer.delay(0.05); } + Timer.delay(1.2); - @After - public void tearDown() throws Exception { - tpcam.reset(); - tpcam.teardown(); - } + double angle = tpcam.getGyro().getAngle(); - @Test - public void testInitial() { - double angle = tpcam.getGyro().getAngle(); - assertEquals(errorMessage(angle, 0), 0, angle, .5); - } + double difference = TEST_ANGLE - angle; - /** - * Test to see if the Servo and the gyroscope is turning 90 degrees Note - * servo on TestBench is not the same type of servo that servo class was - * designed for so setAngle is significantly off. This has been calibrated - * for the servo on the rig. - */ - @Test - public void testGyroAngle() { - //Set angle - for (int i = 0; i < 5; i++) { - tpcam.getPan().set(0); - Timer.delay(.1); - } + double diff = Math.abs(difference); - Timer.delay(0.5); - //Reset for setup - tpcam.getGyro().reset(); - Timer.delay(0.5); + assertEquals(errorMessage(diff, TEST_ANGLE), TEST_ANGLE, angle, 10); + } - //Perform test - for (int i = 0; i < 53; i++) { - tpcam.getPan().set(i / 100.0); - Timer.delay(0.05); - } - Timer.delay(1.2); + @Test + public void testDeviationOverTime() { + // Make sure that the test isn't influenced by any previous motions. + Timer.delay(0.25); + tpcam.getGyro().reset(); + Timer.delay(0.25); + double angle = tpcam.getGyro().getAngle(); + assertEquals(errorMessage(angle, 0), 0, angle, .5); + Timer.delay(5); + angle = tpcam.getGyro().getAngle(); + assertEquals("After 5 seconds " + errorMessage(angle, 0), 0, angle, 1); + } - double angle = tpcam.getGyro().getAngle(); - - double difference = TEST_ANGLE - angle; - - double diff = Math.abs(difference); - - assertEquals(errorMessage(diff, TEST_ANGLE), TEST_ANGLE, angle, 10); - } - - @Test - public void testDeviationOverTime() { - // Make sure that the test isn't influenced by any previous motions. - Timer.delay(0.25); - tpcam.getGyro().reset(); - Timer.delay(0.25); - double angle = tpcam.getGyro().getAngle(); - assertEquals(errorMessage(angle, 0), 0, angle, .5); - Timer.delay(5); - angle = tpcam.getGyro().getAngle(); - assertEquals("After 5 seconds " + errorMessage(angle, 0), 0, angle, 1); - } - - private String errorMessage(double difference, double target) { - return "Gyro angle skewed " + difference + " deg away from target " + target; - } + private String errorMessage(double difference, double target) { + return "Gyro angle skewed " + difference + " deg away from target " + target; + } } diff --git a/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/MotorEncoderTest.java b/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/MotorEncoderTest.java index 2304910b9d..8fb933a8af 100644 --- a/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/MotorEncoderTest.java +++ b/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/MotorEncoderTest.java @@ -1,8 +1,8 @@ /*----------------------------------------------------------------------------*/ -/* Copyright (c) FIRST 2008-2014. All Rights Reserved. */ -/* Open Source Software - may be modified and shared by FRC teams. The code */ +/* Copyright (c) FIRST 2008-2014. All Rights Reserved. */ +/* Open Source Software - may be modified and shared by FRC teams. The code */ /* must be accompanied by the FIRST BSD license file in the root directory of */ -/* the project. */ +/* the project. */ /*----------------------------------------------------------------------------*/ package edu.wpi.first.wpilibj; @@ -29,175 +29,181 @@ import edu.wpi.first.wpilibj.test.TestBench; @RunWith(Parameterized.class) public class MotorEncoderTest extends AbstractComsSetup { - private static final Logger logger = Logger.getLogger(MotorEncoderTest.class.getName()); + private static final Logger logger = Logger.getLogger(MotorEncoderTest.class.getName()); - private static final double MOTOR_RUNTIME = .25; + private static final double MOTOR_RUNTIME = .25; - //private static final List pairs = new ArrayList(); - private static MotorEncoderFixture me = null; + // private static final List pairs = new + // ArrayList(); + private static MotorEncoderFixture me = null; - @Override - protected Logger getClassLogger(){ - return logger; - } + @Override + protected Logger getClassLogger() { + return logger; + } - public MotorEncoderTest(MotorEncoderFixture mef){ - logger.fine("Constructor with: " + mef.getType()); - if(me != null && !me.equals(mef)) me.teardown(); - me = mef; - } + public MotorEncoderTest(MotorEncoderFixture mef) { + logger.fine("Constructor with: " + mef.getType()); + if (me != null && !me.equals(mef)) + me.teardown(); + me = mef; + } - @Parameters(name= "{index}: {0}") - public static Collection[]> generateData(){ - //logger.fine("Loading the MotorList"); - return Arrays.asList(new MotorEncoderFixture[][]{ - {TestBench.getInstance().getTalonPair()}, - {TestBench.getInstance().getVictorPair()}, - {TestBench.getInstance().getJaguarPair()} - }); - } + @Parameters(name = "{index}: {0}") + public static Collection[]> generateData() { + // logger.fine("Loading the MotorList"); + return Arrays.asList(new MotorEncoderFixture[][] { {TestBench.getInstance().getTalonPair()}, + {TestBench.getInstance().getVictorPair()}, {TestBench.getInstance().getJaguarPair()}}); + } - @Before - public void setUp() { - double initialSpeed = me.getMotor().get(); - assertTrue(me.getType() - + " Did not start with an initial speeed of 0 instead got: " - + initialSpeed, Math.abs(initialSpeed) < 0.001); - me.setup(); + @Before + public void setUp() { + double initialSpeed = me.getMotor().get(); + assertTrue(me.getType() + " Did not start with an initial speeed of 0 instead got: " + + initialSpeed, Math.abs(initialSpeed) < 0.001); + me.setup(); - } + } - @After - public void tearDown() throws Exception { - me.reset(); - encodersResetCheck(me); - } + @After + public void tearDown() throws Exception { + me.reset(); + encodersResetCheck(me); + } - @AfterClass - public static void tearDownAfterClass() { - // Clean up the fixture after the test - me.teardown(); - me=null; - } + @AfterClass + public static void tearDownAfterClass() { + // Clean up the fixture after the test + me.teardown(); + me = null; + } - /** - * Test to ensure that the isMotorWithinRange method is functioning properly. - * Really only needs to run on one MotorEncoderFixture to ensure that it is working correctly. - */ - @Test - public void testIsMotorWithinRange(){ - double range = 0.01; - assertTrue(me.getType() + " 1", me.isMotorSpeedWithinRange(0.0, range)); - assertTrue(me.getType() + " 2", me.isMotorSpeedWithinRange(0.0, -range)); - assertFalse(me.getType() + " 3", me.isMotorSpeedWithinRange(1.0, range)); - assertFalse(me.getType() + " 4", - me.isMotorSpeedWithinRange(-1.0, range)); - } + /** + * Test to ensure that the isMotorWithinRange method is functioning properly. + * Really only needs to run on one MotorEncoderFixture to ensure that it is + * working correctly. + */ + @Test + public void testIsMotorWithinRange() { + double range = 0.01; + assertTrue(me.getType() + " 1", me.isMotorSpeedWithinRange(0.0, range)); + assertTrue(me.getType() + " 2", me.isMotorSpeedWithinRange(0.0, -range)); + assertFalse(me.getType() + " 3", me.isMotorSpeedWithinRange(1.0, range)); + assertFalse(me.getType() + " 4", me.isMotorSpeedWithinRange(-1.0, range)); + } - /** - * This test is designed to see if the values of different motors will increment when spun forward - */ - @Test - public void testIncrement() { - int startValue = me.getEncoder().get(); + /** + * This test is designed to see if the values of different motors will + * increment when spun forward + */ + @Test + public void testIncrement() { + int startValue = me.getEncoder().get(); - me.getMotor().set(.75); - Timer.delay(MOTOR_RUNTIME); - int currentValue = me.getEncoder().get(); - assertTrue(me.getType() + " Encoder not incremented: start: " - + startValue + "; current: " + currentValue, - startValue < currentValue); + me.getMotor().set(.75); + Timer.delay(MOTOR_RUNTIME); + int currentValue = me.getEncoder().get(); + assertTrue(me.getType() + " Encoder not incremented: start: " + startValue + "; current: " + + currentValue, startValue < currentValue); - } + } - /** - * This test is designed to see if the values of different motors will decrement when spun in reverse - */ - @Test - public void testDecrement(){ - int startValue = me.getEncoder().get(); + /** + * This test is designed to see if the values of different motors will + * decrement when spun in reverse + */ + @Test + public void testDecrement() { + int startValue = me.getEncoder().get(); - me.getMotor().set(-.75); - Timer.delay(MOTOR_RUNTIME); - int currentValue = me.getEncoder().get(); - assertTrue(me.getType() + " Encoder not decremented: start: " - + startValue + "; current: " + currentValue, - startValue > currentValue); - } + me.getMotor().set(-.75); + Timer.delay(MOTOR_RUNTIME); + int currentValue = me.getEncoder().get(); + assertTrue(me.getType() + " Encoder not decremented: start: " + startValue + "; current: " + + currentValue, startValue > currentValue); + } - /** - * This method test if the counters count when the motors rotate - */ - @Test - public void testCounter(){ - int counter1Start = me.getCounters()[0].get(); - int counter2Start = me.getCounters()[1].get(); + /** + * This method test if the counters count when the motors rotate + */ + @Test + public void testCounter() { + int counter1Start = me.getCounters()[0].get(); + int counter2Start = me.getCounters()[1].get(); - me.getMotor().set(.75); - Timer.delay(MOTOR_RUNTIME); - int counter1End = me.getCounters()[0].get(); - int counter2End = me.getCounters()[1].get(); - assertTrue(me.getType() + " Counter not incremented: start: " - + counter1Start + "; current: " + counter1End, - counter1Start < counter1End); - assertTrue(me.getType() + " Counter not incremented: start: " - + counter1Start + "; current: " + counter2End, - counter2Start < counter2End); - me.reset(); - encodersResetCheck(me); - } + me.getMotor().set(.75); + Timer.delay(MOTOR_RUNTIME); + int counter1End = me.getCounters()[0].get(); + int counter2End = me.getCounters()[1].get(); + assertTrue(me.getType() + " Counter not incremented: start: " + counter1Start + "; current: " + + counter1End, counter1Start < counter1End); + assertTrue(me.getType() + " Counter not incremented: start: " + counter1Start + "; current: " + + counter2End, counter2Start < counter2End); + me.reset(); + encodersResetCheck(me); + } - /** - * Tests to see if you set the speed to something not <= 1.0 if the code appropriately throttles the value - */ - @Test - public void testSetHighForwardSpeed(){ - me.getMotor().set(15); - assertTrue(me.getType() + " Motor speed was not close to 1.0, was: " - + me.getMotor().get(), me.isMotorSpeedWithinRange(1.0, 0.001)); - } + /** + * Tests to see if you set the speed to something not <= 1.0 if the code + * appropriately throttles the value + */ + @Test + public void testSetHighForwardSpeed() { + me.getMotor().set(15); + assertTrue(me.getType() + " Motor speed was not close to 1.0, was: " + me.getMotor().get(), + me.isMotorSpeedWithinRange(1.0, 0.001)); + } - /** - * Tests to see if you set the speed to something not >= -1.0 if the code appropriately throttles the value - */ - @Test - public void testSetHighReverseSpeed() { - me.getMotor().set(-15); - assertTrue(me.getType() + " Motor speed was not close to 1.0, was: " - + me.getMotor().get(), me.isMotorSpeedWithinRange(-1.0, 0.001)); - } + /** + * Tests to see if you set the speed to something not >= -1.0 if the code + * appropriately throttles the value + */ + @Test + public void testSetHighReverseSpeed() { + me.getMotor().set(-15); + assertTrue(me.getType() + " Motor speed was not close to 1.0, was: " + me.getMotor().get(), + me.isMotorSpeedWithinRange(-1.0, 0.001)); + } - @Test - public void testPIDController() { - PIDController pid = new PIDController(0.003, 0.001, 0, me.getEncoder(), - me.getMotor()); - pid.setAbsoluteTolerance(50); - pid.setOutputRange(-0.2, 0.2); - pid.setSetpoint(2500); + @Test + public void testPIDController() { + PIDController pid = new PIDController(0.003, 0.001, 0, me.getEncoder(), me.getMotor()); + pid.setAbsoluteTolerance(50); + pid.setOutputRange(-0.2, 0.2); + pid.setSetpoint(2500); - pid.enable(); - Timer.delay(10.0); - pid.disable(); + pid.enable(); + Timer.delay(10.0); + pid.disable(); - assertTrue("PID loop did not reach setpoint within 10 seconds. The error was: " + pid.getError(), - pid.onTarget()); + assertTrue( + "PID loop did not reach setpoint within 10 seconds. The error was: " + pid.getError(), + pid.onTarget()); - pid.free(); - } + pid.free(); + } - /** - * Checks to see if the encoders and counters are appropriately reset to zero when reset - * @param me The MotorEncoderFixture under test - */ - private void encodersResetCheck(MotorEncoderFixture me){ - assertEquals(me.getType() + " Encoder value was incorrect after reset.", me.getEncoder().get(), 0); - assertEquals(me.getType() + " Motor value was incorrect after reset.", me.getMotor().get(), 0, 0); - assertEquals(me.getType() + " Counter1 value was incorrect after reset.", me.getCounters()[0].get(), 0); - assertEquals(me.getType() + " Counter2 value was incorrect after reset.", me.getCounters()[1].get(), 0); - Timer.delay(0.5); // so this doesn't fail with the 0.5 second default timeout on the encoders - assertTrue(me.getType() + " Encoder.getStopped() returned false after the motor was reset.", me.getEncoder().getStopped()); - } + /** + * Checks to see if the encoders and counters are appropriately reset to zero + * when reset + *$ + * @param me The MotorEncoderFixture under test + */ + private void encodersResetCheck(MotorEncoderFixture me) { + assertEquals(me.getType() + " Encoder value was incorrect after reset.", me.getEncoder().get(), + 0); + assertEquals(me.getType() + " Motor value was incorrect after reset.", me.getMotor().get(), 0, + 0); + assertEquals(me.getType() + " Counter1 value was incorrect after reset.", + me.getCounters()[0].get(), 0); + assertEquals(me.getType() + " Counter2 value was incorrect after reset.", + me.getCounters()[1].get(), 0); + Timer.delay(0.5); // so this doesn't fail with the 0.5 second default + // timeout on the encoders + assertTrue(me.getType() + " Encoder.getStopped() returned false after the motor was reset.", me + .getEncoder().getStopped()); + } } diff --git a/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/MotorInvertingTest.java b/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/MotorInvertingTest.java index 2b60466bb3..a7270545ff 100644 --- a/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/MotorInvertingTest.java +++ b/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/MotorInvertingTest.java @@ -22,97 +22,99 @@ import java.util.logging.Logger; */ @RunWith(Parameterized.class) public class MotorInvertingTest extends AbstractComsSetup { - static MotorEncoderFixture fixture = null; - private static final double motorspeed = 0.35; - private static final double delaytime = 0.3; - - - public MotorInvertingTest(MotorEncoderFixture afixture){ - logger.fine("Constructor with: " + afixture.getType()); - if(fixture != null && !fixture.equals(afixture)) fixture.teardown(); - fixture = afixture; - fixture.setup(); - } - - @Parameterized.Parameters(name= "{index}: {0}") - public static Collection[]> generateData(){ - //logger.fine("Loading the MotorList"); - return Arrays.asList(new MotorEncoderFixture[][]{ - {TestBench.getInstance().getTalonPair()}, - {TestBench.getInstance().getVictorPair()}, - {TestBench.getInstance().getJaguarPair()} - }); - } + static MotorEncoderFixture fixture = null; + private static final double motorspeed = 0.35; + private static final double delaytime = 0.3; - private static final Logger logger = Logger.getLogger(MotorInvertingTest.class.getName()); - - @Override - protected Logger getClassLogger(){ - return logger; - } - @Before - public void setUp() { - // Reset the fixture elements before every test - fixture.reset(); - } + public MotorInvertingTest(MotorEncoderFixture afixture) { + logger.fine("Constructor with: " + afixture.getType()); + if (fixture != null && !fixture.equals(afixture)) + fixture.teardown(); + fixture = afixture; + fixture.setup(); + } - @AfterClass - public static void tearDown() { - fixture.getMotor().setInverted(false); - // Clean up the fixture after the test - fixture.teardown(); - } + @Parameterized.Parameters(name = "{index}: {0}") + public static Collection[]> generateData() { + // logger.fine("Loading the MotorList"); + return Arrays.asList(new MotorEncoderFixture[][] { {TestBench.getInstance().getTalonPair()}, + {TestBench.getInstance().getVictorPair()}, {TestBench.getInstance().getJaguarPair()}}); + } - @Test - public void testInvertingPositive(){ - fixture.getMotor().setInverted(false); - fixture.getMotor().set(motorspeed); - Timer.delay(delaytime); - boolean initDirection = fixture.getEncoder().getDirection(); - fixture.getMotor().setInverted(true); - fixture.getMotor().set(motorspeed); - Timer.delay(delaytime); - assertFalse("Inverting with Positive value does not change direction",fixture.getEncoder().getDirection()==initDirection); - fixture.getMotor().set(0); - } + private static final Logger logger = Logger.getLogger(MotorInvertingTest.class.getName()); - @Test - public void testInvertingNegative(){ - fixture.getMotor().setInverted(false); - fixture.getMotor().set(-motorspeed); - Timer.delay(delaytime); - boolean initDirection = fixture.getEncoder().getDirection(); - fixture.getMotor().setInverted(true); - fixture.getMotor().set(-motorspeed); - Timer.delay(delaytime); - assertFalse("Inverting with Negative value does not change direction",fixture.getEncoder().getDirection()==initDirection); - fixture.getMotor().set(0); - } + @Override + protected Logger getClassLogger() { + return logger; + } - @Test - public void testInvertingSwitchingPosToNeg(){ - fixture.getMotor().setInverted(false); - fixture.getMotor().set(motorspeed); - Timer.delay(delaytime); - boolean initDirection = fixture.getEncoder().getDirection(); - fixture.getMotor().setInverted(true); - fixture.getMotor().set(-motorspeed); - Timer.delay(delaytime); - assertTrue("Inverting with Switching value does change direction", fixture.getEncoder().getDirection() == initDirection); - fixture.getMotor().set(0); - } + @Before + public void setUp() { + // Reset the fixture elements before every test + fixture.reset(); + } - @Test - public void testInvertingSwitchingNegToPos(){ - fixture.getMotor().setInverted(false); - fixture.getMotor().set(-motorspeed); - Timer.delay(delaytime); - boolean initDirection = fixture.getEncoder().getDirection(); - fixture.getMotor().setInverted(true); - fixture.getMotor().set(motorspeed); - Timer.delay(delaytime); - assertTrue("Inverting with Switching value does change direction", fixture.getEncoder().getDirection() == initDirection); - fixture.getMotor().set(0); - } + @AfterClass + public static void tearDown() { + fixture.getMotor().setInverted(false); + // Clean up the fixture after the test + fixture.teardown(); + } + + @Test + public void testInvertingPositive() { + fixture.getMotor().setInverted(false); + fixture.getMotor().set(motorspeed); + Timer.delay(delaytime); + boolean initDirection = fixture.getEncoder().getDirection(); + fixture.getMotor().setInverted(true); + fixture.getMotor().set(motorspeed); + Timer.delay(delaytime); + assertFalse("Inverting with Positive value does not change direction", fixture.getEncoder() + .getDirection() == initDirection); + fixture.getMotor().set(0); + } + + @Test + public void testInvertingNegative() { + fixture.getMotor().setInverted(false); + fixture.getMotor().set(-motorspeed); + Timer.delay(delaytime); + boolean initDirection = fixture.getEncoder().getDirection(); + fixture.getMotor().setInverted(true); + fixture.getMotor().set(-motorspeed); + Timer.delay(delaytime); + assertFalse("Inverting with Negative value does not change direction", fixture.getEncoder() + .getDirection() == initDirection); + fixture.getMotor().set(0); + } + + @Test + public void testInvertingSwitchingPosToNeg() { + fixture.getMotor().setInverted(false); + fixture.getMotor().set(motorspeed); + Timer.delay(delaytime); + boolean initDirection = fixture.getEncoder().getDirection(); + fixture.getMotor().setInverted(true); + fixture.getMotor().set(-motorspeed); + Timer.delay(delaytime); + assertTrue("Inverting with Switching value does change direction", fixture.getEncoder() + .getDirection() == initDirection); + fixture.getMotor().set(0); + } + + @Test + public void testInvertingSwitchingNegToPos() { + fixture.getMotor().setInverted(false); + fixture.getMotor().set(-motorspeed); + Timer.delay(delaytime); + boolean initDirection = fixture.getEncoder().getDirection(); + fixture.getMotor().setInverted(true); + fixture.getMotor().set(motorspeed); + Timer.delay(delaytime); + assertTrue("Inverting with Switching value does change direction", fixture.getEncoder() + .getDirection() == initDirection); + fixture.getMotor().set(0); + } } diff --git a/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/PCMTest.java b/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/PCMTest.java index d70cc4627b..e5ecabb065 100644 --- a/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/PCMTest.java +++ b/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/PCMTest.java @@ -1,8 +1,8 @@ /*----------------------------------------------------------------------------*/ -/* Copyright (c) FIRST 2014. All Rights Reserved. */ -/* Open Source Software - may be modified and shared by FRC teams. The code */ +/* Copyright (c) FIRST 2014. All Rights Reserved. */ +/* Open Source Software - may be modified and shared by FRC teams. The code */ /* must be accompanied by the FIRST BSD license file in the root directory of */ -/* the project. */ +/* the project. */ /*----------------------------------------------------------------------------*/ package edu.wpi.first.wpilibj; @@ -26,152 +26,154 @@ import edu.wpi.first.wpilibj.test.AbstractComsSetup; */ public class PCMTest extends AbstractComsSetup { - private static final Logger logger = Logger.getLogger(PCMTest.class.getName()); - /* The PCM switches the compressor up to 2 seconds after the pressure switch - changes. */ - protected static final double kCompressorDelayTime = 2.0; + private static final Logger logger = Logger.getLogger(PCMTest.class.getName()); + /* + * The PCM switches the compressor up to 2 seconds after the pressure switch + * changes. + */ + protected static final double kCompressorDelayTime = 2.0; - /* Solenoids should change much more quickly */ - protected static final double kSolenoidDelayTime = 1.0; + /* Solenoids should change much more quickly */ + protected static final double kSolenoidDelayTime = 1.0; - /* The voltage divider on the test bench should bring the compressor output - to around these values. */ - protected static final double kCompressorOnVoltage = 5.00; - protected static final double kCompressorOffVoltage = 1.68; + /* + * The voltage divider on the test bench should bring the compressor output to + * around these values. + */ + protected static final double kCompressorOnVoltage = 5.00; + protected static final double kCompressorOffVoltage = 1.68; - private static Compressor compressor; + private static Compressor compressor; - private static DigitalOutput fakePressureSwitch; - private static AnalogInput fakeCompressor; + private static DigitalOutput fakePressureSwitch; + private static AnalogInput fakeCompressor; - private static DigitalInput fakeSolenoid1, fakeSolenoid2; + private static DigitalInput fakeSolenoid1, fakeSolenoid2; - @BeforeClass - public static void setUpBeforeClass() throws Exception { - compressor = new Compressor(); + @BeforeClass + public static void setUpBeforeClass() throws Exception { + compressor = new Compressor(); - fakePressureSwitch = new DigitalOutput(11); - fakeCompressor = new AnalogInput(1); + fakePressureSwitch = new DigitalOutput(11); + fakeCompressor = new AnalogInput(1); - fakeSolenoid1 = new DigitalInput(12); - fakeSolenoid2 = new DigitalInput(13); - } + fakeSolenoid1 = new DigitalInput(12); + fakeSolenoid2 = new DigitalInput(13); + } - @AfterClass - public static void tearDownAfterClass() throws Exception { - compressor.free(); + @AfterClass + public static void tearDownAfterClass() throws Exception { + compressor.free(); - fakePressureSwitch.free(); - fakeCompressor.free(); + fakePressureSwitch.free(); + fakeCompressor.free(); - fakeSolenoid1.free(); - fakeSolenoid2.free(); - } + fakeSolenoid1.free(); + fakeSolenoid2.free(); + } - @Before - public void setUp() throws Exception { - } + @Before + public void setUp() throws Exception {} - @Before - public void reset() throws Exception { - compressor.stop(); - fakePressureSwitch.set(false); - } + @Before + public void reset() throws Exception { + compressor.stop(); + fakePressureSwitch.set(false); + } - @After - public void tearDown() throws Exception { - } + @After + public void tearDown() throws Exception {} - /** - * Test if the compressor turns on and off when the pressure switch is toggled - */ - @Test - public void testPressureSwitch() throws Exception { - double range = 0.1; - reset(); - compressor.setClosedLoopControl(true); + /** + * Test if the compressor turns on and off when the pressure switch is toggled + */ + @Test + public void testPressureSwitch() throws Exception { + double range = 0.1; + reset(); + compressor.setClosedLoopControl(true); - // Turn on the compressor - fakePressureSwitch.set(true); - Timer.delay(kCompressorDelayTime); - assertEquals("Compressor did not turn on when the pressure switch turned on.", - kCompressorOnVoltage, fakeCompressor.getVoltage(), range); + // Turn on the compressor + fakePressureSwitch.set(true); + Timer.delay(kCompressorDelayTime); + assertEquals("Compressor did not turn on when the pressure switch turned on.", + kCompressorOnVoltage, fakeCompressor.getVoltage(), range); - // Turn on the compressor - fakePressureSwitch.set(false); - Timer.delay(kCompressorDelayTime); - assertEquals("Compressor did not turn off when the pressure switch turned off.", - kCompressorOffVoltage, fakeCompressor.getVoltage(), range); - } + // Turn on the compressor + fakePressureSwitch.set(false); + Timer.delay(kCompressorDelayTime); + assertEquals("Compressor did not turn off when the pressure switch turned off.", + kCompressorOffVoltage, fakeCompressor.getVoltage(), range); + } - /** - * Test if the correct solenoids turn on and off when they should - */ - @Test - public void testSolenoid() throws Exception { - reset(); + /** + * Test if the correct solenoids turn on and off when they should + */ + @Test + public void testSolenoid() throws Exception { + reset(); - Solenoid solenoid1 = new Solenoid(0); - Solenoid solenoid2 = new Solenoid(1); + Solenoid solenoid1 = new Solenoid(0); + Solenoid solenoid2 = new Solenoid(1); - solenoid1.set(false); - solenoid2.set(false); - Timer.delay(kSolenoidDelayTime); - assertTrue("Solenoid #1 did not turn on",fakeSolenoid1.get()); - assertTrue("Solenoid #2 did not turn off",fakeSolenoid2.get()); + solenoid1.set(false); + solenoid2.set(false); + Timer.delay(kSolenoidDelayTime); + assertTrue("Solenoid #1 did not turn on", fakeSolenoid1.get()); + assertTrue("Solenoid #2 did not turn off", fakeSolenoid2.get()); - // Turn Solenoid #1 on, and turn Solenoid #2 off - solenoid1.set(true); - solenoid2.set(false); - Timer.delay(kSolenoidDelayTime); - assertFalse("Solenoid #1 did not turn on",fakeSolenoid1.get()); - assertTrue("Solenoid #2 did not turn off",fakeSolenoid2.get()); + // Turn Solenoid #1 on, and turn Solenoid #2 off + solenoid1.set(true); + solenoid2.set(false); + Timer.delay(kSolenoidDelayTime); + assertFalse("Solenoid #1 did not turn on", fakeSolenoid1.get()); + assertTrue("Solenoid #2 did not turn off", fakeSolenoid2.get()); - // Turn Solenoid #1 off, and turn Solenoid #2 on - solenoid1.set(false); - solenoid2.set(true); - Timer.delay(kSolenoidDelayTime); - assertTrue("Solenoid #1 did not turn off",fakeSolenoid1.get()); - assertFalse("Solenoid #2 did not turn on",fakeSolenoid2.get()); + // Turn Solenoid #1 off, and turn Solenoid #2 on + solenoid1.set(false); + solenoid2.set(true); + Timer.delay(kSolenoidDelayTime); + assertTrue("Solenoid #1 did not turn off", fakeSolenoid1.get()); + assertFalse("Solenoid #2 did not turn on", fakeSolenoid2.get()); - // Turn both Solenoids on - solenoid1.set(true); - solenoid2.set(true); - Timer.delay(kSolenoidDelayTime); - assertFalse("Solenoid #1 did not turn on",fakeSolenoid1.get()); - assertFalse("Solenoid #2 did not turn on",fakeSolenoid2.get()); + // Turn both Solenoids on + solenoid1.set(true); + solenoid2.set(true); + Timer.delay(kSolenoidDelayTime); + assertFalse("Solenoid #1 did not turn on", fakeSolenoid1.get()); + assertFalse("Solenoid #2 did not turn on", fakeSolenoid2.get()); - solenoid1.free(); - solenoid2.free(); - } + solenoid1.free(); + solenoid2.free(); + } - /** - * Test if the correct solenoids turn on and off when they should when used - * with the DoubleSolenoid class. - */ - @Test - public void doubleSolenoid() { - DoubleSolenoid solenoid = new DoubleSolenoid(0, 1); + /** + * Test if the correct solenoids turn on and off when they should when used + * with the DoubleSolenoid class. + */ + @Test + public void doubleSolenoid() { + DoubleSolenoid solenoid = new DoubleSolenoid(0, 1); - solenoid.set(DoubleSolenoid.Value.kOff); - Timer.delay(kSolenoidDelayTime); - assertTrue("Solenoid #1 did not turn off", fakeSolenoid1.get()); - assertTrue("Solenoid #2 did not turn off", fakeSolenoid2.get()); + solenoid.set(DoubleSolenoid.Value.kOff); + Timer.delay(kSolenoidDelayTime); + assertTrue("Solenoid #1 did not turn off", fakeSolenoid1.get()); + assertTrue("Solenoid #2 did not turn off", fakeSolenoid2.get()); - solenoid.set(DoubleSolenoid.Value.kForward); - Timer.delay(kSolenoidDelayTime); - assertFalse("Solenoid #1 did not turn on", fakeSolenoid1.get()); - assertTrue("Solenoid #2 did not turn off", fakeSolenoid2.get()); + solenoid.set(DoubleSolenoid.Value.kForward); + Timer.delay(kSolenoidDelayTime); + assertFalse("Solenoid #1 did not turn on", fakeSolenoid1.get()); + assertTrue("Solenoid #2 did not turn off", fakeSolenoid2.get()); - solenoid.set(DoubleSolenoid.Value.kReverse); - Timer.delay(kSolenoidDelayTime); - assertTrue("Solenoid #1 did not turn off", fakeSolenoid1.get()); - assertFalse("Solenoid #2 did not turn on", fakeSolenoid2.get()); + solenoid.set(DoubleSolenoid.Value.kReverse); + Timer.delay(kSolenoidDelayTime); + assertTrue("Solenoid #1 did not turn off", fakeSolenoid1.get()); + assertFalse("Solenoid #2 did not turn on", fakeSolenoid2.get()); - solenoid.free(); - } + solenoid.free(); + } - protected Logger getClassLogger(){ - return logger; - } + protected Logger getClassLogger() { + return logger; + } } diff --git a/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/PDPTest.java b/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/PDPTest.java index d26502544b..98e9aba618 100644 --- a/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/PDPTest.java +++ b/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/PDPTest.java @@ -24,81 +24,81 @@ import edu.wpi.first.wpilibj.test.TestBench; @RunWith(Parameterized.class) public class PDPTest extends AbstractComsSetup { - private static final Logger logger = Logger.getLogger(PCMTest.class.getName()); + private static final Logger logger = Logger.getLogger(PCMTest.class.getName()); - private static PowerDistributionPanel pdp; - private static MotorEncoderFixture me; - private final double expectedStoppedCurrentDraw; + private static PowerDistributionPanel pdp; + private static MotorEncoderFixture me; + private final double expectedStoppedCurrentDraw; - @BeforeClass - public static void setUpBeforeClass() throws Exception { - pdp = new PowerDistributionPanel(); - } + @BeforeClass + public static void setUpBeforeClass() throws Exception { + pdp = new PowerDistributionPanel(); + } - @AfterClass - public static void tearDownAfterClass() throws Exception { - pdp.free(); - pdp=null; - me.teardown(); - me=null; - } + @AfterClass + public static void tearDownAfterClass() throws Exception { + pdp.free(); + pdp = null; + me.teardown(); + me = null; + } - public PDPTest(MotorEncoderFixture mef, Double expectedCurrentDraw){ - logger.fine("Constructor with: " + mef.getType()); - if(me != null && !me.equals(mef)) me.teardown(); - me = mef; - me.setup(); - - this.expectedStoppedCurrentDraw = expectedCurrentDraw; - } + public PDPTest(MotorEncoderFixture mef, Double expectedCurrentDraw) { + logger.fine("Constructor with: " + mef.getType()); + if (me != null && !me.equals(mef)) + me.teardown(); + me = mef; + me.setup(); - @Parameters(name= "{index}: {0}, Expected Stopped Current Draw: {1}") - public static Collection generateData(){ - //logger.fine("Loading the MotorList"); - return Arrays.asList(new Object[][]{ - {TestBench.getInstance().getTalonPair(), new Double(0.0)}, - {TestBench.getInstance().getVictorPair(), new Double(0.0)}, - {TestBench.getInstance().getJaguarPair(), new Double(0.0)} - }); - } + this.expectedStoppedCurrentDraw = expectedCurrentDraw; + } - @After - public void tearDown() throws Exception { - me.reset(); - } + @Parameters(name = "{index}: {0}, Expected Stopped Current Draw: {1}") + public static Collection generateData() { + // logger.fine("Loading the MotorList"); + return Arrays.asList(new Object[][] { + {TestBench.getInstance().getTalonPair(), new Double(0.0)}, + {TestBench.getInstance().getVictorPair(), new Double(0.0)}, + {TestBench.getInstance().getJaguarPair(), new Double(0.0)}}); + } + + @After + public void tearDown() throws Exception { + me.reset(); + } - /** - * Test if the current changes when the motor is driven using a talon - */ - @Test - public void CheckStoppedCurrentForSpeedController() throws CANMessageNotFoundException{ - Timer.delay(0.25); + /** + * Test if the current changes when the motor is driven using a talon + */ + @Test + public void CheckStoppedCurrentForSpeedController() throws CANMessageNotFoundException { + Timer.delay(0.25); - /* The Current should be 0 */ - assertEquals("The low current was not within the expected range.", - expectedStoppedCurrentDraw, pdp.getCurrent(me.getPDPChannel()), 0.001); - } + /* The Current should be 0 */ + assertEquals("The low current was not within the expected range.", expectedStoppedCurrentDraw, + pdp.getCurrent(me.getPDPChannel()), 0.001); + } - /** - * Test if the current changes when the motor is driven using a talon - */ - @Test - public void CheckRunningCurrentForSpeedController() throws CANMessageNotFoundException{ + /** + * Test if the current changes when the motor is driven using a talon + */ + @Test + public void CheckRunningCurrentForSpeedController() throws CANMessageNotFoundException { - /* Set the motor to full forward */ - me.getMotor().set(1.0); - Timer.delay(0.25); + /* Set the motor to full forward */ + me.getMotor().set(1.0); + Timer.delay(0.25); - /* The current should now be greater than the low current */ - assertThat("The driven current is not greater than the resting current.", - pdp.getCurrent(me.getPDPChannel()), is(greaterThan(expectedStoppedCurrentDraw))); - } + /* The current should now be greater than the low current */ + assertThat("The driven current is not greater than the resting current.", + pdp.getCurrent(me.getPDPChannel()), is(greaterThan(expectedStoppedCurrentDraw))); + } - @Override - protected Logger getClassLogger() { - return logger; - } + @Override + protected Logger getClassLogger() { + return logger; + } } diff --git a/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/PIDTest.java b/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/PIDTest.java index e5a9115fb7..c4e026d3b9 100644 --- a/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/PIDTest.java +++ b/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/PIDTest.java @@ -1,8 +1,8 @@ /*----------------------------------------------------------------------------*/ -/* Copyright (c) FIRST 2008-2014. All Rights Reserved. */ -/* Open Source Software - may be modified and shared by FRC teams. The code */ +/* Copyright (c) FIRST 2008-2014. All Rights Reserved. */ +/* Open Source Software - may be modified and shared by FRC teams. The code */ /* must be accompanied by the FIRST BSD license file in the root directory of */ -/* the project. */ +/* the project. */ /*----------------------------------------------------------------------------*/ package edu.wpi.first.wpilibj; @@ -41,162 +41,166 @@ import edu.wpi.first.wpilibj.test.TestBench; @RunWith(Parameterized.class) public class PIDTest extends AbstractComsSetup { - private static final Logger logger = Logger.getLogger(PIDTest.class.getName()); - private NetworkTable table; + private static final Logger logger = Logger.getLogger(PIDTest.class.getName()); + private NetworkTable table; - private static final double absoluteTolerance = 50; - private static final double outputRange = 0.3; + private static final double absoluteTolerance = 50; + private static final double outputRange = 0.3; - private PIDController controller = null; - private static MotorEncoderFixture me = null; + private PIDController controller = null; + private static MotorEncoderFixture me = null; - private final Double k_p, k_i, k_d; + private final Double k_p, k_i, k_d; - @Override - protected Logger getClassLogger(){ - return logger; - } + @Override + protected Logger getClassLogger() { + return logger; + } - public PIDTest(Double p, Double i, Double d, MotorEncoderFixture mef){ - logger.fine("Constructor with: " + mef.getType()); - if(PIDTest.me != null && !PIDTest.me.equals(mef)) PIDTest.me.teardown(); - PIDTest.me = mef; - this.k_p = p; - this.k_i = i; - this.k_d = d; - } + public PIDTest(Double p, Double i, Double d, MotorEncoderFixture mef) { + logger.fine("Constructor with: " + mef.getType()); + if (PIDTest.me != null && !PIDTest.me.equals(mef)) + PIDTest.me.teardown(); + PIDTest.me = mef; + this.k_p = p; + this.k_i = i; + this.k_d = d; + } - @Parameters - public static Collection generateData(){ - //logger.fine("Loading the MotorList"); - Collection data = new ArrayList(); - double kp = 0.001; - double ki = 0.0005; - double kd = 0.0; - for(int i = 0; i < 1; i++){ - data.addAll(Arrays.asList(new Object[][]{ - {kp, ki, kd, TestBench.getInstance().getTalonPair()}, - {kp, ki, kd, TestBench.getInstance().getVictorPair()}, - {kp, ki, kd, TestBench.getInstance().getJaguarPair()}})); - } - return data; - } + @Parameters + public static Collection generateData() { + // logger.fine("Loading the MotorList"); + Collection data = new ArrayList(); + double kp = 0.001; + double ki = 0.0005; + double kd = 0.0; + for (int i = 0; i < 1; i++) { + data.addAll(Arrays.asList(new Object[][] { + {kp, ki, kd, TestBench.getInstance().getTalonPair()}, + {kp, ki, kd, TestBench.getInstance().getVictorPair()}, + {kp, ki, kd, TestBench.getInstance().getJaguarPair()}})); + } + return data; + } - /** - * @throws java.lang.Exception - */ - @BeforeClass - public static void setUpBeforeClass() throws Exception { - } + /** + * @throws java.lang.Exception + */ + @BeforeClass + public static void setUpBeforeClass() throws Exception {} - /** - * @throws java.lang.Exception - */ - @AfterClass - public static void tearDownAfterClass() throws Exception { - logger.fine("TearDownAfterClass: " + me.getType()); - me.teardown(); - me=null; - } + /** + * @throws java.lang.Exception + */ + @AfterClass + public static void tearDownAfterClass() throws Exception { + logger.fine("TearDownAfterClass: " + me.getType()); + me.teardown(); + me = null; + } - /** - * @throws java.lang.Exception - */ - @Before - public void setUp() throws Exception { - logger.fine("Setup: " + me.getType()); - me.setup(); - table = NetworkTable.getTable("TEST_PID"); - controller = new PIDController(k_p, k_i, k_d, me.getEncoder(), me.getMotor()); - controller.initTable(table); - } + /** + * @throws java.lang.Exception + */ + @Before + public void setUp() throws Exception { + logger.fine("Setup: " + me.getType()); + me.setup(); + table = NetworkTable.getTable("TEST_PID"); + controller = new PIDController(k_p, k_i, k_d, me.getEncoder(), me.getMotor()); + controller.initTable(table); + } - /** - * @throws java.lang.Exception - */ - @After - public void tearDown() throws Exception { - logger.fine("Teardown: " + me.getType()); - controller.disable(); - controller.free(); - controller = null; - me.reset(); - } + /** + * @throws java.lang.Exception + */ + @After + public void tearDown() throws Exception { + logger.fine("Teardown: " + me.getType()); + controller.disable(); + controller.free(); + controller = null; + me.reset(); + } - private void setupAbsoluteTolerance(){ - controller.setAbsoluteTolerance(absoluteTolerance); - } - private void setupOutputRange(){ - controller.setOutputRange(-outputRange, outputRange); - } + private void setupAbsoluteTolerance() { + controller.setAbsoluteTolerance(absoluteTolerance); + } - @Test - public void testInitialSettings(){ - setupAbsoluteTolerance(); - setupOutputRange(); - double setpoint = 2500.0; - controller.setSetpoint(setpoint); - assertFalse("PID did not begin disabled", controller.isEnable()); - assertEquals("PID.getError() did not start at " + setpoint, setpoint, controller.getError(), 0); - assertEquals(k_p, table.getNumber("p"), 0); - assertEquals(k_i, table.getNumber("i"), 0); - assertEquals(k_d, table.getNumber("d"), 0); - assertEquals(setpoint, table.getNumber("setpoint"), 0); - assertFalse(table.getBoolean("enabled")); - } + private void setupOutputRange() { + controller.setOutputRange(-outputRange, outputRange); + } - @Test - public void testRestartAfterEnable(){ - setupAbsoluteTolerance(); - setupOutputRange(); - double setpoint = 2500.0; - controller.setSetpoint(setpoint); - controller.enable(); - Timer.delay(.5); - assertTrue(table.getBoolean("enabled")); - assertTrue(controller.isEnable()); - assertThat(0.0, is(not(me.getMotor().get()))); - controller.reset(); - assertFalse(table.getBoolean("enabled")); - assertFalse(controller.isEnable()); - assertEquals(0, me.getMotor().get(), 0); - } + @Test + public void testInitialSettings() { + setupAbsoluteTolerance(); + setupOutputRange(); + double setpoint = 2500.0; + controller.setSetpoint(setpoint); + assertFalse("PID did not begin disabled", controller.isEnable()); + assertEquals("PID.getError() did not start at " + setpoint, setpoint, controller.getError(), 0); + assertEquals(k_p, table.getNumber("p"), 0); + assertEquals(k_i, table.getNumber("i"), 0); + assertEquals(k_d, table.getNumber("d"), 0); + assertEquals(setpoint, table.getNumber("setpoint"), 0); + assertFalse(table.getBoolean("enabled")); + } - @Test - public void testSetSetpoint(){ - setupAbsoluteTolerance(); - setupOutputRange(); - Double setpoint = 2500.0; - controller.disable(); - controller.setSetpoint(setpoint); - controller.enable(); - assertEquals("Did not correctly set set-point",setpoint, new Double(controller.getSetpoint())); - } + @Test + public void testRestartAfterEnable() { + setupAbsoluteTolerance(); + setupOutputRange(); + double setpoint = 2500.0; + controller.setSetpoint(setpoint); + controller.enable(); + Timer.delay(.5); + assertTrue(table.getBoolean("enabled")); + assertTrue(controller.isEnable()); + assertThat(0.0, is(not(me.getMotor().get()))); + controller.reset(); + assertFalse(table.getBoolean("enabled")); + assertFalse(controller.isEnable()); + assertEquals(0, me.getMotor().get(), 0); + } - @Test (timeout = 10000) - public void testRotateToTarget() { - setupAbsoluteTolerance(); - setupOutputRange(); - double setpoint = 2500.0; - assertEquals(pidData() + "did not start at 0", 0, controller.get(), 0); - controller.setSetpoint(setpoint); - assertEquals(pidData() +"did not have an error of " + setpoint, setpoint, controller.getError(), 0); - controller.enable(); - Timer.delay(5); - controller.disable(); - assertTrue(pidData() + "Was not on Target. Controller Error: " + controller.getError(), controller.onTarget()); - } + @Test + public void testSetSetpoint() { + setupAbsoluteTolerance(); + setupOutputRange(); + Double setpoint = 2500.0; + controller.disable(); + controller.setSetpoint(setpoint); + controller.enable(); + assertEquals("Did not correctly set set-point", setpoint, new Double(controller.getSetpoint())); + } - private String pidData(){ - return me.getType() + " PID {P:" +controller.getP() + " I:" + controller.getI() + " D:" + controller.getD() +"} "; - } + @Test(timeout = 10000) + public void testRotateToTarget() { + setupAbsoluteTolerance(); + setupOutputRange(); + double setpoint = 2500.0; + assertEquals(pidData() + "did not start at 0", 0, controller.get(), 0); + controller.setSetpoint(setpoint); + assertEquals(pidData() + "did not have an error of " + setpoint, setpoint, + controller.getError(), 0); + controller.enable(); + Timer.delay(5); + controller.disable(); + assertTrue(pidData() + "Was not on Target. Controller Error: " + controller.getError(), + controller.onTarget()); + } + + private String pidData() { + return me.getType() + " PID {P:" + controller.getP() + " I:" + controller.getI() + " D:" + + controller.getD() + "} "; + } - @Test(expected = RuntimeException.class) - public void testOnTargetNoToleranceSet(){ - setupOutputRange(); - controller.onTarget(); - } + @Test(expected = RuntimeException.class) + public void testOnTargetNoToleranceSet() { + setupOutputRange(); + controller.onTarget(); + } } diff --git a/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/PrefrencesTest.java b/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/PrefrencesTest.java index 45d4e147f0..623ee94cf5 100644 --- a/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/PrefrencesTest.java +++ b/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/PrefrencesTest.java @@ -1,8 +1,8 @@ /*----------------------------------------------------------------------------*/ -/* Copyright (c) FIRST 2008-2014. All Rights Reserved. */ -/* Open Source Software - may be modified and shared by FRC teams. The code */ +/* Copyright (c) FIRST 2008-2014. All Rights Reserved. */ +/* Open Source Software - may be modified and shared by FRC teams. The code */ /* must be accompanied by the FIRST BSD license file in the root directory of */ -/* the project. */ +/* the project. */ /*----------------------------------------------------------------------------*/ package edu.wpi.first.wpilibj; @@ -27,96 +27,95 @@ import edu.wpi.first.wpilibj.test.AbstractComsSetup; * */ public class PrefrencesTest extends AbstractComsSetup { - private static final Logger logger = Logger.getLogger(PrefrencesTest.class.getName()); + private static final Logger logger = Logger.getLogger(PrefrencesTest.class.getName()); - private NetworkTable prefTable; - private Preferences pref; - private long check; + private NetworkTable prefTable; + private Preferences pref; + private long check; - @Override - protected Logger getClassLogger(){ - return logger; - } + @Override + protected Logger getClassLogger() { + return logger; + } - /** - * @throws java.lang.Exception - */ - @Before - public void setUp() throws Exception { - try { - File file = new File("/home/lvuser/wpilib-preferences.ini"); - file.mkdirs(); - if (file.exists()) { - file.delete(); - } - file.createNewFile(); - OutputStream output = new FileOutputStream(file); - output.write("checkedValueInt = 2\ncheckedValueDouble = .2\ncheckedValueFloat = 3.14\ncheckedValueLong = 172\ncheckedValueString =\"hello \nHow are you ?\"\ncheckedValueBoolean = false" - .getBytes()); + /** + * @throws java.lang.Exception + */ + @Before + public void setUp() throws Exception { + try { + File file = new File("/home/lvuser/wpilib-preferences.ini"); + file.mkdirs(); + if (file.exists()) { + file.delete(); + } + file.createNewFile(); + OutputStream output = new FileOutputStream(file); + output + .write("checkedValueInt = 2\ncheckedValueDouble = .2\ncheckedValueFloat = 3.14\ncheckedValueLong = 172\ncheckedValueString =\"hello \nHow are you ?\"\ncheckedValueBoolean = false" + .getBytes()); - } catch (IOException e) { - e.printStackTrace(); - } + } catch (IOException e) { + e.printStackTrace(); + } - pref = Preferences.getInstance(); - prefTable = NetworkTable.getTable("Preferences"); - check = System.currentTimeMillis(); - } + pref = Preferences.getInstance(); + prefTable = NetworkTable.getTable("Preferences"); + check = System.currentTimeMillis(); + } - public void remove() { - pref.remove("checkedValueLong"); - pref.remove("checkedValueDouble"); - pref.remove("checkedValueString"); - pref.remove("checkedValueInt"); - pref.remove("checkedValueFloat"); - pref.remove("checkedValueBoolean"); - } + public void remove() { + pref.remove("checkedValueLong"); + pref.remove("checkedValueDouble"); + pref.remove("checkedValueString"); + pref.remove("checkedValueInt"); + pref.remove("checkedValueFloat"); + pref.remove("checkedValueBoolean"); + } - public void addCheckedValue() { - pref.putLong("checkedValueLong", check); - pref.putDouble("checkedValueDouble", 1); - pref.putString("checkedValueString", "checked"); - pref.putInt("checkedValueInt", 1); - pref.putFloat("checkedValueFloat", 1); - pref.putBoolean("checkedValueBoolean", true); - } + public void addCheckedValue() { + pref.putLong("checkedValueLong", check); + pref.putDouble("checkedValueDouble", 1); + pref.putString("checkedValueString", "checked"); + pref.putInt("checkedValueInt", 1); + pref.putFloat("checkedValueFloat", 1); + pref.putBoolean("checkedValueBoolean", true); + } - @Test - public void testAddRemoveSave() { - assertEquals(pref.getLong("checkedValueLong", 0), 172L); - assertEquals(pref.getDouble("checkedValueDouble", 0), .2, 0); - assertEquals(pref.getString("checkedValueString", ""), - "hello \nHow are you ?"); - assertEquals(pref.getInt("checkedValueInt", 0), 2); - assertEquals(pref.getFloat("checkedValueFloat", 0), 3.14, .001); - assertFalse(pref.getBoolean("checkedValueBoolean", true)); - remove(); - assertEquals(pref.getLong("checkedValueLong", 0), 0); - assertEquals(pref.getDouble("checkedValueDouble", 0), 0, 0); - assertEquals(pref.getString("checkedValueString", ""), ""); - assertEquals(pref.getInt("checkedValueInt", 0), 0); - assertEquals(pref.getFloat("checkedValueFloat", 0), 0, 0); - assertFalse(pref.getBoolean("checkedValueBoolean", false)); - addCheckedValue(); - pref.save(); - assertEquals(check, pref.getLong("checkedValueLong", 0)); - assertEquals(pref.getDouble("checkedValueDouble", 0), 1, 0); - assertEquals(pref.getString("checkedValueString", ""), - "checked"); - assertEquals(pref.getInt("checkedValueInt", 0), 1); - assertEquals(pref.getFloat("checkedValueFloat", 0), 1, 0); - assertTrue(pref.getBoolean("checkedValueBoolean", false)); - } + @Test + public void testAddRemoveSave() { + assertEquals(pref.getLong("checkedValueLong", 0), 172L); + assertEquals(pref.getDouble("checkedValueDouble", 0), .2, 0); + assertEquals(pref.getString("checkedValueString", ""), "hello \nHow are you ?"); + assertEquals(pref.getInt("checkedValueInt", 0), 2); + assertEquals(pref.getFloat("checkedValueFloat", 0), 3.14, .001); + assertFalse(pref.getBoolean("checkedValueBoolean", true)); + remove(); + assertEquals(pref.getLong("checkedValueLong", 0), 0); + assertEquals(pref.getDouble("checkedValueDouble", 0), 0, 0); + assertEquals(pref.getString("checkedValueString", ""), ""); + assertEquals(pref.getInt("checkedValueInt", 0), 0); + assertEquals(pref.getFloat("checkedValueFloat", 0), 0, 0); + assertFalse(pref.getBoolean("checkedValueBoolean", false)); + addCheckedValue(); + pref.save(); + assertEquals(check, pref.getLong("checkedValueLong", 0)); + assertEquals(pref.getDouble("checkedValueDouble", 0), 1, 0); + assertEquals(pref.getString("checkedValueString", ""), "checked"); + assertEquals(pref.getInt("checkedValueInt", 0), 1); + assertEquals(pref.getFloat("checkedValueFloat", 0), 1, 0); + assertTrue(pref.getBoolean("checkedValueBoolean", false)); + } - @Test - public void testPreferencesToNetworkTables(){ - String networkedNumber = "networkCheckedValue"; - int networkNumberValue = 100; - pref.putInt(networkedNumber, networkNumberValue); - assertEquals((new Integer(networkNumberValue).toString()), prefTable.getString(networkedNumber)); - pref.remove(networkedNumber); - } + @Test + public void testPreferencesToNetworkTables() { + String networkedNumber = "networkCheckedValue"; + int networkNumberValue = 100; + pref.putInt(networkedNumber, networkNumberValue); + assertEquals((new Integer(networkNumberValue).toString()), prefTable.getString(networkedNumber)); + pref.remove(networkedNumber); + } } diff --git a/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/RelayCrossConnectTest.java b/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/RelayCrossConnectTest.java index 53483158f4..ba5139034b 100644 --- a/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/RelayCrossConnectTest.java +++ b/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/RelayCrossConnectTest.java @@ -1,8 +1,8 @@ /*----------------------------------------------------------------------------*/ -/* Copyright (c) FIRST 2008-2014. All Rights Reserved. */ -/* Open Source Software - may be modified and shared by FRC teams. The code */ +/* Copyright (c) FIRST 2008-2014. All Rights Reserved. */ +/* Open Source Software - may be modified and shared by FRC teams. The code */ /* must be accompanied by the FIRST BSD license file in the root directory of */ -/* the project. */ +/* the project. */ /*----------------------------------------------------------------------------*/ package edu.wpi.first.wpilibj; @@ -31,84 +31,88 @@ import edu.wpi.first.wpilibj.test.TestBench; * */ public class RelayCrossConnectTest extends AbstractComsSetup { - private static final Logger logger = Logger.getLogger(RelayCrossConnectTest.class.getName()); - private static final NetworkTable table = NetworkTable.getTable("_RELAY_CROSS_CONNECT_TEST_"); - private RelayCrossConnectFxiture relayFixture; - - - /** - * @throws java.lang.Exception - */ - @Before - public void setUp() throws Exception { - relayFixture = TestBench.getRelayCrossConnectFixture(); - relayFixture.setup(); - relayFixture.getRelay().initTable(table); - } + private static final Logger logger = Logger.getLogger(RelayCrossConnectTest.class.getName()); + private static final NetworkTable table = NetworkTable.getTable("_RELAY_CROSS_CONNECT_TEST_"); + private RelayCrossConnectFxiture relayFixture; - /** - * @throws java.lang.Exception - */ - @After - public void tearDown() throws Exception { - relayFixture.reset(); - relayFixture.teardown(); - } - @Test - public void testBothHigh() { - relayFixture.getRelay().setDirection(Direction.kBoth); - relayFixture.getRelay().set(Value.kOn); - relayFixture.getRelay().updateTable(); - assertTrue("Input one was not high when relay set both high", relayFixture.getInputOne().get()); - assertTrue("Input two was not high when relay set both high", relayFixture.getInputTwo().get()); - assertEquals("On", table.getString("Value")); - } - - @Test - public void testFirstHigh() { - relayFixture.getRelay().setDirection(Direction.kBoth); - relayFixture.getRelay().set(Value.kForward); - relayFixture.getRelay().updateTable(); - assertFalse("Input one was not low when relay set Value.kForward", relayFixture.getInputOne().get()); - assertTrue("Input two was not high when relay set Value.kForward", relayFixture.getInputTwo().get()); - assertEquals("Forward", table.getString("Value")); - } - - @Test - public void testSecondHigh() { - relayFixture.getRelay().setDirection(Direction.kBoth); - relayFixture.getRelay().set(Value.kReverse); - relayFixture.getRelay().updateTable(); - assertTrue("Input one was not high when relay set Value.kReverse", relayFixture.getInputOne().get()); - assertFalse("Input two was not low when relay set Value.kReverse", relayFixture.getInputTwo().get()); - assertEquals("Reverse", table.getString("Value")); - } - - @Test(expected=InvalidValueException.class) - public void testSetValueForwardWithDirectionReverseThrowingException(){ - relayFixture.getRelay().setDirection(Direction.kForward); - relayFixture.getRelay().set(Value.kReverse); - } - - @Test(expected=InvalidValueException.class) - public void testSetValueReverseWithDirectionForwardThrowingException(){ - relayFixture.getRelay().setDirection(Direction.kReverse); - relayFixture.getRelay().set(Value.kForward); - } - - @Test - public void testInitialSettings(){ - assertEquals(Value.kOff, relayFixture.getRelay().get()); - //Initially both outputs should be off - assertFalse(relayFixture.getInputOne().get()); - assertFalse(relayFixture.getInputTwo().get()); - assertEquals("Off", table.getString("Value")); - } + /** + * @throws java.lang.Exception + */ + @Before + public void setUp() throws Exception { + relayFixture = TestBench.getRelayCrossConnectFixture(); + relayFixture.setup(); + relayFixture.getRelay().initTable(table); + } - @Override - protected Logger getClassLogger() { - return logger; - } + /** + * @throws java.lang.Exception + */ + @After + public void tearDown() throws Exception { + relayFixture.reset(); + relayFixture.teardown(); + } + + @Test + public void testBothHigh() { + relayFixture.getRelay().setDirection(Direction.kBoth); + relayFixture.getRelay().set(Value.kOn); + relayFixture.getRelay().updateTable(); + assertTrue("Input one was not high when relay set both high", relayFixture.getInputOne().get()); + assertTrue("Input two was not high when relay set both high", relayFixture.getInputTwo().get()); + assertEquals("On", table.getString("Value")); + } + + @Test + public void testFirstHigh() { + relayFixture.getRelay().setDirection(Direction.kBoth); + relayFixture.getRelay().set(Value.kForward); + relayFixture.getRelay().updateTable(); + assertFalse("Input one was not low when relay set Value.kForward", relayFixture.getInputOne() + .get()); + assertTrue("Input two was not high when relay set Value.kForward", relayFixture.getInputTwo() + .get()); + assertEquals("Forward", table.getString("Value")); + } + + @Test + public void testSecondHigh() { + relayFixture.getRelay().setDirection(Direction.kBoth); + relayFixture.getRelay().set(Value.kReverse); + relayFixture.getRelay().updateTable(); + assertTrue("Input one was not high when relay set Value.kReverse", relayFixture.getInputOne() + .get()); + assertFalse("Input two was not low when relay set Value.kReverse", relayFixture.getInputTwo() + .get()); + assertEquals("Reverse", table.getString("Value")); + } + + @Test(expected = InvalidValueException.class) + public void testSetValueForwardWithDirectionReverseThrowingException() { + relayFixture.getRelay().setDirection(Direction.kForward); + relayFixture.getRelay().set(Value.kReverse); + } + + @Test(expected = InvalidValueException.class) + public void testSetValueReverseWithDirectionForwardThrowingException() { + relayFixture.getRelay().setDirection(Direction.kReverse); + relayFixture.getRelay().set(Value.kForward); + } + + @Test + public void testInitialSettings() { + assertEquals(Value.kOff, relayFixture.getRelay().get()); + // Initially both outputs should be off + assertFalse(relayFixture.getInputOne().get()); + assertFalse(relayFixture.getInputTwo().get()); + assertEquals("Off", table.getString("Value")); + } + + @Override + protected Logger getClassLogger() { + return logger; + } } diff --git a/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/SampleTest.java b/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/SampleTest.java index 70859c26c2..a37ccc3e15 100644 --- a/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/SampleTest.java +++ b/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/SampleTest.java @@ -1,8 +1,8 @@ /*----------------------------------------------------------------------------*/ -/* Copyright (c) FIRST 2008-2014. All Rights Reserved. */ -/* Open Source Software - may be modified and shared by FRC teams. The code */ +/* Copyright (c) FIRST 2008-2014. All Rights Reserved. */ +/* Open Source Software - may be modified and shared by FRC teams. The code */ /* must be accompanied by the FIRST BSD license file in the root directory of */ -/* the project. */ +/* the project. */ /*----------------------------------------------------------------------------*/ package edu.wpi.first.wpilibj; @@ -24,50 +24,50 @@ import edu.wpi.first.wpilibj.hal.SWIGTYPE_p_UINT8; /** * Sample test for a sample PID controller. This demonstrates the general * pattern of how to create a test and use testing fixtures and categories. - * + *$ * All tests must extend from {@link AbstractComsSetup} in order to ensure that * Network Communications are set up before the tests are run. - * + *$ * @author Fredric Silberberg */ public class SampleTest extends AbstractComsSetup { - private static final Logger logger = Logger.getLogger(SampleTest.class.getName()); + private static final Logger logger = Logger.getLogger(SampleTest.class.getName()); - static SampleFixture fixture = new SampleFixture(); + static SampleFixture fixture = new SampleFixture(); - protected Logger getClassLogger(){ - return logger; - } + protected Logger getClassLogger() { + return logger; + } - @BeforeClass - public static void classSetup() { - // Set up the fixture before the test is created - fixture.setup(); - } + @BeforeClass + public static void classSetup() { + // Set up the fixture before the test is created + fixture.setup(); + } - @Before - public void setUp() { - // Reset the fixture elements before every test - fixture.reset(); - } + @Before + public void setUp() { + // Reset the fixture elements before every test + fixture.reset(); + } - @AfterClass - public static void tearDown() { - // Clean up the fixture after the test - fixture.teardown(); - } + @AfterClass + public static void tearDown() { + // Clean up the fixture after the test + fixture.teardown(); + } - /** - * This is just a sample test that asserts true. Any traditional junit code - * can be used, these are ordinary junit tests! - */ - @Test - public void test() { + /** + * This is just a sample test that asserts true. Any traditional junit code + * can be used, these are ordinary junit tests! + */ + @Test + public void test() { CanTalonSRX cantalon = new CanTalonSRX(); cantalon.Set(0.5); Timer.delay(0.5); cantalon.Set(0.0); - assertTrue(true); - } + assertTrue(true); + } } diff --git a/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/TimerTest.java b/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/TimerTest.java index 2b1e3321f1..e821b3b085 100644 --- a/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/TimerTest.java +++ b/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/TimerTest.java @@ -1,8 +1,8 @@ /*----------------------------------------------------------------------------*/ -/* Copyright (c) FIRST 2008-2014. All Rights Reserved. */ -/* Open Source Software - may be modified and shared by FRC teams. The code */ +/* Copyright (c) FIRST 2008-2014. All Rights Reserved. */ +/* Open Source Software - may be modified and shared by FRC teams. The code */ /* must be accompanied by the FIRST BSD license file in the root directory of */ -/* the project. */ +/* the project. */ /*----------------------------------------------------------------------------*/ package edu.wpi.first.wpilibj; @@ -16,28 +16,29 @@ import edu.wpi.first.wpilibj.test.AbstractComsSetup; public class TimerTest extends AbstractComsSetup { - private static final Logger logger = Logger.getLogger(TimerTest.class.getName()); - private static final long TIMER_TOLERANCE = (long) (2.5 * 1000); - private static final long TIMER_RUNTIME = 5 * 1000000; + private static final Logger logger = Logger.getLogger(TimerTest.class.getName()); + private static final long TIMER_TOLERANCE = (long) (2.5 * 1000); + private static final long TIMER_RUNTIME = 5 * 1000000; - @Override - protected Logger getClassLogger(){ - return logger; - } + @Override + protected Logger getClassLogger() { + return logger; + } - @Test - public void delayTest(){ - //Given - long startTime = Utility.getFPGATime(); + @Test + public void delayTest() { + // Given + long startTime = Utility.getFPGATime(); - //When - Timer.delay(TIMER_RUNTIME/1000000); - long endTime = Utility.getFPGATime(); - long difference = endTime - startTime; + // When + Timer.delay(TIMER_RUNTIME / 1000000); + long endTime = Utility.getFPGATime(); + long difference = endTime - startTime; - //Then - long offset = difference - TIMER_RUNTIME; - assertEquals("Timer.delay ran " + offset + " microseconds too long", TIMER_RUNTIME, difference, TIMER_TOLERANCE); - } + // Then + long offset = difference - TIMER_RUNTIME; + assertEquals("Timer.delay ran " + offset + " microseconds too long", TIMER_RUNTIME, difference, + TIMER_TOLERANCE); + } } diff --git a/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/WpiLibJTestSuite.java b/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/WpiLibJTestSuite.java index 8df03a4c87..063f067647 100644 --- a/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/WpiLibJTestSuite.java +++ b/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/WpiLibJTestSuite.java @@ -1,8 +1,8 @@ /*----------------------------------------------------------------------------*/ -/* Copyright (c) FIRST 2008-2014. All Rights Reserved. */ -/* Open Source Software - may be modified and shared by FRC teams. The code */ +/* Copyright (c) FIRST 2008-2014. All Rights Reserved. */ +/* Open Source Software - may be modified and shared by FRC teams. The code */ /* must be accompanied by the FIRST BSD license file in the root directory of */ -/* the project. */ +/* the project. */ /*----------------------------------------------------------------------------*/ package edu.wpi.first.wpilibj; @@ -13,29 +13,15 @@ import org.junit.runners.Suite.SuiteClasses; import edu.wpi.first.wpilibj.test.AbstractTestSuite; /** - * @author Jonathan Leitschuh - * Holds all of the tests in the root wpilibj directory - * Please list alphabetically so that it is easy to determine if a test is missing from the list + * @author Jonathan Leitschuh Holds all of the tests in the root wpilibj + * directory Please list alphabetically so that it is easy to determine + * if a test is missing from the list */ @RunWith(Suite.class) -@SuiteClasses({ - AnalogCrossConnectTest.class, - AnalogPotentiometerTest.class, - BuiltInAccelerometerTest.class, - CANTalonTest.class, - CounterTest.class, - DIOCrossConnectTest.class, - EncoderTest.class, - GyroTest.class, - MotorEncoderTest.class, - MotorInvertingTest.class, - PCMTest.class, - PDPTest.class, - PIDTest.class, - PrefrencesTest.class, - RelayCrossConnectTest.class, - SampleTest.class, - TimerTest.class - }) +@SuiteClasses({AnalogCrossConnectTest.class, AnalogPotentiometerTest.class, + BuiltInAccelerometerTest.class, CANTalonTest.class, CounterTest.class, + DIOCrossConnectTest.class, EncoderTest.class, GyroTest.class, MotorEncoderTest.class, + MotorInvertingTest.class, PCMTest.class, PDPTest.class, PIDTest.class, PrefrencesTest.class, + RelayCrossConnectTest.class, SampleTest.class, TimerTest.class}) public class WpiLibJTestSuite extends AbstractTestSuite { } diff --git a/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/can/AbstractCANTest.java b/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/can/AbstractCANTest.java index bbf16501d3..15c5417416 100644 --- a/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/can/AbstractCANTest.java +++ b/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/can/AbstractCANTest.java @@ -1,8 +1,8 @@ /*----------------------------------------------------------------------------*/ -/* Copyright (c) FIRST 2008-2014. All Rights Reserved. */ -/* Open Source Software - may be modified and shared by FRC teams. The code */ +/* Copyright (c) FIRST 2008-2014. All Rights Reserved. */ +/* Open Source Software - may be modified and shared by FRC teams. The code */ /* must be accompanied by the FIRST BSD license file in the root directory of */ -/* the project. */ +/* the project. */ /*----------------------------------------------------------------------------*/ package edu.wpi.first.wpilibj.can; @@ -17,81 +17,92 @@ import edu.wpi.first.wpilibj.test.AbstractComsSetup; import edu.wpi.first.wpilibj.test.TestBench; /** - * Provides a base implementation for CAN Tests that forces a test of a particular mode to provide tests of a certain type. - * This also allows for a standardized base setup for each test. + * Provides a base implementation for CAN Tests that forces a test of a + * particular mode to provide tests of a certain type. This also allows for a + * standardized base setup for each test. + *$ * @author jonathanleitschuh * */ -public abstract class AbstractCANTest extends AbstractComsSetup{ - public static final double kMotorStopTime = 2; - public static final double kMotorTime = 3; - public static final double kMotorTimeSettling = 10; - public static final double kPotentiometerSettlingTime = 10.0; - public static final double kEncoderSettlingTime = 0.50; - public static final double kEncoderSpeedTolerance = 20.0; - public static final double kLimitSettlingTime = 20.0; //timeout in seconds - public static final double kStartupTime = 0.50; - public static final double kEncoderPositionTolerance = .75; - public static final double kPotentiometerPositionTolerance = 10.0/360.0; // +/-10 degrees - public static final double kCurrentTolerance = 0.1; - - - /** Stores the status value for the previous test. This is set immediately after a failure or success and before the me is torn down. */ - private String status = ""; - /** - * Extends the default test watcher in order to provide more information about a tests failure at runtime. - * @author jonathanleitschuh - * - */ - public class CANTestWatcher extends DefaultTestWatcher{ - @Override - protected void failed(Throwable e, Description description) { - super.failed(e, description, status); - } - } - @Override - protected TestWatcher getOverridenTestWatcher(){ - return new CANTestWatcher(); - } - - /** The Fixture under test */ - private CANMotorEncoderFixture me; - - /** - * Retrieves the CANMotorEncoderFixture - * @return the CANMotorEncoderFixture for this test. - */ - public CANMotorEncoderFixture getME(){ - return me; - } - - /** - * This runs BEFORE the setup of the inherited class - */ - @Before - public final void preSetup(){ - status = ""; - me = TestBench.getInstance().getCanJaguarPair(); - me.setup(); - me.getMotor().setSafetyEnabled(false); - } - - @After - public final void tearDown() throws Exception { - try{ - //Stores the status data before tearing it down. - //If the test fails unexpectedly then this could cause an exception. - status = me.printStatus(); - } finally{ - me.teardown(); - } - me = null; - } - - protected void setCANJaguar(double seconds, double value){ - for(int i = 0; i < 50; i++) { - getME().getMotor().set(value); - Timer.delay(seconds / 50.0); - } - } -} \ No newline at end of file +public abstract class AbstractCANTest extends AbstractComsSetup { + public static final double kMotorStopTime = 2; + public static final double kMotorTime = 3; + public static final double kMotorTimeSettling = 10; + public static final double kPotentiometerSettlingTime = 10.0; + public static final double kEncoderSettlingTime = 0.50; + public static final double kEncoderSpeedTolerance = 20.0; + public static final double kLimitSettlingTime = 20.0; // timeout in seconds + public static final double kStartupTime = 0.50; + public static final double kEncoderPositionTolerance = .75; + public static final double kPotentiometerPositionTolerance = 10.0 / 360.0; // +/-10 + // degrees + public static final double kCurrentTolerance = 0.1; + + + /** + * Stores the status value for the previous test. This is set immediately + * after a failure or success and before the me is torn down. + */ + private String status = ""; + + /** + * Extends the default test watcher in order to provide more information about + * a tests failure at runtime. + *$ + * @author jonathanleitschuh + * + */ + public class CANTestWatcher extends DefaultTestWatcher { + @Override + protected void failed(Throwable e, Description description) { + super.failed(e, description, status); + } + } + + @Override + protected TestWatcher getOverridenTestWatcher() { + return new CANTestWatcher(); + } + + /** The Fixture under test */ + private CANMotorEncoderFixture me; + + /** + * Retrieves the CANMotorEncoderFixture + *$ + * @return the CANMotorEncoderFixture for this test. + */ + public CANMotorEncoderFixture getME() { + return me; + } + + /** + * This runs BEFORE the setup of the inherited class + */ + @Before + public final void preSetup() { + status = ""; + me = TestBench.getInstance().getCanJaguarPair(); + me.setup(); + me.getMotor().setSafetyEnabled(false); + } + + @After + public final void tearDown() throws Exception { + try { + // Stores the status data before tearing it down. + // If the test fails unexpectedly then this could cause an exception. + status = me.printStatus(); + } finally { + me.teardown(); + } + me = null; + } + + protected void setCANJaguar(double seconds, double value) { + for (int i = 0; i < 50; i++) { + getME().getMotor().set(value); + Timer.delay(seconds / 50.0); + } + } +} diff --git a/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/can/CANCurrentQuadEncoderModeTest.java b/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/can/CANCurrentQuadEncoderModeTest.java index 61550a3c5b..cfda635b0a 100644 --- a/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/can/CANCurrentQuadEncoderModeTest.java +++ b/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/can/CANCurrentQuadEncoderModeTest.java @@ -1,8 +1,8 @@ /*----------------------------------------------------------------------------*/ -/* Copyright (c) FIRST 2008-2014. All Rights Reserved. */ -/* Open Source Software - may be modified and shared by FRC teams. The code */ +/* Copyright (c) FIRST 2008-2014. All Rights Reserved. */ +/* Open Source Software - may be modified and shared by FRC teams. The code */ /* must be accompanied by the FIRST BSD license file in the root directory of */ -/* the project. */ +/* the project. */ /*----------------------------------------------------------------------------*/ package edu.wpi.first.wpilibj.can; @@ -22,78 +22,86 @@ import edu.wpi.first.wpilibj.Timer; * */ public class CANCurrentQuadEncoderModeTest extends AbstractCANTest { - private static Logger logger = Logger.getLogger(CANCurrentQuadEncoderModeTest.class.getName()); - private static final double kStoppedValue = 0; - private static final double kRunningValue = 3.0; + private static Logger logger = Logger.getLogger(CANCurrentQuadEncoderModeTest.class.getName()); + private static final double kStoppedValue = 0; + private static final double kRunningValue = 3.0; - /* (non-Javadoc) - * @see edu.wpi.first.wpilibj.can.AbstractCANTest#stopMotor() - */ - protected void stopMotor() { - getME().getMotor().set(kStoppedValue); - } + /* + * (non-Javadoc) + *$ + * @see edu.wpi.first.wpilibj.can.AbstractCANTest#stopMotor() + */ + protected void stopMotor() { + getME().getMotor().set(kStoppedValue); + } - /* (non-Javadoc) - * @see edu.wpi.first.wpilibj.can.AbstractCANTest#runMotorForward() - */ - protected void runMotorForward() { - getME().getMotor().set(kRunningValue); - } + /* + * (non-Javadoc) + *$ + * @see edu.wpi.first.wpilibj.can.AbstractCANTest#runMotorForward() + */ + protected void runMotorForward() { + getME().getMotor().set(kRunningValue); + } - /* (non-Javadoc) - * @see edu.wpi.first.wpilibj.can.AbstractCANTest#runMotorReverse() - */ - protected void runMotorReverse() { - getME().getMotor().set(-kRunningValue); - } + /* + * (non-Javadoc) + *$ + * @see edu.wpi.first.wpilibj.can.AbstractCANTest#runMotorReverse() + */ + protected void runMotorReverse() { + getME().getMotor().set(-kRunningValue); + } - @Override - protected Logger getClassLogger() { - return logger; - } + @Override + protected Logger getClassLogger() { + return logger; + } - @Before - public void setUp() throws Exception { - getME().getMotor().setCurrentMode(CANJaguar.kQuadEncoder, 360, 10.0, 4.0, 1.0); - getME().getMotor().enableControl(); - getME().getMotor().set(0.0f); - /* The motor might still have momentum from the previous test. */ - Timer.delay(kStartupTime); - } + @Before + public void setUp() throws Exception { + getME().getMotor().setCurrentMode(CANJaguar.kQuadEncoder, 360, 10.0, 4.0, 1.0); + getME().getMotor().enableControl(); + getME().getMotor().set(0.0f); + /* The motor might still have momentum from the previous test. */ + Timer.delay(kStartupTime); + } - @Ignore - @Test - public void testDriveToCurrentPositive() { - double setpoint = 1.6f; + @Ignore + @Test + public void testDriveToCurrentPositive() { + double setpoint = 1.6f; - /* It should get to the setpoint within 10 seconds */ - for(int i = 0; i < 10; i++) { - setCANJaguar(1.0, setpoint); + /* It should get to the setpoint within 10 seconds */ + for (int i = 0; i < 10; i++) { + setCANJaguar(1.0, setpoint); - if(Math.abs(getME().getMotor().getOutputCurrent() - setpoint) <= kCurrentTolerance) { - break; - } - } + if (Math.abs(getME().getMotor().getOutputCurrent() - setpoint) <= kCurrentTolerance) { + break; + } + } - assertEquals("The desired output current was not reached",setpoint, getME().getMotor().getOutputCurrent(), kCurrentTolerance); - } + assertEquals("The desired output current was not reached", setpoint, getME().getMotor() + .getOutputCurrent(), kCurrentTolerance); + } - @Ignore - @Test - public void testDriveToCurrentNegative() { - double setpoint = -1.6f; + @Ignore + @Test + public void testDriveToCurrentNegative() { + double setpoint = -1.6f; - /* It should get to the setpoint within 10 seconds */ - for(int i = 0; i < 10; i++) { - setCANJaguar(1.0, setpoint); + /* It should get to the setpoint within 10 seconds */ + for (int i = 0; i < 10; i++) { + setCANJaguar(1.0, setpoint); - if(Math.abs(getME().getMotor().getOutputCurrent() - Math.abs(setpoint)) <= kCurrentTolerance) { - break; - } - } + if (Math.abs(getME().getMotor().getOutputCurrent() - Math.abs(setpoint)) <= kCurrentTolerance) { + break; + } + } - assertEquals("The desired output current was not reached", Math.abs(setpoint), getME().getMotor().getOutputCurrent(), kCurrentTolerance); - } + assertEquals("The desired output current was not reached", Math.abs(setpoint), getME() + .getMotor().getOutputCurrent(), kCurrentTolerance); + } } diff --git a/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/can/CANDefaultTest.java b/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/can/CANDefaultTest.java index 51b00ed59c..54524c3ee0 100644 --- a/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/can/CANDefaultTest.java +++ b/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/can/CANDefaultTest.java @@ -1,8 +1,8 @@ /*----------------------------------------------------------------------------*/ -/* Copyright (c) FIRST 2008-2014. All Rights Reserved. */ -/* Open Source Software - may be modified and shared by FRC teams. The code */ +/* Copyright (c) FIRST 2008-2014. All Rights Reserved. */ +/* Open Source Software - may be modified and shared by FRC teams. The code */ /* must be accompanied by the FIRST BSD license file in the root directory of */ -/* the project. */ +/* the project. */ /*----------------------------------------------------------------------------*/ package edu.wpi.first.wpilibj.can; @@ -29,186 +29,205 @@ import edu.wpi.first.wpilibj.Timer; * @author jonathanleitschuh * */ -public class CANDefaultTest extends AbstractCANTest{ - private static final Logger logger = Logger.getLogger(CANDefaultTest.class.getName()); - private final PollingWait wait = new PollingWait().timeoutAfter(65, TimeUnit.MILLISECONDS).pollEvery(10, TimeUnit.MILLISECONDS); +public class CANDefaultTest extends AbstractCANTest { + private static final Logger logger = Logger.getLogger(CANDefaultTest.class.getName()); + private final PollingWait wait = new PollingWait().timeoutAfter(65, TimeUnit.MILLISECONDS) + .pollEvery(10, TimeUnit.MILLISECONDS); - private static final double kSpikeTime = .5; + private static final double kSpikeTime = .5; - @Override - protected Logger getClassLogger() { - return logger; - } + @Override + protected Logger getClassLogger() { + return logger; + } - /** - * @throws java.lang.Exception - */ - @Before - public void setUp() throws Exception { - getME().getMotor().enableControl(); - getME().getMotor().set(0.0f); - /* The motor might still have momentum from the previous test. */ - Timer.delay(kStartupTime/2); - } + /** + * @throws java.lang.Exception + */ + @Before + public void setUp() throws Exception { + getME().getMotor().enableControl(); + getME().getMotor().set(0.0f); + /* The motor might still have momentum from the previous test. */ + Timer.delay(kStartupTime / 2); + } - @Test - public void testDefaultGet(){ - wait.until(new RunnableAssert("Waiting for CAN Jaguar get to return 0") { - @Override - public void run() { - assertEquals("CAN Jaguar did not initialize stopped", 0.0, getME().getMotor().get(), .01f); - } - }); - } + @Test + public void testDefaultGet() { + wait.until(new RunnableAssert("Waiting for CAN Jaguar get to return 0") { + @Override + public void run() { + assertEquals("CAN Jaguar did not initialize stopped", 0.0, getME().getMotor().get(), .01f); + } + }); + } - @Test - public void testDefaultBusVoltage(){ - wait.until(new RunnableAssert("Waiting for default bus voltage to be correct") { - @Override - public void run() { - assertEquals("CAN Jaguar did not start at 14 volts", 14.0f, getME().getMotor().getBusVoltage(), 2.0f); - } - }); - } + @Test + public void testDefaultBusVoltage() { + wait.until(new RunnableAssert("Waiting for default bus voltage to be correct") { + @Override + public void run() { + assertEquals("CAN Jaguar did not start at 14 volts", 14.0f, getME().getMotor() + .getBusVoltage(), 2.0f); + } + }); + } - @Test - public void testDefaultOutputVoltage(){ - wait.until(new RunnableAssert("Waiting for output voltage to be correct") { - @Override - public void run() { - assertEquals("CAN Jaguar did not start with an output voltage of 0", 0.0f, getME().getMotor().getOutputVoltage(), 0.3f); - } - }); - } + @Test + public void testDefaultOutputVoltage() { + wait.until(new RunnableAssert("Waiting for output voltage to be correct") { + @Override + public void run() { + assertEquals("CAN Jaguar did not start with an output voltage of 0", 0.0f, getME() + .getMotor().getOutputVoltage(), 0.3f); + } + }); + } - @Test - public void testDefaultOutputCurrent(){ - wait.until(new RunnableAssert("Waiting for output current to be correct") { - @Override - public void run() { - assertEquals("CAN Jaguar did not start with an output current of 0", 0.0f, getME().getMotor().getOutputCurrent(), 0.3f); - } - }); - } + @Test + public void testDefaultOutputCurrent() { + wait.until(new RunnableAssert("Waiting for output current to be correct") { + @Override + public void run() { + assertEquals("CAN Jaguar did not start with an output current of 0", 0.0f, getME() + .getMotor().getOutputCurrent(), 0.3f); + } + }); + } - @Test - public void testDefaultTemperature(){ - final double room_temp = 18.0f; - wait.until(new RunnableAssert("Waiting for temperature to be correct") { - @Override - public void run() { - assertThat("CAN Jaguar did not start with an initial temperature greater than " + room_temp, getME().getMotor().getTemperature(), is(greaterThan(room_temp))); - } - }); - } + @Test + public void testDefaultTemperature() { + final double room_temp = 18.0f; + wait.until(new RunnableAssert("Waiting for temperature to be correct") { + @Override + public void run() { + assertThat( + "CAN Jaguar did not start with an initial temperature greater than " + room_temp, + getME().getMotor().getTemperature(), is(greaterThan(room_temp))); + } + }); + } - @Test - public void testDefaultForwardLimit(){ - getME().getMotor().configLimitMode(CANJaguar.LimitMode.SwitchInputsOnly); - wait.until(new RunnableAssert("Waiting for forward limit to not be set") { - @Override - public void run() { - getME().getMotor().set(0); - assertTrue("CAN Jaguar did not start with the Forward Limit Switch Off", getME().getMotor().getForwardLimitOK()); - } - }); - } + @Test + public void testDefaultForwardLimit() { + getME().getMotor().configLimitMode(CANJaguar.LimitMode.SwitchInputsOnly); + wait.until(new RunnableAssert("Waiting for forward limit to not be set") { + @Override + public void run() { + getME().getMotor().set(0); + assertTrue("CAN Jaguar did not start with the Forward Limit Switch Off", getME().getMotor() + .getForwardLimitOK()); + } + }); + } - @Test - public void testDefaultReverseLimit(){ - getME().getMotor().configLimitMode(CANJaguar.LimitMode.SwitchInputsOnly); - wait.until(new RunnableAssert("Waiting for reverse limit to not be set") { - @Override - public void run() { - getME().getMotor().set(0); - assertTrue("CAN Jaguar did not start with the Reverse Limit Switch Off", getME().getMotor().getReverseLimitOK()); - } - }); - } + @Test + public void testDefaultReverseLimit() { + getME().getMotor().configLimitMode(CANJaguar.LimitMode.SwitchInputsOnly); + wait.until(new RunnableAssert("Waiting for reverse limit to not be set") { + @Override + public void run() { + getME().getMotor().set(0); + assertTrue("CAN Jaguar did not start with the Reverse Limit Switch Off", getME().getMotor() + .getReverseLimitOK()); + } + }); + } - @Test - public void testDefaultNoFaults(){ - wait.until(new RunnableAssert("Waiting for no faults") { - @Override - public void run() { - assertEquals("CAN Jaguar initialized with Faults", 0, getME().getMotor().getFaults()); - } - }); - } + @Test + public void testDefaultNoFaults() { + wait.until(new RunnableAssert("Waiting for no faults") { + @Override + public void run() { + assertEquals("CAN Jaguar initialized with Faults", 0, getME().getMotor().getFaults()); + } + }); + } - @Test - public void testFakeLimitSwitchForwards() { - //Given - getME().getMotor().configLimitMode(CANJaguar.LimitMode.SwitchInputsOnly); - getME().getMotor().enableControl(); + @Test + public void testFakeLimitSwitchForwards() { + // Given + getME().getMotor().configLimitMode(CANJaguar.LimitMode.SwitchInputsOnly); + getME().getMotor().enableControl(); - //When - getME().getForwardLimit().set(true); + // When + getME().getForwardLimit().set(true); - //Then - PollingWait wait = new PollingWait().timeoutAfter((long)kLimitSettlingTime, TimeUnit.SECONDS).pollEvery(1, TimeUnit.MILLISECONDS); - wait.until(new RunnableAssert("Setting the CANJAguar forward limit switch high") { - @Override - public void run() throws Exception { - getME().getMotor().set(0); - assertFalse("Setting the forward limit switch high did not cause the forward limit switch to trigger", getME().getMotor().getForwardLimitOK()); - } - }); - } + // Then + PollingWait wait = + new PollingWait().timeoutAfter((long) kLimitSettlingTime, TimeUnit.SECONDS).pollEvery(1, + TimeUnit.MILLISECONDS); + wait.until(new RunnableAssert("Setting the CANJAguar forward limit switch high") { + @Override + public void run() throws Exception { + getME().getMotor().set(0); + assertFalse( + "Setting the forward limit switch high did not cause the forward limit switch to trigger", + getME().getMotor().getForwardLimitOK()); + } + }); + } - @Test - public void testFakeLimitSwitchReverse() { - //Given - getME().getMotor().configLimitMode(CANJaguar.LimitMode.SwitchInputsOnly); - getME().getMotor().enableControl(); - - //When - getME().getReverseLimit().set(true); + @Test + public void testFakeLimitSwitchReverse() { + // Given + getME().getMotor().configLimitMode(CANJaguar.LimitMode.SwitchInputsOnly); + getME().getMotor().enableControl(); - //Then - PollingWait wait = new PollingWait().timeoutAfter((long)kLimitSettlingTime, TimeUnit.SECONDS).pollEvery(1, TimeUnit.MILLISECONDS); - wait.until(new RunnableAssert("Setting the CANJAguar reverse limit switch high") { - @Override - public void run() throws Exception { - getME().getMotor().set(0); - assertFalse("Setting the reverse limit switch high did not cause the forward limit switch to trigger", getME().getMotor().getReverseLimitOK()); - } - }); - } - - @Test - public void testPositionModeVerifiesOnBrownOut() { - final double setpoint = 1.0; + // When + getME().getReverseLimit().set(true); - //Given - getME().getMotor().setPositionMode(CANJaguar.kQuadEncoder, 360, 10.0, 0.1, 0.0); - getME().getMotor().enableControl(); - setCANJaguar(kMotorTime, 0.0); + // Then + PollingWait wait = + new PollingWait().timeoutAfter((long) kLimitSettlingTime, TimeUnit.SECONDS).pollEvery(1, + TimeUnit.MILLISECONDS); + wait.until(new RunnableAssert("Setting the CANJAguar reverse limit switch high") { + @Override + public void run() throws Exception { + getME().getMotor().set(0); + assertFalse( + "Setting the reverse limit switch high did not cause the forward limit switch to trigger", + getME().getMotor().getReverseLimitOK()); + } + }); + } - getME().powerOn(); + @Test + public void testPositionModeVerifiesOnBrownOut() { + final double setpoint = 1.0; - //When - /* Turn the spike off and on again */ + // Given + getME().getMotor().setPositionMode(CANJaguar.kQuadEncoder, 360, 10.0, 0.1, 0.0); + getME().getMotor().enableControl(); + setCANJaguar(kMotorTime, 0.0); - getME().powerOff(); - Timer.delay(kSpikeTime); - getME().powerOn(); - Timer.delay(kSpikeTime); + getME().powerOn(); - PollingWait wait = new PollingWait().timeoutAfter(15, TimeUnit.SECONDS).pollEvery(1, TimeUnit.MILLISECONDS); - /* The jaguar should automatically get set to quad encoder position mode, - so it should be able to reach a setpoint in a couple seconds. */ + // When + /* Turn the spike off and on again */ - wait.until(new RunnableAssert("Waiting for CANJaguar to reach set-point") { - @Override - public void run() throws Exception { - getME().getMotor().set(setpoint); - assertEquals("CANJaguar should have resumed PID control after power cycle", - setpoint, getME().getMotor().getPosition(), kEncoderPositionTolerance); - } - }); - } + getME().powerOff(); + Timer.delay(kSpikeTime); + getME().powerOn(); + Timer.delay(kSpikeTime); + + PollingWait wait = + new PollingWait().timeoutAfter(15, TimeUnit.SECONDS).pollEvery(1, TimeUnit.MILLISECONDS); + /* + * The jaguar should automatically get set to quad encoder position mode, so + * it should be able to reach a setpoint in a couple seconds. + */ + + wait.until(new RunnableAssert("Waiting for CANJaguar to reach set-point") { + @Override + public void run() throws Exception { + getME().getMotor().set(setpoint); + assertEquals("CANJaguar should have resumed PID control after power cycle", setpoint, + getME().getMotor().getPosition(), kEncoderPositionTolerance); + } + }); + } } diff --git a/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/can/CANJaguarInversionTest.java b/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/can/CANJaguarInversionTest.java index e788c3be65..4f05885d57 100644 --- a/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/can/CANJaguarInversionTest.java +++ b/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/can/CANJaguarInversionTest.java @@ -9,67 +9,70 @@ import java.util.logging.Logger; /** * Created by Patrick Murphy on 3/30/15. */ -public class CANJaguarInversionTest extends AbstractCANTest{ - private static final Logger logger = Logger.getLogger(CANJaguarInversionTest.class.getName()); - private static final double motorVoltage = 5.0; - private static final double motorPercent = 0.5; - private static final double motorSpeed = 100; - private static final double delayTime = 0.75; - private static final double speedModeDelayTime = 2.0; - @Override - protected Logger getClassLogger() { - return logger; - } - @Test - public void testInvertingVoltageMode(){ - getME().getMotor().setVoltageMode(CANJaguar.kQuadEncoder, 360); - InversionTest(motorVoltage, delayTime); - } - @Test - public void testInvertingPercentMode(){ - getME().getMotor().setPercentMode(CANJaguar.kQuadEncoder, 360); - InversionTest(motorPercent, delayTime); - } - @Test - public void testInvertingSpeedMode(){ - getME().getMotor().setSpeedMode(CANJaguar.kQuadEncoder, 360, 0.1, 0.003, 0.01); - InversionTest(motorSpeed, speedModeDelayTime); - } - /** - * Runs an inversion test - * To use set the jaguar to the proper mode(PercentVbus, voltage, speed) - * @param setpoint the speed/voltage/percent to set the motor to - * @param delayTime the amount of time to delay between starting a motor and checking the encoder - */ - private void InversionTest(double setpoint, double delayTime) { - CANJaguar jag = this.getME().getMotor(); - jag.enableControl(); - jag.setInverted(false); - jag.set(setpoint); - Timer.delay(delayTime); - double initialSpeed = jag.getSpeed(); - jag.set(0.0); - jag.setInverted(true); - jag.set(setpoint); - Timer.delay(delayTime); - jag.set(0.0); - double finalSpeed = jag.getSpeed(); - assertTrue("Inverting with Positive value does not invert direction", - Math.signum(initialSpeed)!= - Math.signum(finalSpeed) - ); - jag.set(-setpoint); - Timer.delay(delayTime); - initialSpeed = jag.getSpeed(); - jag.set(0.0); - jag.setInverted(false); - jag.set(-setpoint); - Timer.delay(delayTime); - finalSpeed = jag.getSpeed(); - jag.set(0.0); - assertTrue("Inverting with Negative value does not invert direction", - Math.signum(initialSpeed)!= - Math.signum(finalSpeed) - ); - } +public class CANJaguarInversionTest extends AbstractCANTest { + private static final Logger logger = Logger.getLogger(CANJaguarInversionTest.class.getName()); + private static final double motorVoltage = 5.0; + private static final double motorPercent = 0.5; + private static final double motorSpeed = 100; + private static final double delayTime = 0.75; + private static final double speedModeDelayTime = 2.0; + + @Override + protected Logger getClassLogger() { + return logger; + } + + @Test + public void testInvertingVoltageMode() { + getME().getMotor().setVoltageMode(CANJaguar.kQuadEncoder, 360); + InversionTest(motorVoltage, delayTime); + } + + @Test + public void testInvertingPercentMode() { + getME().getMotor().setPercentMode(CANJaguar.kQuadEncoder, 360); + InversionTest(motorPercent, delayTime); + } + + @Test + public void testInvertingSpeedMode() { + getME().getMotor().setSpeedMode(CANJaguar.kQuadEncoder, 360, 0.1, 0.003, 0.01); + InversionTest(motorSpeed, speedModeDelayTime); + } + + /** + * Runs an inversion test To use set the jaguar to the proper + * mode(PercentVbus, voltage, speed) + *$ + * @param setpoint the speed/voltage/percent to set the motor to + * @param delayTime the amount of time to delay between starting a motor and + * checking the encoder + */ + private void InversionTest(double setpoint, double delayTime) { + CANJaguar jag = this.getME().getMotor(); + jag.enableControl(); + jag.setInverted(false); + jag.set(setpoint); + Timer.delay(delayTime); + double initialSpeed = jag.getSpeed(); + jag.set(0.0); + jag.setInverted(true); + jag.set(setpoint); + Timer.delay(delayTime); + jag.set(0.0); + double finalSpeed = jag.getSpeed(); + assertTrue("Inverting with Positive value does not invert direction", + Math.signum(initialSpeed) != Math.signum(finalSpeed)); + jag.set(-setpoint); + Timer.delay(delayTime); + initialSpeed = jag.getSpeed(); + jag.set(0.0); + jag.setInverted(false); + jag.set(-setpoint); + Timer.delay(delayTime); + finalSpeed = jag.getSpeed(); + jag.set(0.0); + assertTrue("Inverting with Negative value does not invert direction", + Math.signum(initialSpeed) != Math.signum(finalSpeed)); + } } diff --git a/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/can/CANPercentQuadEncoderModeTest.java b/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/can/CANPercentQuadEncoderModeTest.java index 3360d04279..146f255c5f 100644 --- a/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/can/CANPercentQuadEncoderModeTest.java +++ b/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/can/CANPercentQuadEncoderModeTest.java @@ -1,8 +1,8 @@ /*----------------------------------------------------------------------------*/ -/* Copyright (c) FIRST 2008-2014. All Rights Reserved. */ -/* Open Source Software - may be modified and shared by FRC teams. The code */ +/* Copyright (c) FIRST 2008-2014. All Rights Reserved. */ +/* Open Source Software - may be modified and shared by FRC teams. The code */ /* must be accompanied by the FIRST BSD license file in the root directory of */ -/* the project. */ +/* the project. */ /*----------------------------------------------------------------------------*/ package edu.wpi.first.wpilibj.can; @@ -32,320 +32,368 @@ import edu.wpi.first.wpilibj.Timer; * @author jonathanleitschuh * */ -public class CANPercentQuadEncoderModeTest extends AbstractCANTest{ - private static final Logger logger = Logger.getLogger(CANPercentQuadEncoderModeTest.class.getName()); - private static final double kStoppedValue = 0; - private static final double kRunningValue = 1; - - /* (non-Javadoc) - * @see edu.wpi.first.wpilibj.can.AbstractCANTest#stopMotor() +public class CANPercentQuadEncoderModeTest extends AbstractCANTest { + private static final Logger logger = Logger.getLogger(CANPercentQuadEncoderModeTest.class + .getName()); + private static final double kStoppedValue = 0; + private static final double kRunningValue = 1; + + /* + * (non-Javadoc) + *$ + * @see edu.wpi.first.wpilibj.can.AbstractCANTest#stopMotor() + */ + protected void stopMotor() { + getME().getMotor().set(kStoppedValue); + } + + /* + * (non-Javadoc) + *$ + * @see edu.wpi.first.wpilibj.can.AbstractCANTest#runMotorForward() + */ + protected void runMotorForward() { + getME().getMotor().set(kRunningValue); + } + + /* + * (non-Javadoc) + *$ + * @see edu.wpi.first.wpilibj.can.AbstractCANTest#runMotorReverse() + */ + protected void runMotorReverse() { + getME().getMotor().set(-kRunningValue); + } + + @Override + protected Logger getClassLogger() { + return logger; + } + + @Before + public void setUp() { + getME().getMotor().setPercentMode(CANJaguar.kQuadEncoder, 360); + getME().getMotor().enableControl(); + getME().getMotor().set(0.0f); + /* The motor might still have momentum from the previous test. */ + Timer.delay(kStartupTime); + } + + @Test + public void testDisableStopsTheMotor() { + // given + getME().getMotor().enableControl(); + setCANJaguar(kMotorTime / 2, 1); + getME().getMotor().disableControl(); + // when + simpleLog(Level.FINER, "The motor should stop running now"); + setCANJaguar(kMotorTime / 2, 1); + final double initialPosition = getME().getMotor().getPosition(); + setCANJaguar(kMotorTime / 2, 1); + + // then + assertEquals("Speed did not go to zero when disabled in percent mode", 0, getME().getMotor() + .getSpeed(), kEncoderSpeedTolerance); + assertEquals(initialPosition, getME().getMotor().getPosition(), 10); + } + + @Test + public void testRotateForward() { + // Given + getME().getMotor().enableControl(); + final double initialPosition = getME().getMotor().getPosition(); + // When + /* Drive the speed controller briefly to move the encoder */ + runMotorForward(); + + // Then + PollingWait wait = + new PollingWait().timeoutAfter((long) kMotorTimeSettling, TimeUnit.SECONDS).pollEvery(1, + TimeUnit.MILLISECONDS); + wait.until(new RunnableAssert("CANJaguar position incrementing") { + @Override + public void run() throws Exception { + runMotorForward(); + assertThat("CANJaguar position should have increased after the motor moved", getME() + .getMotor().getPosition(), is(greaterThan(initialPosition))); + } + }); + + stopMotor(); + } + + @Test + public void testRotateReverse() { + // Given + getME().getMotor().enableControl(); + final double initialPosition = getME().getMotor().getPosition(); + // When + /* Drive the speed controller briefly to move the encoder */ + runMotorReverse(); + + // Then + PollingWait wait = + new PollingWait().timeoutAfter((long) kMotorTimeSettling, TimeUnit.SECONDS).pollEvery(1, + TimeUnit.MILLISECONDS); + wait.until(new RunnableAssert("CANJaguar position decrementing") { + @Override + public void run() throws Exception { + runMotorReverse(); + assertThat("CANJaguar position should have decreased after the motor moved", getME() + .getMotor().getPosition(), is(lessThan(initialPosition))); + } + }); + stopMotor(); + } + + /** + * Test if we can limit the Jaguar to not rotate forwards when the fake limit + * switch is tripped + */ + @Test + public void shouldNotRotateForwards_WhenFakeLimitSwitchForwardsIsTripped() { + // Given + getME().getMotor().configLimitMode(CANJaguar.LimitMode.SwitchInputsOnly); + getME().getForwardLimit().set(true); + getME().getReverseLimit().set(false); + getME().getMotor().enableControl(); + + stopMotor(); + Timer.delay(kEncoderSettlingTime); + + PollingWait wait = + new PollingWait().timeoutAfter((long) kLimitSettlingTime, TimeUnit.SECONDS).pollEvery(1, + TimeUnit.MILLISECONDS); + /* Wait until the limits are recognized by the CANJaguar. */ + wait.until(new RunnableAssert( + "Waiting for the forward and reverse limit switches to be in the correct state") { + @Override + public void run() throws Exception { + stopMotor(); + assertFalse("[TEST SETUP] The forward limit switch is not in the correct state", getME() + .getMotor().getForwardLimitOK()); + assertTrue("[TEST SETUP]The reverse limit switch is not in the correct state", getME() + .getMotor().getReverseLimitOK()); + } + }); + + final double initialPosition = getME().getMotor().getPosition(); + + // When + /* + * Drive the speed controller briefly to move the encoder. If the limit + * switch is recognized, it shouldn't actually move. + */ + setCANJaguar(kMotorTime, 1); + stopMotor(); + + // Then + /* The position should be the same, since the limit switch was on. */ + assertEquals("CAN Jaguar should not have moved with the forward limit switch pressed", + initialPosition, getME().getMotor().getPosition(), kEncoderPositionTolerance); + } + + + /** + * Test if we can rotate in reverse when the limit switch + */ + @Test + public void shouldRotateReverse_WhenFakeLimitSwitchForwardsIsTripped() { + // Given + getME().getMotor().configLimitMode(CANJaguar.LimitMode.SwitchInputsOnly); + getME().getForwardLimit().set(true); + getME().getReverseLimit().set(false); + getME().getMotor().enableControl(); + + stopMotor(); + Timer.delay(kEncoderSettlingTime); + + PollingWait limitWait = + new PollingWait().timeoutAfter((long) kLimitSettlingTime, TimeUnit.SECONDS).pollEvery(1, + TimeUnit.MILLISECONDS); + /* Wait until the limits are recognized by the CANJaguar. */ + limitWait.until(new RunnableAssert( + "Waiting for the forward and reverse limit switches to be in the correct state") { + @Override + public void run() throws Exception { + stopMotor(); + assertFalse("[TEST SETUP] The forward limit switch is not in the correct state", getME() + .getMotor().getForwardLimitOK()); + assertTrue("[TEST SETUP] The reverse limit switch is not in the correct state", getME() + .getMotor().getReverseLimitOK()); + } + }); + + final double initialPosition = getME().getMotor().getPosition(); + + // When + /* + * Drive the speed controller in the other direction. It should actually + * move, since only the forward switch is activated. + */ + setCANJaguar(kMotorTime, -1); + // Then + PollingWait wait = + new PollingWait().timeoutAfter((long) kMotorTimeSettling, TimeUnit.SECONDS).pollEvery(1, + TimeUnit.MILLISECONDS); + wait.until(new RunnableAssert("Waiting for the encoder to update") { + @Override + public void run() throws Exception { + runMotorReverse(); + assertThat("CAN Jaguar should have moved in reverse while the forward limit was on", + getME().getMotor().getPosition(), is(lessThan(initialPosition))); + } + + }); + stopMotor(); + + } + + /** + * Test if we can limit the Jaguar to only moving forwards with a fake limit + * switch. + */ + @Test + public void shouldNotRotateReverse_WhenFakeLimitSwitchReversesIsTripped() { + // Given + getME().getMotor().configLimitMode(CANJaguar.LimitMode.SwitchInputsOnly); + getME().getForwardLimit().set(false); + getME().getReverseLimit().set(true); + getME().getMotor().enableControl(); + + stopMotor(); + Timer.delay(kEncoderSettlingTime); + + PollingWait wait = + new PollingWait().timeoutAfter((long) kLimitSettlingTime, TimeUnit.SECONDS).pollEvery(1, + TimeUnit.MILLISECONDS); + /* Wait until the limits are recognized by the CANJaguar. */ + wait.until(new RunnableAssert( + "Waiting for the forward and reverse limit switches to be in the correct state") { + @Override + public void run() throws Exception { + stopMotor(); + assertTrue("[TEST SETUP] The forward limit switch is not in the correct state", getME() + .getMotor().getForwardLimitOK()); + assertFalse("[TEST SETUP] The reverse limit switch is not in the correct state", getME() + .getMotor().getReverseLimitOK()); + } + }); + + final double initialPosition = getME().getMotor().getPosition(); + + // When + /* + * Drive the speed controller backwards briefly to move the encoder. If the + * limit switch is recognized, it shouldn't actually move. + */ + setCANJaguar(kMotorTime, -1); + stopMotor(); + + // Then + /* The position should be the same, since the limit switch was on. */ + assertEquals("CAN Jaguar should not have moved with the limit switch pressed", initialPosition, + getME().getMotor().getPosition(), kEncoderPositionTolerance); + } + + /** + * Test if we can limit the Jaguar to only moving forwards with a fake limit + * switch. + */ + /** + *$ */ - protected void stopMotor() { - getME().getMotor().set(kStoppedValue); - } - /* (non-Javadoc) - * @see edu.wpi.first.wpilibj.can.AbstractCANTest#runMotorForward() - */ - protected void runMotorForward() { - getME().getMotor().set(kRunningValue); - } - /* (non-Javadoc) - * @see edu.wpi.first.wpilibj.can.AbstractCANTest#runMotorReverse() - */ - protected void runMotorReverse() { - getME().getMotor().set(-kRunningValue); - } - - @Override - protected Logger getClassLogger() { - return logger; - } - @Before - public void setUp() { - getME().getMotor().setPercentMode(CANJaguar.kQuadEncoder, 360); - getME().getMotor().enableControl(); - getME().getMotor().set(0.0f); - /* The motor might still have momentum from the previous test. */ - Timer.delay(kStartupTime); - } - - @Test - public void testDisableStopsTheMotor(){ - //given - getME().getMotor().enableControl(); - setCANJaguar(kMotorTime/2, 1); - getME().getMotor().disableControl(); - //when - simpleLog(Level.FINER, "The motor should stop running now"); - setCANJaguar(kMotorTime/2, 1); - final double initialPosition = getME().getMotor().getPosition(); - setCANJaguar(kMotorTime/2, 1); - - //then - assertEquals("Speed did not go to zero when disabled in percent mode", 0, getME().getMotor().getSpeed(), kEncoderSpeedTolerance); - assertEquals(initialPosition, getME().getMotor().getPosition(), 10); - } - - @Test - public void testRotateForward() { - //Given - getME().getMotor().enableControl(); - final double initialPosition = getME().getMotor().getPosition(); - //When - /* Drive the speed controller briefly to move the encoder */ - runMotorForward(); + @Test + public void shouldRotateForward_WhenFakeLimitSwitchReversesIsTripped() { + // Given + getME().getMotor().configLimitMode(CANJaguar.LimitMode.SwitchInputsOnly); + getME().getForwardLimit().set(false); + getME().getReverseLimit().set(true); + getME().getMotor().enableControl(); - //Then - PollingWait wait = new PollingWait().timeoutAfter((long)kMotorTimeSettling, TimeUnit.SECONDS).pollEvery(1, TimeUnit.MILLISECONDS); - wait.until(new RunnableAssert("CANJaguar position incrementing") { - @Override - public void run() throws Exception { - runMotorForward(); - assertThat("CANJaguar position should have increased after the motor moved", getME().getMotor().getPosition(), is(greaterThan(initialPosition))); - } - }); - - stopMotor(); - } - - @Test - public void testRotateReverse() { - //Given - getME().getMotor().enableControl(); - final double initialPosition = getME().getMotor().getPosition(); - //When - /* Drive the speed controller briefly to move the encoder */ - runMotorReverse(); - - //Then - PollingWait wait = new PollingWait().timeoutAfter((long)kMotorTimeSettling, TimeUnit.SECONDS).pollEvery(1, TimeUnit.MILLISECONDS); - wait.until(new RunnableAssert("CANJaguar position decrementing") { - @Override - public void run() throws Exception { - runMotorReverse(); - assertThat("CANJaguar position should have decreased after the motor moved", getME().getMotor().getPosition(), is(lessThan(initialPosition))); - } - }); - stopMotor(); - } - - /** - * Test if we can limit the Jaguar to not rotate forwards when the fake limit switch is tripped - */ - @Test - public void shouldNotRotateForwards_WhenFakeLimitSwitchForwardsIsTripped() { - //Given - getME().getMotor().configLimitMode(CANJaguar.LimitMode.SwitchInputsOnly); - getME().getForwardLimit().set(true); - getME().getReverseLimit().set(false); - getME().getMotor().enableControl(); + PollingWait limitWait = + new PollingWait().timeoutAfter((long) kLimitSettlingTime, TimeUnit.SECONDS).pollEvery(1, + TimeUnit.MILLISECONDS); + /* Wait until the limits are recognized by the CANJaguar. */ + limitWait.until(new RunnableAssert( + "Waiting for the forward and reverse limit switches to be in the correct state") { + @Override + public void run() throws Exception { + stopMotor(); + assertTrue("[TEST SETUP] The forward limit switch is not in the correct state", getME() + .getMotor().getForwardLimitOK()); + assertFalse("[TEST SETUP] The reverse limit switch is not in the correct state", getME() + .getMotor().getReverseLimitOK()); + } + }); - stopMotor(); - Timer.delay(kEncoderSettlingTime); - - PollingWait wait = new PollingWait().timeoutAfter((long)kLimitSettlingTime, TimeUnit.SECONDS).pollEvery(1, TimeUnit.MILLISECONDS); - /* Wait until the limits are recognized by the CANJaguar. */ - wait.until(new RunnableAssert("Waiting for the forward and reverse limit switches to be in the correct state") { - @Override - public void run() throws Exception { - stopMotor(); - assertFalse("[TEST SETUP] The forward limit switch is not in the correct state",getME().getMotor().getForwardLimitOK()); - assertTrue("[TEST SETUP]The reverse limit switch is not in the correct state", getME().getMotor().getReverseLimitOK()); - } - }); + final double initialPosition = getME().getMotor().getPosition(); - final double initialPosition = getME().getMotor().getPosition(); - - //When - /* - * Drive the speed controller briefly to move the encoder. If the limit - * switch is recognized, it shouldn't actually move. - */ - setCANJaguar(kMotorTime, 1); - stopMotor(); - - //Then - /* The position should be the same, since the limit switch was on. */ - assertEquals( - "CAN Jaguar should not have moved with the forward limit switch pressed", - initialPosition, getME().getMotor().getPosition(), - kEncoderPositionTolerance); - } - - - /** - * Test if we can rotate in reverse when the limit switch - */ - @Test - public void shouldRotateReverse_WhenFakeLimitSwitchForwardsIsTripped() { - //Given - getME().getMotor().configLimitMode(CANJaguar.LimitMode.SwitchInputsOnly); - getME().getForwardLimit().set(true); - getME().getReverseLimit().set(false); - getME().getMotor().enableControl(); + // When + /* + * Drive the speed controller in the other direction. It should actually + * move, since only the reverse switch is activated. + */ + setCANJaguar(kMotorTime, 1); + // Then + /* The position should have increased */ + PollingWait wait = + new PollingWait().timeoutAfter((long) kMotorTimeSettling, TimeUnit.SECONDS).pollEvery(1, + TimeUnit.MILLISECONDS); + wait.until(new RunnableAssert("Waiting for the encoder to update") { + @Override + public void run() throws Exception { + runMotorForward(); + assertThat("CAN Jaguar should have moved forwards while the reverse limit was on", getME() + .getMotor().getPosition(), is(greaterThan(initialPosition))); + } - stopMotor(); - Timer.delay(kEncoderSettlingTime); + }); + stopMotor(); + } - PollingWait limitWait = new PollingWait().timeoutAfter((long)kLimitSettlingTime, TimeUnit.SECONDS).pollEvery(1, TimeUnit.MILLISECONDS); - /* Wait until the limits are recognized by the CANJaguar. */ - limitWait.until(new RunnableAssert("Waiting for the forward and reverse limit switches to be in the correct state") { - @Override - public void run() throws Exception { - stopMotor(); - assertFalse("[TEST SETUP] The forward limit switch is not in the correct state",getME().getMotor().getForwardLimitOK()); - assertTrue("[TEST SETUP] The reverse limit switch is not in the correct state", getME().getMotor().getReverseLimitOK()); - } - }); + @Ignore("Encoder is not yet wired to the FPGA") + @Test + public void testRotateForwardEncoderToFPGA() { + getME().getMotor().enableControl(); + final double jagInitialPosition = getME().getMotor().getPosition(); + final double encoderInitialPosition = getME().getEncoder().get(); + getME().getMotor().set(1); + Timer.delay(kMotorStopTime); + getME().getMotor().set(0); - final double initialPosition = getME().getMotor().getPosition(); - - //When - /* - * Drive the speed controller in the other direction. It should actually - * move, since only the forward switch is activated. - */ - setCANJaguar(kMotorTime, -1); - //Then - PollingWait wait = new PollingWait().timeoutAfter((long)kMotorTimeSettling, TimeUnit.SECONDS).pollEvery(1, TimeUnit.MILLISECONDS); - wait.until(new RunnableAssert("Waiting for the encoder to update") { - @Override - public void run() throws Exception { - runMotorReverse(); - assertThat( - "CAN Jaguar should have moved in reverse while the forward limit was on", - getME().getMotor().getPosition(), is(lessThan(initialPosition))); - } - - }); - stopMotor(); + delayTillInCorrectStateWithMessage(Level.FINE, kEncoderSettlingTime, + "Forward Encodeder settling", new BooleanCheck() { + @Override + public boolean getAsBoolean() { + return Math.abs((getME().getMotor().getPosition() - jagInitialPosition) + - (getME().getEncoder().get() - encoderInitialPosition)) < kEncoderPositionTolerance; + } + }); - } + assertEquals(getME().getMotor().getPosition() - jagInitialPosition, getME().getEncoder().get() + - encoderInitialPosition, kEncoderPositionTolerance); + } - /** - * Test if we can limit the Jaguar to only moving forwards with a fake limit - * switch. - */ - @Test - public void shouldNotRotateReverse_WhenFakeLimitSwitchReversesIsTripped() { - //Given - getME().getMotor().configLimitMode(CANJaguar.LimitMode.SwitchInputsOnly); - getME().getForwardLimit().set(false); - getME().getReverseLimit().set(true); - getME().getMotor().enableControl(); + @Ignore("Encoder is not yet wired to the FPGA") + @Test + public void testRotateReverseEncoderToFPGA() { + getME().getMotor().enableControl(); + final double jagInitialPosition = getME().getMotor().getPosition(); + final double encoderInitialPosition = getME().getEncoder().get(); + getME().getMotor().set(-1); + Timer.delay(kMotorStopTime); + getME().getMotor().set(0); - stopMotor(); - Timer.delay(kEncoderSettlingTime); - - PollingWait wait = new PollingWait().timeoutAfter((long)kLimitSettlingTime, TimeUnit.SECONDS).pollEvery(1, TimeUnit.MILLISECONDS); - /* Wait until the limits are recognized by the CANJaguar. */ - wait.until(new RunnableAssert("Waiting for the forward and reverse limit switches to be in the correct state") { - @Override - public void run() throws Exception { - stopMotor(); - assertTrue("[TEST SETUP] The forward limit switch is not in the correct state",getME().getMotor().getForwardLimitOK()); - assertFalse("[TEST SETUP] The reverse limit switch is not in the correct state", getME().getMotor().getReverseLimitOK()); - } - }); - - final double initialPosition = getME().getMotor().getPosition(); - - //When - /* - * Drive the speed controller backwards briefly to move the encoder. If - * the limit switch is recognized, it shouldn't actually move. - */ - setCANJaguar(kMotorTime, -1); - stopMotor(); - - //Then - /* The position should be the same, since the limit switch was on. */ - assertEquals( - "CAN Jaguar should not have moved with the limit switch pressed", - initialPosition, getME().getMotor().getPosition(), - kEncoderPositionTolerance); - } - - /** - * Test if we can limit the Jaguar to only moving forwards with a fake limit - * switch. - */ - /** - * - */ - @Test - public void shouldRotateForward_WhenFakeLimitSwitchReversesIsTripped() { - //Given - getME().getMotor().configLimitMode(CANJaguar.LimitMode.SwitchInputsOnly); - getME().getForwardLimit().set(false); - getME().getReverseLimit().set(true); - getME().getMotor().enableControl(); - - PollingWait limitWait = new PollingWait().timeoutAfter((long)kLimitSettlingTime, TimeUnit.SECONDS).pollEvery(1, TimeUnit.MILLISECONDS); - /* Wait until the limits are recognized by the CANJaguar. */ - limitWait.until(new RunnableAssert("Waiting for the forward and reverse limit switches to be in the correct state") { - @Override - public void run() throws Exception { - stopMotor(); - assertTrue("[TEST SETUP] The forward limit switch is not in the correct state",getME().getMotor().getForwardLimitOK()); - assertFalse("[TEST SETUP] The reverse limit switch is not in the correct state", getME().getMotor().getReverseLimitOK()); - } - }); - - final double initialPosition = getME().getMotor().getPosition(); - - //When - /* - * Drive the speed controller in the other direction. It should actually - * move, since only the reverse switch is activated. - */ - setCANJaguar(kMotorTime, 1); - //Then - /* The position should have increased */ - PollingWait wait = new PollingWait().timeoutAfter((long)kMotorTimeSettling, TimeUnit.SECONDS).pollEvery(1, TimeUnit.MILLISECONDS); - wait.until(new RunnableAssert("Waiting for the encoder to update") { - @Override - public void run() throws Exception { - runMotorForward(); - assertThat( - "CAN Jaguar should have moved forwards while the reverse limit was on", - getME().getMotor().getPosition(), is(greaterThan(initialPosition))); - } - - }); - stopMotor(); - } - - @Ignore("Encoder is not yet wired to the FPGA") - @Test - public void testRotateForwardEncoderToFPGA(){ - getME().getMotor().enableControl(); - final double jagInitialPosition = getME().getMotor().getPosition(); - final double encoderInitialPosition = getME().getEncoder().get(); - getME().getMotor().set(1); - Timer.delay(kMotorStopTime); - getME().getMotor().set(0); - - delayTillInCorrectStateWithMessage(Level.FINE, kEncoderSettlingTime, "Forward Encodeder settling", new BooleanCheck(){@Override - public boolean getAsBoolean(){return Math.abs((getME().getMotor().getPosition()-jagInitialPosition) - - (getME().getEncoder().get() - encoderInitialPosition)) < kEncoderPositionTolerance;}}); - - assertEquals( getME().getMotor().getPosition()-jagInitialPosition, getME().getEncoder().get() - encoderInitialPosition, kEncoderPositionTolerance); - } - - @Ignore("Encoder is not yet wired to the FPGA") - @Test - public void testRotateReverseEncoderToFPGA(){ - getME().getMotor().enableControl(); - final double jagInitialPosition = getME().getMotor().getPosition(); - final double encoderInitialPosition = getME().getEncoder().get(); - getME().getMotor().set(-1); - Timer.delay(kMotorStopTime); - getME().getMotor().set(0); - - delayTillInCorrectStateWithMessage(Level.FINE, kEncoderSettlingTime, "Forward Encodeder settling", new BooleanCheck(){@Override - public boolean getAsBoolean(){return Math.abs((getME().getMotor().getPosition()-jagInitialPosition) - - (getME().getEncoder().get() - encoderInitialPosition)) < kEncoderPositionTolerance;}}); - assertEquals( getME().getMotor().getPosition()-jagInitialPosition, getME().getEncoder().get() - encoderInitialPosition, kEncoderPositionTolerance); - } + delayTillInCorrectStateWithMessage(Level.FINE, kEncoderSettlingTime, + "Forward Encodeder settling", new BooleanCheck() { + @Override + public boolean getAsBoolean() { + return Math.abs((getME().getMotor().getPosition() - jagInitialPosition) + - (getME().getEncoder().get() - encoderInitialPosition)) < kEncoderPositionTolerance; + } + }); + assertEquals(getME().getMotor().getPosition() - jagInitialPosition, getME().getEncoder().get() + - encoderInitialPosition, kEncoderPositionTolerance); + } } diff --git a/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/can/CANPositionPotentiometerModeTest.java b/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/can/CANPositionPotentiometerModeTest.java index 38053b9007..cbc2c4810e 100644 --- a/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/can/CANPositionPotentiometerModeTest.java +++ b/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/can/CANPositionPotentiometerModeTest.java @@ -1,8 +1,8 @@ /*----------------------------------------------------------------------------*/ -/* Copyright (c) FIRST 2008-2014. All Rights Reserved. */ -/* Open Source Software - may be modified and shared by FRC teams. The code */ +/* Copyright (c) FIRST 2008-2014. All Rights Reserved. */ +/* Open Source Software - may be modified and shared by FRC teams. The code */ /* must be accompanied by the FIRST BSD license file in the root directory of */ -/* the project. */ +/* the project. */ /*----------------------------------------------------------------------------*/ package edu.wpi.first.wpilibj.can; @@ -30,124 +30,141 @@ import edu.wpi.first.wpilibj.fixtures.MotorEncoderFixture; * */ public class CANPositionPotentiometerModeTest extends AbstractCANTest { - private static final Logger logger = Logger.getLogger(CANPositionPotentiometerModeTest.class.getName()); - - private static final double kStoppedValue = 0; - - private static final int defaultPotAngle = 180; - private static final double maxPotVoltage = 3.0; - - /* (non-Javadoc) - * @see edu.wpi.first.wpilibj.can.AbstractCANTest#stopMotor() - */ - protected void stopMotor() { - getME().getMotor().set(.5); - } + private static final Logger logger = Logger.getLogger(CANPositionPotentiometerModeTest.class + .getName()); - /* (non-Javadoc) - * @see edu.wpi.first.wpilibj.can.AbstractCANTest#runMotorForward() - */ - protected void runMotorForward() { - getME().getMotor().set(1); - } + private static final double kStoppedValue = 0; - /* (non-Javadoc) - * @see edu.wpi.first.wpilibj.can.AbstractCANTest#runMotorReverse() - */ - protected void runMotorReverse() { - getME().getMotor().set(0); - } - - @Override - protected Logger getClassLogger() { - return logger; - } + private static final int defaultPotAngle = 180; + private static final double maxPotVoltage = 3.0; - @Before - public void setUp() throws Exception { - getME().getMotor().setPositionMode(CANJaguar.kPotentiometer, 5.0, 0.1, 2.0); - //getME().getMotor().configPotentiometerTurns(rotationRange); - getME().getFakePot().setMaxVoltage(maxPotVoltage); - getME().getFakePot().setVoltage(1.5); - stopMotor(); - getME().getMotor().enableControl(); - /* The motor might still have momentum from the previous test. */ - Timer.delay(kStartupTime); - } - + /* + * (non-Javadoc) + *$ + * @see edu.wpi.first.wpilibj.can.AbstractCANTest#stopMotor() + */ + protected void stopMotor() { + getME().getMotor().set(.5); + } - /** - * NOTICE: This is using the {@link MotorEncoderFixture#getEncoder()} instead of the one built into the CAN Jaguar - */ - @Ignore("Encoder is not yet wired to the FPGA") - @Test - public void testRotateForward() { - int initialPosition = getME().getEncoder().get(); - /* Drive the speed controller briefly to move the encoder */ - getME().getMotor().set(kStoppedValue); - Timer.delay(kMotorTimeSettling); - getME().getMotor().set(defaultPotAngle); + /* + * (non-Javadoc) + *$ + * @see edu.wpi.first.wpilibj.can.AbstractCANTest#runMotorForward() + */ + protected void runMotorForward() { + getME().getMotor().set(1); + } - /* The position should have increased */ - assertThat("CAN Jaguar position should have increased after the motor moved", getME().getEncoder().get(), is(greaterThan(initialPosition))); - - } - - /** - * NOTICE: This is using the {@link MotorEncoderFixture#getEncoder()} instead of the one built into the CAN Jaguar - */ - @Ignore("Encoder is not yet wired to the FPGA") - @Test - public void testRotateReverse() { - int initialPosition = getME().getEncoder().get(); - /* Drive the speed controller briefly to move the encoder */ - getME().getMotor().set(kStoppedValue); - Timer.delay(kMotorTimeSettling); - getME().getMotor().set(defaultPotAngle); + /* + * (non-Javadoc) + *$ + * @see edu.wpi.first.wpilibj.can.AbstractCANTest#runMotorReverse() + */ + protected void runMotorReverse() { + getME().getMotor().set(0); + } + + @Override + protected Logger getClassLogger() { + return logger; + } + + @Before + public void setUp() throws Exception { + getME().getMotor().setPositionMode(CANJaguar.kPotentiometer, 5.0, 0.1, 2.0); + // getME().getMotor().configPotentiometerTurns(rotationRange); + getME().getFakePot().setMaxVoltage(maxPotVoltage); + getME().getFakePot().setVoltage(1.5); + stopMotor(); + getME().getMotor().enableControl(); + /* The motor might still have momentum from the previous test. */ + Timer.delay(kStartupTime); + } + + + /** + * NOTICE: This is using the {@link MotorEncoderFixture#getEncoder()} instead + * of the one built into the CAN Jaguar + */ + @Ignore("Encoder is not yet wired to the FPGA") + @Test + public void testRotateForward() { + int initialPosition = getME().getEncoder().get(); + /* Drive the speed controller briefly to move the encoder */ + getME().getMotor().set(kStoppedValue); + Timer.delay(kMotorTimeSettling); + getME().getMotor().set(defaultPotAngle); + + /* The position should have increased */ + assertThat("CAN Jaguar position should have increased after the motor moved", getME() + .getEncoder().get(), is(greaterThan(initialPosition))); + + } + + /** + * NOTICE: This is using the {@link MotorEncoderFixture#getEncoder()} instead + * of the one built into the CAN Jaguar + */ + @Ignore("Encoder is not yet wired to the FPGA") + @Test + public void testRotateReverse() { + int initialPosition = getME().getEncoder().get(); + /* Drive the speed controller briefly to move the encoder */ + getME().getMotor().set(kStoppedValue); + Timer.delay(kMotorTimeSettling); + getME().getMotor().set(defaultPotAngle); + + /* The position should have increased */ + assertThat("CAN Jaguar position should have increased after the motor moved", getME() + .getEncoder().get(), is(greaterThan(initialPosition))); + + } + + /** + * Test if we can get a position in potentiometer mode, using an analog output + * as a fake potentiometer. + */ + @Test + public void testFakePotentiometerPosition() { + // TODO When https://github.com/Pragmatists/JUnitParams/issues/5 is resolved + // make this test parameterized + + // Given + PollingWait wait = + new PollingWait().timeoutAfter((long) kPotentiometerSettlingTime, TimeUnit.SECONDS) + .pollEvery(1, TimeUnit.MILLISECONDS); + RunnableAssert assertion = + new RunnableAssert("Waiting for potentiometer position to be correct") { + @Override + public void run() throws Exception { + getME().getMotor().set(0); + assertEquals( + "CAN Jaguar should have returned the potentiometer position set by the analog output", + getME().getFakePot().getVoltage(), getME().getMotor().getPosition() * 3, + kPotentiometerPositionTolerance * 3); + } + }; + + // When + getME().getFakePot().setVoltage(0.0); + // Then + wait.until(assertion); + + // When + getME().getFakePot().setVoltage(1.0); + // Then + wait.until(assertion); + + // When + getME().getFakePot().setVoltage(2.0); + // Then + wait.until(assertion); + + // When + getME().getFakePot().setVoltage(3.0); + // Then + wait.until(assertion); + } - /* The position should have increased */ - assertThat("CAN Jaguar position should have increased after the motor moved", getME().getEncoder().get(), is(greaterThan(initialPosition))); - - } - - /** - * Test if we can get a position in potentiometer mode, using an analog output - * as a fake potentiometer. - */ - @Test - public void testFakePotentiometerPosition() { - //TODO When https://github.com/Pragmatists/JUnitParams/issues/5 is resolved make this test parameterized - - //Given - PollingWait wait = new PollingWait().timeoutAfter((long)kPotentiometerSettlingTime, TimeUnit.SECONDS).pollEvery(1, TimeUnit.MILLISECONDS); - RunnableAssert assertion = new RunnableAssert("Waiting for potentiometer position to be correct"){ - @Override - public void run() throws Exception { - getME().getMotor().set(0); - assertEquals("CAN Jaguar should have returned the potentiometer position set by the analog output", - getME().getFakePot().getVoltage() , getME().getMotor().getPosition()*3 , kPotentiometerPositionTolerance*3); - } - }; - - //When - getME().getFakePot().setVoltage(0.0); - //Then - wait.until(assertion); - - //When - getME().getFakePot().setVoltage(1.0); - //Then - wait.until(assertion); - - //When - getME().getFakePot().setVoltage(2.0); - //Then - wait.until(assertion); - - //When - getME().getFakePot().setVoltage(3.0); - //Then - wait.until(assertion); - } - } diff --git a/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/can/CANPositionQuadEncoderModeTest.java b/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/can/CANPositionQuadEncoderModeTest.java index cfeda612b2..347e9d0938 100644 --- a/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/can/CANPositionQuadEncoderModeTest.java +++ b/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/can/CANPositionQuadEncoderModeTest.java @@ -1,8 +1,8 @@ /*----------------------------------------------------------------------------*/ -/* Copyright (c) FIRST 2008-2014. All Rights Reserved. */ -/* Open Source Software - may be modified and shared by FRC teams. The code */ +/* Copyright (c) FIRST 2008-2014. All Rights Reserved. */ +/* Open Source Software - may be modified and shared by FRC teams. The code */ /* must be accompanied by the FIRST BSD license file in the root directory of */ -/* the project. */ +/* the project. */ /*----------------------------------------------------------------------------*/ package edu.wpi.first.wpilibj.can; @@ -23,88 +23,98 @@ import edu.wpi.first.wpilibj.Timer; * */ public class CANPositionQuadEncoderModeTest extends AbstractCANTest { - private static final Logger logger = Logger.getLogger(CANPositionQuadEncoderModeTest.class.getName()); - @Override - protected Logger getClassLogger() { - return logger; - } + private static final Logger logger = Logger.getLogger(CANPositionQuadEncoderModeTest.class + .getName()); + + @Override + protected Logger getClassLogger() { + return logger; + } - /* (non-Javadoc) - * @see edu.wpi.first.wpilibj.can.AbstractCANTest#runMotorForward() - */ - protected void runMotorForward() { - double postion = getME().getMotor().getPosition(); - getME().getMotor().set(postion + 100); - } + /* + * (non-Javadoc) + *$ + * @see edu.wpi.first.wpilibj.can.AbstractCANTest#runMotorForward() + */ + protected void runMotorForward() { + double postion = getME().getMotor().getPosition(); + getME().getMotor().set(postion + 100); + } - /* (non-Javadoc) - * @see edu.wpi.first.wpilibj.can.AbstractCANTest#runMotorReverse() - */ - protected void runMotorReverse() { - double postion = getME().getMotor().getPosition(); - getME().getMotor().set(postion - 100); - } + /* + * (non-Javadoc) + *$ + * @see edu.wpi.first.wpilibj.can.AbstractCANTest#runMotorReverse() + */ + protected void runMotorReverse() { + double postion = getME().getMotor().getPosition(); + getME().getMotor().set(postion - 100); + } - @Before - public void setUp() throws Exception { - getME().getMotor().setPositionMode(CANJaguar.kQuadEncoder, 360, 10.0f, 0.01f, 0.0f); - getME().getMotor().enableControl(0); - /* The motor might still have momentum from the previous test. */ - Timer.delay(kStartupTime); - } + @Before + public void setUp() throws Exception { + getME().getMotor().setPositionMode(CANJaguar.kQuadEncoder, 360, 10.0f, 0.01f, 0.0f); + getME().getMotor().enableControl(0); + /* The motor might still have momentum from the previous test. */ + Timer.delay(kStartupTime); + } - @Ignore("The encoder initial position is not validated so is sometimes not set properly") - @Test - public void testSetEncoderInitialPositionWithEnable(){ - //given - final double encoderValue = 4823; - //when - getME().getMotor().enableControl(encoderValue); - getME().getMotor().disableControl(); - delayTillInCorrectStateWithMessage(Level.FINE, kEncoderSettlingTime, "Encoder value settling", new BooleanCheck(){@Override - public boolean getAsBoolean(){ - getME().getMotor().set(getME().getMotor().getPosition()); - return Math.abs(getME().getMotor().getPosition() - encoderValue) < 40; - } - }); - //then - assertEquals(encoderValue, getME().getMotor().getPosition(), 40); - } + @Ignore("The encoder initial position is not validated so is sometimes not set properly") + @Test + public void testSetEncoderInitialPositionWithEnable() { + // given + final double encoderValue = 4823; + // when + getME().getMotor().enableControl(encoderValue); + getME().getMotor().disableControl(); + delayTillInCorrectStateWithMessage(Level.FINE, kEncoderSettlingTime, "Encoder value settling", + new BooleanCheck() { + @Override + public boolean getAsBoolean() { + getME().getMotor().set(getME().getMotor().getPosition()); + return Math.abs(getME().getMotor().getPosition() - encoderValue) < 40; + } + }); + // then + assertEquals(encoderValue, getME().getMotor().getPosition(), 40); + } - /** - * Test if we can set a position and reach that position with PID control on - * the Jaguar. - */ - @Test - public void testEncoderPositionPIDForward() { + /** + * Test if we can set a position and reach that position with PID control on + * the Jaguar. + */ + @Test + public void testEncoderPositionPIDForward() { - double setpoint = getME().getMotor().getPosition() + 1.0f; + double setpoint = getME().getMotor().getPosition() + 1.0f; - /* It should get to the setpoint within 10 seconds */ - getME().getMotor().set(setpoint); - setCANJaguar(kMotorTimeSettling, setpoint); + /* It should get to the setpoint within 10 seconds */ + getME().getMotor().set(setpoint); + setCANJaguar(kMotorTimeSettling, setpoint); - assertEquals("CAN Jaguar should have reached setpoint with PID control", setpoint, getME().getMotor().getPosition(), kEncoderPositionTolerance); - } + assertEquals("CAN Jaguar should have reached setpoint with PID control", setpoint, getME() + .getMotor().getPosition(), kEncoderPositionTolerance); + } - /** - * Test if we can set a position and reach that position with PID control on - * the Jaguar. - */ - @Test - public void testEncoderPositionPIDReverse() { + /** + * Test if we can set a position and reach that position with PID control on + * the Jaguar. + */ + @Test + public void testEncoderPositionPIDReverse() { - double setpoint = getME().getMotor().getPosition() - 1.0f; + double setpoint = getME().getMotor().getPosition() - 1.0f; - /* It should get to the setpoint within 10 seconds */ - getME().getMotor().set(setpoint); - setCANJaguar(kMotorTimeSettling, setpoint); + /* It should get to the setpoint within 10 seconds */ + getME().getMotor().set(setpoint); + setCANJaguar(kMotorTimeSettling, setpoint); - assertEquals("CAN Jaguar should have reached setpoint with PID control", setpoint, getME().getMotor().getPosition(), kEncoderPositionTolerance); - } + assertEquals("CAN Jaguar should have reached setpoint with PID control", setpoint, getME() + .getMotor().getPosition(), kEncoderPositionTolerance); + } } diff --git a/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/can/CANSpeedQuadEncoderModeTest.java b/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/can/CANSpeedQuadEncoderModeTest.java index f94764695d..1759479608 100644 --- a/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/can/CANSpeedQuadEncoderModeTest.java +++ b/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/can/CANSpeedQuadEncoderModeTest.java @@ -1,8 +1,8 @@ /*----------------------------------------------------------------------------*/ -/* Copyright (c) FIRST 2008-2014. All Rights Reserved. */ -/* Open Source Software - may be modified and shared by FRC teams. The code */ +/* Copyright (c) FIRST 2008-2014. All Rights Reserved. */ +/* Open Source Software - may be modified and shared by FRC teams. The code */ /* must be accompanied by the FIRST BSD license file in the root directory of */ -/* the project. */ +/* the project. */ /*----------------------------------------------------------------------------*/ package edu.wpi.first.wpilibj.can; @@ -25,56 +25,62 @@ import edu.wpi.first.wpilibj.Timer; * */ public class CANSpeedQuadEncoderModeTest extends AbstractCANTest { - private static final Logger logger = Logger.getLogger(CANPercentQuadEncoderModeTest.class.getName()); - /** The stopped value in rev/min */ - private static final double kStoppedValue = 0; - /** The running value in rev/min */ - private static final double kRunningValue = 200; + private static final Logger logger = Logger.getLogger(CANPercentQuadEncoderModeTest.class + .getName()); + /** The stopped value in rev/min */ + private static final double kStoppedValue = 0; + /** The running value in rev/min */ + private static final double kRunningValue = 200; - @Override - protected Logger getClassLogger() { - return logger; - } + @Override + protected Logger getClassLogger() { + return logger; + } - @Before - public void setUp() throws Exception { - getME().getMotor().setSpeedMode(CANJaguar.kQuadEncoder, 360, 0.1f, 0.003f, 0.01f); - getME().getMotor().enableControl(); - getME().getMotor().set(0.0f); - /* The motor might still have momentum from the previous test. */ - Timer.delay(kStartupTime); - } + @Before + public void setUp() throws Exception { + getME().getMotor().setSpeedMode(CANJaguar.kQuadEncoder, 360, 0.1f, 0.003f, 0.01f); + getME().getMotor().enableControl(); + getME().getMotor().set(0.0f); + /* The motor might still have momentum from the previous test. */ + Timer.delay(kStartupTime); + } - @Test - public void testDefaultSpeed(){ - assertEquals("CAN Jaguar did not start with an initial speed of zero", 0.0f, getME().getMotor().getSpeed(), 0.3f); - } + @Test + public void testDefaultSpeed() { + assertEquals("CAN Jaguar did not start with an initial speed of zero", 0.0f, getME().getMotor() + .getSpeed(), 0.3f); + } - /** - * Test if we can drive the motor forward in Speed mode and get a - * position back - */ - @Test - public void testRotateForwardSpeed() { - double speed = 50.0f; - double initialPosition = getME().getMotor().getPosition(); - setCANJaguar(2*kMotorTime, speed); - assertEquals("The motor did not reach the required speed in speed mode", speed, getME().getMotor().getSpeed(), kEncoderSpeedTolerance); - assertThat("The motor did not move forward in speed mode", getME().getMotor().getPosition(), is(greaterThan(initialPosition))); - } + /** + * Test if we can drive the motor forward in Speed mode and get a position + * back + */ + @Test + public void testRotateForwardSpeed() { + double speed = 50.0f; + double initialPosition = getME().getMotor().getPosition(); + setCANJaguar(2 * kMotorTime, speed); + assertEquals("The motor did not reach the required speed in speed mode", speed, getME() + .getMotor().getSpeed(), kEncoderSpeedTolerance); + assertThat("The motor did not move forward in speed mode", getME().getMotor().getPosition(), + is(greaterThan(initialPosition))); + } - /** - * Test if we can drive the motor backwards in Speed mode and get a - * position back - */ - @Test - public void testRotateReverseSpeed() { - double speed = -50.0f; - double initialPosition = getME().getMotor().getPosition(); - setCANJaguar(2*kMotorTime, speed); - assertEquals("The motor did not reach the required speed in speed mode", speed, getME().getMotor().getSpeed(), kEncoderSpeedTolerance); - assertThat("The motor did not move in reverse in speed mode", getME().getMotor().getPosition(), is(lessThan(initialPosition))); - } + /** + * Test if we can drive the motor backwards in Speed mode and get a position + * back + */ + @Test + public void testRotateReverseSpeed() { + double speed = -50.0f; + double initialPosition = getME().getMotor().getPosition(); + setCANJaguar(2 * kMotorTime, speed); + assertEquals("The motor did not reach the required speed in speed mode", speed, getME() + .getMotor().getSpeed(), kEncoderSpeedTolerance); + assertThat("The motor did not move in reverse in speed mode", getME().getMotor().getPosition(), + is(lessThan(initialPosition))); + } } diff --git a/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/can/CANTestSuite.java b/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/can/CANTestSuite.java index 63a0179159..2b8bccc442 100644 --- a/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/can/CANTestSuite.java +++ b/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/can/CANTestSuite.java @@ -1,8 +1,8 @@ /*----------------------------------------------------------------------------*/ -/* Copyright (c) FIRST 2008-2014. All Rights Reserved. */ -/* Open Source Software - may be modified and shared by FRC teams. The code */ +/* Copyright (c) FIRST 2008-2014. All Rights Reserved. */ +/* Open Source Software - may be modified and shared by FRC teams. The code */ /* must be accompanied by the FIRST BSD license file in the root directory of */ -/* the project. */ +/* the project. */ /*----------------------------------------------------------------------------*/ package edu.wpi.first.wpilibj.can; @@ -17,15 +17,10 @@ import edu.wpi.first.wpilibj.test.AbstractTestSuite; * */ @RunWith(Suite.class) -@SuiteClasses({ CANCurrentQuadEncoderModeTest.class, - CANDefaultTest.class, - CANJaguarInversionTest.class, - CANPercentQuadEncoderModeTest.class, - CANPositionPotentiometerModeTest.class, - CANPositionQuadEncoderModeTest.class, - CANSpeedQuadEncoderModeTest.class, - CANVoltageQuadEncoderModeTest.class - }) +@SuiteClasses({CANCurrentQuadEncoderModeTest.class, CANDefaultTest.class, + CANJaguarInversionTest.class, CANPercentQuadEncoderModeTest.class, + CANPositionPotentiometerModeTest.class, CANPositionQuadEncoderModeTest.class, + CANSpeedQuadEncoderModeTest.class, CANVoltageQuadEncoderModeTest.class}) public class CANTestSuite extends AbstractTestSuite { } diff --git a/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/can/CANVoltageQuadEncoderModeTest.java b/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/can/CANVoltageQuadEncoderModeTest.java index 538be37b13..e2907e88df 100644 --- a/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/can/CANVoltageQuadEncoderModeTest.java +++ b/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/can/CANVoltageQuadEncoderModeTest.java @@ -1,8 +1,8 @@ /*----------------------------------------------------------------------------*/ -/* Copyright (c) FIRST 2008-2014. All Rights Reserved. */ -/* Open Source Software - may be modified and shared by FRC teams. The code */ +/* Copyright (c) FIRST 2008-2014. All Rights Reserved. */ +/* Open Source Software - may be modified and shared by FRC teams. The code */ /* must be accompanied by the FIRST BSD license file in the root directory of */ -/* the project. */ +/* the project. */ /*----------------------------------------------------------------------------*/ package edu.wpi.first.wpilibj.can; @@ -29,170 +29,191 @@ import edu.wpi.first.wpilibj.Timer; * */ public class CANVoltageQuadEncoderModeTest extends AbstractCANTest { - private static final Logger logger = Logger.getLogger(CANVoltageQuadEncoderModeTest.class.getName()); - /** The stopped value in volts */ - private static final double kStoppedValue = 0; - /** The running value in volts */ - private static final double kRunningValue = 4; - - private static final double kVoltageTolerance = .25; - - private static final PollingWait kWait = new PollingWait().timeoutAfter((long)kMotorTimeSettling, TimeUnit.SECONDS).pollEvery(1, TimeUnit.MILLISECONDS); - - /* (non-Javadoc) - * @see edu.wpi.first.wpilibj.can.AbstractCANTest#stopMotor() - */ - protected void stopMotor() { - getME().getMotor().set(kStoppedValue); - } + private static final Logger logger = Logger.getLogger(CANVoltageQuadEncoderModeTest.class + .getName()); + /** The stopped value in volts */ + private static final double kStoppedValue = 0; + /** The running value in volts */ + private static final double kRunningValue = 4; - /* (non-Javadoc) - * @see edu.wpi.first.wpilibj.can.AbstractCANTest#runMotorForward() - */ - protected void runMotorForward() { - getME().getMotor().set(kRunningValue); - } + private static final double kVoltageTolerance = .25; - /* (non-Javadoc) - * @see edu.wpi.first.wpilibj.can.AbstractCANTest#runMotorReverse() - */ - protected void runMotorReverse() { - getME().getMotor().set(-kRunningValue); - } - - @Override - protected Logger getClassLogger() { - return logger; - } + private static final PollingWait kWait = new PollingWait().timeoutAfter( + (long) kMotorTimeSettling, TimeUnit.SECONDS).pollEvery(1, TimeUnit.MILLISECONDS); - @Before - public void setUp() throws Exception { - getME().getMotor().setVoltageMode(CANJaguar.kQuadEncoder, 360); - getME().getMotor().set(kStoppedValue); - getME().getMotor().enableControl(); - - /* The motor might still have momentum from the previous test. */ - Timer.delay(kStartupTime); - } + /* + * (non-Javadoc) + *$ + * @see edu.wpi.first.wpilibj.can.AbstractCANTest#stopMotor() + */ + protected void stopMotor() { + getME().getMotor().set(kStoppedValue); + } - @Test - public void testRotateForwardToVoltage() { - setCANJaguar(kMotorTime, Math.PI); - assertEquals("The output voltage did not match the desired voltage set-point", Math.PI, getME().getMotor().getOutputVoltage(), kVoltageTolerance); - } + /* + * (non-Javadoc) + *$ + * @see edu.wpi.first.wpilibj.can.AbstractCANTest#runMotorForward() + */ + protected void runMotorForward() { + getME().getMotor().set(kRunningValue); + } - @Test - public void testRotateReverseToVoltage() { - setCANJaguar(kMotorTime, -Math.PI); - assertEquals("The output voltage did not match the desired voltage set-point", -Math.PI, getME().getMotor().getOutputVoltage(), kVoltageTolerance); - } - - - /** - * Sets up the test to have the CANJaguar running at the target voltage - * @param targetValue the target voltage - * @param wait the PollingWait to to use to wait for the setup to complete with - */ - private void setupMotorVoltageForTest(final double targetValue, PollingWait wait){ - getME().getMotor().enableControl(); - setCANJaguar(1, targetValue); - wait.until(new RunnableAssert("[SETUP] Waiting for the output voltage to match the set output value") { - @Override - public void run() throws Exception { - getME().getMotor().set(targetValue); - assertEquals("[TEST SETUP] The output voltage should have matched the set value", targetValue, getME().getMotor().getOutputVoltage(), 0.5); - assertEquals("[TEST SETUP] The set value did not match the get value", targetValue, getME().getMotor().get(), 0.5); - } - }); - } - - - @Test - public void testMaxOutputVoltagePositive(){ - //given - double maxVoltage = 3; - - setupMotorVoltageForTest(kRunningValue, kWait); - - final double fastSpeed = getME().getMotor().getSpeed(); - - //when - getME().getMotor().configMaxOutputVoltage(maxVoltage); - - setCANJaguar(1, kRunningValue); - //Then - kWait.until(new RunnableAssert("Waiting for the speed to reduce using max output voltage") { - @Override - public void run() throws Exception { - runMotorForward(); - assertThat("Speed did not reduce when the max output voltage was set", fastSpeed, is(greaterThan(getME().getMotor().getSpeed()))); - } - }); - - } - - @Test - public void testMaxOutputVoltagePositiveSetToZeroStopsMotor(){ - //given - final double maxVoltage = 0; - - setupMotorVoltageForTest(kRunningValue, kWait); - //when - getME().getMotor().configMaxOutputVoltage(maxVoltage); - - setCANJaguar(1, kRunningValue); - //then - kWait.until(new RunnableAssert("Waiting for the speed to reduce to zero using max output voltage") { - @Override - public void run() throws Exception { - runMotorForward(); - assertEquals("Speed did not go to zero when the max output voltage was set to " + maxVoltage, 0, getME().getMotor().getSpeed(), kEncoderSpeedTolerance); - } - }); - } - - - @Test - public void testMaxOutputVoltageNegative(){ - //given - double maxVoltage = 3; - - setupMotorVoltageForTest(-kRunningValue, kWait); - final double fastSpeed = getME().getMotor().getSpeed(); - - //when - getME().getMotor().configMaxOutputVoltage(maxVoltage); - setCANJaguar(1, -kRunningValue); - - //then - kWait.until(new RunnableAssert("Waiting for the speed to reduce using max output voltage") { - - @Override - public void run() throws Exception { - runMotorReverse(); - assertThat("Speed did not reduce when the max output voltage was set", fastSpeed, is(lessThan(getME().getMotor().getSpeed()))); - } - }); - } - - @Test - public void testMaxOutputVoltageNegativeSetToZeroStopsMotor(){ - //given - final double maxVoltage = 0; - setupMotorVoltageForTest(-kRunningValue, kWait); - - //when - getME().getMotor().configMaxOutputVoltage(maxVoltage); - setCANJaguar(1, -kRunningValue); - - //Then - kWait.until(new RunnableAssert("Waiting for the speed to reduce to zero using max output voltage") { - @Override - public void run() throws Exception { - runMotorReverse(); - assertEquals("Speed did not go to zero when the max output voltage was set to " + maxVoltage, 0, getME().getMotor().getSpeed(), kEncoderSpeedTolerance); - } - }); - } + /* + * (non-Javadoc) + *$ + * @see edu.wpi.first.wpilibj.can.AbstractCANTest#runMotorReverse() + */ + protected void runMotorReverse() { + getME().getMotor().set(-kRunningValue); + } + + @Override + protected Logger getClassLogger() { + return logger; + } + + @Before + public void setUp() throws Exception { + getME().getMotor().setVoltageMode(CANJaguar.kQuadEncoder, 360); + getME().getMotor().set(kStoppedValue); + getME().getMotor().enableControl(); + + /* The motor might still have momentum from the previous test. */ + Timer.delay(kStartupTime); + } + + @Test + public void testRotateForwardToVoltage() { + setCANJaguar(kMotorTime, Math.PI); + assertEquals("The output voltage did not match the desired voltage set-point", Math.PI, getME() + .getMotor().getOutputVoltage(), kVoltageTolerance); + } + + @Test + public void testRotateReverseToVoltage() { + setCANJaguar(kMotorTime, -Math.PI); + assertEquals("The output voltage did not match the desired voltage set-point", -Math.PI, + getME().getMotor().getOutputVoltage(), kVoltageTolerance); + } + + + /** + * Sets up the test to have the CANJaguar running at the target voltage + *$ + * @param targetValue the target voltage + * @param wait the PollingWait to to use to wait for the setup to complete + * with + */ + private void setupMotorVoltageForTest(final double targetValue, PollingWait wait) { + getME().getMotor().enableControl(); + setCANJaguar(1, targetValue); + wait.until(new RunnableAssert( + "[SETUP] Waiting for the output voltage to match the set output value") { + @Override + public void run() throws Exception { + getME().getMotor().set(targetValue); + assertEquals("[TEST SETUP] The output voltage should have matched the set value", + targetValue, getME().getMotor().getOutputVoltage(), 0.5); + assertEquals("[TEST SETUP] The set value did not match the get value", targetValue, getME() + .getMotor().get(), 0.5); + } + }); + } + + + @Test + public void testMaxOutputVoltagePositive() { + // given + double maxVoltage = 3; + + setupMotorVoltageForTest(kRunningValue, kWait); + + final double fastSpeed = getME().getMotor().getSpeed(); + + // when + getME().getMotor().configMaxOutputVoltage(maxVoltage); + + setCANJaguar(1, kRunningValue); + // Then + kWait.until(new RunnableAssert("Waiting for the speed to reduce using max output voltage") { + @Override + public void run() throws Exception { + runMotorForward(); + assertThat("Speed did not reduce when the max output voltage was set", fastSpeed, + is(greaterThan(getME().getMotor().getSpeed()))); + } + }); + + } + + @Test + public void testMaxOutputVoltagePositiveSetToZeroStopsMotor() { + // given + final double maxVoltage = 0; + + setupMotorVoltageForTest(kRunningValue, kWait); + // when + getME().getMotor().configMaxOutputVoltage(maxVoltage); + + setCANJaguar(1, kRunningValue); + // then + kWait.until(new RunnableAssert( + "Waiting for the speed to reduce to zero using max output voltage") { + @Override + public void run() throws Exception { + runMotorForward(); + assertEquals("Speed did not go to zero when the max output voltage was set to " + + maxVoltage, 0, getME().getMotor().getSpeed(), kEncoderSpeedTolerance); + } + }); + } + + + @Test + public void testMaxOutputVoltageNegative() { + // given + double maxVoltage = 3; + + setupMotorVoltageForTest(-kRunningValue, kWait); + final double fastSpeed = getME().getMotor().getSpeed(); + + // when + getME().getMotor().configMaxOutputVoltage(maxVoltage); + setCANJaguar(1, -kRunningValue); + + // then + kWait.until(new RunnableAssert("Waiting for the speed to reduce using max output voltage") { + + @Override + public void run() throws Exception { + runMotorReverse(); + assertThat("Speed did not reduce when the max output voltage was set", fastSpeed, + is(lessThan(getME().getMotor().getSpeed()))); + } + }); + } + + @Test + public void testMaxOutputVoltageNegativeSetToZeroStopsMotor() { + // given + final double maxVoltage = 0; + setupMotorVoltageForTest(-kRunningValue, kWait); + + // when + getME().getMotor().configMaxOutputVoltage(maxVoltage); + setCANJaguar(1, -kRunningValue); + + // Then + kWait.until(new RunnableAssert( + "Waiting for the speed to reduce to zero using max output voltage") { + @Override + public void run() throws Exception { + runMotorReverse(); + assertEquals("Speed did not go to zero when the max output voltage was set to " + + maxVoltage, 0, getME().getMotor().getSpeed(), kEncoderSpeedTolerance); + } + }); + } } diff --git a/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/can/package-info.java b/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/can/package-info.java index a4c9687b57..1a9b6db2a5 100644 --- a/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/can/package-info.java +++ b/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/can/package-info.java @@ -1,8 +1,9 @@ /** - * Provides a suite of tests to cover CANJaguar fully in all different control modes - * and with each supported positional input. Different setup parameters are provided in each Test class. - * All test classes that want to take advantage of the default test setup frameworks in place should - * extend {@link AbstractCANTest} - * + * Provides a suite of tests to cover CANJaguar fully in all different control + * modes and with each supported positional input. Different setup parameters + * are provided in each Test class. All test classes that want to take advantage + * of the default test setup frameworks in place should extend + * {@link AbstractCANTest} + *$ */ package edu.wpi.first.wpilibj.can; \ No newline at end of file diff --git a/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/command/AbstractCommandTest.java b/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/command/AbstractCommandTest.java index 0d8b3f2531..162f43ba10 100644 --- a/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/command/AbstractCommandTest.java +++ b/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/command/AbstractCommandTest.java @@ -1,8 +1,8 @@ /*----------------------------------------------------------------------------*/ -/* Copyright (c) FIRST 2008-2014. All Rights Reserved. */ -/* Open Source Software - may be modified and shared by FRC teams. The code */ +/* Copyright (c) FIRST 2008-2014. All Rights Reserved. */ +/* Open Source Software - may be modified and shared by FRC teams. The code */ /* must be accompanied by the FIRST BSD license file in the root directory of */ -/* the project. */ +/* the project. */ /*----------------------------------------------------------------------------*/ package edu.wpi.first.wpilibj.command; @@ -19,39 +19,41 @@ import edu.wpi.first.wpilibj.test.AbstractComsSetup; * */ public abstract class AbstractCommandTest extends AbstractComsSetup { - - @Before - public void commandSetup(){ - Scheduler.getInstance().removeAll(); - Scheduler.getInstance().enable(); - } - - public class ASubsystem extends Subsystem { - Command command; - protected void initDefaultCommand(){ - if(command != null){ - setDefaultCommand(command); - } - } - - public void init(Command command) { - this.command = command; - } + + @Before + public void commandSetup() { + Scheduler.getInstance().removeAll(); + Scheduler.getInstance().enable(); + } + + public class ASubsystem extends Subsystem { + Command command; + + protected void initDefaultCommand() { + if (command != null) { + setDefaultCommand(command); + } } - - public void assertCommandState(MockCommand command, int initialize, int execute, int isFinished, int end, int interrupted){ - assertEquals(initialize, command.getInitializeCount()); - assertEquals(execute, command.getExecuteCount()); - assertEquals(isFinished, command.getIsFinishedCount()); - assertEquals(end, command.getEndCount()); - assertEquals(interrupted, command.getInterruptedCount()); - } - - public void sleep(int time){ - try { - Thread.sleep(time); - } catch (InterruptedException ex) { - fail("Sleep Interrupted!?!?!?!?"); - } - } + + public void init(Command command) { + this.command = command; + } + } + + public void assertCommandState(MockCommand command, int initialize, int execute, int isFinished, + int end, int interrupted) { + assertEquals(initialize, command.getInitializeCount()); + assertEquals(execute, command.getExecuteCount()); + assertEquals(isFinished, command.getIsFinishedCount()); + assertEquals(end, command.getEndCount()); + assertEquals(interrupted, command.getInterruptedCount()); + } + + public void sleep(int time) { + try { + Thread.sleep(time); + } catch (InterruptedException ex) { + fail("Sleep Interrupted!?!?!?!?"); + } + } } diff --git a/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/command/ButtonTest.java b/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/command/ButtonTest.java index 3227fd6814..1d1eebda32 100644 --- a/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/command/ButtonTest.java +++ b/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/command/ButtonTest.java @@ -1,8 +1,8 @@ /*----------------------------------------------------------------------------*/ -/* Copyright (c) FIRST 2008-2014. All Rights Reserved. */ -/* Open Source Software - may be modified and shared by FRC teams. The code */ +/* Copyright (c) FIRST 2008-2014. All Rights Reserved. */ +/* Open Source Software - may be modified and shared by FRC teams. The code */ /* must be accompanied by the FIRST BSD license file in the root directory of */ -/* the project. */ +/* the project. */ /*----------------------------------------------------------------------------*/ package edu.wpi.first.wpilibj.command; @@ -24,129 +24,126 @@ import edu.wpi.first.wpilibj.mocks.MockCommand; * */ public class ButtonTest extends AbstractCommandTest { - private static final Logger logger = Logger.getLogger(ButtonTest.class.getName()); - - private InternalButton button1; - private InternalButton button2; - - protected Logger getClassLogger(){ - return logger; - } - - /** - * @throws java.lang.Exception - */ - @BeforeClass - public static void setUpBeforeClass() throws Exception { - } + private static final Logger logger = Logger.getLogger(ButtonTest.class.getName()); - /** - * @throws java.lang.Exception - */ - @AfterClass - public static void tearDownAfterClass() throws Exception { - } + private InternalButton button1; + private InternalButton button2; - /** - * @throws java.lang.Exception - */ - @Before - public void setUp() throws Exception { - button1 = new InternalButton(); - button2 = new InternalButton(); - } + protected Logger getClassLogger() { + return logger; + } - /** - * @throws java.lang.Exception - */ - @After - public void tearDown() throws Exception { - } + /** + * @throws java.lang.Exception + */ + @BeforeClass + public static void setUpBeforeClass() throws Exception {} - /** - * Simple Button Test - */ - @Test - public void test() { - MockCommand command1 = new MockCommand(); - MockCommand command2 = new MockCommand(); - MockCommand command3 = new MockCommand(); - MockCommand command4 = new MockCommand(); - - button1.whenPressed(command1); - button1.whenReleased(command2); - button1.whileHeld(command3); - button2.whileHeld(command4); - - assertCommandState(command1, 0, 0, 0, 0, 0); - assertCommandState(command2, 0, 0, 0, 0, 0); - assertCommandState(command3, 0, 0, 0, 0, 0); - assertCommandState(command4, 0, 0, 0, 0, 0); - button1.setPressed(true); - assertCommandState(command1, 0, 0, 0, 0, 0); - assertCommandState(command2, 0, 0, 0, 0, 0); - assertCommandState(command3, 0, 0, 0, 0, 0); - assertCommandState(command4, 0, 0, 0, 0, 0); - Scheduler.getInstance().run(); - assertCommandState(command1, 0, 0, 0, 0, 0); - assertCommandState(command2, 0, 0, 0, 0, 0); - assertCommandState(command3, 0, 0, 0, 0, 0); - assertCommandState(command4, 0, 0, 0, 0, 0); - Scheduler.getInstance().run(); - assertCommandState(command1, 1, 1, 1, 0, 0); - assertCommandState(command2, 0, 0, 0, 0, 0); - assertCommandState(command3, 1, 1, 1, 0, 0); - assertCommandState(command4, 0, 0, 0, 0, 0); - Scheduler.getInstance().run(); - assertCommandState(command1, 1, 2, 2, 0, 0); - assertCommandState(command2, 0, 0, 0, 0, 0); - assertCommandState(command3, 1, 2, 2, 0, 0); - assertCommandState(command4, 0, 0, 0, 0, 0); - button2.setPressed(true); - Scheduler.getInstance().run(); - assertCommandState(command1, 1, 3, 3, 0, 0); - assertCommandState(command2, 0, 0, 0, 0, 0); - assertCommandState(command3, 1, 3, 3, 0, 0); - assertCommandState(command4, 0, 0, 0, 0, 0); - Scheduler.getInstance().run(); - assertCommandState(command1, 1, 4, 4, 0, 0); - assertCommandState(command2, 0, 0, 0, 0, 0); - assertCommandState(command3, 1, 4, 4, 0, 0); - assertCommandState(command4, 1, 1, 1, 0, 0); - button1.setPressed(false); - Scheduler.getInstance().run(); - assertCommandState(command1, 1, 5, 5, 0, 0); - assertCommandState(command2, 0, 0, 0, 0, 0); - assertCommandState(command3, 1, 4, 4, 0, 1); - assertCommandState(command4, 1, 2, 2, 0, 0); - Scheduler.getInstance().run(); - assertCommandState(command1, 1, 6, 6, 0, 0); - assertCommandState(command2, 1, 1, 1, 0, 0); - assertCommandState(command3, 1, 4, 4, 0, 1); - assertCommandState(command4, 1, 3, 3, 0, 0); - button2.setPressed(false); - Scheduler.getInstance().run(); - assertCommandState(command1, 1, 7, 7, 0, 0); - assertCommandState(command2, 1, 2, 2, 0, 0); - assertCommandState(command3, 1, 4, 4, 0, 1); - assertCommandState(command4, 1, 3, 3, 0, 1); - command1.cancel(); - Scheduler.getInstance().run(); - assertCommandState(command1, 1, 7, 7, 0, 1); - assertCommandState(command2, 1, 3, 3, 0, 0); - assertCommandState(command3, 1, 4, 4, 0, 1); - assertCommandState(command4, 1, 3, 3, 0, 1); - command2.setHasFinished(true); - Scheduler.getInstance().run(); - assertCommandState(command1, 1, 7, 7, 0, 1); - assertCommandState(command2, 1, 4, 4, 1, 0); - assertCommandState(command3, 1, 4, 4, 0, 1); - assertCommandState(command4, 1, 3, 3, 0, 1); - Scheduler.getInstance().run(); - assertCommandState(command1, 1, 7, 7, 0, 1); - assertCommandState(command2, 1, 4, 4, 1, 0); - assertCommandState(command3, 1, 4, 4, 0, 1); - assertCommandState(command4, 1, 3, 3, 0, 1); - } + /** + * @throws java.lang.Exception + */ + @AfterClass + public static void tearDownAfterClass() throws Exception {} + + /** + * @throws java.lang.Exception + */ + @Before + public void setUp() throws Exception { + button1 = new InternalButton(); + button2 = new InternalButton(); + } + + /** + * @throws java.lang.Exception + */ + @After + public void tearDown() throws Exception {} + + /** + * Simple Button Test + */ + @Test + public void test() { + MockCommand command1 = new MockCommand(); + MockCommand command2 = new MockCommand(); + MockCommand command3 = new MockCommand(); + MockCommand command4 = new MockCommand(); + + button1.whenPressed(command1); + button1.whenReleased(command2); + button1.whileHeld(command3); + button2.whileHeld(command4); + + assertCommandState(command1, 0, 0, 0, 0, 0); + assertCommandState(command2, 0, 0, 0, 0, 0); + assertCommandState(command3, 0, 0, 0, 0, 0); + assertCommandState(command4, 0, 0, 0, 0, 0); + button1.setPressed(true); + assertCommandState(command1, 0, 0, 0, 0, 0); + assertCommandState(command2, 0, 0, 0, 0, 0); + assertCommandState(command3, 0, 0, 0, 0, 0); + assertCommandState(command4, 0, 0, 0, 0, 0); + Scheduler.getInstance().run(); + assertCommandState(command1, 0, 0, 0, 0, 0); + assertCommandState(command2, 0, 0, 0, 0, 0); + assertCommandState(command3, 0, 0, 0, 0, 0); + assertCommandState(command4, 0, 0, 0, 0, 0); + Scheduler.getInstance().run(); + assertCommandState(command1, 1, 1, 1, 0, 0); + assertCommandState(command2, 0, 0, 0, 0, 0); + assertCommandState(command3, 1, 1, 1, 0, 0); + assertCommandState(command4, 0, 0, 0, 0, 0); + Scheduler.getInstance().run(); + assertCommandState(command1, 1, 2, 2, 0, 0); + assertCommandState(command2, 0, 0, 0, 0, 0); + assertCommandState(command3, 1, 2, 2, 0, 0); + assertCommandState(command4, 0, 0, 0, 0, 0); + button2.setPressed(true); + Scheduler.getInstance().run(); + assertCommandState(command1, 1, 3, 3, 0, 0); + assertCommandState(command2, 0, 0, 0, 0, 0); + assertCommandState(command3, 1, 3, 3, 0, 0); + assertCommandState(command4, 0, 0, 0, 0, 0); + Scheduler.getInstance().run(); + assertCommandState(command1, 1, 4, 4, 0, 0); + assertCommandState(command2, 0, 0, 0, 0, 0); + assertCommandState(command3, 1, 4, 4, 0, 0); + assertCommandState(command4, 1, 1, 1, 0, 0); + button1.setPressed(false); + Scheduler.getInstance().run(); + assertCommandState(command1, 1, 5, 5, 0, 0); + assertCommandState(command2, 0, 0, 0, 0, 0); + assertCommandState(command3, 1, 4, 4, 0, 1); + assertCommandState(command4, 1, 2, 2, 0, 0); + Scheduler.getInstance().run(); + assertCommandState(command1, 1, 6, 6, 0, 0); + assertCommandState(command2, 1, 1, 1, 0, 0); + assertCommandState(command3, 1, 4, 4, 0, 1); + assertCommandState(command4, 1, 3, 3, 0, 0); + button2.setPressed(false); + Scheduler.getInstance().run(); + assertCommandState(command1, 1, 7, 7, 0, 0); + assertCommandState(command2, 1, 2, 2, 0, 0); + assertCommandState(command3, 1, 4, 4, 0, 1); + assertCommandState(command4, 1, 3, 3, 0, 1); + command1.cancel(); + Scheduler.getInstance().run(); + assertCommandState(command1, 1, 7, 7, 0, 1); + assertCommandState(command2, 1, 3, 3, 0, 0); + assertCommandState(command3, 1, 4, 4, 0, 1); + assertCommandState(command4, 1, 3, 3, 0, 1); + command2.setHasFinished(true); + Scheduler.getInstance().run(); + assertCommandState(command1, 1, 7, 7, 0, 1); + assertCommandState(command2, 1, 4, 4, 1, 0); + assertCommandState(command3, 1, 4, 4, 0, 1); + assertCommandState(command4, 1, 3, 3, 0, 1); + Scheduler.getInstance().run(); + assertCommandState(command1, 1, 7, 7, 0, 1); + assertCommandState(command2, 1, 4, 4, 1, 0); + assertCommandState(command3, 1, 4, 4, 0, 1); + assertCommandState(command4, 1, 3, 3, 0, 1); + } } diff --git a/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/command/CommandParallelGroupTest.java b/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/command/CommandParallelGroupTest.java index 9ce6efad14..cb1a9e760d 100644 --- a/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/command/CommandParallelGroupTest.java +++ b/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/command/CommandParallelGroupTest.java @@ -1,8 +1,8 @@ /*----------------------------------------------------------------------------*/ -/* Copyright (c) FIRST 2008-2014. All Rights Reserved. */ -/* Open Source Software - may be modified and shared by FRC teams. The code */ +/* Copyright (c) FIRST 2008-2014. All Rights Reserved. */ +/* Open Source Software - may be modified and shared by FRC teams. The code */ /* must be accompanied by the FIRST BSD license file in the root directory of */ -/* the project. */ +/* the project. */ /*----------------------------------------------------------------------------*/ package edu.wpi.first.wpilibj.command; @@ -21,89 +21,86 @@ import edu.wpi.first.wpilibj.test.AbstractComsSetup; /** * Ported from the old CrioTest Classes + *$ * @author Mitchell * @author Jonathan Leitschuh */ public class CommandParallelGroupTest extends AbstractCommandTest { - private static final Logger logger = Logger.getLogger(CommandParallelGroupTest.class.getName()); - - protected Logger getClassLogger(){ - return logger; - } + private static final Logger logger = Logger.getLogger(CommandParallelGroupTest.class.getName()); - /** - * @throws java.lang.Exception - */ - @BeforeClass - public static void setUpBeforeClass() throws Exception { - } + protected Logger getClassLogger() { + return logger; + } - /** - * @throws java.lang.Exception - */ - @AfterClass - public static void tearDownAfterClass() throws Exception { - } + /** + * @throws java.lang.Exception + */ + @BeforeClass + public static void setUpBeforeClass() throws Exception {} - /** - * @throws java.lang.Exception - */ - @Before - public void setUp() throws Exception { - } + /** + * @throws java.lang.Exception + */ + @AfterClass + public static void tearDownAfterClass() throws Exception {} - /** - * @throws java.lang.Exception - */ - @After - public void tearDown() throws Exception { - } + /** + * @throws java.lang.Exception + */ + @Before + public void setUp() throws Exception {} - /** - * Simple Parallel Command Group With 2 commands one command terminates first - */ - @Test - public void testParallelCommandGroupWithTwoCommands() { - MockCommand command1 = new MockCommand(); - MockCommand command2 = new MockCommand(); + /** + * @throws java.lang.Exception + */ + @After + public void tearDown() throws Exception {} - CommandGroup commandGroup = new CommandGroup(); - commandGroup.addParallel(command1); - commandGroup.addParallel(command2); + /** + * Simple Parallel Command Group With 2 commands one command terminates first + */ + @Test + public void testParallelCommandGroupWithTwoCommands() { + MockCommand command1 = new MockCommand(); + MockCommand command2 = new MockCommand(); - assertCommandState(command1, 0, 0, 0, 0, 0); - assertCommandState(command2, 0, 0, 0, 0, 0); - commandGroup.start(); - assertCommandState(command1, 0, 0, 0, 0, 0); - assertCommandState(command2, 0, 0, 0, 0, 0); - Scheduler.getInstance().run(); - assertCommandState(command1, 0, 0, 0, 0, 0); - assertCommandState(command2, 0, 0, 0, 0, 0); - Scheduler.getInstance().run(); - assertCommandState(command1, 1, 1, 1, 0, 0); - assertCommandState(command2, 1, 1, 1, 0, 0); - Scheduler.getInstance().run(); - assertCommandState(command1, 1, 2, 2, 0, 0); - assertCommandState(command2, 1, 2, 2, 0, 0); - command1.setHasFinished(true); - Scheduler.getInstance().run(); - assertCommandState(command1, 1, 3, 3, 1, 0); - assertCommandState(command2, 1, 3, 3, 0, 0); - Scheduler.getInstance().run(); - assertCommandState(command1, 1, 3, 3, 1, 0); - assertCommandState(command2, 1, 4, 4, 0, 0); - command2.setHasFinished(true); - Scheduler.getInstance().run(); - assertCommandState(command1, 1, 3, 3, 1, 0); - assertCommandState(command2, 1, 5, 5, 1, 0); + CommandGroup commandGroup = new CommandGroup(); + commandGroup.addParallel(command1); + commandGroup.addParallel(command2); - } + assertCommandState(command1, 0, 0, 0, 0, 0); + assertCommandState(command2, 0, 0, 0, 0, 0); + commandGroup.start(); + assertCommandState(command1, 0, 0, 0, 0, 0); + assertCommandState(command2, 0, 0, 0, 0, 0); + Scheduler.getInstance().run(); + assertCommandState(command1, 0, 0, 0, 0, 0); + assertCommandState(command2, 0, 0, 0, 0, 0); + Scheduler.getInstance().run(); + assertCommandState(command1, 1, 1, 1, 0, 0); + assertCommandState(command2, 1, 1, 1, 0, 0); + Scheduler.getInstance().run(); + assertCommandState(command1, 1, 2, 2, 0, 0); + assertCommandState(command2, 1, 2, 2, 0, 0); + command1.setHasFinished(true); + Scheduler.getInstance().run(); + assertCommandState(command1, 1, 3, 3, 1, 0); + assertCommandState(command2, 1, 3, 3, 0, 0); + Scheduler.getInstance().run(); + assertCommandState(command1, 1, 3, 3, 1, 0); + assertCommandState(command2, 1, 4, 4, 0, 0); + command2.setHasFinished(true); + Scheduler.getInstance().run(); + assertCommandState(command1, 1, 3, 3, 1, 0); + assertCommandState(command2, 1, 5, 5, 1, 0); - public void sleep(long time) { - try { - Thread.sleep(time); - } catch (InterruptedException ex) { - fail("Sleep Interrupted!?!?!?!?"); - } - } + } + + public void sleep(long time) { + try { + Thread.sleep(time); + } catch (InterruptedException ex) { + fail("Sleep Interrupted!?!?!?!?"); + } + } } diff --git a/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/command/CommandScheduleTest.java b/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/command/CommandScheduleTest.java index 965c8af8ed..72b404a5b0 100644 --- a/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/command/CommandScheduleTest.java +++ b/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/command/CommandScheduleTest.java @@ -1,8 +1,8 @@ /*----------------------------------------------------------------------------*/ -/* Copyright (c) FIRST 2008-2014. All Rights Reserved. */ -/* Open Source Software - may be modified and shared by FRC teams. The code */ +/* Copyright (c) FIRST 2008-2014. All Rights Reserved. */ +/* Open Source Software - may be modified and shared by FRC teams. The code */ /* must be accompanied by the FIRST BSD license file in the root directory of */ -/* the project. */ +/* the project. */ /*----------------------------------------------------------------------------*/ package edu.wpi.first.wpilibj.command; @@ -20,87 +20,86 @@ import edu.wpi.first.wpilibj.mocks.MockCommand; /** * Ported from the old CrioTest Classes + *$ * @author Mitchell * @author Jonathan Leitschuh */ public class CommandScheduleTest extends AbstractCommandTest { - private static final Logger logger = Logger.getLogger(CommandScheduleTest.class.getName()); - - protected Logger getClassLogger(){ - return logger; - } + private static final Logger logger = Logger.getLogger(CommandScheduleTest.class.getName()); - /** - * @throws java.lang.Exception - */ - @BeforeClass - public static void setUpBeforeClass() throws Exception { - } + protected Logger getClassLogger() { + return logger; + } - /** - * @throws java.lang.Exception - */ - @AfterClass - public static void tearDownAfterClass() throws Exception { - } + /** + * @throws java.lang.Exception + */ + @BeforeClass + public static void setUpBeforeClass() throws Exception {} - /** - * @throws java.lang.Exception - */ - @Before - public void setUp() throws Exception { - } + /** + * @throws java.lang.Exception + */ + @AfterClass + public static void tearDownAfterClass() throws Exception {} - /** - * @throws java.lang.Exception - */ - @After - public void tearDown() throws Exception { - } + /** + * @throws java.lang.Exception + */ + @Before + public void setUp() throws Exception {} - /** - * Simple scheduling of a command and making sure the command is run and successfully terminates - */ - @Test - public void testRunAndTerminate() { - MockCommand command = new MockCommand(); - command.start(); - assertCommandState(command, 0, 0, 0, 0, 0); - Scheduler.getInstance().run(); - assertCommandState(command, 0, 0, 0, 0, 0); - Scheduler.getInstance().run(); - assertCommandState(command, 1, 1, 1, 0, 0); - Scheduler.getInstance().run(); - assertCommandState(command, 1, 2, 2, 0, 0); - command.setHasFinished(true); - assertCommandState(command, 1, 2, 2, 0, 0); - Scheduler.getInstance().run(); - assertCommandState(command, 1, 3, 3, 1, 0); - Scheduler.getInstance().run(); - assertCommandState(command, 1, 3, 3, 1, 0); - } - - /** - * Simple scheduling of a command and making sure the command is run and cancels correctly - */ - @Test - public void testRunAndCancel(){ - MockCommand command = new MockCommand(); - command.start(); - assertCommandState(command, 0, 0, 0, 0, 0); - Scheduler.getInstance().run(); - assertCommandState(command, 0, 0, 0, 0, 0); - Scheduler.getInstance().run(); - assertCommandState(command, 1, 1, 1, 0, 0); - Scheduler.getInstance().run(); - assertCommandState(command, 1, 2, 2, 0, 0); - Scheduler.getInstance().run(); - assertCommandState(command, 1, 3, 3, 0, 0); - command.cancel(); - assertCommandState(command, 1, 3, 3, 0, 0); - Scheduler.getInstance().run(); - assertCommandState(command, 1, 3, 3, 0, 1); - Scheduler.getInstance().run(); - assertCommandState(command, 1, 3, 3, 0, 1); - } + /** + * @throws java.lang.Exception + */ + @After + public void tearDown() throws Exception {} + + /** + * Simple scheduling of a command and making sure the command is run and + * successfully terminates + */ + @Test + public void testRunAndTerminate() { + MockCommand command = new MockCommand(); + command.start(); + assertCommandState(command, 0, 0, 0, 0, 0); + Scheduler.getInstance().run(); + assertCommandState(command, 0, 0, 0, 0, 0); + Scheduler.getInstance().run(); + assertCommandState(command, 1, 1, 1, 0, 0); + Scheduler.getInstance().run(); + assertCommandState(command, 1, 2, 2, 0, 0); + command.setHasFinished(true); + assertCommandState(command, 1, 2, 2, 0, 0); + Scheduler.getInstance().run(); + assertCommandState(command, 1, 3, 3, 1, 0); + Scheduler.getInstance().run(); + assertCommandState(command, 1, 3, 3, 1, 0); + } + + /** + * Simple scheduling of a command and making sure the command is run and + * cancels correctly + */ + @Test + public void testRunAndCancel() { + MockCommand command = new MockCommand(); + command.start(); + assertCommandState(command, 0, 0, 0, 0, 0); + Scheduler.getInstance().run(); + assertCommandState(command, 0, 0, 0, 0, 0); + Scheduler.getInstance().run(); + assertCommandState(command, 1, 1, 1, 0, 0); + Scheduler.getInstance().run(); + assertCommandState(command, 1, 2, 2, 0, 0); + Scheduler.getInstance().run(); + assertCommandState(command, 1, 3, 3, 0, 0); + command.cancel(); + assertCommandState(command, 1, 3, 3, 0, 0); + Scheduler.getInstance().run(); + assertCommandState(command, 1, 3, 3, 0, 1); + Scheduler.getInstance().run(); + assertCommandState(command, 1, 3, 3, 0, 1); + } } diff --git a/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/command/CommandSequentialGroupTest.java b/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/command/CommandSequentialGroupTest.java index fa5ef2d243..2f0bdfb0b9 100644 --- a/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/command/CommandSequentialGroupTest.java +++ b/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/command/CommandSequentialGroupTest.java @@ -1,8 +1,8 @@ /*----------------------------------------------------------------------------*/ -/* Copyright (c) FIRST 2008-2014. All Rights Reserved. */ -/* Open Source Software - may be modified and shared by FRC teams. The code */ +/* Copyright (c) FIRST 2008-2014. All Rights Reserved. */ +/* Open Source Software - may be modified and shared by FRC teams. The code */ /* must be accompanied by the FIRST BSD license file in the root directory of */ -/* the project. */ +/* the project. */ /*----------------------------------------------------------------------------*/ package edu.wpi.first.wpilibj.command; @@ -19,126 +19,124 @@ import edu.wpi.first.wpilibj.mocks.MockCommand; /** * Ported from the old CrioTest Classes + *$ * @author Mitchell * @author Jonathan Leitschuh */ public class CommandSequentialGroupTest extends AbstractCommandTest { - private static final Logger logger = Logger.getLogger(CommandSequentialGroupTest.class.getName()); - - protected Logger getClassLogger(){ - return logger; - } - - /** - * @throws java.lang.Exception - */ - @BeforeClass - public static void setUpBeforeClass() throws Exception { - } + private static final Logger logger = Logger.getLogger(CommandSequentialGroupTest.class.getName()); - /** - * @throws java.lang.Exception - */ - @AfterClass - public static void tearDownAfterClass() throws Exception { - } + protected Logger getClassLogger() { + return logger; + } - /** - * @throws java.lang.Exception - */ - @Before - public void setUp() throws Exception { - } + /** + * @throws java.lang.Exception + */ + @BeforeClass + public static void setUpBeforeClass() throws Exception {} - /** - * @throws java.lang.Exception - */ - @After - public void tearDown() throws Exception { - } + /** + * @throws java.lang.Exception + */ + @AfterClass + public static void tearDownAfterClass() throws Exception {} - /** - * Simple Command Group With 3 commands that all depend on a subsystem. Some commands have a timeout - */ - @Test(timeout = 20000) - public void testThreeCommandOnSubSystem() { - logger.fine("Begining Test"); - final ASubsystem subsystem = new ASubsystem(); - - logger.finest("Creating Mock Command1"); - MockCommand command1 = new MockCommand() { - { - requires(subsystem); - } - }; - logger.finest("Creating Mock Command2"); - MockCommand command2 = new MockCommand() { - { - requires(subsystem); - } - }; - logger.finest("Creating Mock Command3"); - MockCommand command3 = new MockCommand() { - { - requires(subsystem); - } - }; - - logger.finest("Creating Command Group"); - CommandGroup commandGroup = new CommandGroup(); - commandGroup.addSequential(command1, 1.0); - commandGroup.addSequential(command2, 2.0); - commandGroup.addSequential(command3); - - - assertCommandState(command1, 0, 0, 0, 0, 0); - assertCommandState(command2, 0, 0, 0, 0, 0); - assertCommandState(command3, 0, 0, 0, 0, 0); - logger.finest("Starting Command group"); - commandGroup.start(); - assertCommandState(command1, 0, 0, 0, 0, 0); - assertCommandState(command2, 0, 0, 0, 0, 0); - assertCommandState(command3, 0, 0, 0, 0, 0); - Scheduler.getInstance().run(); - assertCommandState(command1, 0, 0, 0, 0, 0); - assertCommandState(command2, 0, 0, 0, 0, 0); - assertCommandState(command3, 0, 0, 0, 0, 0); - Scheduler.getInstance().run(); - assertCommandState(command1, 1, 1, 1, 0, 0); - assertCommandState(command2, 0, 0, 0, 0, 0); - assertCommandState(command3, 0, 0, 0, 0, 0); - sleep(1000);//command 1 timeout - Scheduler.getInstance().run(); - assertCommandState(command1, 1, 1, 1, 0, 1); - assertCommandState(command2, 1, 1, 1, 0, 0); - assertCommandState(command3, 0, 0, 0, 0, 0); - - Scheduler.getInstance().run(); - assertCommandState(command1, 1, 1, 1, 0, 1); - assertCommandState(command2, 1, 2, 2, 0, 0); - assertCommandState(command3, 0, 0, 0, 0, 0); - sleep(2000);//command 2 timeout - Scheduler.getInstance().run(); - assertCommandState(command1, 1, 1, 1, 0, 1); - assertCommandState(command2, 1, 2, 2, 0, 1); - assertCommandState(command3, 1, 1 ,1, 0, 0); - - Scheduler.getInstance().run(); - assertCommandState(command1, 1, 1, 1, 0, 1); - assertCommandState(command2, 1, 2, 2, 0, 1); - assertCommandState(command3, 1, 2, 2, 0, 0); - command3.setHasFinished(true); - assertCommandState(command1, 1, 1, 1, 0, 1); - assertCommandState(command2, 1, 2, 2, 0, 1); - assertCommandState(command3, 1, 2, 2, 0, 0); - Scheduler.getInstance().run(); - assertCommandState(command1, 1, 1, 1, 0, 1); - assertCommandState(command2, 1, 2, 2, 0, 1); - assertCommandState(command3, 1, 3, 3, 1, 0); - Scheduler.getInstance().run(); - assertCommandState(command1, 1, 1, 1, 0, 1); - assertCommandState(command2, 1, 2, 2, 0, 1); - assertCommandState(command3, 1, 3, 3, 1, 0); - } + /** + * @throws java.lang.Exception + */ + @Before + public void setUp() throws Exception {} + + /** + * @throws java.lang.Exception + */ + @After + public void tearDown() throws Exception {} + + /** + * Simple Command Group With 3 commands that all depend on a subsystem. Some + * commands have a timeout + */ + @Test(timeout = 20000) + public void testThreeCommandOnSubSystem() { + logger.fine("Begining Test"); + final ASubsystem subsystem = new ASubsystem(); + + logger.finest("Creating Mock Command1"); + MockCommand command1 = new MockCommand() { + { + requires(subsystem); + } + }; + logger.finest("Creating Mock Command2"); + MockCommand command2 = new MockCommand() { + { + requires(subsystem); + } + }; + logger.finest("Creating Mock Command3"); + MockCommand command3 = new MockCommand() { + { + requires(subsystem); + } + }; + + logger.finest("Creating Command Group"); + CommandGroup commandGroup = new CommandGroup(); + commandGroup.addSequential(command1, 1.0); + commandGroup.addSequential(command2, 2.0); + commandGroup.addSequential(command3); + + + assertCommandState(command1, 0, 0, 0, 0, 0); + assertCommandState(command2, 0, 0, 0, 0, 0); + assertCommandState(command3, 0, 0, 0, 0, 0); + logger.finest("Starting Command group"); + commandGroup.start(); + assertCommandState(command1, 0, 0, 0, 0, 0); + assertCommandState(command2, 0, 0, 0, 0, 0); + assertCommandState(command3, 0, 0, 0, 0, 0); + Scheduler.getInstance().run(); + assertCommandState(command1, 0, 0, 0, 0, 0); + assertCommandState(command2, 0, 0, 0, 0, 0); + assertCommandState(command3, 0, 0, 0, 0, 0); + Scheduler.getInstance().run(); + assertCommandState(command1, 1, 1, 1, 0, 0); + assertCommandState(command2, 0, 0, 0, 0, 0); + assertCommandState(command3, 0, 0, 0, 0, 0); + sleep(1000);// command 1 timeout + Scheduler.getInstance().run(); + assertCommandState(command1, 1, 1, 1, 0, 1); + assertCommandState(command2, 1, 1, 1, 0, 0); + assertCommandState(command3, 0, 0, 0, 0, 0); + + Scheduler.getInstance().run(); + assertCommandState(command1, 1, 1, 1, 0, 1); + assertCommandState(command2, 1, 2, 2, 0, 0); + assertCommandState(command3, 0, 0, 0, 0, 0); + sleep(2000);// command 2 timeout + Scheduler.getInstance().run(); + assertCommandState(command1, 1, 1, 1, 0, 1); + assertCommandState(command2, 1, 2, 2, 0, 1); + assertCommandState(command3, 1, 1, 1, 0, 0); + + Scheduler.getInstance().run(); + assertCommandState(command1, 1, 1, 1, 0, 1); + assertCommandState(command2, 1, 2, 2, 0, 1); + assertCommandState(command3, 1, 2, 2, 0, 0); + command3.setHasFinished(true); + assertCommandState(command1, 1, 1, 1, 0, 1); + assertCommandState(command2, 1, 2, 2, 0, 1); + assertCommandState(command3, 1, 2, 2, 0, 0); + Scheduler.getInstance().run(); + assertCommandState(command1, 1, 1, 1, 0, 1); + assertCommandState(command2, 1, 2, 2, 0, 1); + assertCommandState(command3, 1, 3, 3, 1, 0); + Scheduler.getInstance().run(); + assertCommandState(command1, 1, 1, 1, 0, 1); + assertCommandState(command2, 1, 2, 2, 0, 1); + assertCommandState(command3, 1, 3, 3, 1, 0); + } } diff --git a/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/command/CommandSupersedeTest.java b/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/command/CommandSupersedeTest.java index 690bae1b48..36af21d799 100644 --- a/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/command/CommandSupersedeTest.java +++ b/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/command/CommandSupersedeTest.java @@ -1,8 +1,8 @@ /*----------------------------------------------------------------------------*/ -/* Copyright (c) FIRST 2008-2014. All Rights Reserved. */ -/* Open Source Software - may be modified and shared by FRC teams. The code */ +/* Copyright (c) FIRST 2008-2014. All Rights Reserved. */ +/* Open Source Software - may be modified and shared by FRC teams. The code */ /* must be accompanied by the FIRST BSD license file in the root directory of */ -/* the project. */ +/* the project. */ /*----------------------------------------------------------------------------*/ package edu.wpi.first.wpilibj.command; @@ -18,142 +18,138 @@ import edu.wpi.first.wpilibj.mocks.MockCommand; /** * Ported from the old CrioTest Classes - * + *$ * @author Mitchell * @author Jonathan Leitschuh */ public class CommandSupersedeTest extends AbstractCommandTest { - private static final Logger logger = Logger.getLogger(CommandSupersedeTest.class.getName()); - - protected Logger getClassLogger(){ - return logger; - } + private static final Logger logger = Logger.getLogger(CommandSupersedeTest.class.getName()); - /** - * @throws java.lang.Exception - */ - @BeforeClass - public static void setUpBeforeClass() throws Exception { - } + protected Logger getClassLogger() { + return logger; + } - /** - * @throws java.lang.Exception - */ - @AfterClass - public static void tearDownAfterClass() throws Exception { - } + /** + * @throws java.lang.Exception + */ + @BeforeClass + public static void setUpBeforeClass() throws Exception {} - /** - * @throws java.lang.Exception - */ - @Before - public void setUp() throws Exception { - } + /** + * @throws java.lang.Exception + */ + @AfterClass + public static void tearDownAfterClass() throws Exception {} - /** - * @throws java.lang.Exception - */ - @After - public void tearDown() throws Exception { - } + /** + * @throws java.lang.Exception + */ + @Before + public void setUp() throws Exception {} - /** - * Testing one command superseding another because of dependencies - */ - @Test - public void testOneCommandSupersedingAnotherBecauseOfDependencies() { - final ASubsystem subsystem = new ASubsystem(); + /** + * @throws java.lang.Exception + */ + @After + public void tearDown() throws Exception {} - MockCommand command1 = new MockCommand() { - { - requires(subsystem); - } - }; + /** + * Testing one command superseding another because of dependencies + */ + @Test + public void testOneCommandSupersedingAnotherBecauseOfDependencies() { + final ASubsystem subsystem = new ASubsystem(); - MockCommand command2 = new MockCommand() { - { - requires(subsystem); - } - }; + MockCommand command1 = new MockCommand() { + { + requires(subsystem); + } + }; - assertCommandState(command1, 0, 0, 0, 0, 0); - assertCommandState(command2, 0, 0, 0, 0, 0); - command1.start(); - assertCommandState(command1, 0, 0, 0, 0, 0); - assertCommandState(command2, 0, 0, 0, 0, 0); - Scheduler.getInstance().run(); - assertCommandState(command1, 0, 0, 0, 0, 0); - assertCommandState(command2, 0, 0, 0, 0, 0); - Scheduler.getInstance().run(); - assertCommandState(command1, 1, 1, 1, 0, 0); - assertCommandState(command2, 0, 0, 0, 0, 0); - Scheduler.getInstance().run(); - assertCommandState(command1, 1, 2, 2, 0, 0); - assertCommandState(command2, 0, 0, 0, 0, 0); - Scheduler.getInstance().run(); - assertCommandState(command1, 1, 3, 3, 0, 0); - assertCommandState(command2, 0, 0, 0, 0, 0); - command2.start(); - assertCommandState(command1, 1, 3, 3, 0, 0); - assertCommandState(command2, 0, 0, 0, 0, 0); - Scheduler.getInstance().run(); - assertCommandState(command1, 1, 4, 4, 0, 1); - assertCommandState(command2, 0, 0, 0, 0, 0); - Scheduler.getInstance().run(); - assertCommandState(command1, 1, 4, 4, 0, 1); - assertCommandState(command2, 1, 1, 1, 0, 0); - Scheduler.getInstance().run(); - assertCommandState(command1, 1, 4, 4, 0, 1); - assertCommandState(command2, 1, 2, 2, 0, 0); - Scheduler.getInstance().run(); - assertCommandState(command1, 1, 4, 4, 0, 1); - assertCommandState(command2, 1, 3, 3, 0, 0); - } + MockCommand command2 = new MockCommand() { + { + requires(subsystem); + } + }; - /** - * Testing one command failing superseding another because of dependencies - * because the first command cannot be interrupted" - */ - @Test - public void testCommandFailingSupersedingBecauseFirstCanNotBeInterrupted() { - final ASubsystem subsystem = new ASubsystem(); + assertCommandState(command1, 0, 0, 0, 0, 0); + assertCommandState(command2, 0, 0, 0, 0, 0); + command1.start(); + assertCommandState(command1, 0, 0, 0, 0, 0); + assertCommandState(command2, 0, 0, 0, 0, 0); + Scheduler.getInstance().run(); + assertCommandState(command1, 0, 0, 0, 0, 0); + assertCommandState(command2, 0, 0, 0, 0, 0); + Scheduler.getInstance().run(); + assertCommandState(command1, 1, 1, 1, 0, 0); + assertCommandState(command2, 0, 0, 0, 0, 0); + Scheduler.getInstance().run(); + assertCommandState(command1, 1, 2, 2, 0, 0); + assertCommandState(command2, 0, 0, 0, 0, 0); + Scheduler.getInstance().run(); + assertCommandState(command1, 1, 3, 3, 0, 0); + assertCommandState(command2, 0, 0, 0, 0, 0); + command2.start(); + assertCommandState(command1, 1, 3, 3, 0, 0); + assertCommandState(command2, 0, 0, 0, 0, 0); + Scheduler.getInstance().run(); + assertCommandState(command1, 1, 4, 4, 0, 1); + assertCommandState(command2, 0, 0, 0, 0, 0); + Scheduler.getInstance().run(); + assertCommandState(command1, 1, 4, 4, 0, 1); + assertCommandState(command2, 1, 1, 1, 0, 0); + Scheduler.getInstance().run(); + assertCommandState(command1, 1, 4, 4, 0, 1); + assertCommandState(command2, 1, 2, 2, 0, 0); + Scheduler.getInstance().run(); + assertCommandState(command1, 1, 4, 4, 0, 1); + assertCommandState(command2, 1, 3, 3, 0, 0); + } - MockCommand command1 = new MockCommand() { - { - requires(subsystem); - setInterruptible(false); - } - }; + /** + * Testing one command failing superseding another because of dependencies + * because the first command cannot be interrupted" + */ + @Test + public void testCommandFailingSupersedingBecauseFirstCanNotBeInterrupted() { + final ASubsystem subsystem = new ASubsystem(); - MockCommand command2 = new MockCommand() { - { - requires(subsystem); - } - }; + MockCommand command1 = new MockCommand() { + { + requires(subsystem); + setInterruptible(false); + } + }; - assertCommandState(command1, 0, 0, 0, 0, 0); - assertCommandState(command2, 0, 0, 0, 0, 0); - command1.start(); - assertCommandState(command1, 0, 0, 0, 0, 0); - assertCommandState(command2, 0, 0, 0, 0, 0); - Scheduler.getInstance().run(); - assertCommandState(command1, 0, 0, 0, 0, 0); - assertCommandState(command2, 0, 0, 0, 0, 0); - Scheduler.getInstance().run(); - assertCommandState(command1, 1, 1, 1, 0, 0); - assertCommandState(command2, 0, 0, 0, 0, 0); - Scheduler.getInstance().run(); - assertCommandState(command1, 1, 2, 2, 0, 0); - assertCommandState(command2, 0, 0, 0, 0, 0); - Scheduler.getInstance().run(); - assertCommandState(command1, 1, 3, 3, 0, 0); - assertCommandState(command2, 0, 0, 0, 0, 0); - command2.start(); - assertCommandState(command1, 1, 3, 3, 0, 0); - assertCommandState(command2, 0, 0, 0, 0, 0); - Scheduler.getInstance().run(); - assertCommandState(command1, 1, 4, 4, 0, 0); - assertCommandState(command2, 0, 0, 0, 0, 0); - } + MockCommand command2 = new MockCommand() { + { + requires(subsystem); + } + }; + + assertCommandState(command1, 0, 0, 0, 0, 0); + assertCommandState(command2, 0, 0, 0, 0, 0); + command1.start(); + assertCommandState(command1, 0, 0, 0, 0, 0); + assertCommandState(command2, 0, 0, 0, 0, 0); + Scheduler.getInstance().run(); + assertCommandState(command1, 0, 0, 0, 0, 0); + assertCommandState(command2, 0, 0, 0, 0, 0); + Scheduler.getInstance().run(); + assertCommandState(command1, 1, 1, 1, 0, 0); + assertCommandState(command2, 0, 0, 0, 0, 0); + Scheduler.getInstance().run(); + assertCommandState(command1, 1, 2, 2, 0, 0); + assertCommandState(command2, 0, 0, 0, 0, 0); + Scheduler.getInstance().run(); + assertCommandState(command1, 1, 3, 3, 0, 0); + assertCommandState(command2, 0, 0, 0, 0, 0); + command2.start(); + assertCommandState(command1, 1, 3, 3, 0, 0); + assertCommandState(command2, 0, 0, 0, 0, 0); + Scheduler.getInstance().run(); + assertCommandState(command1, 1, 4, 4, 0, 0); + assertCommandState(command2, 0, 0, 0, 0, 0); + } } diff --git a/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/command/CommandTestSuite.java b/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/command/CommandTestSuite.java index a9fae306a6..468e890762 100644 --- a/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/command/CommandTestSuite.java +++ b/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/command/CommandTestSuite.java @@ -1,8 +1,8 @@ /*----------------------------------------------------------------------------*/ -/* Copyright (c) FIRST 2008-2014. All Rights Reserved. */ -/* Open Source Software - may be modified and shared by FRC teams. The code */ +/* Copyright (c) FIRST 2008-2014. All Rights Reserved. */ +/* Open Source Software - may be modified and shared by FRC teams. The code */ /* must be accompanied by the FIRST BSD license file in the root directory of */ -/* the project. */ +/* the project. */ /*----------------------------------------------------------------------------*/ package edu.wpi.first.wpilibj.command; @@ -17,15 +17,9 @@ import edu.wpi.first.wpilibj.test.AbstractTestSuite; * */ @RunWith(Suite.class) -@SuiteClasses({ - ButtonTest.class, - CommandParallelGroupTest.class, - CommandScheduleTest.class, - CommandSequentialGroupTest.class, - CommandSupersedeTest.class, - CommandTimeoutTest.class, - DefaultCommandTest.class - }) -public class CommandTestSuite extends AbstractTestSuite{ +@SuiteClasses({ButtonTest.class, CommandParallelGroupTest.class, CommandScheduleTest.class, + CommandSequentialGroupTest.class, CommandSupersedeTest.class, CommandTimeoutTest.class, + DefaultCommandTest.class}) +public class CommandTestSuite extends AbstractTestSuite { } diff --git a/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/command/CommandTimeoutTest.java b/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/command/CommandTimeoutTest.java index ca55621283..fa18323137 100644 --- a/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/command/CommandTimeoutTest.java +++ b/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/command/CommandTimeoutTest.java @@ -1,8 +1,8 @@ /*----------------------------------------------------------------------------*/ -/* Copyright (c) FIRST 2008-2014. All Rights Reserved. */ -/* Open Source Software - may be modified and shared by FRC teams. The code */ +/* Copyright (c) FIRST 2008-2014. All Rights Reserved. */ +/* Open Source Software - may be modified and shared by FRC teams. The code */ /* must be accompanied by the FIRST BSD license file in the root directory of */ -/* the project. */ +/* the project. */ /*----------------------------------------------------------------------------*/ package edu.wpi.first.wpilibj.command; @@ -23,75 +23,71 @@ import edu.wpi.first.wpilibj.mocks.MockCommand; * */ public class CommandTimeoutTest extends AbstractCommandTest { - private static final Logger logger = Logger.getLogger(CommandTimeoutTest.class.getName()); - - protected Logger getClassLogger(){ - return logger; - } + private static final Logger logger = Logger.getLogger(CommandTimeoutTest.class.getName()); - /** - * @throws java.lang.Exception - */ - @BeforeClass - public static void setUpBeforeClass() throws Exception { - } + protected Logger getClassLogger() { + return logger; + } - /** - * @throws java.lang.Exception - */ - @AfterClass - public static void tearDownAfterClass() throws Exception { - } + /** + * @throws java.lang.Exception + */ + @BeforeClass + public static void setUpBeforeClass() throws Exception {} - /** - * @throws java.lang.Exception - */ - @Before - public void setUp() throws Exception { - } + /** + * @throws java.lang.Exception + */ + @AfterClass + public static void tearDownAfterClass() throws Exception {} - /** - * @throws java.lang.Exception - */ - @After - public void tearDown() throws Exception { - } + /** + * @throws java.lang.Exception + */ + @Before + public void setUp() throws Exception {} - /** - * Command 2 second Timeout Test - */ - @Test - public void testTwoSecondTimeout() { - final ASubsystem subsystem = new ASubsystem(); + /** + * @throws java.lang.Exception + */ + @After + public void tearDown() throws Exception {} + + /** + * Command 2 second Timeout Test + */ + @Test + public void testTwoSecondTimeout() { + final ASubsystem subsystem = new ASubsystem(); - MockCommand command = new MockCommand() { - { - requires(subsystem); - setTimeout(2); - } - - @Override - public boolean isFinished(){ - return super.isFinished() || isTimedOut(); - } - }; - - command.start(); - assertCommandState(command, 0, 0, 0, 0, 0); - Scheduler.getInstance().run(); - assertCommandState(command, 0, 0, 0, 0, 0); - Scheduler.getInstance().run(); - assertCommandState(command, 1, 1, 1, 0, 0); - Scheduler.getInstance().run(); - assertCommandState(command, 1, 2, 2, 0, 0); - Scheduler.getInstance().run(); - assertCommandState(command, 1, 3, 3, 0, 0); - sleep(2000); - Scheduler.getInstance().run(); - assertCommandState(command, 1, 4, 4, 1, 0); - Scheduler.getInstance().run(); - assertCommandState(command, 1, 4, 4, 1, 0); - } + MockCommand command = new MockCommand() { + { + requires(subsystem); + setTimeout(2); + } + + @Override + public boolean isFinished() { + return super.isFinished() || isTimedOut(); + } + }; + + command.start(); + assertCommandState(command, 0, 0, 0, 0, 0); + Scheduler.getInstance().run(); + assertCommandState(command, 0, 0, 0, 0, 0); + Scheduler.getInstance().run(); + assertCommandState(command, 1, 1, 1, 0, 0); + Scheduler.getInstance().run(); + assertCommandState(command, 1, 2, 2, 0, 0); + Scheduler.getInstance().run(); + assertCommandState(command, 1, 3, 3, 0, 0); + sleep(2000); + Scheduler.getInstance().run(); + assertCommandState(command, 1, 4, 4, 1, 0); + Scheduler.getInstance().run(); + assertCommandState(command, 1, 4, 4, 1, 0); + } } diff --git a/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/command/DefaultCommandTest.java b/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/command/DefaultCommandTest.java index c68dec4f95..32531782e1 100644 --- a/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/command/DefaultCommandTest.java +++ b/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/command/DefaultCommandTest.java @@ -1,8 +1,8 @@ /*----------------------------------------------------------------------------*/ -/* Copyright (c) FIRST 2008-2014. All Rights Reserved. */ -/* Open Source Software - may be modified and shared by FRC teams. The code */ +/* Copyright (c) FIRST 2008-2014. All Rights Reserved. */ +/* Open Source Software - may be modified and shared by FRC teams. The code */ /* must be accompanied by the FIRST BSD license file in the root directory of */ -/* the project. */ +/* the project. */ /*----------------------------------------------------------------------------*/ package edu.wpi.first.wpilibj.command; @@ -23,151 +23,147 @@ import edu.wpi.first.wpilibj.mocks.MockCommand; * */ public class DefaultCommandTest extends AbstractCommandTest { - private static final Logger logger = Logger.getLogger(DefaultCommandTest.class.getName()); - - protected Logger getClassLogger(){ - return logger; - } + private static final Logger logger = Logger.getLogger(DefaultCommandTest.class.getName()); - /** - * @throws java.lang.Exception - */ - @BeforeClass - public static void setUpBeforeClass() throws Exception { - } + protected Logger getClassLogger() { + return logger; + } - /** - * @throws java.lang.Exception - */ - @AfterClass - public static void tearDownAfterClass() throws Exception { - } + /** + * @throws java.lang.Exception + */ + @BeforeClass + public static void setUpBeforeClass() throws Exception {} - /** - * @throws java.lang.Exception - */ - @Before - public void setUp() throws Exception { - } + /** + * @throws java.lang.Exception + */ + @AfterClass + public static void tearDownAfterClass() throws Exception {} - /** - * @throws java.lang.Exception - */ - @After - public void tearDown() throws Exception { - } + /** + * @throws java.lang.Exception + */ + @Before + public void setUp() throws Exception {} - /** - * Testing of default commands where the interrupting command ends itself - */ - @Test - public void testDefaultCommandWhereTheInteruptingCommandEndsItself() { - final ASubsystem subsystem = new ASubsystem(); + /** + * @throws java.lang.Exception + */ + @After + public void tearDown() throws Exception {} + + /** + * Testing of default commands where the interrupting command ends itself + */ + @Test + public void testDefaultCommandWhereTheInteruptingCommandEndsItself() { + final ASubsystem subsystem = new ASubsystem(); - MockCommand defaultCommand = new MockCommand() { - { - requires(subsystem); - } - }; - - MockCommand anotherCommand = new MockCommand() { - { - requires(subsystem); - } - }; - assertCommandState(defaultCommand, 0, 0, 0, 0, 0); - subsystem.init(defaultCommand); - - assertCommandState(defaultCommand, 0, 0, 0, 0, 0); - Scheduler.getInstance().run(); - assertCommandState(defaultCommand, 0, 0, 0, 0, 0); - Scheduler.getInstance().run(); - assertCommandState(defaultCommand, 1, 1, 1, 0, 0); - Scheduler.getInstance().run(); - assertCommandState(defaultCommand, 1, 2, 2, 0, 0); - - anotherCommand.start(); - assertCommandState(defaultCommand, 1, 2, 2, 0, 0); - assertCommandState(anotherCommand, 0, 0, 0, 0, 0); - Scheduler.getInstance().run(); - assertCommandState(defaultCommand, 1, 3, 3, 0, 1); - assertCommandState(anotherCommand, 0, 0, 0, 0, 0); - Scheduler.getInstance().run(); - assertCommandState(defaultCommand, 1, 3, 3, 0, 1); - assertCommandState(anotherCommand, 1, 1, 1, 0, 0); - Scheduler.getInstance().run(); - assertCommandState(defaultCommand, 1, 3, 3, 0, 1); - assertCommandState(anotherCommand, 1, 2, 2, 0, 0); - anotherCommand.setHasFinished(true); - assertCommandState(defaultCommand, 1, 3, 3, 0, 1); - assertCommandState(anotherCommand, 1, 2, 2, 0, 0); - Scheduler.getInstance().run(); - assertCommandState(defaultCommand, 1, 3, 3, 0, 1); - assertCommandState(anotherCommand, 1, 3, 3, 1, 0); - Scheduler.getInstance().run(); - assertCommandState(defaultCommand, 2, 4, 4, 0, 1); - assertCommandState(anotherCommand, 1, 3, 3, 1, 0); - Scheduler.getInstance().run(); - assertCommandState(defaultCommand, 2, 5, 5, 0, 1); - assertCommandState(anotherCommand, 1, 3, 3, 1, 0); - } - - - /** - * Testing of default commands where the interrupting command is canceled - */ - @Test - public void testDefaultCommandsInterruptingCommandCanceled(){ - final ASubsystem subsystem = new ASubsystem(); + MockCommand defaultCommand = new MockCommand() { + { + requires(subsystem); + } + }; + + MockCommand anotherCommand = new MockCommand() { + { + requires(subsystem); + } + }; + assertCommandState(defaultCommand, 0, 0, 0, 0, 0); + subsystem.init(defaultCommand); + + assertCommandState(defaultCommand, 0, 0, 0, 0, 0); + Scheduler.getInstance().run(); + assertCommandState(defaultCommand, 0, 0, 0, 0, 0); + Scheduler.getInstance().run(); + assertCommandState(defaultCommand, 1, 1, 1, 0, 0); + Scheduler.getInstance().run(); + assertCommandState(defaultCommand, 1, 2, 2, 0, 0); + + anotherCommand.start(); + assertCommandState(defaultCommand, 1, 2, 2, 0, 0); + assertCommandState(anotherCommand, 0, 0, 0, 0, 0); + Scheduler.getInstance().run(); + assertCommandState(defaultCommand, 1, 3, 3, 0, 1); + assertCommandState(anotherCommand, 0, 0, 0, 0, 0); + Scheduler.getInstance().run(); + assertCommandState(defaultCommand, 1, 3, 3, 0, 1); + assertCommandState(anotherCommand, 1, 1, 1, 0, 0); + Scheduler.getInstance().run(); + assertCommandState(defaultCommand, 1, 3, 3, 0, 1); + assertCommandState(anotherCommand, 1, 2, 2, 0, 0); + anotherCommand.setHasFinished(true); + assertCommandState(defaultCommand, 1, 3, 3, 0, 1); + assertCommandState(anotherCommand, 1, 2, 2, 0, 0); + Scheduler.getInstance().run(); + assertCommandState(defaultCommand, 1, 3, 3, 0, 1); + assertCommandState(anotherCommand, 1, 3, 3, 1, 0); + Scheduler.getInstance().run(); + assertCommandState(defaultCommand, 2, 4, 4, 0, 1); + assertCommandState(anotherCommand, 1, 3, 3, 1, 0); + Scheduler.getInstance().run(); + assertCommandState(defaultCommand, 2, 5, 5, 0, 1); + assertCommandState(anotherCommand, 1, 3, 3, 1, 0); + } - MockCommand defaultCommand = new MockCommand() { - { - requires(subsystem); - } - }; - - MockCommand anotherCommand = new MockCommand() { - { - requires(subsystem); - } - }; - assertCommandState(defaultCommand, 0, 0, 0, 0, 0); - subsystem.init(defaultCommand); - subsystem.initDefaultCommand(); - assertCommandState(defaultCommand, 0, 0, 0, 0, 0); - Scheduler.getInstance().run(); - assertCommandState(defaultCommand, 0, 0, 0, 0, 0); - Scheduler.getInstance().run(); - assertCommandState(defaultCommand, 1, 1, 1, 0, 0); - Scheduler.getInstance().run(); - assertCommandState(defaultCommand, 1, 2, 2, 0, 0); - - anotherCommand.start(); - assertCommandState(defaultCommand, 1, 2, 2, 0, 0); - assertCommandState(anotherCommand, 0, 0, 0, 0, 0); - Scheduler.getInstance().run(); - assertCommandState(defaultCommand, 1, 3, 3, 0, 1); - assertCommandState(anotherCommand, 0, 0, 0, 0, 0); - Scheduler.getInstance().run(); - assertCommandState(defaultCommand, 1, 3, 3, 0, 1); - assertCommandState(anotherCommand, 1, 1, 1, 0, 0); - Scheduler.getInstance().run(); - assertCommandState(defaultCommand, 1, 3, 3, 0, 1); - assertCommandState(anotherCommand, 1, 2, 2, 0, 0); - anotherCommand.cancel(); - assertCommandState(defaultCommand, 1, 3, 3, 0, 1); - assertCommandState(anotherCommand, 1, 2, 2, 0, 0); - Scheduler.getInstance().run(); - assertCommandState(defaultCommand, 1, 3, 3, 0, 1); - assertCommandState(anotherCommand, 1, 2, 2, 0, 1); - Scheduler.getInstance().run(); - assertCommandState(defaultCommand, 2, 4, 4, 0, 1); - assertCommandState(anotherCommand, 1, 2, 2, 0, 1); - Scheduler.getInstance().run(); - assertCommandState(defaultCommand, 2, 5, 5, 0, 1); - assertCommandState(anotherCommand, 1, 2, 2, 0, 1); - } + /** + * Testing of default commands where the interrupting command is canceled + */ + @Test + public void testDefaultCommandsInterruptingCommandCanceled() { + final ASubsystem subsystem = new ASubsystem(); + + + MockCommand defaultCommand = new MockCommand() { + { + requires(subsystem); + } + }; + + MockCommand anotherCommand = new MockCommand() { + { + requires(subsystem); + } + }; + assertCommandState(defaultCommand, 0, 0, 0, 0, 0); + subsystem.init(defaultCommand); + subsystem.initDefaultCommand(); + assertCommandState(defaultCommand, 0, 0, 0, 0, 0); + Scheduler.getInstance().run(); + assertCommandState(defaultCommand, 0, 0, 0, 0, 0); + Scheduler.getInstance().run(); + assertCommandState(defaultCommand, 1, 1, 1, 0, 0); + Scheduler.getInstance().run(); + assertCommandState(defaultCommand, 1, 2, 2, 0, 0); + + anotherCommand.start(); + assertCommandState(defaultCommand, 1, 2, 2, 0, 0); + assertCommandState(anotherCommand, 0, 0, 0, 0, 0); + Scheduler.getInstance().run(); + assertCommandState(defaultCommand, 1, 3, 3, 0, 1); + assertCommandState(anotherCommand, 0, 0, 0, 0, 0); + Scheduler.getInstance().run(); + assertCommandState(defaultCommand, 1, 3, 3, 0, 1); + assertCommandState(anotherCommand, 1, 1, 1, 0, 0); + Scheduler.getInstance().run(); + assertCommandState(defaultCommand, 1, 3, 3, 0, 1); + assertCommandState(anotherCommand, 1, 2, 2, 0, 0); + anotherCommand.cancel(); + assertCommandState(defaultCommand, 1, 3, 3, 0, 1); + assertCommandState(anotherCommand, 1, 2, 2, 0, 0); + Scheduler.getInstance().run(); + assertCommandState(defaultCommand, 1, 3, 3, 0, 1); + assertCommandState(anotherCommand, 1, 2, 2, 0, 1); + Scheduler.getInstance().run(); + assertCommandState(defaultCommand, 2, 4, 4, 0, 1); + assertCommandState(anotherCommand, 1, 2, 2, 0, 1); + Scheduler.getInstance().run(); + assertCommandState(defaultCommand, 2, 5, 5, 0, 1); + assertCommandState(anotherCommand, 1, 2, 2, 0, 1); + } } diff --git a/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/fixtures/AnalogCrossConnectFixture.java b/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/fixtures/AnalogCrossConnectFixture.java index d9680e4174..54b03729ec 100644 --- a/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/fixtures/AnalogCrossConnectFixture.java +++ b/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/fixtures/AnalogCrossConnectFixture.java @@ -1,8 +1,8 @@ /*----------------------------------------------------------------------------*/ -/* Copyright (c) FIRST 2008-2014. All Rights Reserved. */ -/* Open Source Software - may be modified and shared by FRC teams. The code */ +/* Copyright (c) FIRST 2008-2014. All Rights Reserved. */ +/* Open Source Software - may be modified and shared by FRC teams. The code */ /* must be accompanied by the FIRST BSD license file in the root directory of */ -/* the project. */ +/* the project. */ /*----------------------------------------------------------------------------*/ package edu.wpi.first.wpilibj.fixtures; @@ -13,64 +13,74 @@ import edu.wpi.first.wpilibj.AnalogOutput; * @author jonathanleitschuh * */ -public abstract class AnalogCrossConnectFixture implements ITestFixture{ - private boolean initialized = false; - - private AnalogInput input; - private AnalogOutput output; - - abstract protected AnalogInput giveAnalogInput(); - abstract protected AnalogOutput giveAnalogOutput(); - - - private void initialize(){ - synchronized(this){ - if(!initialized){ - input = giveAnalogInput(); - output = giveAnalogOutput(); - initialized = true; - } - } - } - /* (non-Javadoc) - * @see edu.wpi.first.wpilibj.fixtures.ITestFixture#setup() - */ - @Override - public boolean setup() { - initialize(); - output.setVoltage(0); - return true; - } - /* (non-Javadoc) - * @see edu.wpi.first.wpilibj.fixtures.ITestFixture#reset() - */ - @Override - public boolean reset() { - initialize(); - return true; - } - /* (non-Javadoc) - * @see edu.wpi.first.wpilibj.fixtures.ITestFixture#teardown() - */ - @Override - public boolean teardown() { - input.free(); - output.free(); - return true; - } - - /** - * @return - */ - final public AnalogOutput getOutput() { - initialize(); - return output; - } - - final public AnalogInput getInput() { - initialize(); - return input; - } - - +public abstract class AnalogCrossConnectFixture implements ITestFixture { + private boolean initialized = false; + + private AnalogInput input; + private AnalogOutput output; + + abstract protected AnalogInput giveAnalogInput(); + + abstract protected AnalogOutput giveAnalogOutput(); + + + private void initialize() { + synchronized (this) { + if (!initialized) { + input = giveAnalogInput(); + output = giveAnalogOutput(); + initialized = true; + } + } + } + + /* + * (non-Javadoc) + *$ + * @see edu.wpi.first.wpilibj.fixtures.ITestFixture#setup() + */ + @Override + public boolean setup() { + initialize(); + output.setVoltage(0); + return true; + } + + /* + * (non-Javadoc) + *$ + * @see edu.wpi.first.wpilibj.fixtures.ITestFixture#reset() + */ + @Override + public boolean reset() { + initialize(); + return true; + } + + /* + * (non-Javadoc) + *$ + * @see edu.wpi.first.wpilibj.fixtures.ITestFixture#teardown() + */ + @Override + public boolean teardown() { + input.free(); + output.free(); + return true; + } + + /** + * @return + */ + final public AnalogOutput getOutput() { + initialize(); + return output; + } + + final public AnalogInput getInput() { + initialize(); + return input; + } + + } diff --git a/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/fixtures/CANMotorEncoderFixture.java b/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/fixtures/CANMotorEncoderFixture.java index 75ed0a12a1..ae84bcfda8 100644 --- a/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/fixtures/CANMotorEncoderFixture.java +++ b/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/fixtures/CANMotorEncoderFixture.java @@ -1,8 +1,8 @@ /*----------------------------------------------------------------------------*/ -/* Copyright (c) FIRST 2008-2014. All Rights Reserved. */ -/* Open Source Software - may be modified and shared by FRC teams. The code */ +/* Copyright (c) FIRST 2008-2014. All Rights Reserved. */ +/* Open Source Software - may be modified and shared by FRC teams. The code */ /* must be accompanied by the FIRST BSD license file in the root directory of */ -/* the project. */ +/* the project. */ /*----------------------------------------------------------------------------*/ package edu.wpi.first.wpilibj.fixtures; @@ -20,154 +20,166 @@ import edu.wpi.first.wpilibj.mockhardware.FakePotentiometerSource; * @author jonathanleitschuh * */ -public abstract class CANMotorEncoderFixture extends MotorEncoderFixture implements ITestFixture { - private static final Logger logger = Logger.getLogger(CANMotorEncoderFixture.class.getName()); - public static final double RELAY_POWER_UP_TIME = .75; - private FakePotentiometerSource potSource; - private DigitalOutput forwardLimit; - private DigitalOutput reverseLimit; - private Relay powerCycler; - private boolean initialized = false; - - protected abstract FakePotentiometerSource giveFakePotentiometerSource(); - protected abstract DigitalOutput giveFakeForwardLimit(); - protected abstract DigitalOutput giveFakeReverseLimit(); - protected abstract Relay givePoweCycleRelay(); - - public CANMotorEncoderFixture(){ - } - - private void initialize(){ - synchronized(this){ - if(!initialized){ - initialized = true;//This ensures it is only initialized once - - powerCycler = givePoweCycleRelay(); - powerCycler.setDirection(Direction.kForward); - logger.fine("Turning on the power!"); - powerCycler.set(Value.kForward); - forwardLimit = giveFakeForwardLimit(); - reverseLimit = giveFakeReverseLimit(); - forwardLimit.set(false); - reverseLimit.set(false); - potSource = giveFakePotentiometerSource(); - Timer.delay(RELAY_POWER_UP_TIME); //Delay so the relay has time to boot up - } - } - } - +public abstract class CANMotorEncoderFixture extends MotorEncoderFixture implements + ITestFixture { + private static final Logger logger = Logger.getLogger(CANMotorEncoderFixture.class.getName()); + public static final double RELAY_POWER_UP_TIME = .75; + private FakePotentiometerSource potSource; + private DigitalOutput forwardLimit; + private DigitalOutput reverseLimit; + private Relay powerCycler; + private boolean initialized = false; - @Override - public boolean setup() { - initialize(); //This initializes the Relay first - return super.setup(); - } + protected abstract FakePotentiometerSource giveFakePotentiometerSource(); - @Override - public boolean reset() { - initialize(); - potSource.reset(); - forwardLimit.set(false); - reverseLimit.set(false); - getMotor().setPercentMode(); //Get the Jaguar into a mode where setting the speed means stop - return super.reset(); - } - - @Override - public boolean teardown() { - boolean wasNull = false; - if(potSource != null){ - potSource.free(); - potSource = null; - } else wasNull = true; - if(forwardLimit != null){ - forwardLimit.set(false); - forwardLimit.free(); - forwardLimit = null; - } else wasNull = true; - if(reverseLimit != null){ - reverseLimit.set(false); - reverseLimit.free(); - reverseLimit = null; - } else wasNull = true; - boolean superTornDown = false; - try{ - superTornDown = super.teardown(); - } finally { - try{ - if(getMotor() != null){ - getMotor().disableControl(); - getMotor().free(); - } else wasNull = true; - } finally { - if(powerCycler != null){ - powerCycler.free(); - powerCycler = null; - } else wasNull = true; - } - } - if(wasNull){ - throw new RuntimeException("CANMotorEncoderFixture had a null value at teardown"); - } - - return superTornDown; - } - - public FakePotentiometerSource getFakePot(){ - initialize(); - return potSource; - } - - public DigitalOutput getForwardLimit(){ - initialize(); - return forwardLimit; - } - - public DigitalOutput getReverseLimit(){ - initialize(); - return reverseLimit; - } - - public String printStatus(){ - StringBuilder status = new StringBuilder("CAN Motor Encoder Status: "); - if(getMotor() != null){ - status.append("\t" + getMotor().getDescription() + "\n"); - status.append("\tFault = " + getMotor().getFaults() + "\n"); - status.append("\tValue = " + getMotor().get() + "\n"); - status.append("\tOutputVoltage = " + getMotor().getOutputVoltage() +"\n"); - status.append("\tPosition = " + getMotor().getPosition() + "\n"); - status.append("\tForward Limit Ok = " + getMotor().getForwardLimitOK() + "\n"); - status.append("\tReverse Limit Ok = " + getMotor().getReverseLimitOK() + "\n"); - } else { - status.append("\t" + "CANJaguar Motor = null" + "\n"); - } - if(forwardLimit != null){ - status.append("\tForward Limit Output = " + forwardLimit + "\n"); - } else { - status.append("\tForward Limit Output = null" +"\n"); - } - if(reverseLimit != null){ - status.append("\tReverse Limit Output = " + reverseLimit + "\n"); - } else { - status.append("\tReverse Limit Output = null" +"\n"); - } - - return status.toString(); - } - - public void brownOut(double seconds){ - initialize(); - powerOff(); - Timer.delay(seconds); - powerOn(); - } - public void powerOff(){ - initialize(); - powerCycler.set(Value.kOff); - } - public void powerOn(){ - initialize(); - powerCycler.set(Value.kForward); - } + protected abstract DigitalOutput giveFakeForwardLimit(); + + protected abstract DigitalOutput giveFakeReverseLimit(); + + protected abstract Relay givePoweCycleRelay(); + + public CANMotorEncoderFixture() {} + + private void initialize() { + synchronized (this) { + if (!initialized) { + initialized = true;// This ensures it is only initialized once + + powerCycler = givePoweCycleRelay(); + powerCycler.setDirection(Direction.kForward); + logger.fine("Turning on the power!"); + powerCycler.set(Value.kForward); + forwardLimit = giveFakeForwardLimit(); + reverseLimit = giveFakeReverseLimit(); + forwardLimit.set(false); + reverseLimit.set(false); + potSource = giveFakePotentiometerSource(); + Timer.delay(RELAY_POWER_UP_TIME); // Delay so the relay has time to boot + // up + } + } + } + + + @Override + public boolean setup() { + initialize(); // This initializes the Relay first + return super.setup(); + } + + @Override + public boolean reset() { + initialize(); + potSource.reset(); + forwardLimit.set(false); + reverseLimit.set(false); + getMotor().setPercentMode(); // Get the Jaguar into a mode where setting the + // speed means stop + return super.reset(); + } + + @Override + public boolean teardown() { + boolean wasNull = false; + if (potSource != null) { + potSource.free(); + potSource = null; + } else + wasNull = true; + if (forwardLimit != null) { + forwardLimit.set(false); + forwardLimit.free(); + forwardLimit = null; + } else + wasNull = true; + if (reverseLimit != null) { + reverseLimit.set(false); + reverseLimit.free(); + reverseLimit = null; + } else + wasNull = true; + boolean superTornDown = false; + try { + superTornDown = super.teardown(); + } finally { + try { + if (getMotor() != null) { + getMotor().disableControl(); + getMotor().free(); + } else + wasNull = true; + } finally { + if (powerCycler != null) { + powerCycler.free(); + powerCycler = null; + } else + wasNull = true; + } + } + if (wasNull) { + throw new RuntimeException("CANMotorEncoderFixture had a null value at teardown"); + } + + return superTornDown; + } + + public FakePotentiometerSource getFakePot() { + initialize(); + return potSource; + } + + public DigitalOutput getForwardLimit() { + initialize(); + return forwardLimit; + } + + public DigitalOutput getReverseLimit() { + initialize(); + return reverseLimit; + } + + public String printStatus() { + StringBuilder status = new StringBuilder("CAN Motor Encoder Status: "); + if (getMotor() != null) { + status.append("\t" + getMotor().getDescription() + "\n"); + status.append("\tFault = " + getMotor().getFaults() + "\n"); + status.append("\tValue = " + getMotor().get() + "\n"); + status.append("\tOutputVoltage = " + getMotor().getOutputVoltage() + "\n"); + status.append("\tPosition = " + getMotor().getPosition() + "\n"); + status.append("\tForward Limit Ok = " + getMotor().getForwardLimitOK() + "\n"); + status.append("\tReverse Limit Ok = " + getMotor().getReverseLimitOK() + "\n"); + } else { + status.append("\t" + "CANJaguar Motor = null" + "\n"); + } + if (forwardLimit != null) { + status.append("\tForward Limit Output = " + forwardLimit + "\n"); + } else { + status.append("\tForward Limit Output = null" + "\n"); + } + if (reverseLimit != null) { + status.append("\tReverse Limit Output = " + reverseLimit + "\n"); + } else { + status.append("\tReverse Limit Output = null" + "\n"); + } + + return status.toString(); + } + + public void brownOut(double seconds) { + initialize(); + powerOff(); + Timer.delay(seconds); + powerOn(); + } + + public void powerOff() { + initialize(); + powerCycler.set(Value.kOff); + } + + public void powerOn() { + initialize(); + powerCycler.set(Value.kForward); + } } diff --git a/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/fixtures/DIOCrossConnectFixture.java b/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/fixtures/DIOCrossConnectFixture.java index 9abd6733c0..78fd3b2198 100644 --- a/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/fixtures/DIOCrossConnectFixture.java +++ b/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/fixtures/DIOCrossConnectFixture.java @@ -1,8 +1,8 @@ /*----------------------------------------------------------------------------*/ -/* Copyright (c) FIRST 2008-2014. All Rights Reserved. */ -/* Open Source Software - may be modified and shared by FRC teams. The code */ +/* Copyright (c) FIRST 2008-2014. All Rights Reserved. */ +/* Open Source Software - may be modified and shared by FRC teams. The code */ /* must be accompanied by the FIRST BSD license file in the root directory of */ -/* the project. */ +/* the project. */ /*----------------------------------------------------------------------------*/ package edu.wpi.first.wpilibj.fixtures; @@ -13,63 +13,63 @@ import edu.wpi.first.wpilibj.DigitalInput; import edu.wpi.first.wpilibj.DigitalOutput; public class DIOCrossConnectFixture implements ITestFixture { - - private static final Logger logger = Logger.getLogger(DIOCrossConnectFixture.class.getName()); - - private final DigitalInput input; - private final DigitalOutput output; - private boolean m_allocated; - - public DIOCrossConnectFixture(DigitalInput input, DigitalOutput output) { - assert input != null; - assert output != null; - this.input = input; - this.output = output; - m_allocated = false; - } - - public DIOCrossConnectFixture(Integer input, Integer output){ - assert input != null; - assert output != null; - assert !input.equals(output); - this.input = new DigitalInput(input); - this.output = new DigitalOutput(output); - m_allocated = true; - } - - public DigitalInput getInput(){ - return input; - } - - public DigitalOutput getOutput(){ - return output; - } - @Override - public boolean setup() { - return true; - } + private static final Logger logger = Logger.getLogger(DIOCrossConnectFixture.class.getName()); - @Override - public boolean reset() { - try{ - input.cancelInterrupts(); - } catch(IllegalStateException e) { - //This will happen if the interrupt has not been allocated for this test. - } - output.set(false); - return true; - } + private final DigitalInput input; + private final DigitalOutput output; + private boolean m_allocated; - @Override - public boolean teardown() { - logger.log(Level.FINE,"Begining teardown"); - if(m_allocated){ - input.free(); - output.free(); - m_allocated = false; - } - return true; - } + public DIOCrossConnectFixture(DigitalInput input, DigitalOutput output) { + assert input != null; + assert output != null; + this.input = input; + this.output = output; + m_allocated = false; + } + + public DIOCrossConnectFixture(Integer input, Integer output) { + assert input != null; + assert output != null; + assert !input.equals(output); + this.input = new DigitalInput(input); + this.output = new DigitalOutput(output); + m_allocated = true; + } + + public DigitalInput getInput() { + return input; + } + + public DigitalOutput getOutput() { + return output; + } + + @Override + public boolean setup() { + return true; + } + + @Override + public boolean reset() { + try { + input.cancelInterrupts(); + } catch (IllegalStateException e) { + // This will happen if the interrupt has not been allocated for this test. + } + output.set(false); + return true; + } + + @Override + public boolean teardown() { + logger.log(Level.FINE, "Begining teardown"); + if (m_allocated) { + input.free(); + output.free(); + m_allocated = false; + } + return true; + } } diff --git a/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/fixtures/FakeCounterFixture.java b/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/fixtures/FakeCounterFixture.java index 644a22eef5..9354e7740c 100644 --- a/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/fixtures/FakeCounterFixture.java +++ b/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/fixtures/FakeCounterFixture.java @@ -1,8 +1,8 @@ /*----------------------------------------------------------------------------*/ -/* Copyright (c) FIRST 2008-2014. All Rights Reserved. */ -/* Open Source Software - may be modified and shared by FRC teams. The code */ +/* Copyright (c) FIRST 2008-2014. All Rights Reserved. */ +/* Open Source Software - may be modified and shared by FRC teams. The code */ /* must be accompanied by the FIRST BSD license file in the root directory of */ -/* the project. */ +/* the project. */ /*----------------------------------------------------------------------------*/ package edu.wpi.first.wpilibj.fixtures; @@ -17,87 +17,98 @@ import edu.wpi.first.wpilibj.mockhardware.FakeCounterSource; * */ public class FakeCounterFixture implements ITestFixture { - private static final Logger logger = Logger.getLogger(FakeEncoderFixture.class.getName()); - - private final DIOCrossConnectFixture dio; - private boolean m_allocated; - private final FakeCounterSource source; - private final Counter counter; - - /** - * Constructs a FakeCounterFixture. - * @param dio A previously allocated DIOCrossConnectFixture (must be freed outside this class) - */ - public FakeCounterFixture (DIOCrossConnectFixture dio){ - this.dio = dio; - m_allocated = false; - source = new FakeCounterSource(dio.getOutput()); - counter = new Counter(dio.getInput()); - } - - - /** - * Constructs a FakeCounterFixture using two port numbers - * @param input the input port - * @param output the output port - */ - public FakeCounterFixture(int input, int output){ - this.dio = new DIOCrossConnectFixture(input, output); - m_allocated = true; - source = new FakeCounterSource(dio.getOutput()); - counter = new Counter(dio.getInput()); - } - - /** - * Retrieves the FakeCouterSource for use - * @return the FakeCounterSource - */ - public FakeCounterSource getFakeCounterSource(){ - return source; - } - - /** - * Gets the Counter for use - * @return the Counter - */ - public Counter getCounter(){ - return counter; - } + private static final Logger logger = Logger.getLogger(FakeEncoderFixture.class.getName()); + + private final DIOCrossConnectFixture dio; + private boolean m_allocated; + private final FakeCounterSource source; + private final Counter counter; + + /** + * Constructs a FakeCounterFixture. + *$ + * @param dio A previously allocated DIOCrossConnectFixture (must be freed + * outside this class) + */ + public FakeCounterFixture(DIOCrossConnectFixture dio) { + this.dio = dio; + m_allocated = false; + source = new FakeCounterSource(dio.getOutput()); + counter = new Counter(dio.getInput()); + } + + + /** + * Constructs a FakeCounterFixture using two port numbers + *$ + * @param input the input port + * @param output the output port + */ + public FakeCounterFixture(int input, int output) { + this.dio = new DIOCrossConnectFixture(input, output); + m_allocated = true; + source = new FakeCounterSource(dio.getOutput()); + counter = new Counter(dio.getInput()); + } + + /** + * Retrieves the FakeCouterSource for use + *$ + * @return the FakeCounterSource + */ + public FakeCounterSource getFakeCounterSource() { + return source; + } + + /** + * Gets the Counter for use + *$ + * @return the Counter + */ + public Counter getCounter() { + return counter; + } + + + /* + * (non-Javadoc) + *$ + * @see edu.wpi.first.wpilibj.fixtures.ITestFixture#setup() + */ + @Override + public boolean setup() { + return true; + + } + + /* + * (non-Javadoc) + *$ + * @see edu.wpi.first.wpilibj.fixtures.ITestFixture#reset() + */ + @Override + public boolean reset() { + counter.reset(); + return true; + } + + /* + * (non-Javadoc) + *$ + * @see edu.wpi.first.wpilibj.fixtures.ITestFixture#teardown() + */ + @Override + public boolean teardown() { + logger.log(Level.FINE, "Begining teardown"); + counter.free(); + source.free(); + if (m_allocated) { // Only tear down the dio if this class allocated it + dio.teardown(); + m_allocated = false; + } + return true; + } - - /* (non-Javadoc) - * @see edu.wpi.first.wpilibj.fixtures.ITestFixture#setup() - */ - @Override - public boolean setup() { - return true; - - } - /* (non-Javadoc) - * @see edu.wpi.first.wpilibj.fixtures.ITestFixture#reset() - */ - @Override - public boolean reset() { - counter.reset(); - return true; - } - /* (non-Javadoc) - * @see edu.wpi.first.wpilibj.fixtures.ITestFixture#teardown() - */ - @Override - public boolean teardown() { - logger.log(Level.FINE,"Begining teardown"); - counter.free(); - source.free(); - if(m_allocated){ //Only tear down the dio if this class allocated it - dio.teardown(); - m_allocated = false; - } - return true; - } - - - } diff --git a/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/fixtures/FakeEncoderFixture.java b/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/fixtures/FakeEncoderFixture.java index 19171b33ef..38e78e72a9 100644 --- a/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/fixtures/FakeEncoderFixture.java +++ b/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/fixtures/FakeEncoderFixture.java @@ -1,8 +1,8 @@ /*----------------------------------------------------------------------------*/ -/* Copyright (c) FIRST 2008-2014. All Rights Reserved. */ -/* Open Source Software - may be modified and shared by FRC teams. The code */ +/* Copyright (c) FIRST 2008-2014. All Rights Reserved. */ +/* Open Source Software - may be modified and shared by FRC teams. The code */ /* must be accompanied by the FIRST BSD license file in the root directory of */ -/* the project. */ +/* the project. */ /*----------------------------------------------------------------------------*/ package edu.wpi.first.wpilibj.fixtures; @@ -17,100 +17,108 @@ import edu.wpi.first.wpilibj.mockhardware.FakeEncoderSource; * */ public class FakeEncoderFixture implements ITestFixture { - private static final Logger logger = Logger.getLogger(FakeEncoderFixture.class.getName()); - - private final DIOCrossConnectFixture m_dio1; - private final DIOCrossConnectFixture m_dio2; - private boolean m_allocated; - - private final FakeEncoderSource m_source; - private int m_sourcePort [] = new int[2]; - private final Encoder m_encoder; - private int m_encoderPort [] = new int[2]; - - /** - * Constructs a FakeEncoderFixture from two DIOCrossConnectFixture - * @param dio1 - * @param dio2 - */ - public FakeEncoderFixture(DIOCrossConnectFixture dio1, DIOCrossConnectFixture dio2){ - assert dio1 != null; - assert dio2 != null; - this.m_dio1 = dio1; - this.m_dio2 = dio2; - m_allocated = false; - m_source = new FakeEncoderSource(dio1.getOutput(), dio2.getOutput()); - m_encoder = new Encoder(dio1.getInput(), dio2.getOutput()); - } - - /** - * Construcst a FakeEncoderFixture from a set of Digital I/O ports - * @param inputA - * @param outputA - * @param inputB - * @param outputB - */ - public FakeEncoderFixture(int inputA, int outputA, int inputB, int outputB){ - assert outputA != outputB; - assert outputA != inputA; - assert outputA != inputB; - assert outputB != inputA; - assert outputB != inputB; - assert inputA != inputB; - this.m_dio1 = new DIOCrossConnectFixture(inputA, outputA); - this.m_dio2 = new DIOCrossConnectFixture(inputB, outputB); - m_allocated = true; - m_sourcePort[0] = outputA; - m_sourcePort[1] = outputB; - m_encoderPort[0] = inputA; - m_encoderPort[1] = inputB; - m_source = new FakeEncoderSource(m_dio1.getOutput(), m_dio2.getOutput()); - m_encoder = new Encoder(m_dio1.getInput(), m_dio2.getOutput()); - } - - public FakeEncoderSource getFakeEncoderSource(){ - return m_source; - } - - public Encoder getEncoder(){ - return m_encoder; - } + private static final Logger logger = Logger.getLogger(FakeEncoderFixture.class.getName()); - /* (non-Javadoc) - * @see edu.wpi.first.wpilibj.fixtures.ITestFixture#setup() - */ - @Override - public boolean setup() { - return true; - } + private final DIOCrossConnectFixture m_dio1; + private final DIOCrossConnectFixture m_dio2; + private boolean m_allocated; - /* (non-Javadoc) - * @see edu.wpi.first.wpilibj.fixtures.ITestFixture#reset() - */ - @Override - public boolean reset() { - m_dio1.reset(); - m_dio2.reset(); - m_encoder.reset(); - return true; - } + private final FakeEncoderSource m_source; + private int m_sourcePort[] = new int[2]; + private final Encoder m_encoder; + private int m_encoderPort[] = new int[2]; + + /** + * Constructs a FakeEncoderFixture from two DIOCrossConnectFixture + *$ + * @param dio1 + * @param dio2 + */ + public FakeEncoderFixture(DIOCrossConnectFixture dio1, DIOCrossConnectFixture dio2) { + assert dio1 != null; + assert dio2 != null; + this.m_dio1 = dio1; + this.m_dio2 = dio2; + m_allocated = false; + m_source = new FakeEncoderSource(dio1.getOutput(), dio2.getOutput()); + m_encoder = new Encoder(dio1.getInput(), dio2.getOutput()); + } + + /** + * Construcst a FakeEncoderFixture from a set of Digital I/O ports + *$ + * @param inputA + * @param outputA + * @param inputB + * @param outputB + */ + public FakeEncoderFixture(int inputA, int outputA, int inputB, int outputB) { + assert outputA != outputB; + assert outputA != inputA; + assert outputA != inputB; + assert outputB != inputA; + assert outputB != inputB; + assert inputA != inputB; + this.m_dio1 = new DIOCrossConnectFixture(inputA, outputA); + this.m_dio2 = new DIOCrossConnectFixture(inputB, outputB); + m_allocated = true; + m_sourcePort[0] = outputA; + m_sourcePort[1] = outputB; + m_encoderPort[0] = inputA; + m_encoderPort[1] = inputB; + m_source = new FakeEncoderSource(m_dio1.getOutput(), m_dio2.getOutput()); + m_encoder = new Encoder(m_dio1.getInput(), m_dio2.getOutput()); + } + + public FakeEncoderSource getFakeEncoderSource() { + return m_source; + } + + public Encoder getEncoder() { + return m_encoder; + } + + /* + * (non-Javadoc) + *$ + * @see edu.wpi.first.wpilibj.fixtures.ITestFixture#setup() + */ + @Override + public boolean setup() { + return true; + } + + /* + * (non-Javadoc) + *$ + * @see edu.wpi.first.wpilibj.fixtures.ITestFixture#reset() + */ + @Override + public boolean reset() { + m_dio1.reset(); + m_dio2.reset(); + m_encoder.reset(); + return true; + } + + /* + * (non-Javadoc) + *$ + * @see edu.wpi.first.wpilibj.fixtures.ITestFixture#teardown() + */ + @Override + public boolean teardown() { + logger.fine("Begining teardown"); + m_source.free(); + logger.finer("Source freed " + m_sourcePort[0] + ", " + m_sourcePort[1]); + m_encoder.free(); + logger.finer("Encoder freed " + m_encoderPort[0] + ", " + m_encoderPort[1]); + if (m_allocated) { + m_dio1.teardown(); + m_dio2.teardown(); + } + return true; + } - /* (non-Javadoc) - * @see edu.wpi.first.wpilibj.fixtures.ITestFixture#teardown() - */ - @Override - public boolean teardown() { - logger.fine("Begining teardown"); - m_source.free(); - logger.finer("Source freed " + m_sourcePort[0] + ", " + m_sourcePort[1]); - m_encoder.free(); - logger.finer("Encoder freed " + m_encoderPort[0] + ", " + m_encoderPort[1]); - if(m_allocated){ - m_dio1.teardown(); - m_dio2.teardown(); - } - return true; - } - } diff --git a/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/fixtures/ITestFixture.java b/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/fixtures/ITestFixture.java index c4176f2e49..d93f73ad41 100644 --- a/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/fixtures/ITestFixture.java +++ b/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/fixtures/ITestFixture.java @@ -1,8 +1,8 @@ /*----------------------------------------------------------------------------*/ -/* Copyright (c) FIRST 2008-2014. All Rights Reserved. */ -/* Open Source Software - may be modified and shared by FRC teams. The code */ +/* Copyright (c) FIRST 2008-2014. All Rights Reserved. */ +/* Open Source Software - may be modified and shared by FRC teams. The code */ /* must be accompanied by the FIRST BSD license file in the root directory of */ -/* the project. */ +/* the project. */ /*----------------------------------------------------------------------------*/ package edu.wpi.first.wpilibj.fixtures; @@ -11,43 +11,43 @@ import edu.wpi.first.wpilibj.test.TestBench; /** * Master interface for all test fixtures. This ensures that all test fixtures * have setup and teardown methods, to ensure that the tests run properly. - * + *$ * Test fixtures should be modeled around the content of a test, rather than the * actual physical layout of the testing board. They should obtain references to * hardware from the {@link TestBench} class, which is a singleton. Testing * Fixtures are responsible for ensuring that the hardware is in an appropriate * state for the start of a test, and ensuring that future tests will not be * affected by the results of a test. - * + *$ * @author Fredric Silberberg */ public interface ITestFixture { - /** - * Performs any required setup for this fixture, ensuring that all fixture - * elements are ready for testing. - * - * @return True if the fixture is ready for testing - */ - boolean setup(); + /** + * Performs any required setup for this fixture, ensuring that all fixture + * elements are ready for testing. + *$ + * @return True if the fixture is ready for testing + */ + boolean setup(); - /** - * Resets the fixture back to test start state. This should be called by the - * test class in the test setup method to ensure that the hardware is in the - * default state. This differs from {@link ITestFixture#setup()} as that is - * called once, before the class is constructed, so it may need to start - * sensors. This method should not have to start anything, just reset - * sensors and ensure that motors are stopped. - * - * @return True if the fixture is ready for testing - */ - boolean reset(); + /** + * Resets the fixture back to test start state. This should be called by the + * test class in the test setup method to ensure that the hardware is in the + * default state. This differs from {@link ITestFixture#setup()} as that is + * called once, before the class is constructed, so it may need to start + * sensors. This method should not have to start anything, just reset sensors + * and ensure that motors are stopped. + *$ + * @return True if the fixture is ready for testing + */ + boolean reset(); - /** - * Performs any required teardown after use of the fixture, ensuring that - * future tests will not run into conflicts. - * - * @return True if the teardown succeeded - */ - boolean teardown(); + /** + * Performs any required teardown after use of the fixture, ensuring that + * future tests will not run into conflicts. + *$ + * @return True if the teardown succeeded + */ + boolean teardown(); } diff --git a/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/fixtures/MotorEncoderFixture.java b/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/fixtures/MotorEncoderFixture.java index daf5bda679..3ae5e98e2a 100644 --- a/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/fixtures/MotorEncoderFixture.java +++ b/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/fixtures/MotorEncoderFixture.java @@ -1,8 +1,8 @@ /*----------------------------------------------------------------------------*/ -/* Copyright (c) FIRST 2008-2014. All Rights Reserved. */ -/* Open Source Software - may be modified and shared by FRC teams. The code */ +/* Copyright (c) FIRST 2008-2014. All Rights Reserved. */ +/* Open Source Software - may be modified and shared by FRC teams. The code */ /* must be accompanied by the FIRST BSD license file in the root directory of */ -/* the project. */ +/* the project. */ /*----------------------------------------------------------------------------*/ package edu.wpi.first.wpilibj.fixtures; @@ -18,203 +18,225 @@ import edu.wpi.first.wpilibj.Timer; import edu.wpi.first.wpilibj.test.TestBench; /** - * Represents a physically connected Motor and Encoder to allow for unit tests on these difrent pairs
- * Designed to allow the user to easily setup and tear down the fixture to allow for reuse. - * This class should be explicitly instantiated in the TestBed class to allow any test to access this fixture. - * This allows tests to be mailable so that you can easily reconfigure the physical testbed without breaking the tests. + * Represents a physically connected Motor and Encoder to allow for unit tests + * on these difrent pairs
+ * Designed to allow the user to easily setup and tear down the fixture to allow + * for reuse. This class should be explicitly instantiated in the TestBed class + * to allow any test to access this fixture. This allows tests to be mailable so + * that you can easily reconfigure the physical testbed without breaking the + * tests. * * @author Jonathan Leitschuh * */ -public abstract class MotorEncoderFixture implements ITestFixture { - private static final Logger logger = Logger.getLogger(MotorEncoderFixture.class.getName()); - private boolean initialized = false; - private boolean tornDown = false; - protected T motor; - private Encoder encoder; - private final Counter counters[] = new Counter[2]; - protected DigitalInput aSource; //Stored so it can be freed at tear down - protected DigitalInput bSource; +public abstract class MotorEncoderFixture implements ITestFixture { + private static final Logger logger = Logger.getLogger(MotorEncoderFixture.class.getName()); + private boolean initialized = false; + private boolean tornDown = false; + protected T motor; + private Encoder encoder; + private final Counter counters[] = new Counter[2]; + protected DigitalInput aSource; // Stored so it can be freed at tear down + protected DigitalInput bSource; - /** - * Default constructor for a MotorEncoderFixture - */ - public MotorEncoderFixture(){ - } - - abstract public int getPDPChannel(); + /** + * Default constructor for a MotorEncoderFixture + */ + public MotorEncoderFixture() {} - /** - * Where the implementer of this class should pass the speed controller - * Constructor should only be called from outside this class if the Speed controller - * is not also an implementation of PWM interface - * @return - */ - abstract protected T giveSpeedController(); - /** - * Where the implementer of this class should pass one of the digital inputs
- * CONSTRUCTOR SHOULD NOT BE CALLED FROM OUTSIDE THIS CLASS! - * @return - */ - abstract protected DigitalInput giveDigitalInputA(); - /** - * Where the implementer fo this class should pass the other digital input
- * CONSTRUCTOR SHOULD NOT BE CALLED FROM OUTSIDE THIS CLASS! - * @return Input B to be used when this class is instantiated - */ - abstract protected DigitalInput giveDigitalInputB(); + abstract public int getPDPChannel(); - final private void initialize(){ - synchronized(this){ - if(!initialized){ - initialized = true; //This ensures it is only initialized once - - aSource = giveDigitalInputA(); - bSource = giveDigitalInputB(); - - - encoder = new Encoder(aSource, bSource); - counters[0] = new Counter(aSource); - counters[1] = new Counter(bSource); - logger.fine("Creating the speed controller!"); - motor = giveSpeedController(); //CANJaguar throws an exception if it doesn't get the message - } - } - } + /** + * Where the implementer of this class should pass the speed controller + * Constructor should only be called from outside this class if the Speed + * controller is not also an implementation of PWM interface + *$ + * @return + */ + abstract protected T giveSpeedController(); - @Override - public boolean setup() { - initialize(); - return true; - } + /** + * Where the implementer of this class should pass one of the digital inputs
+ * CONSTRUCTOR SHOULD NOT BE CALLED FROM OUTSIDE THIS CLASS! + *$ + * @return + */ + abstract protected DigitalInput giveDigitalInputA(); - /** - * Gets the motor for this Object - * @return the motor this object refers too - */ - public T getMotor(){ - initialize(); - return motor; - } + /** + * Where the implementer fo this class should pass the other digital input
+ * CONSTRUCTOR SHOULD NOT BE CALLED FROM OUTSIDE THIS CLASS! + *$ + * @return Input B to be used when this class is instantiated + */ + abstract protected DigitalInput giveDigitalInputB(); - /** - * Gets the encoder for this object - * @return the encoder that this object refers too - */ - public Encoder getEncoder(){ - initialize(); - return encoder; - } + final private void initialize() { + synchronized (this) { + if (!initialized) { + initialized = true; // This ensures it is only initialized once - public Counter[] getCounters(){ - initialize(); - return counters; - } + aSource = giveDigitalInputA(); + bSource = giveDigitalInputB(); - /** - * Retrieves the name of the motor that this object refers to - * @return The simple name of the motor {@link Class#getSimpleName()} - */ - public String getType(){ - initialize(); - return motor.getClass().getSimpleName(); - } - /** - * Checks to see if the speed of the motor is within some range of a given value. - * This is used instead of equals() because doubles can have inaccuracies. - * @param value The value to compare against - * @param accuracy The accuracy range to check against to see if the - * @return true if the range of values between motors speed accuracy contains the 'value'. - */ - public boolean isMotorSpeedWithinRange(double value, double accuracy){ - initialize(); - return Math.abs((Math.abs(motor.get()) - Math.abs(value))) < Math.abs(accuracy); - } + encoder = new Encoder(aSource, bSource); + counters[0] = new Counter(aSource); + counters[1] = new Counter(bSource); + logger.fine("Creating the speed controller!"); + motor = giveSpeedController(); // CANJaguar throws an exception if it + // doesn't get the message + } + } + } - @Override - public boolean reset(){ - initialize(); - boolean wasReset = true; - motor.setInverted(false); - motor.set(0); - Timer.delay(TestBench.MOTOR_STOP_TIME); //DEFINED IN THE TestBench - encoder.reset(); - for(Counter c : counters){ - c.reset(); - } + @Override + public boolean setup() { + initialize(); + return true; + } - wasReset = wasReset && motor.get() == 0; - wasReset = wasReset && encoder.get() == 0; - for(Counter c : counters){ - wasReset = wasReset && c.get() == 0; - } + /** + * Gets the motor for this Object + *$ + * @return the motor this object refers too + */ + public T getMotor() { + initialize(); + return motor; + } - return wasReset; - } + /** + * Gets the encoder for this object + *$ + * @return the encoder that this object refers too + */ + public Encoder getEncoder() { + initialize(); + return encoder; + } + + public Counter[] getCounters() { + initialize(); + return counters; + } + + /** + * Retrieves the name of the motor that this object refers to + *$ + * @return The simple name of the motor {@link Class#getSimpleName()} + */ + public String getType() { + initialize(); + return motor.getClass().getSimpleName(); + } + + /** + * Checks to see if the speed of the motor is within some range of a given + * value. This is used instead of equals() because doubles can have + * inaccuracies. + *$ + * @param value The value to compare against + * @param accuracy The accuracy range to check against to see if the + * @return true if the range of values between motors speed accuracy contains + * the 'value'. + */ + public boolean isMotorSpeedWithinRange(double value, double accuracy) { + initialize(); + return Math.abs((Math.abs(motor.get()) - Math.abs(value))) < Math.abs(accuracy); + } + + @Override + public boolean reset() { + initialize(); + boolean wasReset = true; + motor.setInverted(false); + motor.set(0); + Timer.delay(TestBench.MOTOR_STOP_TIME); // DEFINED IN THE TestBench + encoder.reset(); + for (Counter c : counters) { + c.reset(); + } + + wasReset = wasReset && motor.get() == 0; + wasReset = wasReset && encoder.get() == 0; + for (Counter c : counters) { + wasReset = wasReset && c.get() == 0; + } + + return wasReset; + } - /** - * Safely tears down the MotorEncoder Fixture in a way that makes sure that even if an object fails - * to initialize the reset of the fixture can still be torn down and the resources deallocated - */ - @Override - public boolean teardown() { - String type; - if(motor != null){ - type = getType(); - } else { - type = "null"; - } - if(!tornDown){ - boolean wasNull = false; - if(motor instanceof PWM && motor != null){ - ((PWM) motor).free(); - motor = null; - } else if(motor == null) wasNull = true; - if(encoder != null){ - encoder.free(); - encoder = null; - } else wasNull = true; - if(counters[0] != null){ - counters[0].free(); - counters[0] = null; - } else wasNull = true; - if(counters[1] != null){ - counters[1].free(); - counters[1] = null; - } else wasNull = true; - if(aSource != null){ - aSource.free(); - aSource = null; - } else wasNull = true; - if(bSource != null){ - bSource.free(); - bSource = null; - } else wasNull = true; - - tornDown = true; - - if(wasNull){ - throw new NullPointerException("MotorEncoderFixture had null params at teardown"); - } - } else { - throw new RuntimeException(type + " Motor Encoder torn down multiple times"); - } + /** + * Safely tears down the MotorEncoder Fixture in a way that makes sure that + * even if an object fails to initialize the reset of the fixture can still be + * torn down and the resources deallocated + */ + @Override + public boolean teardown() { + String type; + if (motor != null) { + type = getType(); + } else { + type = "null"; + } + if (!tornDown) { + boolean wasNull = false; + if (motor instanceof PWM && motor != null) { + ((PWM) motor).free(); + motor = null; + } else if (motor == null) + wasNull = true; + if (encoder != null) { + encoder.free(); + encoder = null; + } else + wasNull = true; + if (counters[0] != null) { + counters[0].free(); + counters[0] = null; + } else + wasNull = true; + if (counters[1] != null) { + counters[1].free(); + counters[1] = null; + } else + wasNull = true; + if (aSource != null) { + aSource.free(); + aSource = null; + } else + wasNull = true; + if (bSource != null) { + bSource.free(); + bSource = null; + } else + wasNull = true; - return true; - } - - @Override - public String toString(){ - StringBuilder string = new StringBuilder("MotorEncoderFixture<"); - //Get the generic type as a class - @SuppressWarnings("unchecked") - Class class1 = (Class)((ParameterizedType)getClass().getGenericSuperclass()).getActualTypeArguments()[0]; - string.append(class1.getSimpleName()); - string.append(">"); - return string.toString(); - } + tornDown = true; + + if (wasNull) { + throw new NullPointerException("MotorEncoderFixture had null params at teardown"); + } + } else { + throw new RuntimeException(type + " Motor Encoder torn down multiple times"); + } + + return true; + } + + @Override + public String toString() { + StringBuilder string = new StringBuilder("MotorEncoderFixture<"); + // Get the generic type as a class + @SuppressWarnings("unchecked") + Class class1 = + (Class) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0]; + string.append(class1.getSimpleName()); + string.append(">"); + return string.toString(); + } } diff --git a/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/fixtures/RelayCrossConnectFxiture.java b/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/fixtures/RelayCrossConnectFxiture.java index f33db992d8..f4475a5d9f 100644 --- a/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/fixtures/RelayCrossConnectFxiture.java +++ b/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/fixtures/RelayCrossConnectFxiture.java @@ -1,8 +1,8 @@ /*----------------------------------------------------------------------------*/ -/* Copyright (c) FIRST 2008-2014. All Rights Reserved. */ -/* Open Source Software - may be modified and shared by FRC teams. The code */ +/* Copyright (c) FIRST 2008-2014. All Rights Reserved. */ +/* Open Source Software - may be modified and shared by FRC teams. The code */ /* must be accompanied by the FIRST BSD license file in the root directory of */ -/* the project. */ +/* the project. */ /*----------------------------------------------------------------------------*/ package edu.wpi.first.wpilibj.fixtures; @@ -16,79 +16,86 @@ import edu.wpi.first.wpilibj.Relay.Value; * */ public abstract class RelayCrossConnectFxiture implements ITestFixture { - - private DigitalInput inputOne; - private DigitalInput inputTwo; - private Relay relay; - - private boolean initialized = false; - private boolean freed = false; - - - - protected abstract Relay giveRelay(); - - protected abstract DigitalInput giveInputOne(); - - protected abstract DigitalInput giveInputTwo(); - - private void initialize(){ - synchronized(this){ - if(!initialized){ - relay = giveRelay(); - inputOne = giveInputOne(); - inputTwo = giveInputTwo(); - initialized = true; - } - } - } - - public Relay getRelay(){ - initialize(); - return relay; - } - - public DigitalInput getInputOne(){ - initialize(); - return inputOne; - } - - public DigitalInput getInputTwo(){ - initialize(); - return inputTwo; - } - /* (non-Javadoc) - * @see edu.wpi.first.wpilibj.fixtures.ITestFixture#setup() - */ - @Override - public boolean setup() { - initialize(); - return true; - } + private DigitalInput inputOne; + private DigitalInput inputTwo; + private Relay relay; - /* (non-Javadoc) - * @see edu.wpi.first.wpilibj.fixtures.ITestFixture#reset() - */ - @Override - public boolean reset() { - initialize(); - return true; - } + private boolean initialized = false; + private boolean freed = false; - /* (non-Javadoc) - * @see edu.wpi.first.wpilibj.fixtures.ITestFixture#teardown() - */ - @Override - public boolean teardown() { - if(!freed){ - relay.free(); - inputOne.free(); - inputTwo.free(); - freed = true; - } else { - throw new RuntimeException("You attempted to free the " + RelayCrossConnectFxiture.class.getSimpleName() + " multiple times"); - } - return true; - } + + + protected abstract Relay giveRelay(); + + protected abstract DigitalInput giveInputOne(); + + protected abstract DigitalInput giveInputTwo(); + + private void initialize() { + synchronized (this) { + if (!initialized) { + relay = giveRelay(); + inputOne = giveInputOne(); + inputTwo = giveInputTwo(); + initialized = true; + } + } + } + + public Relay getRelay() { + initialize(); + return relay; + } + + public DigitalInput getInputOne() { + initialize(); + return inputOne; + } + + public DigitalInput getInputTwo() { + initialize(); + return inputTwo; + } + + /* + * (non-Javadoc) + *$ + * @see edu.wpi.first.wpilibj.fixtures.ITestFixture#setup() + */ + @Override + public boolean setup() { + initialize(); + return true; + } + + /* + * (non-Javadoc) + *$ + * @see edu.wpi.first.wpilibj.fixtures.ITestFixture#reset() + */ + @Override + public boolean reset() { + initialize(); + return true; + } + + /* + * (non-Javadoc) + *$ + * @see edu.wpi.first.wpilibj.fixtures.ITestFixture#teardown() + */ + @Override + public boolean teardown() { + if (!freed) { + relay.free(); + inputOne.free(); + inputTwo.free(); + freed = true; + } else { + throw new RuntimeException("You attempted to free the " + + RelayCrossConnectFxiture.class.getSimpleName() + " multiple times"); + } + return true; + } } diff --git a/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/fixtures/SampleFixture.java b/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/fixtures/SampleFixture.java index 5ed31a5e3b..d521e6e2e1 100644 --- a/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/fixtures/SampleFixture.java +++ b/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/fixtures/SampleFixture.java @@ -1,8 +1,8 @@ /*----------------------------------------------------------------------------*/ -/* Copyright (c) FIRST 2008-2014. All Rights Reserved. */ -/* Open Source Software - may be modified and shared by FRC teams. The code */ +/* Copyright (c) FIRST 2008-2014. All Rights Reserved. */ +/* Open Source Software - may be modified and shared by FRC teams. The code */ /* must be accompanied by the FIRST BSD license file in the root directory of */ -/* the project. */ +/* the project. */ /*----------------------------------------------------------------------------*/ package edu.wpi.first.wpilibj.fixtures; @@ -10,48 +10,48 @@ package edu.wpi.first.wpilibj.fixtures; /** * This is an example of how to use the {@link ITestFixture} interface to create * test fixtures for a test. - * + *$ * @author Fredric Silberberg - * + *$ */ public class SampleFixture implements ITestFixture { - /** - * {@inheritDoc} - */ - @Override - public boolean setup() { - /* - * If this fixture actually accessed the hardware, here is where it - * would set up the starting state of the test bench. For example, - * reseting encoders, ensuring motors are stopped, reseting any serial - * communication if necessary, etc. - */ - return true; - } + /** + * {@inheritDoc} + */ + @Override + public boolean setup() { + /* + * If this fixture actually accessed the hardware, here is where it would + * set up the starting state of the test bench. For example, reseting + * encoders, ensuring motors are stopped, reseting any serial communication + * if necessary, etc. + */ + return true; + } - @Override - public boolean reset() { - /* - * This is where the fixture would reset any sensors or motors used by - * the fixture to test default state. This method should not worry about - * whether or not the sensors have been allocated correctly, that is the - * job of the setup function. - */ - return false; - } + @Override + public boolean reset() { + /* + * This is where the fixture would reset any sensors or motors used by the + * fixture to test default state. This method should not worry about whether + * or not the sensors have been allocated correctly, that is the job of the + * setup function. + */ + return false; + } - /** - * {@inheritDoc} - */ - @Override - public boolean teardown() { - /* - * This is where the fixture would deallocate and reset back to normal - * conditions any necessary hardware. This includes ensuring motors are - * stopped, stoppable sensors are actually stopped, ensuring serial - * communications are ready for the next test, etc. - */ - return true; - } + /** + * {@inheritDoc} + */ + @Override + public boolean teardown() { + /* + * This is where the fixture would deallocate and reset back to normal + * conditions any necessary hardware. This includes ensuring motors are + * stopped, stoppable sensors are actually stopped, ensuring serial + * communications are ready for the next test, etc. + */ + return true; + } } diff --git a/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/fixtures/TiltPanCameraFixture.java b/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/fixtures/TiltPanCameraFixture.java index 18677c89bc..bdc1cd8798 100644 --- a/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/fixtures/TiltPanCameraFixture.java +++ b/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/fixtures/TiltPanCameraFixture.java @@ -1,8 +1,8 @@ /*----------------------------------------------------------------------------*/ -/* Copyright (c) FIRST 2008-2014. All Rights Reserved. */ -/* Open Source Software - may be modified and shared by FRC teams. The code */ +/* Copyright (c) FIRST 2008-2014. All Rights Reserved. */ +/* Open Source Software - may be modified and shared by FRC teams. The code */ /* must be accompanied by the FIRST BSD license file in the root directory of */ -/* the project. */ +/* the project. */ /*----------------------------------------------------------------------------*/ package edu.wpi.first.wpilibj.fixtures; @@ -13,77 +13,79 @@ import edu.wpi.first.wpilibj.Servo; import edu.wpi.first.wpilibj.Timer; /** - * A class to represent the a physical Camera with two servos (tilt and pan) designed to test to see if the - * gyroscope is operating normally. + * A class to represent the a physical Camera with two servos (tilt and pan) + * designed to test to see if the gyroscope is operating normally. * * @author Jonathan Leitschuh * */ public abstract class TiltPanCameraFixture implements ITestFixture { - public static final Logger logger = Logger.getLogger(TiltPanCameraFixture.class.getName()); + public static final Logger logger = Logger.getLogger(TiltPanCameraFixture.class.getName()); - public static final double RESET_TIME = 2.0; - private Gyro gyro; - private Servo tilt; - private Servo pan; - private boolean initialized = false; + public static final double RESET_TIME = 2.0; + private Gyro gyro; + private Servo tilt; + private Servo pan; + private boolean initialized = false; - protected abstract Gyro giveGyro(); - protected abstract Servo giveTilt(); - protected abstract Servo givePan(); + protected abstract Gyro giveGyro(); - /** - * Constructs the TiltPanCamera - */ - public TiltPanCameraFixture (){} + protected abstract Servo giveTilt(); - @Override - public boolean setup() { - boolean wasSetup = false; - if(!initialized){ - initialized = true; - tilt = giveTilt(); - tilt.set(0); - pan = givePan(); - pan.set(0); - Timer.delay(RESET_TIME); + protected abstract Servo givePan(); - logger.fine("Initializing the gyro"); - gyro = giveGyro(); - gyro.reset(); - wasSetup = true; - } - return wasSetup; - } + /** + * Constructs the TiltPanCamera + */ + public TiltPanCameraFixture() {} - @Override - public boolean reset(){ - gyro.reset(); - return true; - } + @Override + public boolean setup() { + boolean wasSetup = false; + if (!initialized) { + initialized = true; + tilt = giveTilt(); + tilt.set(0); + pan = givePan(); + pan.set(0); + Timer.delay(RESET_TIME); - public Servo getTilt() { - return tilt; - } + logger.fine("Initializing the gyro"); + gyro = giveGyro(); + gyro.reset(); + wasSetup = true; + } + return wasSetup; + } - public Servo getPan() { - return pan; - } + @Override + public boolean reset() { + gyro.reset(); + return true; + } - public Gyro getGyro() { - return gyro; - } + public Servo getTilt() { + return tilt; + } - @Override - public boolean teardown() { - tilt.free(); - tilt = null; - pan.free(); - pan = null; - gyro.free(); - gyro = null; - return true; - } + public Servo getPan() { + return pan; + } + + public Gyro getGyro() { + return gyro; + } + + @Override + public boolean teardown() { + tilt.free(); + tilt = null; + pan.free(); + pan = null; + gyro.free(); + gyro = null; + return true; + } } diff --git a/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/mockhardware/FakeCounterSource.java b/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/mockhardware/FakeCounterSource.java index 1d82f1512b..ad91b2a9b1 100644 --- a/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/mockhardware/FakeCounterSource.java +++ b/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/mockhardware/FakeCounterSource.java @@ -1,8 +1,8 @@ /*----------------------------------------------------------------------------*/ -/* Copyright (c) FIRST 2014. All Rights Reserved. */ -/* Open Source Software - may be modified and shared by FRC teams. The code */ +/* Copyright (c) FIRST 2014. All Rights Reserved. */ +/* Open Source Software - may be modified and shared by FRC teams. The code */ /* must be accompanied by the FIRST BSD license file in the root directory of */ -/* the project. */ +/* the project. */ /*----------------------------------------------------------------------------*/ package edu.wpi.first.wpilibj.mockhardware; @@ -10,143 +10,128 @@ import edu.wpi.first.wpilibj.DigitalOutput; import edu.wpi.first.wpilibj.Timer; /** - * @file FakeCounterSource.java - * Simulates an encoder for testing purposes + * @file FakeCounterSource.java Simulates an encoder for testing purposes * @author Ryan O'Meara */ -public class FakeCounterSource -{ +public class FakeCounterSource { - private Thread m_task; - private int m_count; - private int m_mSec; - private DigitalOutput m_output; - private boolean m_allocated; + private Thread m_task; + private int m_count; + private int m_mSec; + private DigitalOutput m_output; + private boolean m_allocated; - /** - * Thread object that allows emulation of an encoder - */ - private class EncoderThread extends Thread - { + /** + * Thread object that allows emulation of an encoder + */ + private class EncoderThread extends Thread { - FakeCounterSource m_encoder; + FakeCounterSource m_encoder; - EncoderThread(FakeCounterSource encode) - { - m_encoder = encode; - } - - public void run() - { - m_encoder.m_output.set(false); - try - { - for (int i = 0; i < m_encoder.m_count; i++) - { - Thread.sleep(m_encoder.m_mSec); - m_encoder.m_output.set(true); - Thread.sleep(m_encoder.m_mSec); - m_encoder.m_output.set(false); - } - } catch (InterruptedException e) - { - } + EncoderThread(FakeCounterSource encode) { + m_encoder = encode; + } + + public void run() { + m_encoder.m_output.set(false); + try { + for (int i = 0; i < m_encoder.m_count; i++) { + Thread.sleep(m_encoder.m_mSec); + m_encoder.m_output.set(true); + Thread.sleep(m_encoder.m_mSec); + m_encoder.m_output.set(false); } + } catch (InterruptedException e) { + } } + } - /** - * Create a fake encoder on a given port - * @param output the port to output the given signal to - */ - public FakeCounterSource(DigitalOutput output) - { - m_output = output; - m_allocated = false; - initEncoder(); - } + /** + * Create a fake encoder on a given port + *$ + * @param output the port to output the given signal to + */ + public FakeCounterSource(DigitalOutput output) { + m_output = output; + m_allocated = false; + initEncoder(); + } - /** - * Create a fake encoder on a given port - * @param port The port the encoder is supposed to be on - */ - public FakeCounterSource(int port) - { - m_output = new DigitalOutput(port); - m_allocated = true; - initEncoder(); - } + /** + * Create a fake encoder on a given port + *$ + * @param port The port the encoder is supposed to be on + */ + public FakeCounterSource(int port) { + m_output = new DigitalOutput(port); + m_allocated = true; + initEncoder(); + } - /** - * Destroy Object with minimum memory leak - */ - public void free() - { - m_task = null; - if(m_allocated){ - m_output.free(); - m_output = null; - m_allocated = false; - } + /** + * Destroy Object with minimum memory leak + */ + public void free() { + m_task = null; + if (m_allocated) { + m_output.free(); + m_output = null; + m_allocated = false; } + } - /** - * Common initailization code - */ - private void initEncoder() - { - m_mSec = 1; - m_task = new EncoderThread(this); - m_output.set(false); - } + /** + * Common initailization code + */ + private void initEncoder() { + m_mSec = 1; + m_task = new EncoderThread(this); + m_output.set(false); + } - /** - * Starts the thread execution task - */ - public void start() - { - m_task.start(); - } + /** + * Starts the thread execution task + */ + public void start() { + m_task.start(); + } - /** - * Waits for the thread to complete - */ - public void complete() - { - try - { - m_task.join(); - } catch (InterruptedException e) - { - } - m_task = new EncoderThread(this); - Timer.delay(.01); + /** + * Waits for the thread to complete + */ + public void complete() { + try { + m_task.join(); + } catch (InterruptedException e) { } + m_task = new EncoderThread(this); + Timer.delay(.01); + } - /** - * Starts and completes a task set - does not return until thred has finished - * its operations - */ - public void execute() - { - start(); - complete(); - } + /** + * Starts and completes a task set - does not return until thred has finished + * its operations + */ + public void execute() { + start(); + complete(); + } - /** - * Sets the count to run encoder - * @param count The count to emulate to the controller - */ - public void setCount(int count) - { - m_count = count; - } + /** + * Sets the count to run encoder + *$ + * @param count The count to emulate to the controller + */ + public void setCount(int count) { + m_count = count; + } - /** - * Specify the rate to send pulses - * @param mSec The rate to send out pulses at - */ - public void setRate(int mSec) - { - m_mSec = mSec; - } + /** + * Specify the rate to send pulses + *$ + * @param mSec The rate to send out pulses at + */ + public void setRate(int mSec) { + m_mSec = mSec; + } } diff --git a/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/mockhardware/FakeEncoderSource.java b/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/mockhardware/FakeEncoderSource.java index 409d33e72e..d3814504b8 100644 --- a/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/mockhardware/FakeEncoderSource.java +++ b/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/mockhardware/FakeEncoderSource.java @@ -1,8 +1,8 @@ /*----------------------------------------------------------------------------*/ -/* Copyright (c) FIRST 2014. All Rights Reserved. */ -/* Open Source Software - may be modified and shared by FRC teams. The code */ +/* Copyright (c) FIRST 2014. All Rights Reserved. */ +/* Open Source Software - may be modified and shared by FRC teams. The code */ /* must be accompanied by the FIRST BSD license file in the root directory of */ -/* the project. */ +/* the project. */ /*----------------------------------------------------------------------------*/ package edu.wpi.first.wpilibj.mockhardware; @@ -10,172 +10,153 @@ import edu.wpi.first.wpilibj.DigitalOutput; import edu.wpi.first.wpilibj.Timer; /** - * @file FakeEncoderSource.java - * Emulates a quadrature encoder + * @file FakeEncoderSource.java Emulates a quadrature encoder * @author Ryan O'Meara */ -public class FakeEncoderSource -{ +public class FakeEncoderSource { - private Thread m_task; - private int m_count; - private int m_mSec; - private boolean m_forward; - private DigitalOutput m_outputA, m_outputB; - private final boolean allocatedOutputs; + private Thread m_task; + private int m_count; + private int m_mSec; + private boolean m_forward; + private DigitalOutput m_outputA, m_outputB; + private final boolean allocatedOutputs; - /** - * Thread object that allows emulation of a quadrature encoder - */ - private class QuadEncoderThread extends Thread - { + /** + * Thread object that allows emulation of a quadrature encoder + */ + private class QuadEncoderThread extends Thread { - FakeEncoderSource m_encoder; + FakeEncoderSource m_encoder; - QuadEncoderThread(FakeEncoderSource encode) - { - m_encoder = encode; - } - - public void run() - { - - DigitalOutput lead, lag; - - m_encoder.m_outputA.set(false); - m_encoder.m_outputB.set(false); - - if (m_encoder.isForward()) - { - lead = m_encoder.m_outputA; - lag = m_encoder.m_outputB; - } else - { - lead = m_encoder.m_outputB; - lag = m_encoder.m_outputA; - } - - try - { - for (int i = 0; i < m_encoder.m_count; i++) - { - lead.set(true); - Thread.sleep(m_encoder.m_mSec); - lag.set(true); - Thread.sleep(m_encoder.m_mSec); - lead.set(false); - Thread.sleep(m_encoder.m_mSec); - lag.set(false); - Thread.sleep(m_encoder.m_mSec); - } - } catch (InterruptedException e) - { - } + QuadEncoderThread(FakeEncoderSource encode) { + m_encoder = encode; + } + + public void run() { + + DigitalOutput lead, lag; + + m_encoder.m_outputA.set(false); + m_encoder.m_outputB.set(false); + + if (m_encoder.isForward()) { + lead = m_encoder.m_outputA; + lag = m_encoder.m_outputB; + } else { + lead = m_encoder.m_outputB; + lag = m_encoder.m_outputA; + } + + try { + for (int i = 0; i < m_encoder.m_count; i++) { + lead.set(true); + Thread.sleep(m_encoder.m_mSec); + lag.set(true); + Thread.sleep(m_encoder.m_mSec); + lead.set(false); + Thread.sleep(m_encoder.m_mSec); + lag.set(false); + Thread.sleep(m_encoder.m_mSec); } + } catch (InterruptedException e) { + } } + } - public FakeEncoderSource(int portA, int portB) - { - m_outputA = new DigitalOutput(portA); - m_outputB = new DigitalOutput(portB); - allocatedOutputs = true; - initQuadEncoder(); - } + public FakeEncoderSource(int portA, int portB) { + m_outputA = new DigitalOutput(portA); + m_outputB = new DigitalOutput(portB); + allocatedOutputs = true; + initQuadEncoder(); + } - public FakeEncoderSource(DigitalOutput iA, DigitalOutput iB) - { - m_outputA = iA; - m_outputB = iB; - allocatedOutputs = false; - initQuadEncoder(); - } + public FakeEncoderSource(DigitalOutput iA, DigitalOutput iB) { + m_outputA = iA; + m_outputB = iB; + allocatedOutputs = false; + initQuadEncoder(); + } - public void free() - { - m_task = null; - if (allocatedOutputs) { - m_outputA.free(); - m_outputB.free(); - } + public void free() { + m_task = null; + if (allocatedOutputs) { + m_outputA.free(); + m_outputB.free(); } + } - /** - * Common initialization code - */ - private final void initQuadEncoder() - { - m_mSec = 1; - m_forward = true; - m_task = new QuadEncoderThread(this); - m_outputA.set(false); - m_outputB.set(false); - } + /** + * Common initialization code + */ + private final void initQuadEncoder() { + m_mSec = 1; + m_forward = true; + m_task = new QuadEncoderThread(this); + m_outputA.set(false); + m_outputB.set(false); + } - /** - * Starts the thread - */ - public void start() - { - m_task.start(); - } + /** + * Starts the thread + */ + public void start() { + m_task.start(); + } - /** - * Waits for thread to end - */ - public void complete() - { - try - { - m_task.join(); - } catch (InterruptedException e) - { - } - m_task = new QuadEncoderThread(this); - Timer.delay(.01); + /** + * Waits for thread to end + */ + public void complete() { + try { + m_task.join(); + } catch (InterruptedException e) { } + m_task = new QuadEncoderThread(this); + Timer.delay(.01); + } - /** - * Runs and waits for thread to end before returning - */ - public void execute() - { - start(); - complete(); - } + /** + * Runs and waits for thread to end before returning + */ + public void execute() { + start(); + complete(); + } - /** - * Rate of pulses to send - * @param mSec Pulse Rate - */ - public void setRate(int mSec) - { - m_mSec = mSec; - } + /** + * Rate of pulses to send + *$ + * @param mSec Pulse Rate + */ + public void setRate(int mSec) { + m_mSec = mSec; + } - /** - * Set the number of pulses to simulate - * @param count Pulse count - */ - public void setCount(int count) - { - m_count = Math.abs(count); - } + /** + * Set the number of pulses to simulate + *$ + * @param count Pulse count + */ + public void setCount(int count) { + m_count = Math.abs(count); + } - /** - * Set which direction the encoder simulates motion in - * @param isForward Whether to simulate forward motion - */ - public void setForward(boolean isForward) - { - m_forward = isForward; - } + /** + * Set which direction the encoder simulates motion in + *$ + * @param isForward Whether to simulate forward motion + */ + public void setForward(boolean isForward) { + m_forward = isForward; + } - /** - * Accesses whether the encoder is simulating forward motion - * @return Whether the simulated motion is in the forward direction - */ - public boolean isForward() - { - return m_forward; - } + /** + * Accesses whether the encoder is simulating forward motion + *$ + * @return Whether the simulated motion is in the forward direction + */ + public boolean isForward() { + return m_forward; + } } diff --git a/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/mockhardware/FakePotentiometerSource.java b/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/mockhardware/FakePotentiometerSource.java index 99915216a2..19c9fa736f 100644 --- a/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/mockhardware/FakePotentiometerSource.java +++ b/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/mockhardware/FakePotentiometerSource.java @@ -1,8 +1,8 @@ /*----------------------------------------------------------------------------*/ -/* Copyright (c) FIRST 2008-2014. All Rights Reserved. */ -/* Open Source Software - may be modified and shared by FRC teams. The code */ +/* Copyright (c) FIRST 2008-2014. All Rights Reserved. */ +/* Open Source Software - may be modified and shared by FRC teams. The code */ /* must be accompanied by the FIRST BSD license file in the root directory of */ -/* the project. */ +/* the project. */ /*----------------------------------------------------------------------------*/ package edu.wpi.first.wpilibj.mockhardware; @@ -13,69 +13,72 @@ import edu.wpi.first.wpilibj.AnalogOutput; * */ public class FakePotentiometerSource { - private AnalogOutput output; - private boolean m_init_output; - private double potMaxAngle; - private double potMaxVoltage = 5.0; - private final double defaultPotMaxAngle; - public FakePotentiometerSource(AnalogOutput output, double defaultPotMaxAngle){ - this.defaultPotMaxAngle = defaultPotMaxAngle; - potMaxAngle = defaultPotMaxAngle; - this.output = output; - m_init_output = false; - } - - public FakePotentiometerSource(int port, double defaultPotMaxAngle){ - this(new AnalogOutput(port), defaultPotMaxAngle); - m_init_output = true; - } - - /** - * Sets the maximum voltage output. If not the default is 5.0V - * @param voltage The voltage that indicates that the pot is at the max value. - */ - public void setMaxVoltage(double voltage){ - potMaxVoltage = voltage; - } - - public void setRange(double range){ - potMaxAngle = range; - } - - public void reset(){ - potMaxAngle = defaultPotMaxAngle; - output.setVoltage(0.0); - } - - public void setAngle(double angle){ - output.setVoltage((potMaxVoltage/potMaxAngle)*angle); - } - - public void setVoltage(double voltage){ - output.setVoltage(voltage); - } - - public double getVoltage(){ - return output.getVoltage(); - } - - /** - * Returns the currently set angle - * @return - */ - public double getAngle(){ - double voltage = output.getVoltage(); - if(voltage == 0){ //Removes divide by zero error - return 0; - } - return voltage * (potMaxAngle/potMaxVoltage); - } - - public void free(){ - if(m_init_output){ - output.free(); - output = null; - m_init_output = false; - } - } + private AnalogOutput output; + private boolean m_init_output; + private double potMaxAngle; + private double potMaxVoltage = 5.0; + private final double defaultPotMaxAngle; + + public FakePotentiometerSource(AnalogOutput output, double defaultPotMaxAngle) { + this.defaultPotMaxAngle = defaultPotMaxAngle; + potMaxAngle = defaultPotMaxAngle; + this.output = output; + m_init_output = false; + } + + public FakePotentiometerSource(int port, double defaultPotMaxAngle) { + this(new AnalogOutput(port), defaultPotMaxAngle); + m_init_output = true; + } + + /** + * Sets the maximum voltage output. If not the default is 5.0V + *$ + * @param voltage The voltage that indicates that the pot is at the max value. + */ + public void setMaxVoltage(double voltage) { + potMaxVoltage = voltage; + } + + public void setRange(double range) { + potMaxAngle = range; + } + + public void reset() { + potMaxAngle = defaultPotMaxAngle; + output.setVoltage(0.0); + } + + public void setAngle(double angle) { + output.setVoltage((potMaxVoltage / potMaxAngle) * angle); + } + + public void setVoltage(double voltage) { + output.setVoltage(voltage); + } + + public double getVoltage() { + return output.getVoltage(); + } + + /** + * Returns the currently set angle + *$ + * @return + */ + public double getAngle() { + double voltage = output.getVoltage(); + if (voltage == 0) { // Removes divide by zero error + return 0; + } + return voltage * (potMaxAngle / potMaxVoltage); + } + + public void free() { + if (m_init_output) { + output.free(); + output = null; + m_init_output = false; + } + } } diff --git a/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/mocks/MockCommand.java b/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/mocks/MockCommand.java index ae2fe9192e..669bc44db2 100644 --- a/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/mocks/MockCommand.java +++ b/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/mocks/MockCommand.java @@ -3,111 +3,110 @@ package edu.wpi.first.wpilibj.mocks; import edu.wpi.first.wpilibj.command.Command; /** - * A class to simulate a simple command - * The command keeps track of how many times each method was called + * A class to simulate a simple command The command keeps track of how many + * times each method was called * * @author mwills */ -public class MockCommand extends Command{ - private int initializeCount = 0; - private int executeCount = 0; - private int isFinishedCount = 0; - private boolean hasFinished = false; - private int endCount = 0; - private int interruptedCount = 0; - - protected void initialize() { - ++initializeCount; - } +public class MockCommand extends Command { + private int initializeCount = 0; + private int executeCount = 0; + private int isFinishedCount = 0; + private boolean hasFinished = false; + private int endCount = 0; + private int interruptedCount = 0; - protected void execute() { - ++executeCount; - } + protected void initialize() { + ++initializeCount; + } - protected boolean isFinished() { - ++isFinishedCount; - return isHasFinished(); - } + protected void execute() { + ++executeCount; + } - protected void end() { - ++endCount; - } + protected boolean isFinished() { + ++isFinishedCount; + return isHasFinished(); + } - protected void interrupted() { - ++interruptedCount; - } - - - - - - + protected void end() { + ++endCount; + } - /** - * @return how many times the initialize method has been called - */ - public int getInitializeCount() { - return initializeCount; - } - /** - * @return if the initialize method has been called at least once - */ - public boolean hasInitialized(){ - return getInitializeCount()>0; - } + protected void interrupted() { + ++interruptedCount; + } - /** - * @return how many time the execute method has been called - */ - public int getExecuteCount() { - return executeCount; - } - /** - * @return how many times the isFinished method has been called - */ - public int getIsFinishedCount() { - return isFinishedCount; - } - /** - * @return what value the isFinished method will return - */ - public boolean isHasFinished() { - return hasFinished; - } + /** + * @return how many times the initialize method has been called + */ + public int getInitializeCount() { + return initializeCount; + } - /** - * @param set what value the isFinished method will return - */ - public void setHasFinished(boolean hasFinished) { - this.hasFinished = hasFinished; - } + /** + * @return if the initialize method has been called at least once + */ + public boolean hasInitialized() { + return getInitializeCount() > 0; + } - /** - * @return how many times the end method has been called - */ - public int getEndCount() { - return endCount; - } - /** - * @return if the end method has been called at least once - */ - public boolean hasEnd(){ - return getEndCount()>0; - } + /** + * @return how many time the execute method has been called + */ + public int getExecuteCount() { + return executeCount; + } + + /** + * @return how many times the isFinished method has been called + */ + public int getIsFinishedCount() { + return isFinishedCount; + } + + /** + * @return what value the isFinished method will return + */ + public boolean isHasFinished() { + return hasFinished; + } + + /** + * @param set what value the isFinished method will return + */ + public void setHasFinished(boolean hasFinished) { + this.hasFinished = hasFinished; + } + + /** + * @return how many times the end method has been called + */ + public int getEndCount() { + return endCount; + } + + /** + * @return if the end method has been called at least once + */ + public boolean hasEnd() { + return getEndCount() > 0; + } + + /** + * @return how many times the interrupted method has been called + */ + public int getInterruptedCount() { + return interruptedCount; + } + + /** + * @return if the interrupted method has been called at least once + */ + public boolean hasInterrupted() { + return getInterruptedCount() > 0; + } - /** - * @return how many times the interrupted method has been called - */ - public int getInterruptedCount() { - return interruptedCount; - } - /** - * @return if the interrupted method has been called at least once - */ - public boolean hasInterrupted(){ - return getInterruptedCount()>0; - } - } diff --git a/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/smartdashboard/SmartDashboardTest.java b/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/smartdashboard/SmartDashboardTest.java index cd36138790..f64c9fa3ee 100644 --- a/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/smartdashboard/SmartDashboardTest.java +++ b/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/smartdashboard/SmartDashboardTest.java @@ -1,8 +1,8 @@ /*----------------------------------------------------------------------------*/ -/* Copyright (c) FIRST 2008-2014. All Rights Reserved. */ -/* Open Source Software - may be modified and shared by FRC teams. The code */ +/* Copyright (c) FIRST 2008-2014. All Rights Reserved. */ +/* Open Source Software - may be modified and shared by FRC teams. The code */ /* must be accompanied by the FIRST BSD license file in the root directory of */ -/* the project. */ +/* the project. */ /*----------------------------------------------------------------------------*/ package edu.wpi.first.wpilibj.smartdashboard; @@ -26,96 +26,92 @@ import edu.wpi.first.wpilibj.test.AbstractComsSetup; * */ public class SmartDashboardTest extends AbstractComsSetup { - private static final Logger logger = Logger.getLogger(SmartDashboardTest.class.getName()); - private static final NetworkTable table = NetworkTable.getTable("SmartDashboard"); - - protected Logger getClassLogger(){ - return logger; - } - - /** - * @throws java.lang.Exception - */ - @BeforeClass - public static void setUpBeforeClass() throws Exception { - } + private static final Logger logger = Logger.getLogger(SmartDashboardTest.class.getName()); + private static final NetworkTable table = NetworkTable.getTable("SmartDashboard"); - /** - * @throws java.lang.Exception - */ - @AfterClass - public static void tearDownAfterClass() throws Exception { - } + protected Logger getClassLogger() { + return logger; + } - /** - * @throws java.lang.Exception - */ - @Before - public void setUp() throws Exception { - } + /** + * @throws java.lang.Exception + */ + @BeforeClass + public static void setUpBeforeClass() throws Exception {} - /** - * @throws java.lang.Exception - */ - @After - public void tearDown() throws Exception { - } - - @Test(expected=NetworkTableKeyNotDefined.class) - public void testGetBadValue(){ - SmartDashboard.getString("_404_STRING_KEY_SHOULD_NOT_BE_FOUND_"); - } - - @Test - public void testPutString() { - String key = "testPutString"; - String value = "thisIsAValue"; - SmartDashboard.putString(key, value); - assertEquals(value, SmartDashboard.getString(key)); - assertEquals(value, table.getString(key)); - } - - @Test - public void testPutNumber(){ - String key = "testPutNumber"; - int value = 2147483647; - SmartDashboard.putNumber(key, value); - assertEquals(value, SmartDashboard.getNumber(key), 0.01); - assertEquals(value, table.getNumber(key), 0.01); - } - - @Test - public void testPutBoolean(){ - String key = "testPutBoolean"; - boolean value = true; - SmartDashboard.putBoolean(key, value); - assertEquals(value, SmartDashboard.getBoolean(key)); - assertEquals(value, table.getBoolean(key)); - } - - @Test - public void testReplaceString(){ - String key = "testReplaceString"; - String valueOld = "oldValue"; - String valueNew = "newValue"; - SmartDashboard.putString(key, valueOld); - assertEquals(valueOld, SmartDashboard.getString(key)); - assertEquals(valueOld, table.getString(key)); - - SmartDashboard.putString(key, valueNew); - assertEquals(valueNew, SmartDashboard.getString(key)); - assertEquals(valueNew, table.getString(key)); - } - - @Ignore - @Test(expected=IllegalArgumentException.class) - public void testPutStringNullKey(){ - SmartDashboard.putString(null, "This should not work"); - } - - @Ignore - @Test(expected=IllegalArgumentException.class) - public void testPutStringNullValue(){ - SmartDashboard.putString("KEY_SHOULD_NOT_BE_STORED", null); - } + /** + * @throws java.lang.Exception + */ + @AfterClass + public static void tearDownAfterClass() throws Exception {} + + /** + * @throws java.lang.Exception + */ + @Before + public void setUp() throws Exception {} + + /** + * @throws java.lang.Exception + */ + @After + public void tearDown() throws Exception {} + + @Test(expected = NetworkTableKeyNotDefined.class) + public void testGetBadValue() { + SmartDashboard.getString("_404_STRING_KEY_SHOULD_NOT_BE_FOUND_"); + } + + @Test + public void testPutString() { + String key = "testPutString"; + String value = "thisIsAValue"; + SmartDashboard.putString(key, value); + assertEquals(value, SmartDashboard.getString(key)); + assertEquals(value, table.getString(key)); + } + + @Test + public void testPutNumber() { + String key = "testPutNumber"; + int value = 2147483647; + SmartDashboard.putNumber(key, value); + assertEquals(value, SmartDashboard.getNumber(key), 0.01); + assertEquals(value, table.getNumber(key), 0.01); + } + + @Test + public void testPutBoolean() { + String key = "testPutBoolean"; + boolean value = true; + SmartDashboard.putBoolean(key, value); + assertEquals(value, SmartDashboard.getBoolean(key)); + assertEquals(value, table.getBoolean(key)); + } + + @Test + public void testReplaceString() { + String key = "testReplaceString"; + String valueOld = "oldValue"; + String valueNew = "newValue"; + SmartDashboard.putString(key, valueOld); + assertEquals(valueOld, SmartDashboard.getString(key)); + assertEquals(valueOld, table.getString(key)); + + SmartDashboard.putString(key, valueNew); + assertEquals(valueNew, SmartDashboard.getString(key)); + assertEquals(valueNew, table.getString(key)); + } + + @Ignore + @Test(expected = IllegalArgumentException.class) + public void testPutStringNullKey() { + SmartDashboard.putString(null, "This should not work"); + } + + @Ignore + @Test(expected = IllegalArgumentException.class) + public void testPutStringNullValue() { + SmartDashboard.putString("KEY_SHOULD_NOT_BE_STORED", null); + } } diff --git a/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/smartdashboard/SmartDashboardTestSuite.java b/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/smartdashboard/SmartDashboardTestSuite.java index 3eacf12dc8..522f0d3065 100644 --- a/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/smartdashboard/SmartDashboardTestSuite.java +++ b/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/smartdashboard/SmartDashboardTestSuite.java @@ -1,8 +1,8 @@ /*----------------------------------------------------------------------------*/ -/* Copyright (c) FIRST 2008-2014. All Rights Reserved. */ -/* Open Source Software - may be modified and shared by FRC teams. The code */ +/* Copyright (c) FIRST 2008-2014. All Rights Reserved. */ +/* Open Source Software - may be modified and shared by FRC teams. The code */ /* must be accompanied by the FIRST BSD license file in the root directory of */ -/* the project. */ +/* the project. */ /*----------------------------------------------------------------------------*/ package edu.wpi.first.wpilibj.smartdashboard; @@ -17,8 +17,6 @@ import edu.wpi.first.wpilibj.test.AbstractTestSuite; * */ @RunWith(Suite.class) -@SuiteClasses({ - SmartDashboardTest.class -}) -public class SmartDashboardTestSuite extends AbstractTestSuite{ +@SuiteClasses({SmartDashboardTest.class}) +public class SmartDashboardTestSuite extends AbstractTestSuite { } diff --git a/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/test/AbstractComsSetup.java b/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/test/AbstractComsSetup.java index 663e953555..1694078c21 100644 --- a/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/test/AbstractComsSetup.java +++ b/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/test/AbstractComsSetup.java @@ -1,8 +1,8 @@ /*----------------------------------------------------------------------------*/ -/* Copyright (c) FIRST 2008-2014. All Rights Reserved. */ -/* Open Source Software - may be modified and shared by FRC teams. The code */ +/* Copyright (c) FIRST 2008-2014. All Rights Reserved. */ +/* Open Source Software - may be modified and shared by FRC teams. The code */ /* must be accompanied by the FIRST BSD license file in the root directory of */ -/* the project. */ +/* the project. */ /*----------------------------------------------------------------------------*/ package edu.wpi.first.wpilibj.test; @@ -26,173 +26,205 @@ import edu.wpi.first.wpilibj.livewindow.LiveWindow; * the roboRIO. It uses an {@link BeforeClass} statement to initialize network * communications. Any test that needs to use the hardware MUST extend * from this class, to ensure that all of the hardware will be able to run. - * + *$ * @author Fredric Silberberg * @author Jonathan Leitschuh */ public abstract class AbstractComsSetup { - /** Stores whether network coms have been initialized */ - private static boolean initialized = false; - - /** - * This sets up the network communications library to enable the driver - * station. After starting network coms, it will loop until the driver - * station returns that the robot is enabled, to ensure that tests will be - * able to run on the hardware. - * - */ - static{ - if (!initialized) { - // Set some implementations so that the static methods work properly - RobotBase.initializeHardwareConfiguration(); - FRCNetworkCommunicationsLibrary.FRCNetworkCommunicationObserveUserProgramStarting(); - - LiveWindow.setEnabled(false); - TestBench.out().println("Started coms"); + /** Stores whether network coms have been initialized */ + private static boolean initialized = false; - // Wait until the robot is enabled before starting the tests - int i = 0; - while (!DriverStation.getInstance().isEnabled()) { - try { - Thread.sleep(100); - } catch (InterruptedException e) { - e.printStackTrace(); - } - //Prints the message on one line overwriting itself each time - TestBench.out().print("\rWaiting for enable: " + i++); - } - TestBench.out().println(); + /** + * This sets up the network communications library to enable the driver + * station. After starting network coms, it will loop until the driver station + * returns that the robot is enabled, to ensure that tests will be able to run + * on the hardware. + *$ + */ + static { + if (!initialized) { + // Set some implementations so that the static methods work properly + RobotBase.initializeHardwareConfiguration(); + FRCNetworkCommunicationsLibrary.FRCNetworkCommunicationObserveUserProgramStarting(); - // Ready to go! - initialized = true; - TestBench.out().println("Running!"); - } - } + LiveWindow.setEnabled(false); + TestBench.out().println("Started coms"); + + // Wait until the robot is enabled before starting the tests + int i = 0; + while (!DriverStation.getInstance().isEnabled()) { + try { + Thread.sleep(100); + } catch (InterruptedException e) { + e.printStackTrace(); + } + // Prints the message on one line overwriting itself each time + TestBench.out().print("\rWaiting for enable: " + i++); + } + TestBench.out().println(); + + // Ready to go! + initialized = true; + TestBench.out().println("Running!"); + } + } - protected abstract Logger getClassLogger(); - - /** This causes a stack trace to be printed as the test is running as well as at the end */ - @Rule - public final TestWatcher getTestWatcher(){ - return getOverridenTestWatcher(); - } - - /** - * Given as a way to provide a custom test watcher for a test or set of tests - * @return the test watcher to use - */ - protected TestWatcher getOverridenTestWatcher(){ - return new DefaultTestWatcher(); - } - - protected class DefaultTestWatcher extends TestWatcher { - /** - * Allows a failure to supply a custom status message to be displayed along with the stack trace. - */ - protected void failed(Throwable e, Description description, String status){ - TestBench.out().println(); - //Instance of is the best way I know to retrieve this data. - if(e instanceof MultipleFailureException){ - /* MultipleFailureExceptions hold multiple exceptions in one exception. In order to properly display these stack traces - * we have to cast the throwable and work with the list of thrown exceptions stored within it. - */ - int i = 1; //Running exception count - int failureCount = ((MultipleFailureException)e).getFailures().size(); - for(Throwable singleThrown : ((MultipleFailureException)e).getFailures()){ - getClassLogger().logp(Level.SEVERE, description.getClassName(), description.getMethodName(), (i++) + "/" + failureCount - + " "+ description.getDisplayName() + " failed " + singleThrown.getMessage() + "\n" + status, singleThrown); - } - - } else { - getClassLogger().logp(Level.SEVERE, description.getClassName(), description.getMethodName(), description.getDisplayName() + " failed " + e.getMessage() + "\n" + status, e); - } - super.failed(e, description); - } - - /* (non-Javadoc) - * @see org.junit.rules.TestWatcher#failed(java.lang.Throwable, org.junit.runner.Description) - */ - @Override - protected void failed(Throwable e, Description description) { - failed(e, description, ""); - } + protected abstract Logger getClassLogger(); - - /* (non-Javadoc) - * @see org.junit.rules.TestWatcher#starting(org.junit.runner.Description) - */ - @Override - protected void starting(Description description ) { - TestBench.out().println(); - // Wait until the robot is enabled before starting the next tests - int i = 0; - while (!DriverStation.getInstance().isEnabled()) { - try { - Thread.sleep(100); - } catch (InterruptedException e) { - e.printStackTrace(); - } - //Prints the message on one line overwriting itself each time - TestBench.out().print("\rWaiting for enable: " + i++); - } - getClassLogger().logp(Level.INFO, description.getClassName(), description.getMethodName(), "Starting"); - super.starting(description); - } + /** + * This causes a stack trace to be printed as the test is running as well as + * at the end + */ + @Rule + public final TestWatcher getTestWatcher() { + return getOverridenTestWatcher(); + } - @Override - protected void succeeded(Description description) { - simpleLog(Level.INFO, "TEST PASSED!"); - super.succeeded(description); - } + /** + * Given as a way to provide a custom test watcher for a test or set of tests + *$ + * @return the test watcher to use + */ + protected TestWatcher getOverridenTestWatcher() { + return new DefaultTestWatcher(); + } - }; - - /** - * Logs a simple message without the logger formatting associated with it. - * @param level The level to log the message at - * @param message The message to log - */ - protected void simpleLog(Level level, String message){ - if(getClassLogger().isLoggable(level)){ - TestBench.out().println(message); - } - } - - /** - * Provided as a replacement to lambda functions to allow for repeatable checks to see if a correct state is reached - * @author Jonathan Leitschuh - * - */ - public abstract class BooleanCheck{ - public BooleanCheck(){} - /** - * Runs the enclosed code and evaluates it to determine what state it should return. - * @return true if the code provided within the method returns true - */ - abstract public boolean getAsBoolean(); - }; - - /** - * Delays until either the correct state is reached or we reach the timeout. - * @param level The level to log the message at. - * @param timeout How long the delay should run before it should timeout and allow the test to continue - * @param message The message to accompany the delay. The message will display 'message' took 'timeout' seconds if it passed. - * @param correctState A method to determine if the test has reached a state where it is valid to continue - * @return a double representing how long the delay took to run in seconds. - */ - public double delayTillInCorrectStateWithMessage(Level level, double timeout, String message, BooleanCheck correctState){ - int i = 0; - //As long as we are not in the correct state and the timeout has not been reached then continue to run this loop - for(i = 0; i < (timeout * 100) && !correctState.getAsBoolean(); i++){ - Timer.delay(.01); - } - if(correctState.getAsBoolean()){ - simpleLog(level, message + " took " + (i * .01) + " seconds"); - } else { - simpleLog(level, message + " timed out after " + (i * .01) + " seconds"); - } - return i*.01; - } + protected class DefaultTestWatcher extends TestWatcher { + /** + * Allows a failure to supply a custom status message to be displayed along + * with the stack trace. + */ + protected void failed(Throwable e, Description description, String status) { + TestBench.out().println(); + // Instance of is the best way I know to retrieve this data. + if (e instanceof MultipleFailureException) { + /* + * MultipleFailureExceptions hold multiple exceptions in one exception. + * In order to properly display these stack traces we have to cast the + * throwable and work with the list of thrown exceptions stored within + * it. + */ + int i = 1; // Running exception count + int failureCount = ((MultipleFailureException) e).getFailures().size(); + for (Throwable singleThrown : ((MultipleFailureException) e).getFailures()) { + getClassLogger().logp( + Level.SEVERE, + description.getClassName(), + description.getMethodName(), + (i++) + "/" + failureCount + " " + description.getDisplayName() + " failed " + + singleThrown.getMessage() + "\n" + status, singleThrown); + } + + } else { + getClassLogger().logp(Level.SEVERE, description.getClassName(), + description.getMethodName(), + description.getDisplayName() + " failed " + e.getMessage() + "\n" + status, e); + } + super.failed(e, description); + } + + /* + * (non-Javadoc) + *$ + * @see org.junit.rules.TestWatcher#failed(java.lang.Throwable, + * org.junit.runner.Description) + */ + @Override + protected void failed(Throwable e, Description description) { + failed(e, description, ""); + } + + + /* + * (non-Javadoc) + *$ + * @see org.junit.rules.TestWatcher#starting(org.junit.runner.Description) + */ + @Override + protected void starting(Description description) { + TestBench.out().println(); + // Wait until the robot is enabled before starting the next tests + int i = 0; + while (!DriverStation.getInstance().isEnabled()) { + try { + Thread.sleep(100); + } catch (InterruptedException e) { + e.printStackTrace(); + } + // Prints the message on one line overwriting itself each time + TestBench.out().print("\rWaiting for enable: " + i++); + } + getClassLogger().logp(Level.INFO, description.getClassName(), description.getMethodName(), + "Starting"); + super.starting(description); + } + + @Override + protected void succeeded(Description description) { + simpleLog(Level.INFO, "TEST PASSED!"); + super.succeeded(description); + } + + }; + + /** + * Logs a simple message without the logger formatting associated with it. + *$ + * @param level The level to log the message at + * @param message The message to log + */ + protected void simpleLog(Level level, String message) { + if (getClassLogger().isLoggable(level)) { + TestBench.out().println(message); + } + } + + /** + * Provided as a replacement to lambda functions to allow for repeatable + * checks to see if a correct state is reached + *$ + * @author Jonathan Leitschuh + * + */ + public abstract class BooleanCheck { + public BooleanCheck() {} + + /** + * Runs the enclosed code and evaluates it to determine what state it should + * return. + *$ + * @return true if the code provided within the method returns true + */ + abstract public boolean getAsBoolean(); + }; + + /** + * Delays until either the correct state is reached or we reach the timeout. + *$ + * @param level The level to log the message at. + * @param timeout How long the delay should run before it should timeout and + * allow the test to continue + * @param message The message to accompany the delay. The message will display + * 'message' took 'timeout' seconds if it passed. + * @param correctState A method to determine if the test has reached a state + * where it is valid to continue + * @return a double representing how long the delay took to run in seconds. + */ + public double delayTillInCorrectStateWithMessage(Level level, double timeout, String message, + BooleanCheck correctState) { + int i = 0; + // As long as we are not in the correct state and the timeout has not been + // reached then continue to run this loop + for (i = 0; i < (timeout * 100) && !correctState.getAsBoolean(); i++) { + Timer.delay(.01); + } + if (correctState.getAsBoolean()) { + simpleLog(level, message + " took " + (i * .01) + " seconds"); + } else { + simpleLog(level, message + " timed out after " + (i * .01) + " seconds"); + } + return i * .01; + } } diff --git a/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/test/AbstractTestSuite.java b/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/test/AbstractTestSuite.java index 166704d714..67d8b7efdb 100644 --- a/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/test/AbstractTestSuite.java +++ b/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/test/AbstractTestSuite.java @@ -1,8 +1,8 @@ /*----------------------------------------------------------------------------*/ -/* Copyright (c) FIRST 2008-2014. All Rights Reserved. */ -/* Open Source Software - may be modified and shared by FRC teams. The code */ +/* Copyright (c) FIRST 2008-2014. All Rights Reserved. */ +/* Open Source Software - may be modified and shared by FRC teams. The code */ /* must be accompanied by the FIRST BSD license file in the root directory of */ -/* the project. */ +/* the project. */ /*----------------------------------------------------------------------------*/ package edu.wpi.first.wpilibj.test; @@ -20,226 +20,261 @@ import org.junit.runners.Suite.SuiteClasses; import org.junit.runners.model.InitializationError; /** - * Allows tests suites and tests to be run selectively from the command line using a regex text pattern. + * Allows tests suites and tests to be run selectively from the command line + * using a regex text pattern. + *$ * @author jonathanleitschuh * */ public abstract class AbstractTestSuite { - private static final Logger logger = Logger.getLogger(AbstractTestSuite.class.getName()); - - /** - * Gets all of the classes listed within the SuiteClasses annotation. To use it, annotate a class - * with @RunWith(Suite.class) and @SuiteClasses({TestClass1.class, ...}). - * When you run this class, it will run all the tests in all the suite classes. - * When loading the tests using regex the test list will be generated from this annotation. - * @return the list of classes listed in the @SuiteClasses({TestClass1.class, ...}) annotation. - */ - protected List> getAnnotatedTestClasses(){ - SuiteClasses annotation = getClass().getAnnotation(SuiteClasses.class); - List> classes = new Vector>(); - if (annotation == null) { - throw new RuntimeException(String.format("class '%s' must have a SuiteClasses annotation", getClass().getName())); - } - for(Class c : annotation.value()){ - classes.add(c); - } - return classes; - } - - /** - * - * @param check - * @return - */ - private boolean areAnySuperClassesOfTypeAbstractTestSuite(Class check){ - while (check != null) { - if(check.equals(AbstractTestSuite.class)){ - return true; - } - check = check.getSuperclass(); - } - return false; - } - - /** - * Stores a method name and method class pair. Used when searching for methods matching a given regex text. - * @author jonathanleitschuh - * - */ - protected class ClassMethodPair{ - public final Class methodClass; - public final String methodName; - public ClassMethodPair(Class klass, Method m){ - this.methodClass = klass; - this.methodName = m.getName(); - } - - public Request getMethodRunRequest(){ - return Request.method(methodClass, methodName); - } - } - /** - * @param regex - * @return - */ - protected List getMethodMatching(final String regex){ - List classMethodPairs = new Vector(); - //Get all of the test classes - for(Class c : getAllContainedBaseTests()){ - for(Method m : c.getMethods()){ - //If this is a test method that is not trying to be ignored and it matches the regex - if(m.getAnnotation(Test.class) != null && - m.getAnnotation(Ignore.class) == null && - Pattern.matches(regex, m.getName())){ - ClassMethodPair pair = new ClassMethodPair(c, m); - classMethodPairs.add(pair); - } - } - } - return classMethodPairs; - } - - - /** - * Gets all of the test classes listed in this suite. Does not include any of the test suites. All of these classes contain tests. - * @param runningList the running list of classes to prevent recursion. - * @return The list of base test classes. - */ - private List> getAllContainedBaseTests(List> runningList){ - for(Class c: getAnnotatedTestClasses()){ - //Check to see if this is a test class or a suite - if(areAnySuperClassesOfTypeAbstractTestSuite(c)){ - //Create a new instance of this class so that we can retrieve its data - try { - AbstractTestSuite suite = null; - Object o = c.newInstance(); - suite = (AbstractTestSuite) c.newInstance(); - //Add the tests from this suite that match the regex to the list of tests to run - runningList = suite.getAllContainedBaseTests(runningList); - } catch (InstantiationException | IllegalAccessException e) { - //This shouldn't happen unless the constructor is changed in some way. - logger.log(Level.SEVERE, "Test suites can not take paramaters in their constructors.", e); - } - } else if(c.getAnnotation(SuiteClasses.class) != null){ - logger.log(Level.SEVERE, String.format("class '%s' must extend %s to be searchable using regex.", c.getName()), AbstractTestSuite.class.getName()); - } else { //This is a class containing tests - //so add it to the list - runningList.add(c); - } - } - return runningList; - } - - /** - * Gets all of the test classes listed in this suite. Does not include any of the test suites. All of these classes contain tests. - * @return The list of base test classes. - */ - public List> getAllContainedBaseTests(){ - List> runningBaseTests = new Vector >(); - return getAllContainedBaseTests(runningBaseTests); - } - - - /** - * Retrieves all of the classes listed in the @SuiteClasses annotation that match the given regex text. - * @param regex the text pattern to retrieve. - * @param runningList the running list of classes to prevent recursion - * @return The list of classes matching the regex pattern - */ - private List> getAllClassMatching(final String regex, final List> runningList){ - for(Class c : getAnnotatedTestClasses()){ - //Compare the regex against the simple name of the class - if(Pattern.matches(regex, c.getName()) && !runningList.contains(c)){ - runningList.add(c); - } - } - return runningList; - } - /** - * Retrieves all of the classes listed in the @SuiteClasses annotation that match the given regex text. - * @param regex the text pattern to retrieve. - * @return The list of classes matching the regex pattern - */ - public List> getAllClassMatching(final String regex){ - final List> matchingClasses = new Vector>(); - return getAllClassMatching(regex, matchingClasses); - } - - /** - * Searches through all of the suites and tests and loads only the test or test suites matching the regex text. - * This method also prevents a single test from being loaded multiple times by loading the suite first then - * loading tests from all non loaded suites. - * - * @param regex the regex text to search for - * @return the list of suite and/or test classes matching the regex. - */ - private List> getSuiteOrTestMatchingRegex(final String regex, List> runningList){ - //Get any test suites matching the regex using the superclass methods - runningList = getAllClassMatching(regex, runningList); - - - //Then search any test suites not retrieved already for test classes matching the regex. - List> unCollectedSuites = getAllClasses(); - //If we already have a test suite then we don't want to load the test twice so remove the suite from the list - unCollectedSuites.removeAll(runningList); - for(Class c: unCollectedSuites){ - //Prevents recursively adding tests/suites that have already been added - if(!runningList.contains(c)){ - try { - AbstractTestSuite suite = null; - //Check the class to make sure that it is not a test class - if(areAnySuperClassesOfTypeAbstractTestSuite(c)){ - //Create a new instance of this class so that we can retrieve its data. - Object o = c.newInstance(); - suite = (AbstractTestSuite) c.newInstance(); - //Add the tests from this suite that match the regex to the list of tests to run - runningList = suite.getSuiteOrTestMatchingRegex(regex, runningList); - } - - } catch (InstantiationException | IllegalAccessException e) { - //This shouldn't happen unless the constructor is changed in some way. - logger.log(Level.SEVERE, "Test suites can not take paramaters in their constructors.", e); - } - } - } - return runningList; - } - - /** - * Searches through all of the suites and tests and loads only the test or test suites matching the regex text. - * This method also prevents a single test from being loaded multiple times by loading the suite first then - * loading tests from all non loaded suites. - * - * @param regex the regex text to search for - * @return the list of suite and/or test classes matching the regex. - */ - protected List> getSuiteOrTestMatchingRegex(final String regex){ - final List> matchingClasses = new Vector>(); - return getSuiteOrTestMatchingRegex(regex, matchingClasses); - } - - - - /** - * Retrieves all of the classes listed in the @SuiteClasses annotation. - * @return - * @throws InitializationError If the @SuiteClasses annotation is missing. - */ - public List> getAllClasses(){ - return getAnnotatedTestClasses(); - } - - /** - * Gets the name of all of the classes listed within the @SuiteClasses annotation. - * @return the list of classes. - * @throws InitializationError If the @SuiteClasses annotation is missing. - */ - public List getAllClassName(){ - List classNames = new Vector(); - for(Class c : getAnnotatedTestClasses()){ - classNames.add(c.getName()); - } - return classNames; - } -} + private static final Logger logger = Logger.getLogger(AbstractTestSuite.class.getName()); + /** + * Gets all of the classes listed within the SuiteClasses annotation. To use + * it, annotate a class with @RunWith(Suite.class) and + * @SuiteClasses({TestClass1.class, ...}). When you run this + * class, it will run all the tests in all the suite classes. When loading the + * tests using regex the test list will be generated from this annotation. + *$ + * @return the list of classes listed in the + * @SuiteClasses({TestClass1.class, ...}) annotation. + */ + protected List> getAnnotatedTestClasses() { + SuiteClasses annotation = getClass().getAnnotation(SuiteClasses.class); + List> classes = new Vector>(); + if (annotation == null) { + throw new RuntimeException(String.format("class '%s' must have a SuiteClasses annotation", + getClass().getName())); + } + for (Class c : annotation.value()) { + classes.add(c); + } + return classes; + } + + /** + *$ + * @param check + * @return + */ + private boolean areAnySuperClassesOfTypeAbstractTestSuite(Class check) { + while (check != null) { + if (check.equals(AbstractTestSuite.class)) { + return true; + } + check = check.getSuperclass(); + } + return false; + } + + /** + * Stores a method name and method class pair. Used when searching for methods + * matching a given regex text. + *$ + * @author jonathanleitschuh + * + */ + protected class ClassMethodPair { + public final Class methodClass; + public final String methodName; + + public ClassMethodPair(Class klass, Method m) { + this.methodClass = klass; + this.methodName = m.getName(); + } + + public Request getMethodRunRequest() { + return Request.method(methodClass, methodName); + } + } + + /** + * @param regex + * @return + */ + protected List getMethodMatching(final String regex) { + List classMethodPairs = new Vector(); + // Get all of the test classes + for (Class c : getAllContainedBaseTests()) { + for (Method m : c.getMethods()) { + // If this is a test method that is not trying to be ignored and it + // matches the regex + if (m.getAnnotation(Test.class) != null && m.getAnnotation(Ignore.class) == null + && Pattern.matches(regex, m.getName())) { + ClassMethodPair pair = new ClassMethodPair(c, m); + classMethodPairs.add(pair); + } + } + } + return classMethodPairs; + } + + + /** + * Gets all of the test classes listed in this suite. Does not include any of + * the test suites. All of these classes contain tests. + *$ + * @param runningList the running list of classes to prevent recursion. + * @return The list of base test classes. + */ + private List> getAllContainedBaseTests(List> runningList) { + for (Class c : getAnnotatedTestClasses()) { + // Check to see if this is a test class or a suite + if (areAnySuperClassesOfTypeAbstractTestSuite(c)) { + // Create a new instance of this class so that we can retrieve its data + try { + AbstractTestSuite suite = null; + Object o = c.newInstance(); + suite = (AbstractTestSuite) c.newInstance(); + // Add the tests from this suite that match the regex to the list of + // tests to run + runningList = suite.getAllContainedBaseTests(runningList); + } catch (InstantiationException | IllegalAccessException e) { + // This shouldn't happen unless the constructor is changed in some + // way. + logger.log(Level.SEVERE, "Test suites can not take paramaters in their constructors.", e); + } + } else if (c.getAnnotation(SuiteClasses.class) != null) { + logger.log(Level.SEVERE, + String.format("class '%s' must extend %s to be searchable using regex.", c.getName()), + AbstractTestSuite.class.getName()); + } else { // This is a class containing tests + // so add it to the list + runningList.add(c); + } + } + return runningList; + } + + /** + * Gets all of the test classes listed in this suite. Does not include any of + * the test suites. All of these classes contain tests. + *$ + * @return The list of base test classes. + */ + public List> getAllContainedBaseTests() { + List> runningBaseTests = new Vector>(); + return getAllContainedBaseTests(runningBaseTests); + } + + + /** + * Retrieves all of the classes listed in the + * @SuiteClasses annotation that match the given regex text. + *$ + * @param regex the text pattern to retrieve. + * @param runningList the running list of classes to prevent recursion + * @return The list of classes matching the regex pattern + */ + private List> getAllClassMatching(final String regex, final List> runningList) { + for (Class c : getAnnotatedTestClasses()) { + // Compare the regex against the simple name of the class + if (Pattern.matches(regex, c.getName()) && !runningList.contains(c)) { + runningList.add(c); + } + } + return runningList; + } + + /** + * Retrieves all of the classes listed in the + * @SuiteClasses annotation that match the given regex text. + *$ + * @param regex the text pattern to retrieve. + * @return The list of classes matching the regex pattern + */ + public List> getAllClassMatching(final String regex) { + final List> matchingClasses = new Vector>(); + return getAllClassMatching(regex, matchingClasses); + } + + /** + * Searches through all of the suites and tests and loads only the test or + * test suites matching the regex text. This method also prevents a single + * test from being loaded multiple times by loading the suite first then + * loading tests from all non loaded suites. + *$ + * @param regex the regex text to search for + * @return the list of suite and/or test classes matching the regex. + */ + private List> getSuiteOrTestMatchingRegex(final String regex, List> runningList) { + // Get any test suites matching the regex using the superclass methods + runningList = getAllClassMatching(regex, runningList); + + + // Then search any test suites not retrieved already for test classes + // matching the regex. + List> unCollectedSuites = getAllClasses(); + // If we already have a test suite then we don't want to load the test twice + // so remove the suite from the list + unCollectedSuites.removeAll(runningList); + for (Class c : unCollectedSuites) { + // Prevents recursively adding tests/suites that have already been added + if (!runningList.contains(c)) { + try { + AbstractTestSuite suite = null; + // Check the class to make sure that it is not a test class + if (areAnySuperClassesOfTypeAbstractTestSuite(c)) { + // Create a new instance of this class so that we can retrieve its + // data. + Object o = c.newInstance(); + suite = (AbstractTestSuite) c.newInstance(); + // Add the tests from this suite that match the regex to the list of + // tests to run + runningList = suite.getSuiteOrTestMatchingRegex(regex, runningList); + } + + } catch (InstantiationException | IllegalAccessException e) { + // This shouldn't happen unless the constructor is changed in some + // way. + logger.log(Level.SEVERE, "Test suites can not take paramaters in their constructors.", e); + } + } + } + return runningList; + } + + /** + * Searches through all of the suites and tests and loads only the test or + * test suites matching the regex text. This method also prevents a single + * test from being loaded multiple times by loading the suite first then + * loading tests from all non loaded suites. + *$ + * @param regex the regex text to search for + * @return the list of suite and/or test classes matching the regex. + */ + protected List> getSuiteOrTestMatchingRegex(final String regex) { + final List> matchingClasses = new Vector>(); + return getSuiteOrTestMatchingRegex(regex, matchingClasses); + } + + + + /** + * Retrieves all of the classes listed in the + * @SuiteClasses annotation. + *$ + * @return + * @throws InitializationError If the @SuiteClasses annotation is + * missing. + */ + public List> getAllClasses() { + return getAnnotatedTestClasses(); + } + + /** + * Gets the name of all of the classes listed within the + * @SuiteClasses annotation. + *$ + * @return the list of classes. + * @throws InitializationError If the @SuiteClasses annotation is + * missing. + */ + public List getAllClassName() { + List classNames = new Vector(); + for (Class c : getAnnotatedTestClasses()) { + classNames.add(c.getName()); + } + return classNames; + } +} diff --git a/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/test/AntJunitLanucher.java b/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/test/AntJunitLanucher.java index 9e129bbe87..ec06198ef1 100644 --- a/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/test/AntJunitLanucher.java +++ b/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/test/AntJunitLanucher.java @@ -1,8 +1,8 @@ /*----------------------------------------------------------------------------*/ -/* Copyright (c) FIRST 2008-2014. All Rights Reserved. */ -/* Open Source Software - may be modified and shared by FRC teams. The code */ +/* Copyright (c) FIRST 2008-2014. All Rights Reserved. */ +/* Open Source Software - may be modified and shared by FRC teams. The code */ /* must be accompanied by the FIRST BSD license file in the root directory of */ -/* the project. */ +/* the project. */ /*----------------------------------------------------------------------------*/ package edu.wpi.first.wpilibj.test; @@ -18,72 +18,71 @@ import org.apache.tools.ant.taskdefs.optional.junit.JUnitTest; /** * Provides an entry point for tests to run with ANT. This allows ant to output * JUnit XML test results for Jenkins. - * + *$ * @author jonathanleitschuh * */ public class AntJunitLanucher { - public static void main(String... args) { - if (args.length == 0) { - String path = String.format("%s/%s", - System.getProperty("user.dir"), "/testResults/AntReports"); - String pathToReports = path; - Project project = new Project(); + public static void main(String... args) { + if (args.length == 0) { + String path = + String.format("%s/%s", System.getProperty("user.dir"), "/testResults/AntReports"); + String pathToReports = path; + Project project = new Project(); - try { - // Create the file to store the test output - new File(pathToReports).mkdirs(); - JUnitTask task = new JUnitTask(); + try { + // Create the file to store the test output + new File(pathToReports).mkdirs(); + JUnitTask task = new JUnitTask(); - project.setProperty("java.io.tmpdir", pathToReports); + project.setProperty("java.io.tmpdir", pathToReports); - /* Output to screen */ - FormatterElement.TypeAttribute typeScreen = new FormatterElement.TypeAttribute(); - typeScreen.setValue("plain"); - FormatterElement formatToScreen = new FormatterElement(); - formatToScreen.setType(typeScreen); - formatToScreen.setUseFile(false); - formatToScreen.setOutput(System.out); - task.addFormatter(formatToScreen); + /* Output to screen */ + FormatterElement.TypeAttribute typeScreen = new FormatterElement.TypeAttribute(); + typeScreen.setValue("plain"); + FormatterElement formatToScreen = new FormatterElement(); + formatToScreen.setType(typeScreen); + formatToScreen.setUseFile(false); + formatToScreen.setOutput(System.out); + task.addFormatter(formatToScreen); - // add a build listener to the project - BuildLogger logger = new DefaultLogger(); - logger.setOutputPrintStream(System.out); - logger.setErrorPrintStream(System.err); - logger.setMessageOutputLevel(Project.MSG_INFO); - logger.setEmacsMode(true); - project.addBuildListener(logger); + // add a build listener to the project + BuildLogger logger = new DefaultLogger(); + logger.setOutputPrintStream(System.out); + logger.setErrorPrintStream(System.err); + logger.setMessageOutputLevel(Project.MSG_INFO); + logger.setEmacsMode(true); + project.addBuildListener(logger); - task.setProject(project); + task.setProject(project); - // Set the output to the XML file - FormatterElement.TypeAttribute type = new FormatterElement.TypeAttribute(); - type.setValue("xml"); + // Set the output to the XML file + FormatterElement.TypeAttribute type = new FormatterElement.TypeAttribute(); + type.setValue("xml"); - FormatterElement formater = new FormatterElement(); - formater.setType(type); - task.addFormatter(formater); + FormatterElement formater = new FormatterElement(); + formater.setType(type); + task.addFormatter(formater); - // Create the JUnitTest - JUnitTest test = new JUnitTest(TestSuite.class.getName()); - test.setTodir(new File(pathToReports)); - task.addTest(test); + // Create the JUnitTest + JUnitTest test = new JUnitTest(TestSuite.class.getName()); + test.setTodir(new File(pathToReports)); + task.addTest(test); - TestBench.out().println("Beginning Test Execution With ANT"); - task.execute(); - } catch (Exception e) { - e.printStackTrace(); - } - } else { - TestBench.out().println( - "Run will not output XML for Jenkins because " - + "tests are not being run with ANT"); - // This should never return as it makes its own call to - // System.exit(); - TestSuite.main(args); - } - System.exit(0); - } + TestBench.out().println("Beginning Test Execution With ANT"); + task.execute(); + } catch (Exception e) { + e.printStackTrace(); + } + } else { + TestBench.out().println( + "Run will not output XML for Jenkins because " + "tests are not being run with ANT"); + // This should never return as it makes its own call to + // System.exit(); + TestSuite.main(args); + } + System.exit(0); + } } diff --git a/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/test/QuickTest.java b/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/test/QuickTest.java index 47ed8ba446..db90340f4f 100644 --- a/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/test/QuickTest.java +++ b/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/test/QuickTest.java @@ -1,8 +1,8 @@ /*----------------------------------------------------------------------------*/ -/* Copyright (c) FIRST 2008-2014. All Rights Reserved. */ -/* Open Source Software - may be modified and shared by FRC teams. The code */ +/* Copyright (c) FIRST 2008-2014. All Rights Reserved. */ +/* Open Source Software - may be modified and shared by FRC teams. The code */ /* must be accompanied by the FIRST BSD license file in the root directory of */ -/* the project. */ +/* the project. */ /*----------------------------------------------------------------------------*/ package edu.wpi.first.wpilibj.test; @@ -11,27 +11,32 @@ import java.util.logging.Logger; import org.junit.Test; /** - * This class is designated to allow for simple testing of the library without the overlying testing framework. - * This test is NOT run as a normal part of the testing process and must be explicitly - * selected at runtime by using the 'quick' argument. - * - * This test should never be committed with changes to it but can be used during development to aid in feature testing. - * + * This class is designated to allow for simple testing of the library without + * the overlying testing framework. This test is NOT run as a normal part of the + * testing process and must be explicitly selected at runtime by using the + * 'quick' argument. + *$ + * This test should never be committed with changes to it but can be used during + * development to aid in feature testing. + *$ * @author Jonathan Leitschuh */ public class QuickTest extends AbstractComsSetup { - private static final Logger logger = Logger.getLogger(QuickTest.class.getName()); - /* (non-Javadoc) - * @see edu.wpi.first.wpilibj.test.AbstractComsSetup#getClassLogger() - */ - @Override - protected Logger getClassLogger() { - return logger; - } + private static final Logger logger = Logger.getLogger(QuickTest.class.getName()); + + /* + * (non-Javadoc) + *$ + * @see edu.wpi.first.wpilibj.test.AbstractComsSetup#getClassLogger() + */ + @Override + protected Logger getClassLogger() { + return logger; + } - @Test - public void test() { - - } + @Test + public void test() { + + } } diff --git a/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/test/RepeatRule.java b/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/test/RepeatRule.java index 22295f0f6a..c8753090ad 100644 --- a/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/test/RepeatRule.java +++ b/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/test/RepeatRule.java @@ -1,8 +1,8 @@ /*----------------------------------------------------------------------------*/ -/* Copyright (c) FIRST 2008-2014. All Rights Reserved. */ -/* Open Source Software - may be modified and shared by FRC teams. The code */ +/* Copyright (c) FIRST 2008-2014. All Rights Reserved. */ +/* Open Source Software - may be modified and shared by FRC teams. The code */ /* must be accompanied by the FIRST BSD license file in the root directory of */ -/* the project. */ +/* the project. */ /*----------------------------------------------------------------------------*/ package edu.wpi.first.wpilibj.test; @@ -15,47 +15,50 @@ import org.junit.runner.Description; import org.junit.runners.model.Statement; /** - * This JUnit Rule allows you to apply this rule to any test to allow it to run multiple times. - * This is important if you have a test that fails only "sometimes" and needs to be rerun to find the issue. - * - * This code was originally found here: - * Running JUnit Tests Repeatedly Without Loops + * This JUnit Rule allows you to apply this rule to any test to allow it to run + * multiple times. This is important if you have a test that fails only + * "sometimes" and needs to be rerun to find the issue. + *$ + * This code was originally found here: Running JUnit Tests Repeatedly Without Loops + *$ * @author Frank Appel */ public class RepeatRule implements TestRule { - @Retention( RetentionPolicy.RUNTIME ) - @Target({java.lang.annotation.ElementType.METHOD} ) - public @interface Repeat { - public abstract int times(); - } + @Retention(RetentionPolicy.RUNTIME) + @Target({java.lang.annotation.ElementType.METHOD}) + public @interface Repeat { + public abstract int times(); + } + + + private static class RepeatStatement extends Statement { - - private static class RepeatStatement extends Statement { - private final int times; private final Statement statement; - - private RepeatStatement( int times, Statement statement ) { + + private RepeatStatement(int times, Statement statement) { this.times = times; this.statement = statement; } - + @Override public void evaluate() throws Throwable { - for( int i = 0; i < times; i++ ) { + for (int i = 0; i < times; i++) { statement.evaluate(); } } } - + @Override - public Statement apply( Statement statement, Description description ) { + public Statement apply(Statement statement, Description description) { Statement result = statement; - Repeat repeat = description.getAnnotation( Repeat.class ); - if( repeat != null ) { + Repeat repeat = description.getAnnotation(Repeat.class); + if (repeat != null) { int times = repeat.times(); - result = new RepeatStatement( times, statement ); + result = new RepeatStatement(times, statement); } return result; } -} \ No newline at end of file +} diff --git a/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/test/TestBench.java b/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/test/TestBench.java index 7f7ee08951..9c8765f68c 100644 --- a/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/test/TestBench.java +++ b/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/test/TestBench.java @@ -1,8 +1,8 @@ /*----------------------------------------------------------------------------*/ -/* Copyright (c) FIRST 2008-2014. All Rights Reserved. */ -/* Open Source Software - may be modified and shared by FRC teams. The code */ +/* Copyright (c) FIRST 2008-2014. All Rights Reserved. */ +/* Open Source Software - may be modified and shared by FRC teams. The code */ /* must be accompanied by the FIRST BSD license file in the root directory of */ -/* the project. */ +/* the project. */ /*----------------------------------------------------------------------------*/ package edu.wpi.first.wpilibj.test; @@ -42,374 +42,399 @@ import edu.wpi.first.wpilibj.mockhardware.FakePotentiometerSource; */ public final class TestBench { - /** - * The time that it takes to have a motor go from rotating at full speed to - * completely stopped - */ - public static final double MOTOR_STOP_TIME = 0.25; + /** + * The time that it takes to have a motor go from rotating at full speed to + * completely stopped + */ + public static final double MOTOR_STOP_TIME = 0.25; - public static final int kTalonChannel = 10; - public static final int kVictorChannel = 1; - public static final int kJaguarChannel = 2; + public static final int kTalonChannel = 10; + public static final int kVictorChannel = 1; + public static final int kJaguarChannel = 2; - /*TiltPanCamera Channels */ - public static final int kGyroChannel = 0; - public static final double kGyroSensitivity = 0.013; - public static final int kTiltServoChannel = 9; - public static final int kPanServoChannel = 8; + /* TiltPanCamera Channels */ + public static final int kGyroChannel = 0; + public static final double kGyroSensitivity = 0.013; + public static final int kTiltServoChannel = 9; + public static final int kPanServoChannel = 8; - /* PowerDistributionPanel channels */ - public static final int kJaguarPDPChannel = 6; - public static final int kVictorPDPChannel = 8; - public static final int kTalonPDPChannel = 11; - public static final int kCANJaguarPDPChannel = 5; + /* PowerDistributionPanel channels */ + public static final int kJaguarPDPChannel = 6; + public static final int kVictorPDPChannel = 8; + public static final int kTalonPDPChannel = 11; + public static final int kCANJaguarPDPChannel = 5; - /* CAN ASSOICATED CHANNELS */ - public static final int kCANRelayPowerCycler = 1; - public static final int kFakeJaguarPotentiometer = 1; - public static final int kFakeJaguarForwardLimit = 20; - public static final int kFakeJaguarReverseLimit = 21; - public static final int kCANJaguarID = 2; + /* CAN ASSOICATED CHANNELS */ + public static final int kCANRelayPowerCycler = 1; + public static final int kFakeJaguarPotentiometer = 1; + public static final int kFakeJaguarForwardLimit = 20; + public static final int kFakeJaguarReverseLimit = 21; + public static final int kCANJaguarID = 2; - //THESE MUST BE IN INCREMENTING ORDER - public static final int DIOCrossConnectB2 = 9; - public static final int DIOCrossConnectB1 = 8; - public static final int DIOCrossConnectA2 = 7; - public static final int DIOCrossConnectA1 = 6; + // THESE MUST BE IN INCREMENTING ORDER + public static final int DIOCrossConnectB2 = 9; + public static final int DIOCrossConnectB1 = 8; + public static final int DIOCrossConnectA2 = 7; + public static final int DIOCrossConnectA1 = 6; - /** The Singleton instance of the Test Bench */ - private static TestBench instance = null; + /** The Singleton instance of the Test Bench */ + private static TestBench instance = null; - /** - * The single constructor for the TestBench. This method is private in order - * to prevent multiple TestBench objects from being allocated - */ - protected TestBench() { - } + /** + * The single constructor for the TestBench. This method is private in order + * to prevent multiple TestBench objects from being allocated + */ + protected TestBench() {} - /** - * Constructs a new set of objects representing a connected set of Talon - * controlled Motors and an encoder - * - * @return a freshly allocated Talon, Encoder pair - */ - public MotorEncoderFixture getTalonPair() { + /** + * Constructs a new set of objects representing a connected set of Talon + * controlled Motors and an encoder + * + * @return a freshly allocated Talon, Encoder pair + */ + public MotorEncoderFixture getTalonPair() { - MotorEncoderFixture talonPair = new MotorEncoderFixture(){ - @Override - protected Talon giveSpeedController() { - return new Talon(kTalonChannel); - } - @Override - protected DigitalInput giveDigitalInputA() { - return new DigitalInput(0); - } - @Override - protected DigitalInput giveDigitalInputB() { - return new DigitalInput(1); - } - @Override - public int getPDPChannel() { - return kTalonPDPChannel; - } - }; - return talonPair; - } + MotorEncoderFixture talonPair = new MotorEncoderFixture() { + @Override + protected Talon giveSpeedController() { + return new Talon(kTalonChannel); + } - /** - * Constructs a new set of objects representing a connected set of Victor - * controlled Motors and an encoder - * - * @return a freshly allocated Victor, Encoder pair - */ - public MotorEncoderFixture getVictorPair() { + @Override + protected DigitalInput giveDigitalInputA() { + return new DigitalInput(0); + } - MotorEncoderFixture vicPair = new MotorEncoderFixture(){ - @Override - protected Victor giveSpeedController() { - return new Victor(kVictorChannel); - } + @Override + protected DigitalInput giveDigitalInputB() { + return new DigitalInput(1); + } - @Override - protected DigitalInput giveDigitalInputA() { - return new DigitalInput(2); - } + @Override + public int getPDPChannel() { + return kTalonPDPChannel; + } + }; + return talonPair; + } - @Override - protected DigitalInput giveDigitalInputB() { - return new DigitalInput(3); - } - @Override - public int getPDPChannel() { - return kVictorPDPChannel; - } - }; - return vicPair; - } + /** + * Constructs a new set of objects representing a connected set of Victor + * controlled Motors and an encoder + * + * @return a freshly allocated Victor, Encoder pair + */ + public MotorEncoderFixture getVictorPair() { - /** - * Constructs a new set of objects representing a connected set of Jaguar - * controlled Motors and an encoder - * - * @return a freshly allocated Jaguar, Encoder pair - */ - public MotorEncoderFixture getJaguarPair() { - MotorEncoderFixture jagPair = new MotorEncoderFixture(){ - @Override - protected Jaguar giveSpeedController() { - return new Jaguar(kJaguarChannel); - } + MotorEncoderFixture vicPair = new MotorEncoderFixture() { + @Override + protected Victor giveSpeedController() { + return new Victor(kVictorChannel); + } - @Override - protected DigitalInput giveDigitalInputA() { - return new DigitalInput(4); - } + @Override + protected DigitalInput giveDigitalInputA() { + return new DigitalInput(2); + } - @Override - protected DigitalInput giveDigitalInputB() { - return new DigitalInput(5); - } - @Override - public int getPDPChannel() { - return kJaguarPDPChannel; - } - }; - return jagPair; - } + @Override + protected DigitalInput giveDigitalInputB() { + return new DigitalInput(3); + } - public class BaseCANMotorEncoderFixture extends CANMotorEncoderFixture{ - @Override - protected CANJaguar giveSpeedController() { - return new CANJaguar(kCANJaguarID); - } - @Override - protected DigitalInput giveDigitalInputA() { - return new DigitalInput(18); - } - @Override - protected DigitalInput giveDigitalInputB() { - return new DigitalInput(19); - } - @Override - protected FakePotentiometerSource giveFakePotentiometerSource() { - return new FakePotentiometerSource(kFakeJaguarPotentiometer, 360); - } - @Override - protected DigitalOutput giveFakeForwardLimit() { - return new DigitalOutput(kFakeJaguarForwardLimit); - } - @Override - protected DigitalOutput giveFakeReverseLimit() { - return new DigitalOutput(kFakeJaguarReverseLimit); - } - /* (non-Javadoc) - * @see edu.wpi.first.wpilibj.fixtures.CANMotorEncoderFixture#givePoweCycleRelay() - */ - @Override - protected Relay givePoweCycleRelay() { - return new Relay(kCANRelayPowerCycler); - } + @Override + public int getPDPChannel() { + return kVictorPDPChannel; + } + }; + return vicPair; + } - @Override - public int getPDPChannel() { - return kCANJaguarPDPChannel; - } - } + /** + * Constructs a new set of objects representing a connected set of Jaguar + * controlled Motors and an encoder + * + * @return a freshly allocated Jaguar, Encoder pair + */ + public MotorEncoderFixture getJaguarPair() { + MotorEncoderFixture jagPair = new MotorEncoderFixture() { + @Override + protected Jaguar giveSpeedController() { + return new Jaguar(kJaguarChannel); + } - /** - * Constructs a new set of objects representing a connected set of CANJaguar - * controlled Motors and an encoder
- * Note: The CANJaguar is not freshly allocated because the CANJaguar lacks - * a free() method - * - * @return an existing CANJaguar and a freshly allocated Encoder - */ - public CANMotorEncoderFixture getCanJaguarPair() { - CANMotorEncoderFixture canPair = new BaseCANMotorEncoderFixture(); - return canPair; - } + @Override + protected DigitalInput giveDigitalInputA() { + return new DigitalInput(4); + } - /** - * Constructs a new set of two Servo's and a Gyroscope. - * - * @return a freshly allocated Servo's and a freshly allocated Gyroscope - */ - public TiltPanCameraFixture getTiltPanCam() { - TiltPanCameraFixture tpcam = new TiltPanCameraFixture(){ - @Override - protected Gyro giveGyro() { - Gyro gyro = new Gyro(kGyroChannel); - gyro.setSensitivity(kGyroSensitivity); - return gyro; - } + @Override + protected DigitalInput giveDigitalInputB() { + return new DigitalInput(5); + } - @Override - protected Servo giveTilt() { - return new Servo(kTiltServoChannel); - } + @Override + public int getPDPChannel() { + return kJaguarPDPChannel; + } + }; + return jagPair; + } - @Override - protected Servo givePan() { - return new Servo(kPanServoChannel); - } - }; + public class BaseCANMotorEncoderFixture extends CANMotorEncoderFixture { + @Override + protected CANJaguar giveSpeedController() { + return new CANJaguar(kCANJaguarID); + } - return tpcam; - } + @Override + protected DigitalInput giveDigitalInputA() { + return new DigitalInput(18); + } - public DIOCrossConnectFixture getDIOCrossConnectFixture(int inputPort, - int outputPort) { - DIOCrossConnectFixture dio = new DIOCrossConnectFixture(inputPort, outputPort); - return dio; - } + @Override + protected DigitalInput giveDigitalInputB() { + return new DigitalInput(19); + } - /** - * Gets two lists of possible DIO pairs for the two pairs - * @return - */ - private List> getDIOCrossConnect(){ - List> pairs = new ArrayList>(); - List setA = Arrays.asList(new Integer[][] { - { new Integer(DIOCrossConnectA1), new Integer(DIOCrossConnectA2) }, - { new Integer(DIOCrossConnectA2), new Integer(DIOCrossConnectA1) } - }); - pairs.add(setA); + @Override + protected FakePotentiometerSource giveFakePotentiometerSource() { + return new FakePotentiometerSource(kFakeJaguarPotentiometer, 360); + } - List setB = Arrays.asList(new Integer[][] { - { new Integer(DIOCrossConnectB1), new Integer(DIOCrossConnectB2) }, - { new Integer(DIOCrossConnectB2), new Integer(DIOCrossConnectB1) } - }); - pairs.add(setB); - //NOTE: IF MORE DIOCROSSCONNECT PAIRS ARE ADDED ADD THEM HERE - return pairs; - } + @Override + protected DigitalOutput giveFakeForwardLimit() { + return new DigitalOutput(kFakeJaguarForwardLimit); + } - public static AnalogCrossConnectFixture getAnalogCrossConnectFixture(){ - AnalogCrossConnectFixture analogIO = new AnalogCrossConnectFixture() { - @Override - protected AnalogOutput giveAnalogOutput() { - return new AnalogOutput(0); - } + @Override + protected DigitalOutput giveFakeReverseLimit() { + return new DigitalOutput(kFakeJaguarReverseLimit); + } - @Override - protected AnalogInput giveAnalogInput() { - return new AnalogInput(2); - } - }; - return analogIO; - } + /* + * (non-Javadoc) + *$ + * @see + * edu.wpi.first.wpilibj.fixtures.CANMotorEncoderFixture#givePoweCycleRelay + * () + */ + @Override + protected Relay givePoweCycleRelay() { + return new Relay(kCANRelayPowerCycler); + } - public static RelayCrossConnectFxiture getRelayCrossConnectFixture(){ - RelayCrossConnectFxiture relay = new RelayCrossConnectFxiture() { + @Override + public int getPDPChannel() { + return kCANJaguarPDPChannel; + } + } - @Override - protected Relay giveRelay() { - return new Relay(0); - } + /** + * Constructs a new set of objects representing a connected set of CANJaguar + * controlled Motors and an encoder
+ * Note: The CANJaguar is not freshly allocated because the CANJaguar lacks a + * free() method + * + * @return an existing CANJaguar and a freshly allocated Encoder + */ + public CANMotorEncoderFixture getCanJaguarPair() { + CANMotorEncoderFixture canPair = new BaseCANMotorEncoderFixture(); + return canPair; + } - @Override - protected DigitalInput giveInputTwo() { - return new DigitalInput(18); - } + /** + * Constructs a new set of two Servo's and a Gyroscope. + * + * @return a freshly allocated Servo's and a freshly allocated Gyroscope + */ + public TiltPanCameraFixture getTiltPanCam() { + TiltPanCameraFixture tpcam = new TiltPanCameraFixture() { + @Override + protected Gyro giveGyro() { + Gyro gyro = new Gyro(kGyroChannel); + gyro.setSensitivity(kGyroSensitivity); + return gyro; + } - @Override - protected DigitalInput giveInputOne() { - return new DigitalInput(19); - } - }; - return relay; - } + @Override + protected Servo giveTilt() { + return new Servo(kTiltServoChannel); + } - /** - * Return a single Collection containing all of the DIOCrossConnectFixtures in all two pair combinations - * @return - */ - public Collection getDIOCrossConnectCollection() { - Collection pairs = new ArrayList(); - for(Collection collection : getDIOCrossConnect()){ - pairs.addAll(collection); - } - return pairs; - } + @Override + protected Servo givePan() { + return new Servo(kPanServoChannel); + } + }; - /** - * Gets an array of pairs for the encoder to use using two different lists - * @param listA - * @param listB - * @param flip whether this encoder needs to be flipped - * @return A list of different inputs to use for the tests - */ - private Collection getPairArray(List listA, List listB, boolean flip){ - Collection encoderPortPairs = new ArrayList(); - for (Integer[] portPairsA : listA) { - ArrayList construtorInput = new ArrayList(); - Integer inputs[] = new Integer[5]; - inputs[0] = portPairsA[0]; // InputA - inputs[1] = portPairsA[1]; // InputB + return tpcam; + } - for (Integer[] portPairsB : listB) { - inputs[2] = portPairsB[0]; // OutputA - inputs[3] = portPairsB[1]; // OutputB - inputs [4] = flip? 0 : 1; // The flip bit - } + public DIOCrossConnectFixture getDIOCrossConnectFixture(int inputPort, int outputPort) { + DIOCrossConnectFixture dio = new DIOCrossConnectFixture(inputPort, outputPort); + return dio; + } - construtorInput.add(inputs); + /** + * Gets two lists of possible DIO pairs for the two pairs + *$ + * @return + */ + private List> getDIOCrossConnect() { + List> pairs = new ArrayList>(); + List setA = + Arrays.asList(new Integer[][] { + {new Integer(DIOCrossConnectA1), new Integer(DIOCrossConnectA2)}, + {new Integer(DIOCrossConnectA2), new Integer(DIOCrossConnectA1)}}); + pairs.add(setA); - inputs = inputs.clone(); - for (Integer[] portPairsB : listB) { - inputs[2] = portPairsB[1]; // OutputA - inputs[3] = portPairsB[0]; // OutputB - inputs [4] = flip? 0 : 1; //The flip bit - } - construtorInput.add(inputs); - encoderPortPairs.addAll(construtorInput); - } - return encoderPortPairs; - } + List setB = + Arrays.asList(new Integer[][] { + {new Integer(DIOCrossConnectB1), new Integer(DIOCrossConnectB2)}, + {new Integer(DIOCrossConnectB2), new Integer(DIOCrossConnectB1)}}); + pairs.add(setB); + // NOTE: IF MORE DIOCROSSCONNECT PAIRS ARE ADDED ADD THEM HERE + return pairs; + } - /** - * Constructs the list of inputs to be used for the encoder test - * @return A collection of different input pairs to use for the encoder - */ - public Collection getEncoderDIOCrossConnectCollection() { - Collection encoderPortPairs = new ArrayList(); - assert getDIOCrossConnect().size() == 2; - encoderPortPairs.addAll(getPairArray(getDIOCrossConnect().get(0), getDIOCrossConnect().get(1), false)); - encoderPortPairs.addAll(getPairArray(getDIOCrossConnect().get(1), getDIOCrossConnect().get(0), false)); - assert (encoderPortPairs.size() == 8); - return encoderPortPairs; - } + public static AnalogCrossConnectFixture getAnalogCrossConnectFixture() { + AnalogCrossConnectFixture analogIO = new AnalogCrossConnectFixture() { + @Override + protected AnalogOutput giveAnalogOutput() { + return new AnalogOutput(0); + } - /** - * Gets the singleton of the TestBench. If the TestBench is not already - * allocated in constructs an new instance of it. Otherwise it returns the - * existing instance. - * - * @return The Singleton instance of the TestBench - */ - public static TestBench getInstance() { - if (instance == null) { - instance = new TestBench(); - } - return instance; - } + @Override + protected AnalogInput giveAnalogInput() { + return new AnalogInput(2); + } + }; + return analogIO; + } - /** - * Provides access to the output stream for the test system. This should be used instead of System.out - * This is gives us a way to implement changes to where the output text of this test system is sent. - * @return The test bench global print stream. - */ - public static PrintStream out(){ - return System.out; - } + public static RelayCrossConnectFxiture getRelayCrossConnectFixture() { + RelayCrossConnectFxiture relay = new RelayCrossConnectFxiture() { - /** - * Provides access to the error stream for the test system. This should be used instead of System.err - * This is gives us a way to implement changes to where the output text of this test system is sent. - * @return The test bench global print stream. - */ - public static PrintStream err(){ - return System.err; - } + @Override + protected Relay giveRelay() { + return new Relay(0); + } + + @Override + protected DigitalInput giveInputTwo() { + return new DigitalInput(18); + } + + @Override + protected DigitalInput giveInputOne() { + return new DigitalInput(19); + } + }; + return relay; + } + + /** + * Return a single Collection containing all of the DIOCrossConnectFixtures in + * all two pair combinations + *$ + * @return + */ + public Collection getDIOCrossConnectCollection() { + Collection pairs = new ArrayList(); + for (Collection collection : getDIOCrossConnect()) { + pairs.addAll(collection); + } + return pairs; + } + + /** + * Gets an array of pairs for the encoder to use using two different lists + *$ + * @param listA + * @param listB + * @param flip whether this encoder needs to be flipped + * @return A list of different inputs to use for the tests + */ + private Collection getPairArray(List listA, List listB, + boolean flip) { + Collection encoderPortPairs = new ArrayList(); + for (Integer[] portPairsA : listA) { + ArrayList construtorInput = new ArrayList(); + Integer inputs[] = new Integer[5]; + inputs[0] = portPairsA[0]; // InputA + inputs[1] = portPairsA[1]; // InputB + + for (Integer[] portPairsB : listB) { + inputs[2] = portPairsB[0]; // OutputA + inputs[3] = portPairsB[1]; // OutputB + inputs[4] = flip ? 0 : 1; // The flip bit + } + + construtorInput.add(inputs); + + inputs = inputs.clone(); + for (Integer[] portPairsB : listB) { + inputs[2] = portPairsB[1]; // OutputA + inputs[3] = portPairsB[0]; // OutputB + inputs[4] = flip ? 0 : 1; // The flip bit + } + construtorInput.add(inputs); + encoderPortPairs.addAll(construtorInput); + } + return encoderPortPairs; + } + + /** + * Constructs the list of inputs to be used for the encoder test + *$ + * @return A collection of different input pairs to use for the encoder + */ + public Collection getEncoderDIOCrossConnectCollection() { + Collection encoderPortPairs = new ArrayList(); + assert getDIOCrossConnect().size() == 2; + encoderPortPairs.addAll(getPairArray(getDIOCrossConnect().get(0), getDIOCrossConnect().get(1), + false)); + encoderPortPairs.addAll(getPairArray(getDIOCrossConnect().get(1), getDIOCrossConnect().get(0), + false)); + assert (encoderPortPairs.size() == 8); + return encoderPortPairs; + } + + /** + * Gets the singleton of the TestBench. If the TestBench is not already + * allocated in constructs an new instance of it. Otherwise it returns the + * existing instance. + * + * @return The Singleton instance of the TestBench + */ + public static TestBench getInstance() { + if (instance == null) { + instance = new TestBench(); + } + return instance; + } + + /** + * Provides access to the output stream for the test system. This should be + * used instead of System.out This is gives us a way to implement changes to + * where the output text of this test system is sent. + *$ + * @return The test bench global print stream. + */ + public static PrintStream out() { + return System.out; + } + + /** + * Provides access to the error stream for the test system. This should be + * used instead of System.err This is gives us a way to implement changes to + * where the output text of this test system is sent. + *$ + * @return The test bench global print stream. + */ + public static PrintStream err() { + return System.err; + } } diff --git a/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/test/TestSuite.java b/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/test/TestSuite.java index fbce7c8b1c..27027a20cb 100644 --- a/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/test/TestSuite.java +++ b/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/test/TestSuite.java @@ -1,8 +1,8 @@ /*----------------------------------------------------------------------------*/ -/* Copyright (c) FIRST 2008-2014. All Rights Reserved. */ -/* Open Source Software - may be modified and shared by FRC teams. The code */ +/* Copyright (c) FIRST 2008-2014. All Rights Reserved. */ +/* Open Source Software - may be modified and shared by FRC teams. The code */ /* must be accompanied by the FIRST BSD license file in the root directory of */ -/* the project. */ +/* the project. */ /*----------------------------------------------------------------------------*/ package edu.wpi.first.wpilibj.test; @@ -38,324 +38,345 @@ import edu.wpi.first.wpilibj.smartdashboard.SmartDashboardTestSuite; * suite classes annotation. */ @RunWith(Suite.class) -//These are listed on separate lines to prevent merge conflicts -@SuiteClasses({ - WpiLibJTestSuite.class, - CANTestSuite.class, - CommandTestSuite.class, - SmartDashboardTestSuite.class -}) +// These are listed on separate lines to prevent merge conflicts +@SuiteClasses({WpiLibJTestSuite.class, CANTestSuite.class, CommandTestSuite.class, + SmartDashboardTestSuite.class}) public class TestSuite extends AbstractTestSuite { - static{ - //Sets up the logging output - final InputStream inputStream = TestSuite.class.getResourceAsStream("/logging.properties"); - try - { - if(inputStream == null ) throw new NullPointerException("./logging.properties was not loaded"); - LogManager.getLogManager().readConfiguration(inputStream); - Logger.getAnonymousLogger().info("Loaded"); - } - catch (final IOException | NullPointerException e) - { - Logger.getAnonymousLogger().severe("Could not load default logging.properties file"); - Logger.getAnonymousLogger().severe(e.getMessage()); - } + static { + // Sets up the logging output + final InputStream inputStream = TestSuite.class.getResourceAsStream("/logging.properties"); + try { + if (inputStream == null) + throw new NullPointerException("./logging.properties was not loaded"); + LogManager.getLogManager().readConfiguration(inputStream); + Logger.getAnonymousLogger().info("Loaded"); + } catch (final IOException | NullPointerException e) { + Logger.getAnonymousLogger().severe("Could not load default logging.properties file"); + Logger.getAnonymousLogger().severe(e.getMessage()); + } - TestBench.out().println("Starting Tests"); - } - private static final Logger WPILIBJ_ROOT_LOGGER = Logger.getLogger("edu.wpi.first.wpilibj"); - private static final Logger WPILIBJ_COMMAND_ROOT_LOGGER = Logger.getLogger("edu.wpi.first.wpilibj.command"); - - - private static final Class QUICK_TEST = QuickTest.class; - private static final String QUICK_TEST_FLAG = "--quick"; - private static final String HELP_FLAG = "--help"; - private static final String METHOD_NAME_FILTER = "--methodFilter="; - private static final String METHOD_REPEAT_FILTER = "--repeat="; - private static final String CLASS_NAME_FILTER = "--filter="; - - private static TestSuite instance = null; - - public static TestSuite getInstance(){ - if(instance == null){ - instance = new TestSuite(); - } - return instance; - } + TestBench.out().println("Starting Tests"); + } + private static final Logger WPILIBJ_ROOT_LOGGER = Logger.getLogger("edu.wpi.first.wpilibj"); + private static final Logger WPILIBJ_COMMAND_ROOT_LOGGER = Logger + .getLogger("edu.wpi.first.wpilibj.command"); - /** - * This has to be public so that the JUnit4 - */ - public TestSuite(){} - /** - * Displays a help message for the user when they use the --help flag at runtime. - */ - protected static void displayHelp(){ - StringBuilder helpMessage = new StringBuilder("Test Parameters help: \n"); - helpMessage.append("\t" + QUICK_TEST_FLAG + " will cause the quick test to be run. Ignores other flags except for " + METHOD_REPEAT_FILTER + "\n"); - helpMessage.append("\t" + CLASS_NAME_FILTER + " will use the supplied regex text to search for suite/test class names " - + "matching the regex and run them.\n"); - helpMessage.append("\t" + METHOD_NAME_FILTER + " will use the supplied regex text to search for test methods (excluding methods " - + "with the @Ignore annotation) and run only those methods. Can be paired with " + METHOD_REPEAT_FILTER + " to " - + "repeat the selected tests multiple times.\n"); - helpMessage.append("\t" + METHOD_REPEAT_FILTER + " will repeat the tests selected with either " + QUICK_TEST_FLAG + " or " + CLASS_NAME_FILTER + - " and run them the given number of times.\n"); - helpMessage.append("[NOTE] All regex uses the syntax defined by java.util.regex.Pattern. This documentation can be found at " - + "http://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html\n"); - helpMessage.append("\n"); - helpMessage.append("\n"); - - TestBench.out().println(helpMessage); - } - - /** - * Lets the user know that they used the TestSuite improperly and gives details about how to use it correctly in the future. - */ - protected static void displayInvalidUsage(String message, String... args){ - StringBuilder invalidMessage = new StringBuilder("Invalid Usage: " + message + "\n"); - invalidMessage.append("Params received: "); - for(String a : args){ - invalidMessage.append(a + " "); - } - invalidMessage.append("\n"); - invalidMessage.append("For details on proper usage of the runtime flags please run again with the " + HELP_FLAG + " flag.\n\n"); - - TestBench.out().println(invalidMessage); - - } - - /** - * Prints the loaded tests before they are run. - * @param classes the classes that were loaded. - */ - protected static void printLoadedTests(final Class... classes){ - StringBuilder loadedTestsMessage = new StringBuilder("The following tests were loaded:\n"); - Package p = null; - for(Class c : classes){ - if(c.getPackage().equals(p)){ - p = c.getPackage(); - loadedTestsMessage.append(p.getName() + "\n"); - } - loadedTestsMessage.append("\t" + c.getSimpleName() + "\n"); - } - TestBench.out().println(loadedTestsMessage); - } - - - /** - * Parses the arguments passed at runtime and runs the appropriate tests based upon these arguments - * @param args the args passed into the program at runtime - * @return the restults of the tests that have run. If no tests were run then null is returned. - */ - protected static Result parseArgsRunAndGetResult(final String[] args){ - if(args.length == 0){ //If there are no args passed at runtime then just run all of the tests. - printLoadedTests(TestSuite.class); - return JUnitCore.runClasses(TestSuite.class); - } - - //The method filter was passed - boolean methodFilter = false; - String methodRegex = ""; - //The class filter was passed - boolean classFilter = false; - String classRegex = ""; - boolean repeatFilter = false; - int repeatCount = 1; - - for(String s : args){ - if(Pattern.matches(METHOD_NAME_FILTER + ".*", s)){ - methodFilter = true; - methodRegex = new String(s).replace(METHOD_NAME_FILTER, ""); - } - if(Pattern.matches(METHOD_REPEAT_FILTER + ".*", s)){ - repeatFilter = true; - try{ - repeatCount = Integer.parseInt(new String(s).replace(METHOD_REPEAT_FILTER, "")); - } catch (NumberFormatException e){ - displayInvalidUsage("The argument passed to the repeat rule was not a valid integer.", args); - } - } - if(Pattern.matches(CLASS_NAME_FILTER + ".*", s)){ - classFilter = true; - classRegex = new String(s).replace(CLASS_NAME_FILTER, ""); - } - } - - - - ArrayList argsParsed = new ArrayList(Arrays.asList(args)); - if(argsParsed.contains(HELP_FLAG)){ - //If the user inputs the help flag then return the help message and exit without running any tests - displayHelp(); - return null; - } - if(argsParsed.contains(QUICK_TEST_FLAG)){ - printLoadedTests(QUICK_TEST); - return JUnitCore.runClasses(QUICK_TEST); - } - - /** - * Stores the data from multiple {@link Result}s in one class that can be returned to display the results. - */ - class MultipleResult extends Result{ - private static final long serialVersionUID = 1L; - private final List failures = new Vector(); - private int runCount = 0; - private int ignoreCount = 0; - private long runTime = 0; - - @Override - public int getRunCount() { - return runCount; - } - @Override - public int getFailureCount() { - return failures.size(); - } - @Override - public long getRunTime() { - return runTime; - } - @Override - public List getFailures() { - return failures; - } - @Override - public int getIgnoreCount() { - return ignoreCount; - } - /** - * Adds the given result's data to this result - * @param r the result to add to this result - */ - void addResult(Result r){ - failures.addAll(r.getFailures()); - runCount += r.getRunCount(); - ignoreCount += r.getIgnoreCount(); - runTime += r.getRunTime(); - } - } - - //If a specific method has been requested - if(methodFilter){ - List pairs = (new TestSuite()).getMethodMatching(methodRegex); - if(pairs.size() == 0){ - displayInvalidUsage("None of the arguments passed to the method name filter matched.", args); - return null; - } - //Print out the list of tests before we run them - TestBench.out().println("Running the following tests:"); - Class classListing = null; - for(ClassMethodPair p : pairs){ - if(!p.methodClass.equals(classListing)){ - //Only display the class name every time it changes - classListing = p.methodClass; - TestBench.out().println(classListing); - } - TestBench.out().println("\t" + p.methodName); - } - - - //The test results will be saved here - MultipleResult results = new MultipleResult(); - //Runs tests multiple times if the repeat rule is used - for(int i = 0; i < repeatCount; i++){ - //Now run all of the tests - for(ClassMethodPair p : pairs){ - Result result = (new JUnitCore()).run(p.getMethodRunRequest()); - //Store the given results in one cohesive result - results.addResult(result); - } - } - - return results; - } - - //If a specific class has been requested - if(classFilter){ - List> testClasses = (new TestSuite()).getSuiteOrTestMatchingRegex(classRegex); - if(testClasses.size() == 0){ - displayInvalidUsage("None of the arguments passed to the filter matched.", args); - return null; - } - printLoadedTests(testClasses.toArray(new Class[0])); - MultipleResult results = new MultipleResult(); - //Runs tests multiple times if the repeat rule is used - for(int i = 0; i < repeatCount; i++){ - Result result = (new JUnitCore()).run(testClasses.toArray(new Class[0])); - //Store the given results in one cohesive result - results.addResult(result); - } - return results; - } - displayInvalidUsage("None of the parameters that you passed matched any of the accepted flags.", args); - - return null; - } - - protected static void displayResults(Result result){ - //Results are collected and displayed here - TestBench.out().println("\n"); - if(!result.wasSuccessful()){ - //Prints out a list of stack traces for the failed tests - TestBench.out().println("Failure List: "); - for(Failure f : result.getFailures()){ - TestBench.out().println(f.getDescription()); - TestBench.out().println(f.getTrace()); - } - TestBench.out().println(); - TestBench.out().println("FAILURES!!!"); - //Print the test statistics - TestBench.out().println("Tests run: " + result.getRunCount() + - ", Failures: " + result.getFailureCount() + - ", Ignored: " + result.getIgnoreCount() + - ", In " + result.getRunTime() + "ms"); - - //Prints out a list of test that failed - TestBench.out().println("Failure List (short):"); - String failureClass = result.getFailures().get(0).getDescription().getClassName(); - TestBench.out().println(failureClass); - for(Failure f : result.getFailures()){ - if(!failureClass.equals(f.getDescription().getClassName())){ - failureClass = f.getDescription().getClassName(); - TestBench.out().println(failureClass); - } - TestBench.err().println("\t" + f.getDescription()); - } - } else { - TestBench.out().println("SUCCESS!"); - TestBench.out().println("Tests run: " + result.getRunCount() + - ", Ignored: " + result.getIgnoreCount() + - ", In " + result.getRunTime() + "ms"); - } - TestBench.out().println(); - } + private static final Class QUICK_TEST = QuickTest.class; + private static final String QUICK_TEST_FLAG = "--quick"; + private static final String HELP_FLAG = "--help"; + private static final String METHOD_NAME_FILTER = "--methodFilter="; + private static final String METHOD_REPEAT_FILTER = "--repeat="; + private static final String CLASS_NAME_FILTER = "--filter="; - /** - * This is used by ant to get the Junit tests. This is required because the tests try to load using a - * JUnit 3 framework. JUnit4 uses annotations to load tests. This method allows JUnit3 to load JUnit4 tests. - */ - public static junit.framework.Test suite(){ - return new JUnit4TestAdapter(TestSuite.class); - } - - - /** - * The method called at runtime - * @param args The test suites to run - */ - public static void main(String[] args) { - TestBench.out().println("JUnit version " + Version.id()); - - //Tests are run here - Result result = parseArgsRunAndGetResult(args); - if(result != null){ - //Results are collected and displayed here - displayResults(result); - - System.exit(result.wasSuccessful() ? 0 : 1); - } - System.exit(1); - } + private static TestSuite instance = null; + + public static TestSuite getInstance() { + if (instance == null) { + instance = new TestSuite(); + } + return instance; + } + + /** + * This has to be public so that the JUnit4 + */ + public TestSuite() {} + + /** + * Displays a help message for the user when they use the --help flag at + * runtime. + */ + protected static void displayHelp() { + StringBuilder helpMessage = new StringBuilder("Test Parameters help: \n"); + helpMessage.append("\t" + QUICK_TEST_FLAG + + " will cause the quick test to be run. Ignores other flags except for " + + METHOD_REPEAT_FILTER + "\n"); + helpMessage.append("\t" + CLASS_NAME_FILTER + + " will use the supplied regex text to search for suite/test class names " + + "matching the regex and run them.\n"); + helpMessage.append("\t" + METHOD_NAME_FILTER + + " will use the supplied regex text to search for test methods (excluding methods " + + "with the @Ignore annotation) and run only those methods. Can be paired with " + + METHOD_REPEAT_FILTER + " to " + "repeat the selected tests multiple times.\n"); + helpMessage.append("\t" + METHOD_REPEAT_FILTER + " will repeat the tests selected with either " + + QUICK_TEST_FLAG + " or " + CLASS_NAME_FILTER + + " and run them the given number of times.\n"); + helpMessage + .append("[NOTE] All regex uses the syntax defined by java.util.regex.Pattern. This documentation can be found at " + + "http://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html\n"); + helpMessage.append("\n"); + helpMessage.append("\n"); + + TestBench.out().println(helpMessage); + } + + /** + * Lets the user know that they used the TestSuite improperly and gives + * details about how to use it correctly in the future. + */ + protected static void displayInvalidUsage(String message, String... args) { + StringBuilder invalidMessage = new StringBuilder("Invalid Usage: " + message + "\n"); + invalidMessage.append("Params received: "); + for (String a : args) { + invalidMessage.append(a + " "); + } + invalidMessage.append("\n"); + invalidMessage + .append("For details on proper usage of the runtime flags please run again with the " + + HELP_FLAG + " flag.\n\n"); + + TestBench.out().println(invalidMessage); + + } + + /** + * Prints the loaded tests before they are run. + *$ + * @param classes the classes that were loaded. + */ + protected static void printLoadedTests(final Class... classes) { + StringBuilder loadedTestsMessage = new StringBuilder("The following tests were loaded:\n"); + Package p = null; + for (Class c : classes) { + if (c.getPackage().equals(p)) { + p = c.getPackage(); + loadedTestsMessage.append(p.getName() + "\n"); + } + loadedTestsMessage.append("\t" + c.getSimpleName() + "\n"); + } + TestBench.out().println(loadedTestsMessage); + } + + + /** + * Parses the arguments passed at runtime and runs the appropriate tests based + * upon these arguments + *$ + * @param args the args passed into the program at runtime + * @return the restults of the tests that have run. If no tests were run then + * null is returned. + */ + protected static Result parseArgsRunAndGetResult(final String[] args) { + if (args.length == 0) { // If there are no args passed at runtime then just + // run all of the tests. + printLoadedTests(TestSuite.class); + return JUnitCore.runClasses(TestSuite.class); + } + + // The method filter was passed + boolean methodFilter = false; + String methodRegex = ""; + // The class filter was passed + boolean classFilter = false; + String classRegex = ""; + boolean repeatFilter = false; + int repeatCount = 1; + + for (String s : args) { + if (Pattern.matches(METHOD_NAME_FILTER + ".*", s)) { + methodFilter = true; + methodRegex = new String(s).replace(METHOD_NAME_FILTER, ""); + } + if (Pattern.matches(METHOD_REPEAT_FILTER + ".*", s)) { + repeatFilter = true; + try { + repeatCount = Integer.parseInt(new String(s).replace(METHOD_REPEAT_FILTER, "")); + } catch (NumberFormatException e) { + displayInvalidUsage("The argument passed to the repeat rule was not a valid integer.", + args); + } + } + if (Pattern.matches(CLASS_NAME_FILTER + ".*", s)) { + classFilter = true; + classRegex = new String(s).replace(CLASS_NAME_FILTER, ""); + } + } + + + + ArrayList argsParsed = new ArrayList(Arrays.asList(args)); + if (argsParsed.contains(HELP_FLAG)) { + // If the user inputs the help flag then return the help message and exit + // without running any tests + displayHelp(); + return null; + } + if (argsParsed.contains(QUICK_TEST_FLAG)) { + printLoadedTests(QUICK_TEST); + return JUnitCore.runClasses(QUICK_TEST); + } + + /** + * Stores the data from multiple {@link Result}s in one class that can be + * returned to display the results. + */ + class MultipleResult extends Result { + private static final long serialVersionUID = 1L; + private final List failures = new Vector(); + private int runCount = 0; + private int ignoreCount = 0; + private long runTime = 0; + + @Override + public int getRunCount() { + return runCount; + } + + @Override + public int getFailureCount() { + return failures.size(); + } + + @Override + public long getRunTime() { + return runTime; + } + + @Override + public List getFailures() { + return failures; + } + + @Override + public int getIgnoreCount() { + return ignoreCount; + } + + /** + * Adds the given result's data to this result + *$ + * @param r the result to add to this result + */ + void addResult(Result r) { + failures.addAll(r.getFailures()); + runCount += r.getRunCount(); + ignoreCount += r.getIgnoreCount(); + runTime += r.getRunTime(); + } + } + + // If a specific method has been requested + if (methodFilter) { + List pairs = (new TestSuite()).getMethodMatching(methodRegex); + if (pairs.size() == 0) { + displayInvalidUsage("None of the arguments passed to the method name filter matched.", args); + return null; + } + // Print out the list of tests before we run them + TestBench.out().println("Running the following tests:"); + Class classListing = null; + for (ClassMethodPair p : pairs) { + if (!p.methodClass.equals(classListing)) { + // Only display the class name every time it changes + classListing = p.methodClass; + TestBench.out().println(classListing); + } + TestBench.out().println("\t" + p.methodName); + } + + + // The test results will be saved here + MultipleResult results = new MultipleResult(); + // Runs tests multiple times if the repeat rule is used + for (int i = 0; i < repeatCount; i++) { + // Now run all of the tests + for (ClassMethodPair p : pairs) { + Result result = (new JUnitCore()).run(p.getMethodRunRequest()); + // Store the given results in one cohesive result + results.addResult(result); + } + } + + return results; + } + + // If a specific class has been requested + if (classFilter) { + List> testClasses = (new TestSuite()).getSuiteOrTestMatchingRegex(classRegex); + if (testClasses.size() == 0) { + displayInvalidUsage("None of the arguments passed to the filter matched.", args); + return null; + } + printLoadedTests(testClasses.toArray(new Class[0])); + MultipleResult results = new MultipleResult(); + // Runs tests multiple times if the repeat rule is used + for (int i = 0; i < repeatCount; i++) { + Result result = (new JUnitCore()).run(testClasses.toArray(new Class[0])); + // Store the given results in one cohesive result + results.addResult(result); + } + return results; + } + displayInvalidUsage( + "None of the parameters that you passed matched any of the accepted flags.", args); + + return null; + } + + protected static void displayResults(Result result) { + // Results are collected and displayed here + TestBench.out().println("\n"); + if (!result.wasSuccessful()) { + // Prints out a list of stack traces for the failed tests + TestBench.out().println("Failure List: "); + for (Failure f : result.getFailures()) { + TestBench.out().println(f.getDescription()); + TestBench.out().println(f.getTrace()); + } + TestBench.out().println(); + TestBench.out().println("FAILURES!!!"); + // Print the test statistics + TestBench.out().println( + "Tests run: " + result.getRunCount() + ", Failures: " + result.getFailureCount() + + ", Ignored: " + result.getIgnoreCount() + ", In " + result.getRunTime() + "ms"); + + // Prints out a list of test that failed + TestBench.out().println("Failure List (short):"); + String failureClass = result.getFailures().get(0).getDescription().getClassName(); + TestBench.out().println(failureClass); + for (Failure f : result.getFailures()) { + if (!failureClass.equals(f.getDescription().getClassName())) { + failureClass = f.getDescription().getClassName(); + TestBench.out().println(failureClass); + } + TestBench.err().println("\t" + f.getDescription()); + } + } else { + TestBench.out().println("SUCCESS!"); + TestBench.out().println( + "Tests run: " + result.getRunCount() + ", Ignored: " + result.getIgnoreCount() + ", In " + + result.getRunTime() + "ms"); + } + TestBench.out().println(); + } + + /** + * This is used by ant to get the Junit tests. This is required because the + * tests try to load using a JUnit 3 framework. JUnit4 uses annotations to + * load tests. This method allows JUnit3 to load JUnit4 tests. + */ + public static junit.framework.Test suite() { + return new JUnit4TestAdapter(TestSuite.class); + } + + + /** + * The method called at runtime + *$ + * @param args The test suites to run + */ + public static void main(String[] args) { + TestBench.out().println("JUnit version " + Version.id()); + + // Tests are run here + Result result = parseArgsRunAndGetResult(args); + if (result != null) { + // Results are collected and displayed here + displayResults(result); + + System.exit(result.wasSuccessful() ? 0 : 1); + } + System.exit(1); + } } diff --git a/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/test/package-info.java b/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/test/package-info.java index ef0fce79fa..eadb82b3c0 100644 --- a/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/test/package-info.java +++ b/wpilibj/wpilibJavaIntegrationTests/src/main/java/edu/wpi/first/wpilibj/test/package-info.java @@ -1,11 +1,13 @@ /** - * This is the starting point for the integration testing framework. - * This package should contain classes that are not explicitly for testing the + * This is the starting point for the integration testing framework. This + * package should contain classes that are not explicitly for testing the * library but instead provide the framework that the tests can extend from. - * Every test should extend from {@link edu.wpi.first.wpilibj.test.AbstractComsSetup} - * to ensure that Network Communications is properly instantiated before the test is run. - * - * The {@link edu.wpi.first.wpilibj.test.TestBench} should contain the port numbers for all of the hardware and these values should not be explicitly defined - * anywhere else in the testing framework. + * Every test should extend from + * {@link edu.wpi.first.wpilibj.test.AbstractComsSetup} to ensure that Network + * Communications is properly instantiated before the test is run. + *$ + * The {@link edu.wpi.first.wpilibj.test.TestBench} should contain the port + * numbers for all of the hardware and these values should not be explicitly + * defined anywhere else in the testing framework. */ package edu.wpi.first.wpilibj.test; \ No newline at end of file diff --git a/wpilibj/wpilibJavaIntegrationTests/src/test/java/edu/wpi/first/wpilibj/test/AbstractTestSuiteTest.java b/wpilibj/wpilibJavaIntegrationTests/src/test/java/edu/wpi/first/wpilibj/test/AbstractTestSuiteTest.java index 9c2684ca97..64ff7a0813 100644 --- a/wpilibj/wpilibJavaIntegrationTests/src/test/java/edu/wpi/first/wpilibj/test/AbstractTestSuiteTest.java +++ b/wpilibj/wpilibJavaIntegrationTests/src/test/java/edu/wpi/first/wpilibj/test/AbstractTestSuiteTest.java @@ -1,8 +1,8 @@ /*----------------------------------------------------------------------------*/ -/* Copyright (c) FIRST 2008-2014. All Rights Reserved. */ -/* Open Source Software - may be modified and shared by FRC teams. The code */ +/* Copyright (c) FIRST 2008-2014. All Rights Reserved. */ +/* Open Source Software - may be modified and shared by FRC teams. The code */ /* must be accompanied by the FIRST BSD license file in the root directory of */ -/* the project. */ +/* the project. */ /*----------------------------------------------------------------------------*/ package edu.wpi.first.wpilibj.test; @@ -28,115 +28,125 @@ import edu.wpi.first.wpilibj.test.AbstractTestSuite.ClassMethodPair; * */ public class AbstractTestSuiteTest { - - @Ignore("Prevents ANT from trying to run these as tests") - @RunWith(Suite.class) - @SuiteClasses({ - FirstSampleTest.class, - SecondSampleTest.class, - ThirdSampleTest.class, - FourthSampleTest.class, - UnusualTest.class, - ExampleSubSuite.class, - EmptySuite.class - }) - class TestForAbstractTestSuite extends AbstractTestSuite{ - } - - TestForAbstractTestSuite testSuite; - /** - * @throws java.lang.Exception - */ - @Before - public void setUp() throws Exception { - testSuite = new TestForAbstractTestSuite(); - } + @Ignore("Prevents ANT from trying to run these as tests") + @RunWith(Suite.class) + @SuiteClasses({FirstSampleTest.class, SecondSampleTest.class, ThirdSampleTest.class, + FourthSampleTest.class, UnusualTest.class, ExampleSubSuite.class, EmptySuite.class}) + class TestForAbstractTestSuite extends AbstractTestSuite { + } - @Test - public void testGetTestsMatchingAll() throws InitializationError { - //when - List> collectedTests = testSuite.getAllClassMatching(".*"); - //then - assertEquals(7, collectedTests.size()); - } - - @Test - public void testGetTestsMatchingSample() throws InitializationError{ - //when - List> collectedTests = testSuite.getAllClassMatching(".*Sample.*"); - //then - assertEquals(4, collectedTests.size()); - } - - @Test - public void testGetTestsMatchingUnusual() throws InitializationError{ - //when - List> collectedTests = testSuite.getAllClassMatching(".*Unusual.*"); - //then - assertEquals(1, collectedTests.size()); - assertEquals(UnusualTest.class, collectedTests.get(0)); - } - - @Test - public void testGetTestsFromSuiteMatchingAll() throws InitializationError { - //when - List> collectedTests = testSuite.getSuiteOrTestMatchingRegex(".*"); - //then - assertEquals(7, collectedTests.size()); - } - - @Test - public void testGetTestsFromSuiteMatchingTest() throws InitializationError { - //when - List> collectedTests = testSuite.getSuiteOrTestMatchingRegex(".*Test.*"); - //then - assertEquals(7, collectedTests.size()); - assertThat(collectedTests, hasItems(new Class[] {FirstSubSuiteTest.class, SecondSubSuiteTest.class, UnusualTest.class})); - assertThat(collectedTests, not(hasItems(new Class[] {ExampleSubSuite.class, EmptySuite.class}))); - } - - @Test - public void testGetMethodFromTest(){ - //when - List pairs = testSuite.getMethodMatching(".*Method.*"); - //then - assertEquals(1, pairs.size()); - assertEquals(FirstSubSuiteTest.class, pairs.get(0).methodClass); - assertEquals(FirstSubSuiteTest.METHODNAME, pairs.get(0).methodName); - - } + TestForAbstractTestSuite testSuite; + + /** + * @throws java.lang.Exception + */ + @Before + public void setUp() throws Exception { + testSuite = new TestForAbstractTestSuite(); + } + + @Test + public void testGetTestsMatchingAll() throws InitializationError { + // when + List> collectedTests = testSuite.getAllClassMatching(".*"); + // then + assertEquals(7, collectedTests.size()); + } + + @Test + public void testGetTestsMatchingSample() throws InitializationError { + // when + List> collectedTests = testSuite.getAllClassMatching(".*Sample.*"); + // then + assertEquals(4, collectedTests.size()); + } + + @Test + public void testGetTestsMatchingUnusual() throws InitializationError { + // when + List> collectedTests = testSuite.getAllClassMatching(".*Unusual.*"); + // then + assertEquals(1, collectedTests.size()); + assertEquals(UnusualTest.class, collectedTests.get(0)); + } + + @Test + public void testGetTestsFromSuiteMatchingAll() throws InitializationError { + // when + List> collectedTests = testSuite.getSuiteOrTestMatchingRegex(".*"); + // then + assertEquals(7, collectedTests.size()); + } + + @Test + public void testGetTestsFromSuiteMatchingTest() throws InitializationError { + // when + List> collectedTests = testSuite.getSuiteOrTestMatchingRegex(".*Test.*"); + // then + assertEquals(7, collectedTests.size()); + assertThat(collectedTests, hasItems(new Class[] {FirstSubSuiteTest.class, + SecondSubSuiteTest.class, UnusualTest.class})); + assertThat(collectedTests, + not(hasItems(new Class[] {ExampleSubSuite.class, EmptySuite.class}))); + } + + @Test + public void testGetMethodFromTest() { + // when + List pairs = testSuite.getMethodMatching(".*Method.*"); + // then + assertEquals(1, pairs.size()); + assertEquals(FirstSubSuiteTest.class, pairs.get(0).methodClass); + assertEquals(FirstSubSuiteTest.METHODNAME, pairs.get(0).methodName); + + } } -class FirstSampleTest {} -class SecondSampleTest {} -class ThirdSampleTest {} -class FourthSampleTest {} +class FirstSampleTest { +} + + +class SecondSampleTest { +} + + +class ThirdSampleTest { +} + + +class FourthSampleTest { +} + + +class UnusualTest { +} // This is a member of both suites -class UnusualTest {} //This is a member of both suites @Ignore("Prevents ANT from trying to run these as tests") -class FirstSubSuiteTest{ - public static final String METHODNAME = "aTestMethod"; - @Test - public void aTestMethod(){ - } +class FirstSubSuiteTest { + public static final String METHODNAME = "aTestMethod"; + + @Test + public void aTestMethod() {} } -class SecondSubSuiteTest{} + + +class SecondSubSuiteTest { +} + @RunWith(Suite.class) -@SuiteClasses({ - FirstSubSuiteTest.class, - SecondSubSuiteTest.class, - UnusualTest.class -}) +@SuiteClasses({FirstSubSuiteTest.class, SecondSubSuiteTest.class, UnusualTest.class}) @Ignore("Prevents ANT from trying to run these as tests") -class ExampleSubSuite extends AbstractTestSuite{} +class ExampleSubSuite extends AbstractTestSuite { +} + @Ignore("Prevents ANT from trying to run these as tests") @RunWith(Suite.class) @SuiteClasses({}) -class EmptySuite extends AbstractTestSuite{} - +class EmptySuite extends AbstractTestSuite { +}