First stable compilation with ModbusRTU and ModbusTCP
This commit is contained in:
95
lib/Core/Categories/ModbusCoil.h
Normal file
95
lib/Core/Categories/ModbusCoil.h
Normal file
@@ -0,0 +1,95 @@
|
||||
/**
|
||||
* @file ModbusCoil.h
|
||||
* @brief Defines the ModbusCoil class for handling Modbus coils.
|
||||
* @author Emmanuel Hernandez Cruz
|
||||
* @date 2025-09-04
|
||||
*
|
||||
* This file contains the definition of the ModbusCoil class, which is a specific
|
||||
* implementation of the ModbusPoint for handling coils (digital outputs).
|
||||
*/
|
||||
#ifndef ModbusCoil_h
|
||||
#define ModbusCoil_h
|
||||
|
||||
#include "ModbusPoint.h"
|
||||
|
||||
/**
|
||||
* @class ModbusCoil
|
||||
* @brief Represents a Modbus coil point.
|
||||
*
|
||||
* This class provides a concrete implementation for a Modbus coil,
|
||||
* which is a single bit digital output. It inherits from ModbusPoint
|
||||
* and implements its virtual functions for coil-specific operations.
|
||||
*/
|
||||
template<typename T>
|
||||
class ModbusCoil : public ModbusPoint<T>{
|
||||
public:
|
||||
/**
|
||||
* @brief Constructor for the ModbusCoil class.
|
||||
* @param server Pointer to the ModbusIP server instance.
|
||||
* @param address The Modbus address of the coil.
|
||||
* @param value The initial value of the coil.
|
||||
* @param description A description of the coil.
|
||||
*/
|
||||
ModbusCoil(T* server, int address, int value, const char* description);
|
||||
|
||||
/**
|
||||
* @brief Adds the coil to the Modbus server.
|
||||
*/
|
||||
void addToModbusServer() override;
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* @brief Sets the internal value of the coil.
|
||||
* @param value The new value for the coil.
|
||||
*/
|
||||
void setValue(int value) override;
|
||||
|
||||
/**
|
||||
* @brief Gets the current internal value of the coil.
|
||||
* @return The current value of the coil.
|
||||
*/
|
||||
int getValue() const override;
|
||||
|
||||
|
||||
};
|
||||
|
||||
template<typename T>
|
||||
ModbusCoil<T>::ModbusCoil(T* server, int address, int value, const char* description)
|
||||
: ModbusPoint<T>(server, address, value, description){
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Adds the coil to the Modbus server's register map.
|
||||
*/
|
||||
template<typename T>
|
||||
void ModbusCoil<T>::addToModbusServer(){
|
||||
this->_server->addCoil(this->_address, this->_value);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @brief Sets the internal value of the coil.
|
||||
*
|
||||
* If the new value is different from the current value, it updates the
|
||||
* internal value and marks the point as dirty, indicating it needs to be
|
||||
* written to the Modbus server.
|
||||
*
|
||||
* @param value The new value for the coil.
|
||||
*/
|
||||
template<typename T>
|
||||
void ModbusCoil<T>::setValue(int value){
|
||||
this->_server->Coil(this->_address, value);
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Gets the current internal value of the coil.
|
||||
* @return The current value.
|
||||
*/
|
||||
template<typename T>
|
||||
int ModbusCoil<T>::getValue() const{
|
||||
return this->_server->Coil(this->_address);
|
||||
}
|
||||
|
||||
#endif
|
||||
116
lib/Core/Categories/ModbusFloatDecorator.h
Normal file
116
lib/Core/Categories/ModbusFloatDecorator.h
Normal file
@@ -0,0 +1,116 @@
|
||||
/**
|
||||
* @file ModbusFloatDecorator.h
|
||||
* @brief Defines the ModbusFloatDecorator class for handling 32-bit float values.
|
||||
* @author Emmanuel Hernandez Cruz
|
||||
* @date 2025-09-05
|
||||
*
|
||||
* This file contains the definition for a decorator that combines two 16-bit
|
||||
* Modbus registers to represent a single 32-bit floating-point value.
|
||||
*/
|
||||
#ifndef ModbusFloatDecorator_h
|
||||
#define ModbusFloatDecorator_h
|
||||
#include <stdint.h>
|
||||
#include "ModbusPointDecorator.h"
|
||||
|
||||
/**
|
||||
* @union cracked_float_t
|
||||
* @brief A union to easily convert between a 32-bit float and two 16-bit integers.
|
||||
*
|
||||
* This union allows type-punning between a `float` and an array of two `int16_t`
|
||||
* values, which simplifies splitting a float into high and low words for Modbus
|
||||
* transmission.
|
||||
*/
|
||||
typedef union{
|
||||
float v; /**< @brief The value as a 32-bit float. */
|
||||
int16_t as_int[2]; /**< @brief The value as two 16-bit integers. */
|
||||
} cracked_float_t;
|
||||
|
||||
/**
|
||||
* @class ModbusFloatDecorator
|
||||
* @brief A decorator that combines two 16-bit registers into a 32-bit float.
|
||||
*
|
||||
* This class wraps two consecutive ModbusPoint objects (a low-word and a
|
||||
* high-word point) and treats them as a single 32-bit float value. It
|
||||
* overrides the necessary methods to handle reading, writing, and value
|
||||
* conversion across both underlying registers.
|
||||
*/
|
||||
template<typename T>
|
||||
class ModbusFloatDecorator : public ModbusPointDecorator<T> {
|
||||
public:
|
||||
/**
|
||||
* @brief Constructs a new ModbusFloatDecorator object.
|
||||
* @param point A pointer to the ModbusPoint for the low-order word.
|
||||
* @param highOrderPoint A pointer to the ModbusPoint for the high-order word.
|
||||
*/
|
||||
ModbusFloatDecorator(ModbusPoint<T>* point, ModbusPoint<T>* highOrderPoint)
|
||||
: ModbusPointDecorator<T>(point), _highOrderPoint(highOrderPoint) {}
|
||||
|
||||
/**
|
||||
* @brief Returns the logical type of the point.
|
||||
* @return Always returns `PointType::FLOAT`.
|
||||
*/
|
||||
PointType getType() const override { return PointType::FLOAT; }
|
||||
|
||||
/**
|
||||
* @brief Sets the 32-bit float value by casting an integer.
|
||||
* This method is an override for the base class and calls `setFloatValue`.
|
||||
* @param value The integer value to set (will be cast to float).
|
||||
*/
|
||||
void setValue(int value) override {
|
||||
setFloatValue(static_cast<float>(value));
|
||||
}
|
||||
/**
|
||||
* @brief Sets the 32-bit float value by splitting it into two 16-bit words.
|
||||
*
|
||||
* This method uses a union to split the float into two 16-bit integers
|
||||
* and sets the values on the two underlying Modbus points.
|
||||
* @note The order of `as_int[0]` vs `as_int[1]` might need to be swapped
|
||||
* depending on the endianness of the target Modbus device.
|
||||
*
|
||||
* @param value The 32-bit float value to set.
|
||||
*/
|
||||
void setFloatValue(float value) {
|
||||
cracked_float_t buffer;
|
||||
buffer.v = value;
|
||||
this->_point->setValue(buffer.as_int[0]);
|
||||
_highOrderPoint->setValue(buffer.as_int[1]);
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Gets the 32-bit float value, cast to an integer.
|
||||
* @return The integer representation of the full float value.
|
||||
*/
|
||||
int getValue() const override {
|
||||
return static_cast<int>(getFloatValue());
|
||||
}
|
||||
/**
|
||||
* @brief Gets the combined 32-bit float value from the two registers.
|
||||
*
|
||||
* This method reads the 16-bit integer values from the two underlying
|
||||
* points and uses a union to reconstruct the 32-bit float value.
|
||||
*
|
||||
* @return The reconstructed 32-bit float value.
|
||||
*/
|
||||
float getFloatValue() const {
|
||||
cracked_float_t buffer;
|
||||
// Directly read the two 16-bit words from the Modbus server
|
||||
buffer.as_int[0] = this->_point->getServer()->Hreg(this->_point->getAddress());
|
||||
buffer.as_int[1] = _highOrderPoint->getServer()->Hreg(_highOrderPoint->getAddress());
|
||||
return buffer.v;
|
||||
}
|
||||
|
||||
// --- Housekeeping Methods ---
|
||||
|
||||
/** @brief Adds both underlying registers to the Modbus server. */
|
||||
void addToModbusServer() override {
|
||||
this->_point->addToModbusServer();
|
||||
_highOrderPoint->addToModbusServer();
|
||||
}
|
||||
|
||||
|
||||
|
||||
private:
|
||||
ModbusPoint<T>* _highOrderPoint; /**< @brief Pointer to the ModbusPoint for the high-order word. */
|
||||
};
|
||||
|
||||
#endif
|
||||
75
lib/Core/Categories/ModbusHreg.h
Normal file
75
lib/Core/Categories/ModbusHreg.h
Normal file
@@ -0,0 +1,75 @@
|
||||
/**
|
||||
* @file ModbusHreg.h
|
||||
* @brief Defines the ModbusHreg class for handling Modbus holding registers.
|
||||
* @author Emmanuel Hernandez Cruz
|
||||
* @date 2025-09-04
|
||||
*
|
||||
* This file contains the definition of the ModbusHreg class, which is a specific
|
||||
* implementation of the ModbusPoint for handling holding registers (16-bit).
|
||||
*/
|
||||
#ifndef ModbusHreg_h
|
||||
#define ModbusHreg_h
|
||||
|
||||
#include "ModbusPoint.h"
|
||||
|
||||
/**
|
||||
* @class ModbusHreg
|
||||
* @brief Represents a Modbus holding register point.
|
||||
*
|
||||
* This class provides a concrete implementation for a Modbus holding register,
|
||||
* which is a 16-bit read/write register. It inherits from ModbusPoint
|
||||
* and implements its virtual functions for holding register-specific operations.
|
||||
*/
|
||||
template<typename T>
|
||||
class ModbusHreg : public ModbusPoint<T>{
|
||||
public:
|
||||
/**
|
||||
* @brief Constructor for the ModbusHreg class.
|
||||
* @param server Pointer to the ModbusIP server instance.
|
||||
* @param address The Modbus address of the holding register.
|
||||
* @param value The initial value of the holding register.
|
||||
* @param description A description of the holding register.
|
||||
*/
|
||||
ModbusHreg(T* server, int address, int value, const char* description);
|
||||
|
||||
/**
|
||||
* @brief Adds the holding register to the Modbus server.
|
||||
*/
|
||||
void addToModbusServer() override;
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* @brief Sets the internal value of the holding register.
|
||||
* @param value The new value for the holding register.
|
||||
*/
|
||||
void setValue(int value) override;
|
||||
|
||||
/**
|
||||
* @brief Gets the current internal value of the holding register.
|
||||
* @return The current value of the holding register.
|
||||
*/
|
||||
int getValue() const override;
|
||||
|
||||
|
||||
};
|
||||
|
||||
template<typename T>
|
||||
ModbusHreg<T>::ModbusHreg(T* server, int address, int value, const char* description)
|
||||
: ModbusPoint<T>(server, address, value, description) {}
|
||||
|
||||
template<typename T>
|
||||
void ModbusHreg<T>::addToModbusServer() {
|
||||
this->_server->addHreg(this->_address, this->_value);
|
||||
}
|
||||
|
||||
template<typename T>
|
||||
void ModbusHreg<T>::setValue(int value) {
|
||||
this->_server->Hreg(this->_address, value);
|
||||
}
|
||||
|
||||
template<typename T>
|
||||
int ModbusHreg<T>::getValue() const {
|
||||
return this->_server->Hreg(this->_address);
|
||||
}
|
||||
#endif
|
||||
82
lib/Core/Categories/ModbusIreg.h
Normal file
82
lib/Core/Categories/ModbusIreg.h
Normal file
@@ -0,0 +1,82 @@
|
||||
/**
|
||||
* @file ModbusIreg.h
|
||||
* @brief Defines the ModbusIreg class for handling Modbus Input Registers.
|
||||
* @author Emmanuel Hernandez Cruz
|
||||
* @date 2025-09-04
|
||||
*
|
||||
* This file contains the definition of the ModbusIreg class, which is a specific
|
||||
* implementation of the ModbusPoint for handling input registers (16-bit read-only).
|
||||
*/
|
||||
#ifndef ModbusIreg_h
|
||||
#define ModbusIreg_h
|
||||
|
||||
#include "ModbusPoint.h"
|
||||
|
||||
/**
|
||||
* @class ModbusIreg
|
||||
* @brief Represents a Modbus Input Register point.
|
||||
*
|
||||
* This class provides a concrete implementation for a Modbus input register,
|
||||
* which is a 16-bit read-only register. It inherits from ModbusPoint
|
||||
* and implements its virtual functions for input register-specific operations.
|
||||
*/
|
||||
template<typename T>
|
||||
class ModbusIreg : public ModbusPoint<T>{
|
||||
public:
|
||||
/**
|
||||
* @brief Constructor for the ModbusIreg class.
|
||||
* @param server Pointer to the ModbusIP server instance.
|
||||
* @param address The Modbus address of the input register.
|
||||
* @param value The initial value of the input register.
|
||||
* @param description A description of the input register.
|
||||
*/
|
||||
ModbusIreg(T* server, int address, int value, const char* description);
|
||||
|
||||
/**
|
||||
* @brief Adds the input register to the Modbus server.
|
||||
*/
|
||||
void addToModbusServer() override;
|
||||
|
||||
/**
|
||||
* @brief Sets the internal value of the input register.
|
||||
* @param value The new value for the input register.
|
||||
*/
|
||||
void setValue(int value) override;
|
||||
/**
|
||||
* @brief Gets the current internal value of the input register.
|
||||
* @return The current value of the input register.
|
||||
*/
|
||||
int getValue() const override;
|
||||
};
|
||||
|
||||
template<typename T>
|
||||
ModbusIreg<T>::ModbusIreg(T* server, int address, int value, const char* description)
|
||||
: ModbusPoint<T>(server, address, value, description){
|
||||
|
||||
}
|
||||
/**
|
||||
* @brief Sets the internal value of the input register and marks it as dirty.
|
||||
* @param value The new value for the input register.
|
||||
*/
|
||||
template<typename T>
|
||||
void ModbusIreg<T>::setValue(int value){
|
||||
this->_server->Ireg(this->_address, value);
|
||||
}
|
||||
/**
|
||||
* @brief Gets the current internal value of the input register.
|
||||
* @return The current value.
|
||||
*/
|
||||
template<typename T>
|
||||
int ModbusIreg<T>::getValue() const {
|
||||
return this->_server->Ireg(this->_address);
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Adds the input register to the Modbus server's register map.
|
||||
*/
|
||||
template<typename T>
|
||||
void ModbusIreg<T>::addToModbusServer(){
|
||||
this->_server->addIreg(this->_address, this->_value);
|
||||
}
|
||||
|
||||
#endif
|
||||
83
lib/Core/Categories/ModbusIsts.h
Normal file
83
lib/Core/Categories/ModbusIsts.h
Normal file
@@ -0,0 +1,83 @@
|
||||
/**
|
||||
* @file ModbusIsts.h
|
||||
* @brief Defines the ModbusIsts class for handling Modbus Input Status (Discrete Inputs).
|
||||
* @author Emmanuel Hernandez Cruz
|
||||
* @date 2025-09-04
|
||||
*
|
||||
* This file contains the definition of the ModbusIsts class, which is a specific
|
||||
* implementation of the ModbusPoint for handling discrete inputs (read-only coils).
|
||||
*/
|
||||
#ifndef ModbusIsts_h
|
||||
#define ModbusIsts_h
|
||||
|
||||
#include "ModbusPoint.h"
|
||||
|
||||
/**
|
||||
* @class ModbusIsts
|
||||
* @brief Represents a Modbus Input Status (Discrete Input) point.
|
||||
*
|
||||
* This class provides a concrete implementation for a Modbus discrete input,
|
||||
* which is a single bit read-only value. It inherits from ModbusPoint
|
||||
* and implements its virtual functions for discrete input-specific operations.
|
||||
*/
|
||||
template<typename T>
|
||||
class ModbusIsts : public ModbusPoint<T>{
|
||||
public:
|
||||
/**
|
||||
* @brief Constructor for the ModbusIsts class.
|
||||
* @param server Pointer to the ModbusIP server instance.
|
||||
* @param address The Modbus address of the discrete input.
|
||||
* @param value The initial value of the discrete input.
|
||||
* @param description A description of the discrete input.
|
||||
*/
|
||||
ModbusIsts(T* server, int address, int value, const char* description);
|
||||
|
||||
/**
|
||||
* @brief Adds the discrete input to the Modbus server.
|
||||
*/
|
||||
void addToModbusServer() override;
|
||||
|
||||
/**
|
||||
* @brief Sets the internal value of the discrete input.
|
||||
* @param value The new value for the discrete input.
|
||||
*/
|
||||
void setValue(int value) override;
|
||||
/**
|
||||
* @brief Gets the current internal value of the discrete input.
|
||||
* @return The current value of the discrete input.
|
||||
*/
|
||||
int getValue() const override;
|
||||
|
||||
};
|
||||
|
||||
template<typename T>
|
||||
ModbusIsts<T>::ModbusIsts(T* server, int address, int value, const char* description)
|
||||
: ModbusPoint<T>(server, address, value, description){
|
||||
|
||||
}
|
||||
/**
|
||||
* @brief Sets the internal value of the discrete input and marks it as dirty.
|
||||
* @param value The new value for the discrete input.
|
||||
*/
|
||||
template<typename T>
|
||||
void ModbusIsts<T>::setValue(int value){
|
||||
this->_server->Ists(this->_address, value);
|
||||
}
|
||||
/**ss
|
||||
* @brief Gets the current internal value of the discrete input.
|
||||
* @return The current value.
|
||||
*/
|
||||
template<typename T>
|
||||
int ModbusIsts<T>::getValue() const{
|
||||
return this->_server->Ists(this->_address);
|
||||
}
|
||||
/**
|
||||
* @brief Adds the discrete input to the Modbus server's register map.
|
||||
*/
|
||||
template<typename T>
|
||||
void ModbusIsts<T>::addToModbusServer(){
|
||||
this->_server->addIsts(this->_address, this->_value);
|
||||
}
|
||||
|
||||
|
||||
#endif
|
||||
86
lib/Core/Categories/ModbusLongDecorator.h
Normal file
86
lib/Core/Categories/ModbusLongDecorator.h
Normal file
@@ -0,0 +1,86 @@
|
||||
/**
|
||||
* @file ModbusLongDecorator.h
|
||||
* @brief Defines the ModbusLongDecorator class for handling 32-bit long values.
|
||||
* @author Emmanuel Hernandez Cruz
|
||||
* @date 2025-09-05
|
||||
*
|
||||
* This file contains the definition for a decorator that combines two 16-bit
|
||||
* Modbus registers to represent a single 32-bit long integer value.
|
||||
*/
|
||||
#ifndef ModbusLongDecorator_h
|
||||
#define ModbusLongDecorator_h
|
||||
|
||||
#include "ModbusPointDecorator.h"
|
||||
|
||||
/**
|
||||
* @class ModbusLongDecorator
|
||||
* @brief A decorator that combines two 16-bit registers into a 32-bit long.
|
||||
*
|
||||
* This class wraps two consecutive ModbusPoint objects (a low-word and a
|
||||
* high-word point) and treats them as a single 32-bit long integer. It
|
||||
* overrides the necessary methods to handle reading, writing, and value
|
||||
* conversion across both underlying registers.
|
||||
*/
|
||||
template<typename T>
|
||||
class ModbusLongDecorator : public ModbusPointDecorator<T> {
|
||||
public:
|
||||
/**
|
||||
* @brief Constructs a new ModbusLongDecorator object.
|
||||
* @param point A pointer to the ModbusPoint for the low-order word (LSB).
|
||||
* @param highOrderPoint A pointer to the ModbusPoint for the high-order word (MSB).
|
||||
*/
|
||||
ModbusLongDecorator(ModbusPoint<T>* point, ModbusPoint<T>* highOrderPoint)
|
||||
: ModbusPointDecorator<T>(point), _highOrderPoint(highOrderPoint) {}
|
||||
|
||||
/**
|
||||
* @brief Returns the logical type of the point.
|
||||
* @return Always returns `PointType::LONG`.
|
||||
*/
|
||||
PointType getType() const override { return PointType::LONG; }
|
||||
|
||||
// --- Housekeeping Methods ---
|
||||
|
||||
/** @brief Adds both underlying registers to the Modbus server. */
|
||||
void addToModbusServer() override {
|
||||
this->_point->addToModbusServer();
|
||||
_highOrderPoint->addToModbusServer();
|
||||
}
|
||||
|
||||
|
||||
|
||||
// --- Value Getters and Setters ---
|
||||
|
||||
/**
|
||||
* @brief Sets the 32-bit long value by splitting it into two 16-bit words.
|
||||
* This method is an override for the base class and calls `setLongValue`.
|
||||
* @param value The integer value to set (will be cast to long).
|
||||
*/
|
||||
void setValue(int value) override {
|
||||
setLongValue(static_cast<long>(value));
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Sets the 32-bit long value by splitting it into two 16-bit words.
|
||||
* @param value The 32-bit long value to set.
|
||||
*/
|
||||
void setLongValue(long value) {
|
||||
this->_point->setValue(value & 0xFFFF); // Low Word (LSB)
|
||||
_highOrderPoint->setValue((value >> 16) & 0xFFFF); // High Word (MSB)
|
||||
}
|
||||
|
||||
/** @brief Gets the combined 32-bit long value from the two registers. */
|
||||
long getLongValue() const {
|
||||
long lsb = this->_point->getValue();
|
||||
long msb = _highOrderPoint->getValue();
|
||||
return (msb << 16) | lsb;
|
||||
}
|
||||
|
||||
/** @brief Gets the 32-bit long value, cast to an integer. */
|
||||
int getValue() const override {
|
||||
return static_cast<int>(getLongValue());
|
||||
}
|
||||
private:
|
||||
ModbusPoint<T>* _highOrderPoint; /**< @brief Pointer to the ModbusPoint for the high-order word. */
|
||||
};
|
||||
|
||||
#endif
|
||||
101
lib/Core/Categories/ModbusPoint.h
Normal file
101
lib/Core/Categories/ModbusPoint.h
Normal file
@@ -0,0 +1,101 @@
|
||||
/**
|
||||
* @file ModbusPoint.h
|
||||
* @brief Defines the abstract base class for all Modbus points.
|
||||
* @author Emmanuel Hernandez Cruz
|
||||
* @date 2025-09-04
|
||||
*
|
||||
* This file contains the definition of the abstract ModbusPoint class, which
|
||||
* serves as the base for all specific Modbus point types (Coils, Registers, etc.).
|
||||
* It defines the common interface for interacting with Modbus points.
|
||||
*/
|
||||
#ifndef ModbusPoint_h
|
||||
#define ModbusPoint_h
|
||||
#include <string.h>
|
||||
/**
|
||||
* @enum PointType
|
||||
* @brief Identifies the logical type of a Modbus point.
|
||||
*
|
||||
* This enum is used to distinguish between simple points and decorated points
|
||||
* that represent more complex data types like floats or longs.
|
||||
*/
|
||||
enum class PointType {
|
||||
GENERIC, /**< @brief A standard, non-decorated point. */
|
||||
FLOAT, /**< @brief A point decorated to handle 32-bit float values. */
|
||||
LONG, /**< @brief A point decorated to handle 32-bit long integer values. */
|
||||
SCALE /**< @brief A point decorated to apply a scaling factor (e.g., 10x). */
|
||||
};
|
||||
|
||||
/**
|
||||
* @class ModbusPoint
|
||||
* @brief Abstract base class representing a single point in the Modbus map.
|
||||
*
|
||||
* This class defines the common interface and data for all types of Modbus
|
||||
* points. Concrete implementations (e.g., ModbusCoil, ModbusHreg) and decorators
|
||||
* must inherit from this class and implement its pure virtual functions.
|
||||
*/
|
||||
template<typename T>
|
||||
class ModbusPoint{
|
||||
public:
|
||||
/**
|
||||
* @brief Constructs a new ModbusPoint object.
|
||||
* @param server Pointer to the ModbusIP server instance.
|
||||
* @param address The Modbus address of the point.
|
||||
* @param value The initial value of the point.
|
||||
* @param description A descriptive name for the point.
|
||||
*/
|
||||
ModbusPoint(T* server, int address, int value, const char* description);
|
||||
|
||||
// --- Getters ---
|
||||
/** @brief Gets a pointer to the ModbusIP server instance. */
|
||||
T* getServer() const { return _server; }
|
||||
/** @brief Gets the Modbus address of the point. */
|
||||
int getAddress() const { return _address; }
|
||||
/** @brief Gets the initial value assigned to the point at creation. */
|
||||
float getInitialValue() const { return _value; }
|
||||
/** @brief Gets the descriptive name of the point. */
|
||||
const char* getDescription() const { return _description; }
|
||||
|
||||
// --- Virtual Interface ---
|
||||
|
||||
/** @brief Returns the logical type of the point (e.g., FLOAT, LONG). */
|
||||
virtual PointType getType() const { return PointType::GENERIC; }
|
||||
/** @brief Pure virtual function to add the point to the Modbus server's registers. */
|
||||
virtual void addToModbusServer() = 0;
|
||||
/** @brief Pure virtual function to read the point's value from the Modbus server. */
|
||||
|
||||
/** @brief Pure virtual function to set the point's internal value. */
|
||||
virtual void setValue(int value) = 0;
|
||||
/** @brief Pure virtual function to get the point's internal value. */
|
||||
virtual int getValue() const = 0;
|
||||
|
||||
// --- Dirty Flag ---
|
||||
|
||||
/**
|
||||
* @brief Checks if the point's value has changed since the last write.
|
||||
* @return True if the value is dirty, false otherwise.
|
||||
*/
|
||||
bool isDirty() const { return _dirty; }
|
||||
/**
|
||||
* @brief Sets the dirty flag for the point.
|
||||
* @param dirty The new state of the dirty flag.
|
||||
*/
|
||||
void setDirty(bool dirty) { _dirty = dirty; }
|
||||
|
||||
/** @brief Virtual destructor to ensure proper cleanup of derived classes. */
|
||||
virtual ~ModbusPoint() = default;
|
||||
|
||||
protected:
|
||||
T* _server; /**< @brief Pointer to the global ModbusIP server instance. */
|
||||
int _address; /**< @brief The Modbus address of this point. */
|
||||
int _value; /**< @brief The current internal value of this point. */
|
||||
char _description[35]; /**< @brief A descriptive name for this point. */
|
||||
bool _dirty = false; /**< @brief Flag to track if the value has changed and needs to be written. */
|
||||
};
|
||||
|
||||
template<typename T>
|
||||
ModbusPoint<T>::ModbusPoint(T* server, int address, int value, const char* description)
|
||||
: _server(server), _address(address), _value(value) {
|
||||
strncpy(_description, description, sizeof(_description) - 1);
|
||||
_description[sizeof(_description) - 1] = '\0';
|
||||
}
|
||||
#endif
|
||||
60
lib/Core/Categories/ModbusPointDecorator.h
Normal file
60
lib/Core/Categories/ModbusPointDecorator.h
Normal file
@@ -0,0 +1,60 @@
|
||||
/**
|
||||
* @file ModbusPointDecorator.h
|
||||
* @brief Defines the base decorator class for Modbus points.
|
||||
* @author Emmanuel Hernandez Cruz
|
||||
* @date 2025-09-05
|
||||
*
|
||||
* This file contains the definition for ModbusPointDecorator, which is the
|
||||
* abstract base class for all decorators in the Decorator design pattern.
|
||||
* It wraps a ModbusPoint and forwards all calls to it by default.
|
||||
*/
|
||||
#ifndef ModbusPointDecorator_h
|
||||
#define ModbusPointDecorator_h
|
||||
#include "ModbusPoint.h"
|
||||
|
||||
/**
|
||||
* @class ModbusPointDecorator
|
||||
* @brief An abstract base class for decorating ModbusPoint objects.
|
||||
*
|
||||
* This class follows the Decorator pattern. It wraps a `ModbusPoint` object
|
||||
* and provides a default implementation for all virtual methods that simply
|
||||
* delegate the call to the wrapped object. Concrete decorators should inherit
|
||||
* from this class and override the specific methods they need to modify.
|
||||
*/
|
||||
template<typename T>
|
||||
class ModbusPointDecorator : public ModbusPoint<T>{
|
||||
public:
|
||||
/**
|
||||
* @brief Constructs a new ModbusPointDecorator object.
|
||||
*
|
||||
* Initializes the base ModbusPoint with the properties of the wrapped point
|
||||
* and stores a pointer to the wrapped point.
|
||||
*
|
||||
* @param point A pointer to the ModbusPoint object to be decorated.
|
||||
*/
|
||||
ModbusPointDecorator(ModbusPoint<T>* point) : ModbusPoint<T>(
|
||||
point->getServer(),
|
||||
point->getAddress(),
|
||||
point->getInitialValue(),
|
||||
point->getDescription()),
|
||||
_point(point) {}
|
||||
|
||||
// --- Delegated Methods ---
|
||||
// These methods simply forward the call to the wrapped _point object.
|
||||
// Concrete decorators can override them to add new behavior.
|
||||
|
||||
void addToModbusServer() override{
|
||||
_point->addToModbusServer();
|
||||
}
|
||||
|
||||
void setValue(int value) override {
|
||||
_point->setValue(value);
|
||||
}
|
||||
int getValue() const override{
|
||||
return _point->getValue();
|
||||
}
|
||||
|
||||
protected:
|
||||
ModbusPoint<T>* _point; /**< @brief Pointer to the wrapped ModbusPoint object. */
|
||||
};
|
||||
#endif
|
||||
103
lib/Core/Categories/ModbusPointFactory.h
Normal file
103
lib/Core/Categories/ModbusPointFactory.h
Normal file
@@ -0,0 +1,103 @@
|
||||
/**
|
||||
* @file ModbusPointFactory.h
|
||||
* @brief Defines the factory function for creating ModbusPoint objects.
|
||||
* @author Emmanuel Hernandez Cruz
|
||||
* @date 2025-09-05
|
||||
*
|
||||
* This file provides the interface for a factory function that simplifies the
|
||||
* creation of various ModbusPoint types (e.g., Coils, Holding Registers) and
|
||||
* their decorators (e.g., for scaling, float, or long values).
|
||||
*/
|
||||
#ifndef ModbusPointFactory_h
|
||||
#define ModbusPointFactory_h
|
||||
#include "ModbusPoint.h"
|
||||
#include "ModbusCoil.h"
|
||||
#include "ModbusIsts.h"
|
||||
#include "ModbusIreg.h"
|
||||
#include "ModbusHreg.h"
|
||||
#include "ModbusScaleDecorator.h"
|
||||
#include "ModbusLongDecorator.h"
|
||||
#include "ModbusFloatDecorator.h"
|
||||
#include <Arduino.h>
|
||||
|
||||
|
||||
/**
|
||||
* @brief Creates a specific ModbusPoint object based on a category code.
|
||||
*
|
||||
* This factory function acts as a centralized point for instantiating different
|
||||
* concrete ModbusPoint classes and applying decorators. It takes a category
|
||||
* code and other parameters, and returns a pointer to the appropriate object.
|
||||
*
|
||||
* @param server Pointer to the ModbusIP server instance.
|
||||
* @param category An integer code representing the type of Modbus point to create
|
||||
* (e.g., COIL, HR, IR_FLOAT from config.h).
|
||||
* @param address The Modbus address for the point.
|
||||
* @param value The initial value for the point.
|
||||
* @param description A descriptive name for the point.
|
||||
* @return A pointer to a newly created ModbusPoint object. The caller is
|
||||
* responsible for managing the memory of this object. Returns nullptr
|
||||
* if the category is not recognized.
|
||||
*/
|
||||
template<typename T>
|
||||
ModbusPoint<T>* createModbusPoint(T* server, int category, int address, int value, const char* description);
|
||||
|
||||
template<typename T>
|
||||
ModbusPoint<T>* createModbusPoint(T* server, int category, int address, int value, const char* description) {
|
||||
switch (category) {
|
||||
case COIL:
|
||||
Serial.printf("Creating Coil: %s\n", description);
|
||||
return new ModbusCoil<T>(server, address, value, description);
|
||||
|
||||
case DI:
|
||||
Serial.printf("Creating Digital Input: %s\n", description);
|
||||
return new ModbusIsts<T>(server, address, value, description);
|
||||
|
||||
case IR:
|
||||
Serial.printf("Creating Input Register: %s\n", description);
|
||||
return new ModbusIreg<T>(server, address, value, description);
|
||||
|
||||
case IR_10X: {
|
||||
Serial.printf("Creating Input Register 10x: %s\n", description);
|
||||
ModbusPoint<T>* point = new ModbusIreg<T>(server, address, value, description);
|
||||
return new ModbusScaleDecorator<T>(point);
|
||||
}
|
||||
case IR_LONG: {
|
||||
Serial.printf("Creating Input Register Long: %s\n", description);
|
||||
ModbusPoint<T>* point = new ModbusIreg<T>(server, address, 0, description);
|
||||
ModbusPoint<T>* highOrderPoint = new ModbusIreg<T>(server, address + 1, 0, "");
|
||||
return new ModbusLongDecorator<T>(point, highOrderPoint);
|
||||
}
|
||||
case IR_FLOAT: {
|
||||
Serial.printf("Creating Input Register Float: %s\n", description);
|
||||
ModbusPoint<T>* point = new ModbusIreg<T>(server, address, 0, description);
|
||||
ModbusPoint<T>* highOrderPoint = new ModbusIreg<T>(server, address + 1, 0, "");
|
||||
return new ModbusFloatDecorator<T>(point, highOrderPoint);
|
||||
}
|
||||
case HR:
|
||||
Serial.printf("Creating Holding Register: %s\n", description);
|
||||
return new ModbusHreg<T>(server, address, value, description);
|
||||
|
||||
case HR_10x: {
|
||||
Serial.printf("Creating Holding Register 10x: %s\n", description);
|
||||
ModbusPoint<T>* point = new ModbusHreg<T>(server, address, value, description);
|
||||
return new ModbusScaleDecorator<T>(point);
|
||||
}
|
||||
case HR_LONG: {
|
||||
Serial.printf("Creating Holding Register Long: %s\n", description);
|
||||
ModbusPoint<T>* point = new ModbusHreg<T>(server, address, 0, description);
|
||||
ModbusPoint<T>* highOrderPoint = new ModbusHreg<T>(server, address + 1 , 0, "");
|
||||
return new ModbusLongDecorator<T>(point, highOrderPoint);
|
||||
}
|
||||
case HR_FLOAT: {
|
||||
Serial.printf("Creating Holding Register Float: %s\n", description);
|
||||
ModbusPoint<T>* point = new ModbusHreg<T>(server, address, 0, description);
|
||||
ModbusPoint<T>* highOrderPoint = new ModbusHreg<T>(server, address + 1 , 0, "");
|
||||
return new ModbusFloatDecorator<T>(point, highOrderPoint);
|
||||
}
|
||||
default:
|
||||
Serial.printf("ERROR: Unknown Modbus category %d for '%s'\n", category, description);
|
||||
return nullptr;
|
||||
}
|
||||
}
|
||||
|
||||
#endif
|
||||
50
lib/Core/Categories/ModbusScaleDecorator.h
Normal file
50
lib/Core/Categories/ModbusScaleDecorator.h
Normal file
@@ -0,0 +1,50 @@
|
||||
/**
|
||||
* @file ModbusScaleDecorator.h
|
||||
* @brief Defines the ModbusScaleDecorator class for scaling Modbus point values.
|
||||
* @author Emmanuel Hernandez Cruz
|
||||
* @date 2025-09-05
|
||||
*
|
||||
* This file contains the definition for a decorator that applies a 10x scaling
|
||||
* factor to a Modbus point. This is useful for representing decimal values
|
||||
* in integer registers (e.g., storing 12.3 as 123).
|
||||
*/
|
||||
#ifndef ModbusScaleDecorator_h
|
||||
#define ModbusScaleDecorator_h
|
||||
|
||||
#include "ModbusPointDecorator.h"
|
||||
|
||||
/**
|
||||
* @class ModbusScaleDecorator
|
||||
* @brief A decorator that multiplies/divides a Modbus point's value by 10.
|
||||
*
|
||||
* This class wraps a ModbusPoint and intercepts its `getValue` and `setValue`
|
||||
* calls. When setting a value, it multiplies the input by 10 before storing it.
|
||||
* When getting a value, it divides the stored value by 10.
|
||||
*/
|
||||
template<typename T>
|
||||
class ModbusScaleDecorator : public ModbusPointDecorator<T> {
|
||||
public:
|
||||
/**
|
||||
* @brief Constructs a new ModbusScaleDecorator object.
|
||||
* @param point A pointer to the ModbusPoint object to be decorated.
|
||||
*/
|
||||
ModbusScaleDecorator<T>(ModbusPoint<T>* point) : ModbusPointDecorator<T>(point) {}
|
||||
|
||||
/**
|
||||
* @brief Sets the value of the underlying point after scaling it up by 10.
|
||||
* @param value The logical value to set (e.g., 12 for 12.0).
|
||||
*/
|
||||
void setValue(int value) override {
|
||||
this->_point->setValue(value * 10);
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Gets the value from the underlying point after scaling it down by 10.
|
||||
* @return The logical, scaled-down value (e.g., 12 if the stored value is 120).
|
||||
*/
|
||||
int getValue() const override {
|
||||
return this->_point->getValue() / 10;
|
||||
}
|
||||
};
|
||||
|
||||
#endif
|
||||
223
lib/Core/Equipment/Equipment.h
Normal file
223
lib/Core/Equipment/Equipment.h
Normal file
@@ -0,0 +1,223 @@
|
||||
/**
|
||||
* @file Equipment.h
|
||||
* @brief Defines the main Equipment class for the device emulator.
|
||||
* @author Emmanuel Hernandez Cruz
|
||||
* @date 2025-09-02
|
||||
*
|
||||
* This file contains the definition for the Equipment class, which acts as the
|
||||
* central context for the State design pattern. It manages the current state
|
||||
* of the device and holds all of its Modbus points.
|
||||
*/
|
||||
#ifndef Equipment_h
|
||||
#define Equipment_h
|
||||
#include <Arduino.h>
|
||||
#include <map>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
#include "States/State_Standby.h"
|
||||
|
||||
// Forward Declarations
|
||||
template<typename T> class State;
|
||||
template<typename T> class ModbusPoint;
|
||||
|
||||
/**
|
||||
* @class Equipment
|
||||
* @brief The main class representing the emulated device.
|
||||
*
|
||||
* This class orchestrates the device's behavior. It holds a collection of all
|
||||
* Modbus points and manages the device's current operational state (e.g.,
|
||||
* Standby, Running) by delegating actions to a concrete State object.
|
||||
*/
|
||||
template<typename T>
|
||||
class Equipment{
|
||||
public:
|
||||
/**
|
||||
* @brief Constructs a new Equipment object.
|
||||
* Initializes the device in the default initial state (Standby).
|
||||
*/
|
||||
Equipment();
|
||||
Equipment(T* server);
|
||||
/** @brief The main update loop for the equipment, called repeatedly. Delegates to the current state. */
|
||||
void update();
|
||||
/** @brief Delegates the enter state logic to the current state object. */
|
||||
void enterState();
|
||||
/** @brief Delegates the exit state logic to the current state object. */
|
||||
void exitState();
|
||||
/**
|
||||
* @brief Sets a simple integer identifier for the current state.
|
||||
* @param stateId The integer ID representing the state.
|
||||
*/
|
||||
void setState(int stateId);
|
||||
/**
|
||||
* @brief Gets the simple integer identifier for the current state.
|
||||
* @return The integer ID of the state.
|
||||
*/
|
||||
int getState();
|
||||
/**
|
||||
* @brief Reads all the points generated for the equipment from the Modbus server to the objects
|
||||
*/
|
||||
void readAllPoints();
|
||||
/**
|
||||
* @brief Writes all the points generated for the equipment from the objects to the Modbus server
|
||||
*/
|
||||
void writeAllPoints();
|
||||
/**
|
||||
* @brief Transitions the equipment to a new state.
|
||||
* Handles exiting the old state, deleting it, and entering the new one.
|
||||
* @param newState A pointer to the new State object. The Equipment takes ownership.
|
||||
*/
|
||||
void changeState(State<T>* newState);
|
||||
/**
|
||||
* @brief Adds a Modbus point to the equipment's internal map.
|
||||
* @param description The unique string description used as a key.
|
||||
* @param point A pointer to the ModbusPoint object.
|
||||
*/
|
||||
void addModbusPoint(const std::string& description, ModbusPoint<T>* point);
|
||||
/**
|
||||
* @brief Retrieves a Modbus point by its description.
|
||||
* @param description The string key for the Modbus point.
|
||||
* @return A pointer to the ModbusPoint object, or nullptr if not found.
|
||||
*/
|
||||
ModbusPoint<T>* getModbusPoint(const std::string& description);
|
||||
/**
|
||||
* @brief Sets the value of a specific Modbus point.
|
||||
* @param description The string key for the Modbus point.
|
||||
* @param value The value to set.
|
||||
*/
|
||||
void setModbusPoint(const std::string& description, float value);
|
||||
|
||||
private:
|
||||
State<T>* _state; /**< @brief Pointer to the current state object. */
|
||||
std::map<std::string, ModbusPoint<T>*> _points;/**< @brief Map of all Modbus points, keyed by description. */
|
||||
int _stateId; /**< @brief A simple integer identifier for the current state. */
|
||||
std::vector<ModbusPoint<T>*> _allPoints; /**< @brief Vector of all Modbus points. */
|
||||
T* _server;
|
||||
};
|
||||
|
||||
template<typename T>
|
||||
Equipment<T>::Equipment() : _server(nullptr) {
|
||||
this->_state = new StandbyState<T>();
|
||||
this->_state->enterState(this);
|
||||
}
|
||||
|
||||
template<typename T>
|
||||
Equipment<T>::Equipment(T* server)
|
||||
: _server(server)
|
||||
{
|
||||
this->_state = new StandbyState<T>();
|
||||
this->_state->enterState(this);
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief The main update loop for the equipment.
|
||||
*
|
||||
* This method delegates the update logic to the current state object. If the
|
||||
* state's update method returns a pointer to a new state, this method
|
||||
* triggers a state transition.
|
||||
*/
|
||||
template<typename T>
|
||||
void Equipment<T>::update() {
|
||||
State<T>* newState = this->_state->update(this);
|
||||
if (newState != nullptr) {
|
||||
changeState(newState);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Delegates the enter state logic to the current state object.
|
||||
*/
|
||||
template<typename T>
|
||||
void Equipment<T>::enterState() {
|
||||
this->_state->enterState(this);
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Delegates the exit state logic to the current state object.
|
||||
*/
|
||||
template<typename T>
|
||||
void Equipment<T>::exitState() {
|
||||
this->_state->exitState(this);
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Adds a Modbus point to the equipment's internal collections.
|
||||
* The point is added to a map for quick lookup by description and to a
|
||||
* vector for simple iteration.
|
||||
* @param description The unique string description used as a key.
|
||||
* @param point A pointer to the ModbusPoint object.
|
||||
*/
|
||||
template<typename T>
|
||||
void Equipment<T>::addModbusPoint(const std::string& description, ModbusPoint<T>* point) {
|
||||
this->_points[description] = point;
|
||||
this->_allPoints.push_back(point);
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Retrieves a Modbus point by its description.
|
||||
* @param description The string key for the Modbus point.
|
||||
* @return A pointer to the ModbusPoint object, or nullptr if not found.
|
||||
*/
|
||||
template<typename T>
|
||||
ModbusPoint<T>* Equipment<T>::getModbusPoint(const std::string& description) {
|
||||
auto it = this->_points.find(description);
|
||||
if (it != this->_points.end()) {
|
||||
return it->second;
|
||||
}
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Sets the value of a specific Modbus point.
|
||||
* @param description The string key for the Modbus point.
|
||||
* @param value The value to set.
|
||||
*/
|
||||
template<typename T>
|
||||
void Equipment<T>::setModbusPoint(const std::string& description, float value) {
|
||||
ModbusPoint<T>* point = getModbusPoint(description);
|
||||
if (point != nullptr) {
|
||||
point->setValue(value);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Gets the simple integer identifier for the current state.
|
||||
* @return The integer ID of the state.
|
||||
*/
|
||||
template<typename T>
|
||||
int Equipment<T>::getState() {
|
||||
return _stateId;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Sets a simple integer identifier for the current state.
|
||||
* @param stateId The integer ID representing the state.
|
||||
*/
|
||||
template<typename T>
|
||||
void Equipment<T>::setState(int stateId) {
|
||||
this->_stateId = stateId;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Transitions the equipment to a new state.
|
||||
*
|
||||
* This method handles the full lifecycle of a state transition: it calls
|
||||
* `exitState` on the current state, deletes the old state object to prevent
|
||||
* memory leaks, assigns the new state, and finally calls `enterState` on the
|
||||
* new state.
|
||||
*
|
||||
* @param newState A pointer to the new State object. The Equipment takes ownership.
|
||||
*/
|
||||
template<typename T>
|
||||
void Equipment<T>::changeState(State<T>* newState) {
|
||||
if (this->_state != nullptr) {
|
||||
this->_state->exitState(this);
|
||||
delete this->_state;
|
||||
}
|
||||
this->_state = newState;
|
||||
|
||||
if (this->_state != nullptr) {
|
||||
this->_state->enterState(this);
|
||||
}
|
||||
}
|
||||
|
||||
#endif
|
||||
113
lib/Core/README.md
Normal file
113
lib/Core/README.md
Normal file
@@ -0,0 +1,113 @@
|
||||
# Industrial Equipment Emulator
|
||||
|
||||
This project is an Arduino-based emulator for an industrial equipment. It simulates the behavior of a real-world device (like a Computer Room Air Handler - CRAH) and communicates over Wi-Fi using the Modbus IP protocol.
|
||||
|
||||
The primary goal is to provide a flexible and extensible virtual device for testing, development, and training purposes without needing physical hardware.
|
||||
|
||||
## Core Concepts for Automation Professionals
|
||||
|
||||
This software is built using a few key Object-Oriented Programming (OOP) concepts that make it powerful and easy to modify. If you think in terms of control systems, these concepts will feel very familiar.
|
||||
|
||||
### 1. The State Pattern: "What is the machine's current operating mode?"
|
||||
|
||||
In industrial automation, a machine has different operating modes: **Standby**, **Running**, **Alarm/Fault**, **Manual Override**, etc. The machine behaves differently in each mode.
|
||||
|
||||
The **State Pattern** organizes the code to mirror these real-world machine modes.
|
||||
|
||||
* **Analogy:** Think of a PLC program. Instead of having one massive ladder logic routine with dozens of branches checking `IF machine_is_running THEN... ELSE IF machine_is_in_standby THEN...`, you create separate routines for each mode.
|
||||
|
||||
* **How it works here:**
|
||||
* The `Equipment` class is our main "machine".
|
||||
* We have separate classes for each state: `State_Standby`, `State_Running`, `State_Fail`.
|
||||
* The `Equipment` object holds onto the *current* state object (e.g., an instance of `State_Running`).
|
||||
* The main `loop()` simply tells the current state object to `update()`.
|
||||
* All the logic for the running mode is contained entirely within `State_Running.cpp`. All the logic for standby is in `State_Standby.cpp`.
|
||||
|
||||
* **Key Benefit:** To change how the machine behaves in "Running" mode, you only need to modify the `State_Running.cpp` file. You don't have to touch any other part of the system. To add a new "Maintenance" mode, you just create a new `State_Maintenance.cpp` file. This is much safer and easier than editing a giant `if/else` block.
|
||||
|
||||
* **Files to see:**
|
||||
* `States/State.h`: The "template" for all state classes.
|
||||
* `States/State_Running.cpp`: Defines all behavior when the unit is running.
|
||||
* `States/State_Standby.cpp`: Defines all behavior when the unit is in standby.
|
||||
* `Equipment/Equipment.cpp`: The main machine that `changeState()`s between different modes.
|
||||
|
||||
---
|
||||
|
||||
### 2. The Strategy Pattern: "How should this specific value behave?"
|
||||
|
||||
Within a single operating mode (like "Running"), different components might have different behaviors. For example, one fan's speed might be constant, another might ramp up and down, and a sensor reading might fluctuate randomly to simulate real-world conditions.
|
||||
|
||||
The **Strategy Pattern** lets us define these individual behaviors as interchangeable "algorithms" or "strategies".
|
||||
|
||||
* **Analogy:** Think of a function block in a PLC. You might have a `RAMP` block, a `PID` block, or a `SQUARE_WAVE_GENERATOR` block. The Strategy Pattern lets us create these as software objects. We can then "assign" a behavior strategy to a specific Modbus point.
|
||||
|
||||
* **How it works here:**
|
||||
* We have a family of "Strategy" classes: `RampStrategy`, `SawStrategy`, `RandomStrategy`, `SquareStrategy`, etc.
|
||||
* Inside a state file like `State_Running.cpp`, we assign these strategies to specific Modbus points. For example:
|
||||
```cpp
|
||||
// From State_Running.cpp
|
||||
// Assign a ramp behavior to Fan #5
|
||||
addStrategy("Speed EC Fan #5", new RampStrategy(100.0f, 1.5f, 2000));
|
||||
// Assign a random behavior to Fan #4
|
||||
addStrategy("Speed EC Fan #4", new RandomStrategy(1000));
|
||||
// Assign a sawtooth wave behavior to Fan #3
|
||||
addStrategy("Speed EC Fan #3", new SawStrategy(50.0f, 100.0f, 5.0f, 750));
|
||||
```
|
||||
|
||||
* **Key Benefit:** This makes the emulator incredibly dynamic. You can easily change the behavior of any point just by swapping out its strategy. Want Fan #4 to have a square wave pattern instead of random? Just change one line in `State_Running.cpp`. You don't have to rewrite any core logic.
|
||||
|
||||
* **Files to see:**
|
||||
* `Strategies/Strategy_Behavior.h`: The "template" for all behavior strategies.
|
||||
* `Strategies/Strategy_Ramp.h`, `Strategies/Strategy_Saw.h`, etc.: The specific, reusable behavior algorithms.
|
||||
* `States/State_Running.cpp`: Where strategies are assigned to Modbus points for that state.
|
||||
|
||||
---
|
||||
|
||||
### 3. The Decorator Pattern: "How do we handle special data types?"
|
||||
|
||||
Modbus registers are fundamentally just 16-bit integers. However, in the real world, we use these integers to represent many different data types: booleans (coils), scaled integers (e.g., `value * 10`), 32-bit long integers, and 32-bit floating-point numbers.
|
||||
|
||||
The **Decorator Pattern** lets us "wrap" a basic Modbus point to add this extra functionality for handling data types without creating a whole new class for every possible combination.
|
||||
|
||||
* **Analogy:** Think of a basic 4-20mA analog input card. That's your base object. Now, you add a "scaling block" in your PLC to convert the raw 4-20mA signal into a temperature in Celsius. That scaling block is a "Decorator". It doesn't change the input card, it just wraps its output to make it more useful.
|
||||
|
||||
* **How it works here:**
|
||||
* We start with a basic `ModbusPoint` (like `ModbusHreg` for a Holding Register).
|
||||
* If a point needs to be treated as a float, we "decorate" or "wrap" it with a `ModbusFloatDecorator`. This decorator knows how to take two 16-bit registers and combine them into a single 32-bit float value, and vice-versa.
|
||||
* If a point needs to be scaled, we can wrap it with a `ModbusScaleDecorator`.
|
||||
|
||||
* **Key Benefit:** This keeps our code clean and avoids an explosion of classes. We don't need `ModbusFloatHoldingRegister`, `ModbusScaledHoldingRegister`, `ModbusLongInputRegister`, etc. We have our basic point types (`Coil`, `Hreg`, `Ireg`) and we simply "decorate" them with the data handling logic they need. This is all handled automatically by the `ModbusPointFactory`.
|
||||
|
||||
* **Files to see:**
|
||||
* `Categories/ModbusPoint.h`: The base for all points.
|
||||
* `Categories/ModbusPointDecorator.h`: The base "wrapper" class.
|
||||
* `Categories/ModbusFloatDecorator.h`: A specific wrapper that adds floating-point logic.
|
||||
* `Categories/ModbusPointFactory.cpp`: The factory that automatically creates and decorates points based on the `config.h` map.
|
||||
|
||||
## Project Structure
|
||||
|
||||
* `BaseEmulator.ino`: The main entry point of the Arduino program. It handles Wi-Fi setup, initializes the Modbus server, and runs the main loop.
|
||||
* `config.h`: The central configuration file. **This is where you define all the Modbus points for the device.** You set the register type, address, and description here.
|
||||
* `/Equipment`: Contains the `Equipment` class, which represents the overall state machine.
|
||||
* `/Categories`: Contains the classes for different types of Modbus points (`ModbusCoil`, `ModbusHreg`) and the Decorators (`ModbusFloatDecorator`).
|
||||
* `/States`: Contains the different operating modes for the `Equipment` (e.g., `State_Running`).
|
||||
* `/Strategies`: Contains the reusable behavior algorithms for Modbus points (e.g., `Strategy_Ramp`).
|
||||
|
||||
## How to Modify or Extend the Emulator
|
||||
|
||||
1. **To add or change a Modbus point:**
|
||||
* Open `config.h`.
|
||||
* Set Wifi parameters to communicate to the network.
|
||||
* Add a new line to the `mb_map` array, defining its category (e.g., `HR_FLOAT`), address, initial value, and a unique description.
|
||||
|
||||
2. **To change how a point behaves in the "Running" state:**
|
||||
* Open `States/State_Running.cpp`.
|
||||
* In the `RunningState()` constructor, find or add an `addStrategy()` call for that point's description.
|
||||
* Assign it a new or different strategy (e.g., change `new RandomStrategy(...)` to `new SingleValueStrategy(...)`).
|
||||
|
||||
3. **To add a new operating mode (e.g., "Cleaning Cycle"):**
|
||||
* Create new files: `States/State_Cleaning.h` and `States/State_Cleaning.cpp`.
|
||||
* Implement the logic for that mode, including adding strategies for how points should behave.
|
||||
* Update the state-switching logic (e.g., in `State_Running.cpp` or `State_Standby.cpp`) to allow transitioning into your new `CleaningState`.
|
||||
|
||||
---
|
||||
167
lib/Core/States/State.h
Normal file
167
lib/Core/States/State.h
Normal file
@@ -0,0 +1,167 @@
|
||||
/**
|
||||
* @file State.h
|
||||
* @brief Defines the abstract base class for all device states.
|
||||
* @author Emmanuel Hernandez Cruz
|
||||
* @date 2025-09-04
|
||||
*
|
||||
* This file contains the definition of the abstract State class, which is a base
|
||||
* to implement the State Pattern. Concrete states (Standby, Running, Random, Fail, etc.)
|
||||
* will inherit from this class.
|
||||
*/
|
||||
#ifndef State_h
|
||||
#define State_h
|
||||
#include <string>
|
||||
#include <Arduino.h>
|
||||
#include <map>
|
||||
#include "Strategies/Strategy_PID.h"
|
||||
#include "Categories/ModbusFloatDecorator.h"
|
||||
#include "Categories/ModbusPoint.h"
|
||||
|
||||
// Forward Declarations
|
||||
template<typename T>class Equipment;
|
||||
class Strategy_Behavior;
|
||||
|
||||
/**
|
||||
* @class State
|
||||
* @brief Abstract base class for a state in the State design pattern.
|
||||
*
|
||||
* This class defines the interface for all concrete states. It manages a
|
||||
* collection of "strategies" that define how Modbus points behave while the
|
||||
* equipment is in this state.
|
||||
*/
|
||||
template<typename T>
|
||||
class State{
|
||||
public:
|
||||
/**
|
||||
* @brief Virtual destructor.
|
||||
* Cleans up all associated Strategy_Behavior objects.
|
||||
*/
|
||||
virtual ~State();
|
||||
|
||||
/**
|
||||
* @brief Executes the state's logic for one update cycle.
|
||||
* This method applies the state's strategies and checks for transitions.
|
||||
* @param equipment Pointer to the Equipment instance.
|
||||
* @return A pointer to a new State if a transition should occur, otherwise nullptr.
|
||||
*/
|
||||
virtual State* update(Equipment<T>* equipment) = 0;
|
||||
/**
|
||||
* @brief Logic to execute once when entering this state.
|
||||
* @param equipment Pointer to the Equipment instance.
|
||||
*/
|
||||
virtual void enterState(Equipment<T>* equipment) {}
|
||||
/**
|
||||
* @brief Logic to execute once when exiting this state.
|
||||
* @param equipment Pointer to the Equipment instance.
|
||||
*/
|
||||
virtual void exitState(Equipment<T>* equipment) {}
|
||||
/**
|
||||
* @brief Logic to apply all strategies created.
|
||||
* @param equipment Pointer to the Equipment instance.
|
||||
*/
|
||||
virtual void _applyStrategies(Equipment<T>* equipment);
|
||||
|
||||
|
||||
protected:
|
||||
/**
|
||||
* @brief Adds a behavior strategy for a specific Modbus point.
|
||||
* @param pointDescription The description of the Modbus point to apply the strategy to.
|
||||
* @param strategy A pointer to the Strategy_Behavior object. The State will take ownership.
|
||||
*/
|
||||
float getPointValue(Equipment<T>* equipment, const std::string& pointName);
|
||||
void setPointValue(Equipment<T>* equipment, const std::string& pointName, float value);
|
||||
void addStrategy(const std::string& pointDescription, Strategy_Behavior* strategy);
|
||||
std::map<std::string, Strategy_Behavior*> _strategies;
|
||||
};
|
||||
|
||||
template<typename T>
|
||||
State<T>::~State(){
|
||||
for (auto const& pair : this->_strategies) {
|
||||
delete pair.second; // 'second' is the pointer to Strategy_Behavior
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Adds a new strategy to the state's behavior map.
|
||||
*
|
||||
* The State object takes ownership of the strategy pointer and will be
|
||||
* responsible for its deletion.
|
||||
*
|
||||
* @param pointDescription The description of the Modbus point this strategy applies to.
|
||||
* @param strategy A pointer to a Strategy_Behavior object.
|
||||
*/
|
||||
template<typename T>
|
||||
void State<T>::addStrategy(const std::string& pointDescription, Strategy_Behavior* strategy){
|
||||
this->_strategies[pointDescription] = strategy;
|
||||
}
|
||||
|
||||
template<typename T>
|
||||
float State<T>::getPointValue(Equipment<T>* equipment, const std::string& pointName) {
|
||||
ModbusPoint<T>* point = equipment->getModbusPoint(pointName);
|
||||
if (!point) return 0.0f;
|
||||
|
||||
if (point->getType() == PointType::FLOAT) {
|
||||
// If it's a float, cast and get the full float value
|
||||
return static_cast<ModbusFloatDecorator<T>*>(point)->getFloatValue();
|
||||
} else {
|
||||
// Otherwise, get the standard integer value
|
||||
return static_cast<float>(point->getValue());
|
||||
}
|
||||
}
|
||||
|
||||
template<typename T>
|
||||
void State<T>::setPointValue(Equipment<T>* equipment, const std::string& pointName, float value) {
|
||||
ModbusPoint<T>* point = equipment->getModbusPoint(pointName);
|
||||
if (!point) return;
|
||||
|
||||
if (point->getType() == PointType::FLOAT) {
|
||||
static_cast<ModbusFloatDecorator<T>*>(point)->setFloatValue(value);
|
||||
} else {
|
||||
point->setValue(round(value));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Applies all registered strategies for the current state.
|
||||
*
|
||||
* This helper method iterates through all strategies associated with this state.
|
||||
* For each strategy that is ready to run (based on its internal timer), it
|
||||
* retrieves the corresponding Modbus point and applies the new value.
|
||||
* It handles both integer and float point types.
|
||||
*
|
||||
* @param equipment A pointer to the main Equipment object.
|
||||
*/
|
||||
template<typename T>
|
||||
void State<T>::_applyStrategies(Equipment<T>* equipment) {
|
||||
unsigned long currentTime = millis();
|
||||
|
||||
// Use the C++11 compatible for-loop for std::map
|
||||
for (auto const& pair : this->_strategies) {
|
||||
const std::string& description = pair.first;
|
||||
Strategy_Behavior* strategy = pair.second;
|
||||
|
||||
if (strategy->isReady(currentTime)) {
|
||||
ModbusPoint<T>* outputPoint = equipment->getModbusPoint(description);
|
||||
if (!outputPoint) continue;
|
||||
|
||||
float inputValue;
|
||||
|
||||
if (strategy->isPID()) {
|
||||
PIDStrategy* pid = static_cast<PIDStrategy*>(strategy);
|
||||
inputValue = getPointValue(equipment, pid->getInputSensorName());
|
||||
|
||||
ModbusPoint<T>* PIDsetpoint = equipment->getModbusPoint(pid->getSetpointName());
|
||||
if (PIDsetpoint) {
|
||||
pid->setSetpoint(PIDsetpoint->getValue());
|
||||
}
|
||||
} else {
|
||||
inputValue = getPointValue(equipment, description);
|
||||
}
|
||||
|
||||
float newValue = strategy->execute(inputValue);
|
||||
setPointValue(equipment, description, newValue);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#endif
|
||||
50
lib/Core/States/State_Fail.h
Normal file
50
lib/Core/States/State_Fail.h
Normal file
@@ -0,0 +1,50 @@
|
||||
/**
|
||||
* @file State_Fail.h
|
||||
* @brief Defines the FailState class for the device.
|
||||
* @author Emmanuel Hernandez Cruz
|
||||
* @date 2025-09-05
|
||||
*
|
||||
* This file contains the definition for the FailState, which represents
|
||||
* a state where the equipment has encountered an error or fault condition.
|
||||
*/
|
||||
#ifndef Fail_State_h
|
||||
#define Fail_State_h
|
||||
|
||||
#include "State.h" // Include the base class header
|
||||
|
||||
#include <vector>
|
||||
#include <string>
|
||||
|
||||
template<typename T> class Equipment;
|
||||
/**
|
||||
* @class FailState
|
||||
* @brief Represents a failure or alarm state of the equipment.
|
||||
*
|
||||
* In this state, the equipment is in a non-operational fault condition.
|
||||
* It can be configured to apply specific strategies to its Modbus points to
|
||||
* simulate a particular failure scenario (e.g., setting alarm bits, stopping fans).
|
||||
* It waits for a command to transition to another state, such as returning to
|
||||
* Standby after the fault is cleared.
|
||||
*/
|
||||
template<typename T>
|
||||
class FailState : public State<T> {
|
||||
public:
|
||||
/**
|
||||
* @brief Constructs a new FailState object.
|
||||
* This is where strategies for failure behavior would be initialized.
|
||||
*/
|
||||
FailState(const std::vector<std::string>& activeAlarms);
|
||||
|
||||
/**
|
||||
* @brief Executes the fail state's logic for one update cycle.
|
||||
* This method applies the state's strategies and checks for a state transition command.
|
||||
* @param equipment Pointer to the Equipment instance.
|
||||
* @return A pointer to a new State if a transition should occur, otherwise nullptr.
|
||||
*/
|
||||
State<T>* update(Equipment<T>* equipment) override;
|
||||
/** @brief Logic to execute once when entering the fail state. */
|
||||
void enterState(Equipment<T>* equipment) override;
|
||||
/** @brief Logic to execute once when exiting the fail state. */
|
||||
void exitState(Equipment<T>* equipment) override;
|
||||
};
|
||||
#endif
|
||||
47
lib/Core/States/State_Running.h
Normal file
47
lib/Core/States/State_Running.h
Normal file
@@ -0,0 +1,47 @@
|
||||
/**
|
||||
* @file State_Running.h
|
||||
* @brief Defines the RunningState class for the device.
|
||||
* @author Emmanuel Hernandez Cruz
|
||||
* @date 2025-09-05
|
||||
*
|
||||
* This file contains the definition for the RunningState, which represents
|
||||
* the state where the equipment is actively performing its primary function.
|
||||
*/
|
||||
#ifndef Running_State_h
|
||||
#define Running_State_h
|
||||
|
||||
#include "State.h" // Include the base class header
|
||||
template<typename T> class Equipment;
|
||||
|
||||
/**
|
||||
* @class RunningState
|
||||
* @brief Represents the active running state of the equipment.
|
||||
*
|
||||
* In this state, the equipment is fully operational and performing its main
|
||||
* tasks. It applies a set of predefined strategies to its Modbus points to
|
||||
* simulate active behavior (e.g., fans running at various speeds) and waits
|
||||
* for a command to transition to another state.
|
||||
*/
|
||||
template<typename T>
|
||||
class RunningState : public State<T> {
|
||||
public:
|
||||
/**
|
||||
* @brief Constructs a new RunningState object.
|
||||
* Initializes the strategies for various Modbus points that are active
|
||||
* during the running state, such as setting fan speed behaviors.
|
||||
*/
|
||||
RunningState();
|
||||
|
||||
/**
|
||||
* @brief Executes the running state's logic for one update cycle.
|
||||
* This method applies the state's strategies and checks for a state transition command.
|
||||
* @param equipment Pointer to the Equipment instance.
|
||||
* @return A pointer to a new State if a transition should occur, otherwise nullptr.
|
||||
*/
|
||||
State<T>* update(Equipment<T>* equipment) override;
|
||||
/** @brief Logic to execute once when entering the running state. */
|
||||
void enterState(Equipment<T>* equipment) override;
|
||||
/** @brief Logic to execute once when exiting the running state. */
|
||||
void exitState(Equipment<T>* equipment) override;
|
||||
};
|
||||
#endif
|
||||
48
lib/Core/States/State_Standby.h
Normal file
48
lib/Core/States/State_Standby.h
Normal file
@@ -0,0 +1,48 @@
|
||||
/**
|
||||
* @file State_Standby.h
|
||||
* @brief Defines the StandbyState class for the device.
|
||||
* @author Emmanuel Hernandez Cruz
|
||||
* @date 2025-09-05
|
||||
*
|
||||
* This file contains the definition for the StandbyState, which represents
|
||||
* the state where the equipment is idle but ready to start. It defines
|
||||
* specific behaviors for Modbus points while in this state.
|
||||
*/
|
||||
#ifndef Standby_State_h
|
||||
#define Standby_State_h
|
||||
|
||||
#include "State.h" // Include the base class header
|
||||
|
||||
template<typename T> class Equipment;
|
||||
/**
|
||||
* @class StandbyState
|
||||
* @brief Represents the standby state of the equipment.
|
||||
*
|
||||
* In this state, the equipment is operational but not actively running its
|
||||
* primary function. It applies a set of predefined strategies to its Modbus
|
||||
* points to simulate standby behavior and waits for a command to transition
|
||||
* to another state (e.g., Running).
|
||||
*/
|
||||
template<typename T>
|
||||
class StandbyState : public State<T> {
|
||||
public:
|
||||
/**
|
||||
* @brief Constructs a new StandbyState object.
|
||||
* Initializes the strategies for various Modbus points that are active
|
||||
* during the standby state.
|
||||
*/
|
||||
StandbyState();
|
||||
|
||||
/**
|
||||
* @brief Executes the standby state's logic for one update cycle.
|
||||
* This method applies the state's strategies and checks for a state transition command.
|
||||
* @param equipment Pointer to the Equipment instance.
|
||||
* @return A pointer to a new State if a transition should occur, otherwise nullptr.
|
||||
*/
|
||||
State<T>* update(Equipment<T>* equipment) override;
|
||||
/** @brief Logic to execute once when entering the standby state. */
|
||||
void enterState(Equipment<T>* equipment) override;
|
||||
/** @brief Logic to execute once when exiting the standby state. */
|
||||
void exitState(Equipment<T>* equipment) override;
|
||||
};
|
||||
#endif
|
||||
65
lib/Core/Strategies/Strategy_Behavior.h
Normal file
65
lib/Core/Strategies/Strategy_Behavior.h
Normal file
@@ -0,0 +1,65 @@
|
||||
/**
|
||||
* @file Strategy_Behavior.h
|
||||
* @brief Defines the abstract base class for all behavior strategies.
|
||||
* @author Emmanuel Hernandez Cruz
|
||||
* @date 2025-09-05
|
||||
*
|
||||
* This file contains the interface for the Strategy design pattern. All concrete
|
||||
* value-generation algorithms (e.g., Ramp, Saw, Random) will inherit from
|
||||
* the Strategy_Behavior class defined here.
|
||||
*/
|
||||
#ifndef strategy_behavior_h
|
||||
#define strategy_behavior_h
|
||||
|
||||
/**
|
||||
* @class Strategy_Behavior
|
||||
* @brief Abstract base class for a value-generation strategy.
|
||||
*
|
||||
* This class defines the common interface for all strategies. It includes a
|
||||
* pure virtual `execute` method that must be implemented by concrete strategies
|
||||
* and a helper method `isReady` to manage the update timing.
|
||||
*/
|
||||
class Strategy_Behavior {
|
||||
public:
|
||||
/**
|
||||
* @brief Constructs a new Strategy_Behavior object.
|
||||
* @param interval The update interval in milliseconds. The strategy will only
|
||||
* be ready to execute after this interval has passed.
|
||||
*/
|
||||
Strategy_Behavior(unsigned long interval)
|
||||
: _interval(interval), _previousMillis(0) {}
|
||||
|
||||
/**
|
||||
* @brief Virtual destructor.
|
||||
*/
|
||||
virtual ~Strategy_Behavior() = default;
|
||||
|
||||
/**
|
||||
* @brief Pure virtual method to execute the strategy's logic.
|
||||
* Concrete classes must implement this to define their behavior.
|
||||
* @param currentValue The current value of the point, which can be used by the strategy.
|
||||
* @return The newly calculated value.
|
||||
*/
|
||||
virtual float execute(float currentValue) = 0;
|
||||
|
||||
/**
|
||||
* @brief Checks if the strategy's update interval has elapsed.
|
||||
* @param currentMillis The current time from `millis()`.
|
||||
* @return True if the strategy should be executed, false otherwise.
|
||||
*/
|
||||
bool isReady(unsigned long currentMillis) {
|
||||
if (currentMillis - _previousMillis >= _interval) {
|
||||
_previousMillis = currentMillis;
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
virtual bool isPID() const { return false; }
|
||||
|
||||
protected:
|
||||
unsigned long _previousMillis; /**< @brief The timestamp of the last execution. */
|
||||
unsigned long _interval; /**< @brief How often the strategy should run, in milliseconds. */
|
||||
};
|
||||
|
||||
#endif
|
||||
73
lib/Core/Strategies/Strategy_PID.cpp
Normal file
73
lib/Core/Strategies/Strategy_PID.cpp
Normal file
@@ -0,0 +1,73 @@
|
||||
/**
|
||||
* @file Strategy_PID.cpp
|
||||
* @brief Implementation of the PIDStrategy class.
|
||||
* @author Emmanuel Hernandez Cruz
|
||||
* @date 2025-09-08
|
||||
*/
|
||||
#include "Strategy_PID.h"
|
||||
#include <Arduino.h>
|
||||
|
||||
// CORRECTED CONSTRUCTOR
|
||||
// You should pass in your gains here, but for now we'll add setters and initialize to 0.
|
||||
PIDStrategy::PIDStrategy(const std::string& setpointName, unsigned long interval, const std::string& inputSensorName)
|
||||
: Strategy_Behavior(interval), _setpointName(setpointName), _inputSensorName(inputSensorName) {
|
||||
|
||||
_kp = -2.0;
|
||||
_ki = -0.1;
|
||||
_kd = 0.0;
|
||||
_input = 0.0;
|
||||
_lastError = 0.0;
|
||||
_integral = 0.0;
|
||||
_lastTime = millis();
|
||||
}
|
||||
|
||||
// It's good practice to have methods to set your gains
|
||||
void PIDStrategy::setGains(float kp, float ki, float kd) {
|
||||
_kp = kp;
|
||||
_ki = ki;
|
||||
_kd = kd;
|
||||
}
|
||||
|
||||
void PIDStrategy::setSetpoint(float setpoint) {
|
||||
_setpoint = setpoint;
|
||||
}
|
||||
|
||||
// This function is less necessary if execute() takes the current value, but can be used for setting an initial state.
|
||||
void PIDStrategy::setInput(float input) {
|
||||
_input = input;
|
||||
}
|
||||
|
||||
|
||||
float PIDStrategy::execute(float currentValue) {
|
||||
unsigned long now = millis();
|
||||
float timeChange = (float)(now - _lastTime);
|
||||
|
||||
if (timeChange <= 0) {
|
||||
Serial.printf("PID strategy delta time 0.\n");
|
||||
return 0;
|
||||
}
|
||||
|
||||
_input = currentValue;
|
||||
float error = _setpoint - _input;
|
||||
_integral += error * timeChange;
|
||||
if (_integral > 100.0) _integral = 100.0;
|
||||
if (_integral < -100.0) _integral = -100.0;
|
||||
|
||||
float derivative = (error - _lastError) / timeChange;
|
||||
float output = (_kp * error) + (_ki * _integral) + (_kd * derivative);
|
||||
_lastError = error;
|
||||
_lastTime = now;
|
||||
|
||||
if (output > 100.0) output = 100.0;
|
||||
if (output < 0.0) output = 0.0;
|
||||
Serial.printf("PID timeChange: %f.\n", timeChange);
|
||||
Serial.printf("PID _input: %f.\n", _input);
|
||||
Serial.printf("PID error: %f.\n", error);
|
||||
Serial.printf("PID _integral: %f.\n", _integral);
|
||||
Serial.printf("PID derivative: %f.\n", derivative);
|
||||
Serial.printf("PID _kp: %f.\n", _kp);
|
||||
Serial.printf("PID _ki: %f.\n", _ki);
|
||||
Serial.printf("PID _kd: %f.\n", _kd);
|
||||
Serial.printf("PID output: %f.\n", output);
|
||||
return output;
|
||||
}
|
||||
43
lib/Core/Strategies/Strategy_PID.h
Normal file
43
lib/Core/Strategies/Strategy_PID.h
Normal file
@@ -0,0 +1,43 @@
|
||||
// In BaseEmulator/Strategies/Strategy_PID.h
|
||||
|
||||
#ifndef PID_Strategy_h
|
||||
#define PID_Strategy_h
|
||||
|
||||
#include "Strategy_Behavior.h"
|
||||
#include <string>
|
||||
|
||||
class PIDStrategy : public Strategy_Behavior {
|
||||
public:
|
||||
// MODIFIED CONSTRUCTOR: Takes the setpoint, interval, and the name of the input sensor.
|
||||
PIDStrategy(const std::string& setpointName, unsigned long interval, const std::string& inputSensorName);
|
||||
|
||||
float execute(float currentValue) override;
|
||||
|
||||
// Add a getter for the sensor name
|
||||
std::string getInputSensorName() const { return _inputSensorName; }
|
||||
|
||||
std::string getSetpointName() const { return _setpointName; }
|
||||
|
||||
// Add this virtual function to easily identify this strategy as a PID
|
||||
bool isPID() const override { return true; }
|
||||
|
||||
// ... (other methods like setSetpoint, setGains)
|
||||
void setSetpoint(float setpoint);
|
||||
void setGains(float kp, float ki, float kd);
|
||||
void setInput(float input);
|
||||
|
||||
|
||||
private:
|
||||
// ... (PID variables like _kp, _ki, _kd, etc.)
|
||||
float _kp;
|
||||
float _ki;
|
||||
float _kd;
|
||||
unsigned long _lastTime;
|
||||
float _setpoint;
|
||||
float _input;
|
||||
float _lastError;
|
||||
float _integral;
|
||||
std::string _inputSensorName; // <-- Add this to store the name of our input
|
||||
std::string _setpointName; // <-- Add this to store the name of our input
|
||||
};
|
||||
#endif
|
||||
51
lib/Core/Strategies/Strategy_Ramp.cpp
Normal file
51
lib/Core/Strategies/Strategy_Ramp.cpp
Normal file
@@ -0,0 +1,51 @@
|
||||
/**
|
||||
* @file Strategy_Ramp.cpp
|
||||
* @brief Implementation of the RampStrategy class.
|
||||
* @author Emmanuel Hernandez Cruz
|
||||
* @date 2025-09-05
|
||||
*/
|
||||
#include "Strategy_Ramp.h"
|
||||
#include <Arduino.h>
|
||||
/**
|
||||
* @brief Constructs a new RampStrategy object.
|
||||
*
|
||||
* Initializes the ramp strategy by passing the update interval to the
|
||||
* base Strategy_Behavior class and storing the target value and step.
|
||||
*
|
||||
* @param targetValue The destination value for the ramp.
|
||||
* @param step The amount to increment or decrement on each execution.
|
||||
* @param interval The time in milliseconds between each value change.
|
||||
*/
|
||||
RampStrategy::RampStrategy(float targetValue, float step, unsigned long interval)
|
||||
: Strategy_Behavior(interval), _targetValue(targetValue), _step(step) {}
|
||||
|
||||
/**
|
||||
* @brief Calculates the next value in the ramp sequence towards a target.
|
||||
*
|
||||
* This method compares the current value to the target value and returns
|
||||
* the current value incremented or decremented by the step amount. To prevent
|
||||
* overshooting, if the next step would pass the target, it returns the target
|
||||
* value directly. If the target is already reached, it returns the current value.
|
||||
*
|
||||
* @param currentValue The current value, used to determine the next step.
|
||||
* @return The next value in the ramp sequence.
|
||||
*/
|
||||
float RampStrategy::execute(float currentValue) {
|
||||
if (currentValue > _targetValue) {
|
||||
// Prevent overshooting the target when decrementing
|
||||
Serial.println("Ramp strategy going down.");
|
||||
return (currentValue - _step < _targetValue) ? _targetValue : currentValue - _step;
|
||||
} else if (currentValue < _targetValue) {
|
||||
// Prevent overshooting the target when incrementing
|
||||
Serial.println("Ramp strategy going up.");
|
||||
return (currentValue + _step > _targetValue) ? _targetValue : currentValue + _step;
|
||||
} else { // currentValue is already at the target
|
||||
Serial.println("Ramp strategy at target.");
|
||||
return _targetValue;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
void RampStrategy::setTarget(float targetValue) {
|
||||
_targetValue = targetValue;
|
||||
}
|
||||
48
lib/Core/Strategies/Strategy_Ramp.h
Normal file
48
lib/Core/Strategies/Strategy_Ramp.h
Normal file
@@ -0,0 +1,48 @@
|
||||
/**
|
||||
* @file Strategy_Ramp.h
|
||||
* @brief Defines the RampStrategy class for ramping a value towards a target.
|
||||
* @author Emmanuel Hernandez Cruz
|
||||
* @date 2025-09-05
|
||||
*
|
||||
* This file contains the definition for a behavior strategy that incrementally
|
||||
* changes a value until it reaches a specified target value.
|
||||
*/
|
||||
#ifndef Ramp_Strategy_h
|
||||
#define Ramp_Strategy_h
|
||||
|
||||
#include "Strategy_Behavior.h"
|
||||
|
||||
/**
|
||||
* @class RampStrategy
|
||||
* @brief A strategy that moves a value towards a target by a fixed step.
|
||||
*
|
||||
* This class implements the Strategy_Behavior interface to produce a ramping
|
||||
* effect. On each `execute` call, it increments or decrements the current
|
||||
* value by a fixed step until the target value is reached.
|
||||
*/
|
||||
class RampStrategy : public Strategy_Behavior {
|
||||
public:
|
||||
/**
|
||||
* @brief Constructs a new RampStrategy object.
|
||||
* @param targetValue The destination value for the ramp.
|
||||
* @param step The amount to increment or decrement on each execution.
|
||||
* @param interval The time in milliseconds between each value change.
|
||||
*/
|
||||
RampStrategy(float targetValue, float step, unsigned long interval);
|
||||
/**
|
||||
* @brief Executes the strategy to set the target setpoint in the ramp strategy.
|
||||
* @param targetValue The target value that is going to be set.
|
||||
*/
|
||||
void setTarget(float targetValue);
|
||||
/**
|
||||
* @brief Executes the strategy to get the next value in the ramp sequence.
|
||||
* @param currentValue The current value, used to determine the next step.
|
||||
* @return The next value in the ramp sequence.
|
||||
*/
|
||||
float execute(float currentValue) override;
|
||||
|
||||
private:
|
||||
float _targetValue; /**< @brief The target value that the strategy will ramp towards. */
|
||||
float _step; /**< @brief The value to add or subtract on each execution. */
|
||||
};
|
||||
#endif
|
||||
36
lib/Core/Strategies/Strategy_Random.cpp
Normal file
36
lib/Core/Strategies/Strategy_Random.cpp
Normal file
@@ -0,0 +1,36 @@
|
||||
/**
|
||||
* @file Strategy_Random.cpp
|
||||
* @brief Implementation of the RandomStrategy class.
|
||||
* @author Emmanuel Hernandez Cruz
|
||||
* @date 2025-09-05
|
||||
*/
|
||||
#include "Strategy_Random.h"
|
||||
#include <cstdlib>
|
||||
#include <Arduino.h>
|
||||
|
||||
/**
|
||||
* @brief Constructs a new RandomStrategy object.
|
||||
*
|
||||
* Initializes the random strategy by passing the update interval to the
|
||||
* base Strategy_Behavior class.
|
||||
*
|
||||
* @param interval The time in milliseconds between each value generation.
|
||||
*/
|
||||
RandomStrategy::RandomStrategy(unsigned long interval)
|
||||
: Strategy_Behavior(interval) {}
|
||||
|
||||
/**
|
||||
* @brief Generates a new random value between 0.0 and 100.0.
|
||||
*
|
||||
* This method calculates a random integer between 0 and 1000 and divides
|
||||
* it by 10.0 to produce a floating-point number. The `currentValue`
|
||||
* parameter is ignored.
|
||||
*
|
||||
* @param currentValue The current value of the Modbus point (ignored).
|
||||
* @return A random floating-point number between 0.0 and 100.0.
|
||||
*/
|
||||
float RandomStrategy::execute(float currentValue) {
|
||||
int randomNum = rand() % 1001;
|
||||
Serial.println("Random strategy.");
|
||||
return randomNum / 10.0;
|
||||
}
|
||||
37
lib/Core/Strategies/Strategy_Random.h
Normal file
37
lib/Core/Strategies/Strategy_Random.h
Normal file
@@ -0,0 +1,37 @@
|
||||
/**
|
||||
* @file Strategy_Random.h
|
||||
* @brief Defines the RandomStrategy class for generating random values.
|
||||
* @author Emmanuel Hernandez Cruz
|
||||
* @date 2025-09-05
|
||||
*
|
||||
* This file contains the definition for a behavior strategy that generates
|
||||
* a random floating-point number between 0.0 and 100.0.
|
||||
*/
|
||||
#ifndef Random_Strategy_h
|
||||
#define Random_Strategy_h
|
||||
|
||||
#include "Strategy_Behavior.h"
|
||||
|
||||
/**
|
||||
* @class RandomStrategy
|
||||
* @brief A strategy that generates a random value on each execution.
|
||||
*
|
||||
* This class implements the Strategy_Behavior interface to produce a random
|
||||
* value. Each time `execute` is called, it returns a new random float
|
||||
* between 0.0 and 100.0.
|
||||
*/
|
||||
class RandomStrategy : public Strategy_Behavior {
|
||||
public:
|
||||
/**
|
||||
* @brief Constructs a new RandomStrategy object.
|
||||
* @param interval The time in milliseconds between each value generation.
|
||||
*/
|
||||
RandomStrategy(unsigned long interval);
|
||||
/**
|
||||
* @brief Executes the strategy to generate a new random value.
|
||||
* @param currentValue The current value of the Modbus point (ignored).
|
||||
* @return A random floating-point number between 0.0 and 100.0.
|
||||
*/
|
||||
float execute(float currentValue) override;
|
||||
};
|
||||
#endif
|
||||
54
lib/Core/Strategies/Strategy_Saw.cpp
Normal file
54
lib/Core/Strategies/Strategy_Saw.cpp
Normal file
@@ -0,0 +1,54 @@
|
||||
/**
|
||||
* @file Strategy_Saw.cpp
|
||||
* @brief Implementation of the SawStrategy class.
|
||||
* @author Emmanuel Hernandez Cruz
|
||||
* @date 2025-09-05
|
||||
*/
|
||||
#include "Strategy_Saw.h"
|
||||
#include <Arduino.h>
|
||||
/**
|
||||
* @brief Constructs a new SawStrategy object.
|
||||
*
|
||||
* Initializes the sawtooth wave strategy by passing the update interval to the
|
||||
* base Strategy_Behavior class and storing the wave's parameters.
|
||||
*
|
||||
* @param minValue The lower bound of the sawtooth wave.
|
||||
* @param maxValue The upper bound of the sawtooth wave.
|
||||
* @param step The amount to increment or decrement on each execution.
|
||||
* @param interval The time in milliseconds between each value change.
|
||||
*/
|
||||
SawStrategy::SawStrategy(float minValue, float maxValue, float step, unsigned long interval)
|
||||
: Strategy_Behavior(interval), _minValue(minValue), _maxValue(maxValue), _step(step) {}
|
||||
|
||||
void SawStrategy::setMinValue(float minValue) {
|
||||
_minValue = minValue;
|
||||
}
|
||||
|
||||
void SawStrategy::setMaxValue(float maxValue) {
|
||||
_maxValue = maxValue;
|
||||
}
|
||||
/**
|
||||
* @brief Calculates the next value in the sawtooth wave sequence.
|
||||
*
|
||||
* This method checks if the current value has reached the upper or lower
|
||||
* bounds and reverses the direction if necessary. It then returns the
|
||||
* current value incremented or decremented by the step amount.
|
||||
*
|
||||
* @param currentValue The current value, used to determine the next step.
|
||||
* @return The next value in the sawtooth sequence.
|
||||
*/
|
||||
float SawStrategy::execute(float currentValue) {
|
||||
if (currentValue >= _maxValue) {
|
||||
_goingUp = false;
|
||||
} else if (currentValue <= _minValue) {
|
||||
_goingUp = true;
|
||||
}
|
||||
|
||||
if (_goingUp) {
|
||||
Serial.println("Saw Strategy going up.");
|
||||
return currentValue + _step;
|
||||
} else {
|
||||
Serial.println("Saw Strategy going down.");
|
||||
return currentValue - _step;
|
||||
}
|
||||
}
|
||||
54
lib/Core/Strategies/Strategy_Saw.h
Normal file
54
lib/Core/Strategies/Strategy_Saw.h
Normal file
@@ -0,0 +1,54 @@
|
||||
/**
|
||||
* @file Strategy_Saw.h
|
||||
* @brief Defines the SawStrategy class for generating a sawtooth wave pattern.
|
||||
* @author Emmanuel Hernandez Cruz
|
||||
* @date 2025-09-05
|
||||
*
|
||||
* This file contains the definition for a behavior strategy that creates a
|
||||
* sawtooth (or triangular) wave. The value ramps up from a minimum to a
|
||||
* maximum and then ramps back down, repeating the cycle.
|
||||
*/
|
||||
#ifndef Saw_Strategy_h
|
||||
#define Saw_Strategy_h
|
||||
|
||||
#include "Strategy_Behavior.h"
|
||||
|
||||
/**
|
||||
* @class SawStrategy
|
||||
* @brief A strategy that generates a value that moves up and down between two bounds.
|
||||
*
|
||||
* This class implements the Strategy_Behavior interface to produce a sawtooth
|
||||
* wave. On each `execute` call, it increments or decrements the current value
|
||||
* by a fixed step. The direction reverses when the value hits the minimum or
|
||||
* maximum bound.
|
||||
*/
|
||||
class SawStrategy : public Strategy_Behavior {
|
||||
public:
|
||||
/**
|
||||
* @brief Constructs a new SawStrategy object.
|
||||
* @param minValue The lower bound of the sawtooth wave.
|
||||
* @param maxValue The upper bound of the sawtooth wave.
|
||||
* @param step The amount to increment or decrement on each execution.
|
||||
* @param interval The time in milliseconds between each value change.
|
||||
*/
|
||||
SawStrategy(float minValue, float maxValue, float step, unsigned long interval);
|
||||
/**
|
||||
* @brief Executes the strategy to get the next value in the sawtooth wave.
|
||||
* @param currentValue The current value, used to determine the next step.
|
||||
* @return The next value in the sawtooth sequence.
|
||||
*/
|
||||
float execute(float currentValue) override;
|
||||
|
||||
void setMinValue(float minValue);
|
||||
|
||||
void setMaxValue(float maxValue);
|
||||
|
||||
|
||||
|
||||
private:
|
||||
float _minValue; /**< @brief The lower bound of the sawtooth wave. */
|
||||
float _maxValue; /**< @brief The upper bound of the sawtooth wave. */
|
||||
float _step; /**< @brief The value to add or subtract on each execution. */
|
||||
bool _goingUp = true; /**< @brief Tracks the current direction of the wave (up or down). */
|
||||
};
|
||||
#endif
|
||||
45
lib/Core/Strategies/Strategy_SingleValue.cpp
Normal file
45
lib/Core/Strategies/Strategy_SingleValue.cpp
Normal file
@@ -0,0 +1,45 @@
|
||||
/**
|
||||
* @file Strategy_SingleValue.cpp
|
||||
* @brief Implementation of the SingleValueStrategy class.
|
||||
* @author Emmanuel Hernandez Cruz
|
||||
* @date 2025-09-05
|
||||
*/
|
||||
#include "Strategy_SingleValue.h"
|
||||
#include <cstdlib>
|
||||
#include <Arduino.h>
|
||||
/**
|
||||
* @brief Constructs a new SingleValueStrategy object.
|
||||
*
|
||||
* Initializes the strategy by passing the update interval to the base
|
||||
* Strategy_Behavior class and storing the base setpoint value.
|
||||
*
|
||||
* @param setpoint The base value around which noise will be generated.
|
||||
* @param interval The time in milliseconds between each value generation.
|
||||
*/
|
||||
SingleValueStrategy::SingleValueStrategy(float setpoint, float noiseMagnitude, unsigned long interval)
|
||||
: Strategy_Behavior(interval), _setpoint(setpoint), _noiseMagnitude(noiseMagnitude) {}
|
||||
|
||||
void SingleValueStrategy::setSetpoint(float setpoint) {
|
||||
_setpoint = setpoint;
|
||||
}
|
||||
/**
|
||||
* @brief Generates a new value by adding random noise to the setpoint.
|
||||
*
|
||||
* This method calculates a random noise value between -10.0 and +10.0 and
|
||||
* adds it to the stored setpoint. The `currentValue` parameter is ignored.
|
||||
*
|
||||
* @param currentValue The current value of the Modbus point (ignored).
|
||||
* @return The setpoint with added random noise.
|
||||
*/
|
||||
float SingleValueStrategy::execute(float currentValue) {
|
||||
if(_noiseMagnitude <= 0){
|
||||
Serial.println("Single value strategy static.");
|
||||
return _setpoint;
|
||||
}
|
||||
|
||||
int noiseInt = rand() % 201;
|
||||
noiseInt -= 100;
|
||||
float noise = (noiseInt / 100) * _noiseMagnitude;
|
||||
Serial.println("Single value strategy with noise.");
|
||||
return _setpoint + noise;
|
||||
}
|
||||
44
lib/Core/Strategies/Strategy_SingleValue.h
Normal file
44
lib/Core/Strategies/Strategy_SingleValue.h
Normal file
@@ -0,0 +1,44 @@
|
||||
/**
|
||||
* @file Strategy_SingleValue.h
|
||||
* @brief Defines the SingleValueStrategy class for setup a value with noise.
|
||||
* @author Emmanuel Hernandez Cruz
|
||||
* @date 2025-09-05
|
||||
*
|
||||
* This file contains the definition for a behavior strategy that sets the
|
||||
* value to a setpoint and the generates simulates noise with a random number.
|
||||
*/
|
||||
#ifndef SingleValue_strategy_h
|
||||
#define SingleValue_strategy_h
|
||||
#include "Strategy_Behavior.h"
|
||||
|
||||
/**
|
||||
* @class SingleValueStrategy
|
||||
* @brief A strategy that sets a value to a setpoint and generates noise around it.
|
||||
*
|
||||
* This class implements the Strategy_Behavior interface to produce a noise
|
||||
* pattern. Each time `execute` is called, it add a random number (+/-10) to
|
||||
* emulate noise around the value
|
||||
*/
|
||||
class SingleValueStrategy : public Strategy_Behavior {
|
||||
public:
|
||||
/**
|
||||
* @brief Constructs a new SquareStrategy object.
|
||||
* @param setpoiny Target value.
|
||||
* @param interval The time in milliseconds between each value toggle.
|
||||
*/
|
||||
SingleValueStrategy(float setpoint, float noiseMagnitude, unsigned long interval);
|
||||
/**
|
||||
* @brief Executes the strategy to get the next random value around setpoint.
|
||||
* @param currentValue The current value of the Modbus point (ignored in this strategy).
|
||||
* @return The next value in the sequence, either the lower or upper bound.
|
||||
*/
|
||||
float execute(float currentValue) override;
|
||||
|
||||
void setSetpoint(float setpoint);
|
||||
|
||||
|
||||
private:
|
||||
float _setpoint;
|
||||
float _noiseMagnitude;
|
||||
};
|
||||
#endif
|
||||
44
lib/Core/Strategies/Strategy_Square.cpp
Normal file
44
lib/Core/Strategies/Strategy_Square.cpp
Normal file
@@ -0,0 +1,44 @@
|
||||
/**
|
||||
* @file Strategy_Square.cpp
|
||||
* @brief Implementation of the SquareStrategy class.
|
||||
* @author Emmanuel Hernandez Cruz
|
||||
* @date 2025-09-05
|
||||
*/
|
||||
#include "Strategy_Square.h"
|
||||
#include <Arduino.h>
|
||||
/**
|
||||
* @brief Constructs a new SquareStrategy object.
|
||||
*
|
||||
* Initializes the square wave strategy by passing the update interval to the
|
||||
* base Strategy_Behavior class and storing the lower and upper bounds.
|
||||
*
|
||||
* @param lowerValue The lower value of the square wave.
|
||||
* @param upperValue The upper value of the square wave.
|
||||
* @param interval The time in milliseconds between each value toggle.
|
||||
*/
|
||||
SquareStrategy::SquareStrategy(float lowerValue, float upperValue, unsigned long interval)
|
||||
: Strategy_Behavior(interval), _lowerValue(lowerValue), _upperValue(upperValue) {}
|
||||
|
||||
/**
|
||||
* @brief Toggles between the upper and lower values on each execution.
|
||||
* @param currentValue The current value of the Modbus point (ignored).
|
||||
* @return The next value in the square wave sequence.
|
||||
*/
|
||||
void SquareStrategy::setLowerValue(float lowerValue) {
|
||||
_lowerValue = lowerValue;
|
||||
}
|
||||
|
||||
void SquareStrategy::setUpperValue(float upperValue) {
|
||||
_upperValue = upperValue;
|
||||
}
|
||||
|
||||
float SquareStrategy::execute(float currentValue) {
|
||||
_upState = !_upState;
|
||||
if(_upState){
|
||||
Serial.println("Square Strategy high state.");
|
||||
return _upperValue;
|
||||
} else {
|
||||
Serial.println("Square Strategy low state.");
|
||||
return _lowerValue;
|
||||
}
|
||||
}
|
||||
45
lib/Core/Strategies/Strategy_Square.h
Normal file
45
lib/Core/Strategies/Strategy_Square.h
Normal file
@@ -0,0 +1,45 @@
|
||||
/**
|
||||
* @file Strategy_Square.h
|
||||
* @brief Defines the SquareStrategy class for generating a square wave pattern.
|
||||
* @author Emmanuel Hernandez Cruz
|
||||
* @date 2025-09-05
|
||||
*
|
||||
* This file contains the definition for a behavior strategy that alternates
|
||||
* between a lower and an upper value, creating a square wave effect.
|
||||
*/
|
||||
#ifndef square_strategy_h
|
||||
#define square_strategy_h
|
||||
#include "Strategy_Behavior.h"
|
||||
|
||||
/**
|
||||
* @class SquareStrategy
|
||||
* @brief A strategy that alternates between a lower and an upper value on each execution.
|
||||
*
|
||||
* This class implements the Strategy_Behavior interface to produce a square wave
|
||||
* pattern. Each time `execute` is called, it toggles between returning the
|
||||
* `_lowerValue` and the `_upperValue`.
|
||||
*/
|
||||
class SquareStrategy : public Strategy_Behavior {
|
||||
public:
|
||||
/**
|
||||
* @brief Constructs a new SquareStrategy object.
|
||||
* @param lowerValue The lower value of the square wave.
|
||||
* @param upperValue The upper value of the square wave.
|
||||
* @param interval The time in milliseconds between each value toggle.
|
||||
*/
|
||||
SquareStrategy(float lowerValue, float upperValue, unsigned long interval);
|
||||
/**
|
||||
* @brief Executes the strategy to get the next value in the square wave.
|
||||
* @param currentValue The current value of the Modbus point (ignored in this strategy).
|
||||
* @return The next value in the sequence, either the lower or upper bound.
|
||||
*/
|
||||
float execute(float currentValue) override;
|
||||
void setLowerValue(float lowerValue);
|
||||
void setUpperValue(float upperValue);
|
||||
|
||||
private:
|
||||
float _lowerValue; /**< @brief The lower bound of the square wave. */
|
||||
float _upperValue; /**< @brief The upper bound of the square wave. */
|
||||
bool _upState = true; /**< @brief The internal state to track whether to return the upper or lower value. */
|
||||
};
|
||||
#endif
|
||||
38
lib/Core/Strategies/Strategy_Totalizer.cpp
Normal file
38
lib/Core/Strategies/Strategy_Totalizer.cpp
Normal file
@@ -0,0 +1,38 @@
|
||||
/**
|
||||
* @file Strategy_Totalizer.cpp
|
||||
* @brief Implementation of the TotalizerStrategy class.
|
||||
* @author Emmanuel Hernandez Cruz
|
||||
* @date 2025-09-05
|
||||
*/
|
||||
#include "Strategy_Totalizer.h"
|
||||
#include <cstdlib>
|
||||
#include <Arduino.h>
|
||||
/**
|
||||
* @brief Constructs a new TotalizerStrategy object.
|
||||
*
|
||||
* Initializes the square wave strategy by passing the update interval to the
|
||||
* base Strategy_Behavior class and storing the lower and upper bounds.
|
||||
*
|
||||
* @param lowerValue The lower value of the square wave.
|
||||
* @param upperValue The upper value of the square wave.
|
||||
* @param interval The time in milliseconds between each value toggle.
|
||||
*/
|
||||
TotalizerStrategy::TotalizerStrategy(unsigned long interval)
|
||||
: Strategy_Behavior(interval) {
|
||||
int randomNum = rand() % 1001;
|
||||
_currentValue = randomNum;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Toggles between the upper and lower values on each execution.
|
||||
* @param currentValue The current value of the Modbus point (ignored).
|
||||
* @return The next value in the square wave sequence.
|
||||
*/
|
||||
float TotalizerStrategy::execute(float currentValue) {
|
||||
_currentValue += 1;
|
||||
if (_currentValue >60000) {
|
||||
_currentValue = 0;
|
||||
}
|
||||
Serial.println("Totalizer strategy adding up.");
|
||||
return _currentValue;
|
||||
}
|
||||
42
lib/Core/Strategies/Strategy_Totalizer.h
Normal file
42
lib/Core/Strategies/Strategy_Totalizer.h
Normal file
@@ -0,0 +1,42 @@
|
||||
/**
|
||||
* @file Strategy_Square.h
|
||||
* @brief Defines the SquareStrategy class for generating a square wave pattern.
|
||||
* @author Emmanuel Hernandez Cruz
|
||||
* @date 2025-09-05
|
||||
*
|
||||
* This file contains the definition for a behavior strategy that alternates
|
||||
* between a lower and an upper value, creating a square wave effect.
|
||||
*/
|
||||
#ifndef totalizer_strategy_h
|
||||
#define totalizer_strategy_h
|
||||
#include "Strategy_Behavior.h"
|
||||
|
||||
/**
|
||||
* @class SquareStrategy
|
||||
* @brief A strategy that alternates between a lower and an upper value on each execution.
|
||||
*
|
||||
* This class implements the Strategy_Behavior interface to produce a square wave
|
||||
* pattern. Each time `execute` is called, it toggles between returning the
|
||||
* `_lowerValue` and the `_upperValue`.
|
||||
*/
|
||||
class TotalizerStrategy : public Strategy_Behavior {
|
||||
public:
|
||||
/**
|
||||
* @brief Constructs a new SquareStrategy object.
|
||||
* @param lowerValue The lower value of the square wave.
|
||||
* @param upperValue The upper value of the square wave.
|
||||
* @param interval The time in milliseconds between each value toggle.
|
||||
*/
|
||||
TotalizerStrategy(unsigned long interval);
|
||||
/**
|
||||
* @brief Executes the strategy to get the next value in the square wave.
|
||||
* @param currentValue The current value of the Modbus point (ignored in this strategy).
|
||||
* @return The next value in the sequence, either the lower or upper bound.
|
||||
*/
|
||||
float execute(float currentValue) override;
|
||||
|
||||
private:
|
||||
float _currentValue; /**< @brief The lower bound of the square wave. */
|
||||
|
||||
};
|
||||
#endif
|
||||
69
lib/Core/core.h
Normal file
69
lib/Core/core.h
Normal file
@@ -0,0 +1,69 @@
|
||||
/**
|
||||
* @file core.h
|
||||
* @brief Core constants and definitions for the Industrial Emulator project.
|
||||
* @author Emmanuel Hernandez Cruz
|
||||
* @date 2025-09-06
|
||||
*
|
||||
* This file contains shared constants, enumerations, and definitions that are
|
||||
* used across both the main application firmware and the Core library.
|
||||
* Placing these in a central, shared header prevents duplication and makes
|
||||
* configuration easier.
|
||||
* @note This file is intended to be included in the main `.ino` file.
|
||||
*/
|
||||
#ifndef CORE_H
|
||||
#define CORE_H
|
||||
#include "Equipment/Equipment.h"
|
||||
|
||||
// Include the appropriate Modbus library header based on the build flag.
|
||||
// Define USE_MODBUS_IP in your build flags (e.g., platformio.ini) for Modbus IP.
|
||||
// Otherwise, it will default to Modbus RTU.
|
||||
#if defined(USE_MODBUS_IP)
|
||||
#include <ModbusIP_ESP8266.h> // Or your specific Modbus IP library
|
||||
#else
|
||||
#include <ModbusRTU.h> // Or your specific Modbus RTU library
|
||||
#endif
|
||||
|
||||
const int COIL = 0; /**< @brief 0x: R/W Coil */
|
||||
const int DI = 1; /**< @brief 1x: R Discrete Inputs */
|
||||
const int IR = 3; /**< @brief 3x: R Input Register - Single word */
|
||||
const int IR_10X = 31; /**< @brief 3x: R Input Register - Single word, 10x scaled */
|
||||
const int IR_LONG = 32; /**< @brief 3x: R Input Register - Double word, Long type */
|
||||
const int IR_FLOAT = 33; /**< @brief 3x: R Input Register - Double word, Float encoding */
|
||||
const int HR = 4; /**< @brief 4x: R/W Holding Register - Single word */
|
||||
const int HR_10x = 41; /**< @brief 4x: R/W Holding Register - Single word, 10x scaled */
|
||||
const int HR_LONG = 42; /**< @brief 4x: R/W Holding Register - Double word, Long type */
|
||||
const int HR_FLOAT = 43; /**< @brief 4x: R/W Holding Register - Double word, Float encoding */
|
||||
|
||||
/**
|
||||
* @struct modbusMap
|
||||
* @brief Defines the structure for a single entry in the Modbus map.
|
||||
*/
|
||||
struct modbusMap
|
||||
{
|
||||
int category; /**< @brief The Modbus category (e.g., COIL, HR, IR_FLOAT). */
|
||||
int address; /**< @brief The Modbus address (0-9999). */
|
||||
int value; /**< @brief The initial value for the point. */
|
||||
char description[35];/**< @brief A descriptive name for the point. Used as a key for access. */
|
||||
};
|
||||
|
||||
/**
|
||||
* @brief The main loop previous milliseconds.
|
||||
*/
|
||||
unsigned long previousMillis = 0;
|
||||
|
||||
/**
|
||||
* @brief Global Modbus object instance.
|
||||
* The type is determined at compile time based on the USE_MODBUS_IP flag.
|
||||
*/
|
||||
#if defined(USE_MODBUS_IP)
|
||||
extern ModbusIP mb; // Use ModbusIP class
|
||||
/** @brief An instance of the Equipment class, representing the emulated Equipment unit. */
|
||||
Equipment<ModbusIP> EquipmentInstance(&mb);
|
||||
#else
|
||||
extern ModbusRTU mb; // Use ModbusRTU class
|
||||
/** @brief An instance of the Equipment class, representing the emulated Equipment unit. */
|
||||
Equipment<ModbusRTU> EquipmentInstance(&mb);
|
||||
#endif
|
||||
|
||||
|
||||
#endif // CORE_H
|
||||
Reference in New Issue
Block a user