Documentation updated

This commit is contained in:
2025-09-15 09:19:13 -05:00
parent ac20b82496
commit 5a0b02ccdf
41 changed files with 673 additions and 377 deletions

View File

@@ -9,7 +9,6 @@
*/
#ifndef ModbusCoil_h
#define ModbusCoil_h
#include "ModbusPoint.h"
/**
@@ -37,8 +36,6 @@ public:
*/
void addToModbusServer() override;
/**
* @brief Sets the internal value of the coil.
* @param value The new value for the coil.
@@ -50,32 +47,26 @@ public:
* @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){
}
: ModbusPoint<T>(server, address, value, description) {}
/**
* @brief Adds the coil to the Modbus server's register map.
* This method uses the underlying Modbus library to register a new coil
* at the specified address with its initial value.
*/
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.
*
* @brief Sets the value of the coil on the Modbus server.
* This method directly calls the Modbus library function to write the
* new value to the coil's address.
* @param value The new value for the coil.
*/
template<typename T>
@@ -84,7 +75,7 @@ void ModbusCoil<T>::setValue(int value){
}
/**
* @brief Gets the current internal value of the coil.
* @brief Gets the current value of the coil from the Modbus server.
* @return The current value.
*/
template<typename T>

View File

@@ -16,9 +16,9 @@
* @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.
* This union allows for type-punning between a `float` and an array of two
* `int16_t` values. This simplifies splitting a float into high and low words
* for Modbus transmission or reconstructing it from two registers.
*/
typedef union{
float v; /**< @brief The value as a 32-bit float. */
@@ -39,7 +39,7 @@ 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 point A pointer to the ModbusPoint for the low-order word (LSW).
* @param highOrderPoint A pointer to the ModbusPoint for the high-order word.
*/
ModbusFloatDecorator(ModbusPoint<T>* point, ModbusPoint<T>* highOrderPoint)
@@ -63,10 +63,10 @@ public:
* @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.
* and then writes these values to the two underlying Modbus points.
*
* @note The order of `as_int[0]` (LSW) and `as_int[1]` (MSW) 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) {
@@ -87,15 +87,16 @@ public:
* @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.
* Modbus 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());
cracked_float_t buffer;
// Read the two 16-bit words from the underlying points and combine them.
// Note: This assumes a specific word order (endianness).
buffer.as_int[0] = this->_point->getValue();
buffer.as_int[1] = _highOrderPoint->getValue();
return buffer.v;
}
@@ -107,8 +108,6 @@ public:
_highOrderPoint->addToModbusServer();
}
private:
ModbusPoint<T>* _highOrderPoint; /**< @brief Pointer to the ModbusPoint for the high-order word. */
};

View File

@@ -40,13 +40,13 @@ public:
/**
* @brief Sets the internal value of the holding register.
* @brief Sets the value of the holding register on the Modbus server.
* @param value The new value for the holding register.
*/
void setValue(int value) override;
/**
* @brief Gets the current internal value of the holding register.
* @brief Gets the current value of the holding register from the Modbus server.
* @return The current value of the holding register.
*/
int getValue() const override;
@@ -58,16 +58,31 @@ template<typename T>
ModbusHreg<T>::ModbusHreg(T* server, int address, int value, const char* description)
: ModbusPoint<T>(server, address, value, description) {}
/**
* @brief Adds the holding register to the Modbus server's register map.
* This method uses the underlying Modbus library to register a new holding
* register at the specified address with its initial value.
*/
template<typename T>
void ModbusHreg<T>::addToModbusServer() {
this->_server->addHreg(this->_address, this->_value);
}
/**
* @brief Sets the value of the holding register on the Modbus server.
* This method directly calls the Modbus library function to write the
* new value to the holding register's address.
* @param value The new 16-bit value for the register.
*/
template<typename T>
void ModbusHreg<T>::setValue(int value) {
this->_server->Hreg(this->_address, value);
}
/**
* @brief Gets the current value of the holding register from the Modbus server.
* @return The current 16-bit value from the register.
*/
template<typename T>
int ModbusHreg<T>::getValue() const {
return this->_server->Hreg(this->_address);

View File

@@ -36,14 +36,14 @@ public:
* @brief Adds the input register to the Modbus server.
*/
void addToModbusServer() override;
/**
* @brief Sets the internal value of the input register.
* @brief Sets the value of the input register on the Modbus server.
* @param value The new value for the input register.
*/
void setValue(int value) override;
/**
* @brief Gets the current internal value of the input register.
* @brief Gets the current value of the input register from the Modbus server.
* @return The current value of the input register.
*/
int getValue() const override;
@@ -51,20 +51,22 @@ public:
template<typename T>
ModbusIreg<T>::ModbusIreg(T* server, int address, int value, const char* description)
: ModbusPoint<T>(server, address, value, 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.
* @brief Sets the value of the input register on the Modbus server.
* This method directly calls the Modbus library function to write the
* new value to the input register's address. This is how the emulator's
* internal logic updates the value that a Modbus master can read.
* @param value The new 16-bit value for the 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.
* @brief Gets the current value of the input register from the Modbus server.
* @return The current 16-bit value from the register.
*/
template<typename T>
int ModbusIreg<T>::getValue() const {
@@ -73,6 +75,8 @@ int ModbusIreg<T>::getValue() const {
/**
* @brief Adds the input register to the Modbus server's register map.
* This method uses the underlying Modbus library to register a new input
* register at the specified address with its initial value.
*/
template<typename T>
void ModbusIreg<T>::addToModbusServer(){

View File

@@ -36,14 +36,14 @@ public:
* @brief Adds the discrete input to the Modbus server.
*/
void addToModbusServer() override;
/**
* @brief Sets the internal value of the discrete input.
* @brief Sets the value of the discrete input on the Modbus server.
* @param value The new value for the discrete input.
*/
void setValue(int value) override;
/**
* @brief Gets the current internal value of the discrete input.
* @brief Gets the current value of the discrete input from the Modbus server.
* @return The current value of the discrete input.
*/
int getValue() const override;
@@ -52,19 +52,21 @@ public:
template<typename T>
ModbusIsts<T>::ModbusIsts(T* server, int address, int value, const char* description)
: ModbusPoint<T>(server, address, value, description){
: ModbusPoint<T>(server, address, value, description) {}
}
/**
* @brief Sets the internal value of the discrete input and marks it as dirty.
* @brief Sets the value of the discrete input on the Modbus server.
* This method directly calls the Modbus library function to write the
* new value to the discrete input's address. This is how the emulator's
* internal logic updates the value that a Modbus master can read.
* @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.
/**
* @brief Gets the current value of the discrete input from the Modbus server.
* @return The current value.
*/
template<typename T>
@@ -73,11 +75,12 @@ int ModbusIsts<T>::getValue() const{
}
/**
* @brief Adds the discrete input to the Modbus server's register map.
* This method uses the underlying Modbus library to register a new discrete
* input at the specified address with its initial value.
*/
template<typename T>
void ModbusIsts<T>::addToModbusServer(){
this->_server->addIsts(this->_address, this->_value);
}
#endif

View File

@@ -25,9 +25,9 @@ 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).
* @brief Constructs a new ModbusLongDecorator.
* @param point A pointer to the ModbusPoint for the low-order word (LSW).
* @param highOrderPoint A pointer to the ModbusPoint for the high-order word (MSW).
*/
ModbusLongDecorator(ModbusPoint<T>* point, ModbusPoint<T>* highOrderPoint)
: ModbusPointDecorator<T>(point), _highOrderPoint(highOrderPoint) {}
@@ -61,18 +61,29 @@ public:
/**
* @brief Sets the 32-bit long value by splitting it into two 16-bit words.
*
* This method uses bitwise operations to extract the low word (Least
* Significant Word) and the high word (Most Significant Word) from the
* 32-bit long value. It then writes these 16-bit words to their
* respective underlying Modbus points.
*
* @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)
this->_point->setValue(value & 0xFFFF); // Low Word (LSW)
_highOrderPoint->setValue((value >> 16) & 0xFFFF); // High Word (MSW)
}
/** @brief Gets the combined 32-bit long value from the two registers. */
/**
* @brief Gets the combined 32-bit long value from the two registers.
* This method reads the 16-bit values from the two underlying Modbus points
* and reconstructs the 32-bit long value using bitwise operations.
* @return The reconstructed 32-bit long value.
*/
long getLongValue() const {
long lsb = this->_point->getValue();
long msb = _highOrderPoint->getValue();
return (msb << 16) | lsb;
long lsw = this->_point->getValue();
long msw = _highOrderPoint->getValue();
return (msw << 16) | lsw;
}
/** @brief Gets the 32-bit long value, cast to an integer. */

View File

@@ -38,7 +38,7 @@ class ModbusPoint{
public:
/**
* @brief Constructs a new ModbusPoint object.
* @param server Pointer to the ModbusIP server instance.
* @param server Pointer to the Modbus server instance (e.g., ModbusIP or ModbusRTU).
* @param address The Modbus address of the point.
* @param value The initial value of the point.
* @param description A descriptive name for the point.
@@ -46,12 +46,12 @@ public:
ModbusPoint(T* server, int address, int value, const char* description);
// --- Getters ---
/** @brief Gets a pointer to the ModbusIP server instance. */
/** @brief Gets a pointer to the Modbus 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; }
int getInitialValue() const { return _value; }
/** @brief Gets the descriptive name of the point. */
const char* getDescription() const { return _description; }
@@ -59,13 +59,12 @@ public:
/** @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. */
/** @brief Pure virtual function to add the point to the Modbus server's register map. */
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. */
/** @brief Pure virtual function to set the point's value on the Modbus server. */
virtual void setValue(int value) = 0;
/** @brief Pure virtual function to get the point's internal value. */
/** @brief Pure virtual function to get the point's value from the Modbus server. */
virtual int getValue() const = 0;
// --- Dirty Flag ---
@@ -85,7 +84,7 @@ public:
virtual ~ModbusPoint() = default;
protected:
T* _server; /**< @brief Pointer to the global ModbusIP server instance. */
T* _server; /**< @brief Pointer to the global Modbus 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. */

View File

@@ -30,6 +30,9 @@ public:
* Initializes the base ModbusPoint with the properties of the wrapped point
* and stores a pointer to the wrapped point.
*
* @note The decorator does not take ownership of the wrapped point. The
* caller is responsible for managing its lifecycle.
*
* @param point A pointer to the ModbusPoint object to be decorated.
*/
ModbusPointDecorator(ModbusPoint<T>* point) : ModbusPoint<T>(
@@ -38,18 +41,37 @@ public:
point->getInitialValue(),
point->getDescription()),
_point(point) {}
/**
* @brief Virtual destructor.
* Does not delete the wrapped `_point` as it does not own it.
*/
virtual ~ModbusPointDecorator() = default;
// --- Delegated Methods ---
// These methods simply forward the call to the wrapped _point object.
// Concrete decorators can override them to add new behavior.
/**
* @brief Delegates the call to add the point to the Modbus server.
* Forwards the `addToModbusServer` call to the wrapped `ModbusPoint` object.
*/
void addToModbusServer() override{
_point->addToModbusServer();
}
/**
* @brief Delegates the call to set the point's value.
* Forwards the `setValue` call to the wrapped `ModbusPoint` object.
*/
void setValue(int value) override {
_point->setValue(value);
}
/**
* @brief Delegates the call to get the point's value.
* Forwards the `getValue` call to the wrapped `ModbusPoint` object.
* @return The value from the wrapped point.
*/
int getValue() const override{
return _point->getValue();
}

View File

@@ -22,25 +22,37 @@
/**
* @brief Creates a specific ModbusPoint object based on a category code.
* @brief Creates and decorates a ModbusPoint object based on its type.
*
* 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.
* concrete ModbusPoint classes and applying decorators (e.g., for scaling,
* floats, or longs). It encapsulates the logic for building both simple
* single-register points and complex multi-register points.
*
* @param server Pointer to the ModbusIP server instance.
* @tparam T The type of the Modbus server object (e.g., ModbusIP, ModbusRTU).
* @param server Pointer to the Modbus 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.
* (e.g., COIL, HR, HR_FLOAT).
* @param address The starting Modbus address for the point. For multi-register
* types (float, long), this factory will also use `address + 1`.
* @param value The initial value for the point. Note: This is ignored for
* multi-register types, which are initialized to 0.
* @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.
* @return A pointer to the newly created ModbusPoint object.
* @retval ModbusPoint* A pointer to the fully constructed (and possibly
* decorated) Modbus point. The caller is responsible for
* managing the memory of this object.
* @retval nullptr If the category code is not recognized.
*/
template<typename T>
ModbusPoint<T>* createModbusPoint(T* server, int category, int address, int value, const char* description);
/**
* @brief Implementation of the ModbusPoint factory function.
*
* This function contains the switch-case logic to determine which concrete
* ModbusPoint class to instantiate and which decorators to apply.
*/
template<typename T>
ModbusPoint<T>* createModbusPoint(T* server, int category, int address, int value, const char* description) {
switch (category) {
@@ -57,18 +69,20 @@ ModbusPoint<T>* createModbusPoint(T* server, int category, int address, int valu
return new ModbusIreg<T>(server, address, value, description);
case IR_10X: {
Serial.printf("Creating Input Register 10x: %s\n", description);
Serial.printf("Creating Scaled 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);
// Create the low and high word registers for the 32-bit long
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);
// Create the low and high word registers for the 32-bit float
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);
@@ -78,18 +92,21 @@ ModbusPoint<T>* createModbusPoint(T* server, int category, int address, int valu
return new ModbusHreg<T>(server, address, value, description);
case HR_10x: {
Serial.printf("Creating Holding Register 10x: %s\n", description);
Serial.printf("Creating Scaled Holding Register (10x): %s\n", description);
// Create a base holding register and wrap it with the scaling decorator
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);
// Create the low and high word registers for the 32-bit long
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);
// Create the low and high word registers for the 32-bit float
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);

View File

@@ -18,29 +18,39 @@
* @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.
* calls to implement fixed-point arithmetic. It allows a 16-bit integer
* register to represent a value with one decimal place (e.g., storing the
* logical value 12.3 as the integer 123).
*
* - `setValue(123)` will store the integer `123` in the underlying point.
* - `getValue()` will read `123` from the underlying point and return `12`.
*/
template<typename T>
class ModbusScaleDecorator : public ModbusPointDecorator<T> {
public:
/**
* @brief Constructs a new ModbusScaleDecorator object.
* @brief Constructs a new ModbusScaleDecorator.
* @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).
* @brief Sets the raw integer value on the underlying point.
* This method directly passes the provided integer value to the wrapped
* Modbus point. It is intended to be used with values that are already
* scaled (e.g., to set a logical value of 25.5, call `setValue(255)`).
* @param value The scaled integer value to store (e.g., 123 to represent 12.3).
*/
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).
* @brief Gets the integer part of the logical value.
* This method retrieves the raw integer from the underlying point and
* divides it by 10 to get the integer component of the logical value.
* @return The integer part of the logical value (e.g., returns 12 if the
* stored value is 123).
*/
int getValue() const override {
return this->_point->getValue() / 10;

View File

@@ -29,13 +29,14 @@ template<typename T> class ModbusPoint;
* Standby, Running) by delegating actions to a concrete State object.
*/
template<typename T>
class Equipment{
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();
@@ -53,14 +54,6 @@ public:
* @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.
@@ -82,15 +75,15 @@ public:
/**
* @brief Sets the value of a specific Modbus point.
* @param description The string key for the Modbus point.
* @param value The value to set.
* @param value The value to set. Note: This float may be truncated or cast
* depending on the underlying point's `setValue` implementation.
*/
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. */
int _stateId; /**< @brief A simple integer identifier for the current state. */
T* _server;
};
@@ -100,6 +93,10 @@ Equipment<T>::Equipment() : _server(nullptr) {
this->_state->enterState(this);
}
/**
* @brief Constructs a new Equipment object with a server instance.
* @param server Pointer to the Modbus server instance (e.g., ModbusIP, ModbusRTU).
*/
template<typename T>
Equipment<T>::Equipment(T* server)
: _server(server)
@@ -149,7 +146,6 @@ void Equipment<T>::exitState() {
template<typename T>
void Equipment<T>::addModbusPoint(const std::string& description, ModbusPoint<T>* point) {
this->_points[description] = point;
this->_allPoints.push_back(point);
}
/**
@@ -168,8 +164,9 @@ ModbusPoint<T>* Equipment<T>::getModbusPoint(const std::string& description) {
/**
* @brief Sets the value of a specific Modbus point.
* Finds the point by its description and calls its `setValue` method.
* @param description The string key for the Modbus point.
* @param value The value to set.
* @param value The value to set. This float is cast to an int before being passed.
*/
template<typename T>
void Equipment<T>::setModbusPoint(const std::string& description, float value) {

View File

@@ -1,113 +0,0 @@
# 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`.
---

View File

@@ -56,7 +56,7 @@ public:
*/
virtual void exitState(Equipment<T>* equipment) {}
/**
* @brief Logic to apply all strategies created.
* @brief Applies all registered strategies for the current state.
* @param equipment Pointer to the Equipment instance.
*/
virtual void _applyStrategies(Equipment<T>* equipment);
@@ -64,14 +64,30 @@ public:
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.
* @brief Gets the value of a Modbus point, handling float types correctly.
* This is a helper function to safely read a value from a point, whether it's
* a standard integer register or a `ModbusFloatDecorator`.
* @param equipment Pointer to the Equipment instance.
* @param pointName The description key of the Modbus point to read.
* @return The value of the point as a float. Returns 0.0f if not found.
*/
float getPointValue(Equipment<T>* equipment, const std::string& pointName);
/**
* @brief Sets the value of a Modbus point, handling float types correctly.
* This is a helper function to safely write a value to a point, whether it's
* a standard integer register or a `ModbusFloatDecorator`.
* @param equipment Pointer to the Equipment instance.
* @param pointName The description key of the Modbus point to write to.
* @param value The float value to set. It will be rounded for integer points.
*/
void setPointValue(Equipment<T>* equipment, const std::string& pointName, float value);
/**
* @brief Adds a behavior strategy for a specific Modbus point in this state.
* @param pointDescription The description of the Modbus point to apply the strategy to.
* @param strategy A pointer to the Strategy_Behavior object. The State takes ownership.
*/
void addStrategy(const std::string& pointDescription, Strategy_Behavior* strategy);
std::map<std::string, Strategy_Behavior*> _strategies;
std::map<std::string, Strategy_Behavior*> _strategies; /**< @brief Map of strategies active in this state, keyed by point description. */
};
template<typename T>
@@ -95,6 +111,15 @@ void State<T>::addStrategy(const std::string& pointDescription, Strategy_Behavio
this->_strategies[pointDescription] = strategy;
}
/**
* @brief Gets the value of a Modbus point, correctly handling float types.
* This helper function checks if the point is a `ModbusFloatDecorator` and calls
* `getFloatValue()` if it is. Otherwise, it gets the standard integer value and
* casts it to a float.
* @param equipment Pointer to the Equipment instance.
* @param pointName The description key of the Modbus point.
* @return The point's value as a float. Returns 0.0f if the point is not found.
*/
template<typename T>
float State<T>::getPointValue(Equipment<T>* equipment, const std::string& pointName) {
ModbusPoint<T>* point = equipment->getModbusPoint(pointName);
@@ -109,6 +134,15 @@ float State<T>::getPointValue(Equipment<T>* equipment, const std::string& pointN
}
}
/**
* @brief Sets the value of a Modbus point, correctly handling float types.
* This helper function checks if the point is a `ModbusFloatDecorator` and calls
* `setFloatValue()` if it is. Otherwise, it rounds the float to the nearest
* integer and calls the standard `setValue()`.
* @param equipment Pointer to the Equipment instance.
* @param pointName The description key of the Modbus point.
* @param value The value to set.
*/
template<typename T>
void State<T>::setPointValue(Equipment<T>* equipment, const std::string& pointName, float value) {
ModbusPoint<T>* point = equipment->getModbusPoint(pointName);

View File

@@ -30,21 +30,33 @@ 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.
* @brief Constructs a new FailState object with a list of active alarms.
* @param activeAlarms A vector of strings, where each string is the
* description of a Modbus point to be set as an active alarm.
*/
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.
* This method applies any failure-related strategies and checks for a
* command to clear the alarm (e.g., via a Modbus write), which would
* trigger a transition back to a safe state like Standby.
* @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. */
/**
* @brief Logic to execute once when entering the fail state.
* Typically sets alarm bits and brings the equipment to a safe, non-operational condition.
*/
void enterState(Equipment<T>* equipment) override;
/** @brief Logic to execute once when exiting the fail state. */
/**
* @brief Logic to execute once when exiting the fail state.
* Typically clears alarm bits before transitioning to the next state.
*/
void exitState(Equipment<T>* equipment) override;
private:
std::vector<std::string> _activeAlarms; /**< @brief Stores the descriptions of points to be set as active alarms. */
};
#endif

View File

@@ -34,14 +34,26 @@ public:
/**
* @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.
* This method applies all active strategies (e.g., for fan speeds, temperatures)
* and checks for conditions that would trigger a state transition, such as a
* command to stop or a fault condition.
* @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. */
/**
* @brief Logic to execute once when entering the running state.
* Typically sets status bits to indicate the equipment is active (e.g.,
* setting an "On/Off" point to 1).
* @param equipment Pointer to the Equipment instance.
*/
void enterState(Equipment<T>* equipment) override;
/** @brief Logic to execute once when exiting the running state. */
/**
* @brief Logic to execute once when exiting the running state.
* Typically resets status bits to indicate the equipment is no longer
* active before transitioning to the next state.
* @param equipment Pointer to the Equipment instance.
*/
void exitState(Equipment<T>* equipment) override;
};
#endif

View File

@@ -35,14 +35,27 @@ public:
/**
* @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.
* This method applies any standby-specific strategies and checks for conditions
* that would trigger a state transition, such as a "start" command received
* via a Modbus write.
* @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. */
/**
* @brief Logic to execute once when entering the standby state.
* Typically sets status bits to indicate the equipment is idle (e.g.,
* setting an "On/Off" point to 0).
* @param equipment Pointer to the Equipment instance.
*/
void enterState(Equipment<T>* equipment) override;
/** @brief Logic to execute once when exiting the standby state. */
/**
* @brief Logic to execute once when exiting the standby state.
* This method is called just before transitioning to a new state. It can be
* used to perform any cleanup specific to the standby state before the new
* state's `enterState` is called.
* @param equipment Pointer to the Equipment instance.
*/
void exitState(Equipment<T>* equipment) override;
};
#endif

View File

@@ -31,6 +31,7 @@ public:
/**
* @brief Virtual destructor.
* Ensures that derived strategy objects are properly destroyed.
*/
virtual ~Strategy_Behavior() = default;
@@ -44,6 +45,9 @@ public:
/**
* @brief Checks if the strategy's update interval has elapsed.
* This method manages the execution frequency of the strategy. It should be
* called in each update loop to determine if it's time to execute the
* strategy's logic again.
* @param currentMillis The current time from `millis()`.
* @return True if the strategy should be executed, false otherwise.
*/
@@ -55,6 +59,12 @@ public:
return false;
}
/**
* @brief Identifies if the strategy is a PID controller.
* This virtual method provides a way to check for a specific strategy type
* without using `dynamic_cast`. It is overridden by `PIDStrategy` to return true.
* @return `false` for all non-PID strategies, `true` for PID strategies.
*/
virtual bool isPID() const { return false; }
protected:

View File

@@ -7,8 +7,15 @@
#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.
/**
* @brief Constructs a new PIDStrategy object.
* Initializes the PID controller with default gains and stores the names of the
* Modbus points used for the setpoint and the process variable input.
* @param setpointName The description key for the Modbus point that holds the setpoint value.
* @param interval The update interval in milliseconds, passed to the base class.
* @param inputSensorName The description key for the Modbus point that provides the
* process variable (the input to the PID controller).
*/
PIDStrategy::PIDStrategy(const std::string& setpointName, unsigned long interval, const std::string& inputSensorName)
: Strategy_Behavior(interval), _setpointName(setpointName), _inputSensorName(inputSensorName) {
@@ -21,23 +28,47 @@ PIDStrategy::PIDStrategy(const std::string& setpointName, unsigned long interval
_lastTime = millis();
}
// It's good practice to have methods to set your gains
/**
* @brief Sets the gains for the PID controller.
* @param kp The proportional gain (P). Determines the reaction to the current error.
* @param ki The integral gain (I). Determines the reaction based on the sum of recent errors.
* @param kd The derivative gain (D). Determines the reaction based on the rate at which the error has been changing.
*/
void PIDStrategy::setGains(float kp, float ki, float kd) {
_kp = kp;
_ki = ki;
_kd = kd;
}
/**
* @brief Updates the target setpoint for the PID controller.
* This value is typically read from a Modbus register in the `_applyStrategies` loop.
* @param setpoint The new target value for the process variable.
*/
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.
/**
* @brief Manually sets the process variable (input) value.
* @note This is typically not needed as the `execute` method receives the current
* input value on each call from the `_applyStrategies` loop.
* @param input The new process variable value.
*/
void PIDStrategy::setInput(float input) {
_input = input;
}
/**
* @brief Executes one cycle of the PID control algorithm.
*
* This method calculates the error between the setpoint and the current input,
* computes the proportional, integral (with anti-windup), and derivative terms,
* and returns a new control output value. The final output is clamped between 0.0 and 100.0.
*
* @param currentValue The current process variable (e.g., temperature) read from the input sensor.
* @return The calculated control output (e.g., fan speed), clamped between 0.0 and 100.0.
*/
float PIDStrategy::execute(float currentValue) {
unsigned long now = millis();
float timeChange = (float)(now - _lastTime);
@@ -60,14 +91,6 @@ float PIDStrategy::execute(float currentValue) {
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;
}

View File

@@ -1,4 +1,13 @@
// In BaseEmulator/Strategies/Strategy_PID.h
/**
* @file Strategy_PID.h
* @brief Defines the PIDStrategy class for PID control logic.
* @author Emmanuel Hernandez Cruz
* @date 2025-09-06
*
* This file contains the definition for a behavior strategy that implements a
* Proportional-Integral-Derivative (PID) controller. It's used to control a
* process variable by adjusting an output based on a setpoint.
*/
#ifndef PID_Strategy_h
#define PID_Strategy_h
@@ -6,38 +15,69 @@
#include "Strategy_Behavior.h"
#include <string>
/**
* @class PIDStrategy
* @brief A strategy that implements a PID (Proportional-Integral-Derivative) controller.
*
* This class inherits from Strategy_Behavior and provides the logic for a PID
* controller. It calculates an output value designed to drive a process variable
* (read from an input sensor) towards a desired setpoint. The setpoint itself
* is also read from a Modbus point.
*/
class PIDStrategy : public Strategy_Behavior {
public:
// MODIFIED CONSTRUCTOR: Takes the setpoint, interval, and the name of the input sensor.
/**
* @brief Constructs a new PIDStrategy object.
* @param setpointName The description key for the Modbus point that holds the setpoint value.
* @param interval The update interval in milliseconds for the PID calculation.
* @param inputSensorName The description key for the Modbus point that provides the
* process variable (the input to the PID controller).
*/
PIDStrategy(const std::string& setpointName, unsigned long interval, const std::string& inputSensorName);
/**
* @brief Executes one cycle of the PID control algorithm.
* @param currentValue The current process variable (e.g., temperature) read from the input sensor.
* @return The calculated control output (e.g., fan speed), clamped between 0.0 and 100.0.
*/
float execute(float currentValue) override;
// Add a getter for the sensor name
/**
* @brief Gets the name of the Modbus point used as the process variable input.
* @return The description key of the input sensor point.
*/
std::string getInputSensorName() const { return _inputSensorName; }
/**
* @brief Gets the name of the Modbus point used as the setpoint.
* @return The description key of the setpoint point.
*/
std::string getSetpointName() const { return _setpointName; }
// Add this virtual function to easily identify this strategy as a PID
/**
* @brief Identifies this strategy as a PID controller.
* @return Always returns `true`.
*/
bool isPID() const override { return true; }
// ... (other methods like setSetpoint, setGains)
/** @brief Updates the target setpoint for the PID controller. */
void setSetpoint(float setpoint);
/** @brief Sets the gains for the PID controller (Proportional, Integral, Derivative). */
void setGains(float kp, float ki, float kd);
/** @brief Manually sets the process variable (input) value. */
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
float _kp; /**< @brief Proportional gain. */
float _ki; /**< @brief Integral gain. */
float _kd; /**< @brief Derivative gain. */
unsigned long _lastTime; /**< @brief Timestamp of the last calculation. */
float _setpoint; /**< @brief The target value for the process variable. */
float _input; /**< @brief The current value of the process variable. */
float _lastError; /**< @brief The error from the previous calculation. */
float _integral; /**< @brief The accumulated integral term. */
std::string _inputSensorName; /**< @brief The description key for the input sensor point. */
std::string _setpointName; /**< @brief The description key for the setpoint point. */
};
#endif

View File

@@ -46,6 +46,11 @@ float RampStrategy::execute(float currentValue) {
}
/**
* @brief Sets a new target value for the ramp.
* This allows the ramp's destination to be changed dynamically at runtime.
* @param targetValue The new target value for the ramp.
*/
void RampStrategy::setTarget(float targetValue) {
_targetValue = targetValue;
}

View File

@@ -30,12 +30,18 @@ public:
*/
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.
* @brief Sets a new target value for the ramp.
* This allows the ramp's destination to be changed dynamically at runtime.
* @param targetValue The new target value for the ramp.
*/
void setTarget(float targetValue);
/**
* @brief Executes the strategy to get the next value in the ramp sequence.
* @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.
* @param currentValue The current value, used to determine the next step.
* @return The next value in the ramp sequence.
*/

View File

@@ -20,10 +20,18 @@
SawStrategy::SawStrategy(float minValue, float maxValue, float step, unsigned long interval)
: Strategy_Behavior(interval), _minValue(minValue), _maxValue(maxValue), _step(step) {}
/**
* @brief Sets a new minimum value for the sawtooth wave.
* @param minValue The new lower bound for the wave.
*/
void SawStrategy::setMinValue(float minValue) {
_minValue = minValue;
}
/**
* @brief Sets a new maximum value for the sawtooth wave.
* @param maxValue The new upper bound for the wave.
*/
void SawStrategy::setMaxValue(float maxValue) {
_maxValue = maxValue;
}

View File

@@ -39,8 +39,16 @@ public:
*/
float execute(float currentValue) override;
/**
* @brief Sets a new minimum value for the sawtooth wave.
* @param minValue The new lower bound for the wave.
*/
void setMinValue(float minValue);
/**
* @brief Sets a new maximum value for the sawtooth wave.
* @param maxValue The new upper bound for the wave.
*/
void setMaxValue(float maxValue);

View File

@@ -19,6 +19,11 @@
SingleValueStrategy::SingleValueStrategy(float setpoint, float noiseMagnitude, unsigned long interval)
: Strategy_Behavior(interval), _setpoint(setpoint), _noiseMagnitude(noiseMagnitude) {}
/**
* @brief Sets a setpoint value for the single value strategy.
* @param setpoint The new setpoint target for the single value strategy.
*/
void SingleValueStrategy::setSetpoint(float setpoint) {
_setpoint = setpoint;
}

View File

@@ -1,11 +1,11 @@
/**
* @file Strategy_SingleValue.h
* @brief Defines the SingleValueStrategy class for setup a value with noise.
* @brief Defines the SingleValueStrategy class for generating a value with random 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.
* This file contains the definition for a behavior strategy that maintains a
* value around a given setpoint by adding random noise.
*/
#ifndef SingleValue_strategy_h
#define SingleValue_strategy_h
@@ -13,32 +13,38 @@
/**
* @class SingleValueStrategy
* @brief A strategy that sets a value to a setpoint and generates noise around it.
* @brief A strategy that generates a value that fluctuates around a setpoint.
*
* 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
* This class implements the Strategy_Behavior interface to produce a value that
* fluctuates around a central setpoint. Each time `execute` is called, it adds
* a small, random amount of noise to the setpoint 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.
* @brief Constructs a new SingleValueStrategy object.
* @param setpoint The base value around which noise will be generated.
* @param noiseMagnitude The maximum amount of noise to add or subtract.
* @param interval The time in milliseconds between each value generation.
*/
SingleValueStrategy(float setpoint, float noiseMagnitude, unsigned long interval);
/**
* @brief Executes the strategy to get the next random value around setpoint.
* @brief Generates a new value by adding random noise to the 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.
* @return The setpoint with added random noise.
*/
float execute(float currentValue) override;
/**
* @brief Sets a setpoint value for the single value strategy.
* @param setpoint The new setpoint target for the single value strategy.
*/
void setSetpoint(float setpoint);
private:
float _setpoint;
float _noiseMagnitude;
float _setpoint; /**< @brief The setpoint for the single value strategy. */
float _noiseMagnitude; /**< @brief The noise magnitude for the target value. */
};
#endif

View File

@@ -19,19 +19,28 @@
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.
* @brief Sets a new lower value for the square wave.
* @param lowerValue The new lower bound for the wave.
*/
void SquareStrategy::setLowerValue(float lowerValue) {
_lowerValue = lowerValue;
}
/**
* @brief Sets a new upper value for the square wave.
* @param upperValue The new upper bound for the wave.
*/
void SquareStrategy::setUpperValue(float upperValue) {
_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.
*/
float SquareStrategy::execute(float currentValue) {
_upState = !_upState;
if(_upState){

View File

@@ -34,7 +34,15 @@ public:
* @return The next value in the sequence, either the lower or upper bound.
*/
float execute(float currentValue) override;
/**
* @brief Sets a new lower value for the square wave.
* @param lowerValue The new lower bound for the wave.
*/
void setLowerValue(float lowerValue);
/**
* @brief Sets a new upper value for the square wave.
* @param upperValue The new upper bound for the wave.
*/
void setUpperValue(float upperValue);
private:

View File

@@ -10,12 +10,11 @@
/**
* @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.
* Initializes the totalizer by passing the update interval to the base
* Strategy_Behavior class and setting the initial value to a random number
* between 0 and 1000.
*
* @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.
* @param interval The time in milliseconds between each increment.
*/
TotalizerStrategy::TotalizerStrategy(unsigned long interval)
: Strategy_Behavior(interval) {
@@ -24,9 +23,9 @@ TotalizerStrategy::TotalizerStrategy(unsigned long interval)
}
/**
* @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.
* @brief Increments the totalizer's value on each execution.
* @param currentValue The current value of the Modbus point (ignored in this strategy).
* @return The new, incremented value. The value resets to 0 if it exceeds 60000.
*/
float TotalizerStrategy::execute(float currentValue) {
_currentValue += 1;

View File

@@ -1,42 +1,39 @@
/**
* @file Strategy_Square.h
* @brief Defines the SquareStrategy class for generating a square wave pattern.
* @file Strategy_Totalizer.h
* @brief Defines the TotalizerStrategy class for simulating an accumulating value.
* @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.
* This file contains the definition for a behavior strategy that increments
* a value at a regular interval, simulating a run-time counter or totalizer.
*/
#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.
* @class TotalizerStrategy
* @brief A strategy that increments a 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`.
* This class implements the Strategy_Behavior interface to produce a continuously
* increasing value. Each time `execute` is called, it increments its internal
* counter and returns the new value.
*/
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.
* @brief Constructs a new TotalizerStrategy object.
* @param interval The time in milliseconds between each increment.
*/
TotalizerStrategy(unsigned long interval);
/**
* @brief Executes the strategy to get the next value in the square wave.
* @brief Executes the strategy to get the next incremented value.
* @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.
* @return The new, incremented value.
*/
float execute(float currentValue) override;
private:
float _currentValue; /**< @brief The lower bound of the square wave. */
float _currentValue; /**< @brief The current accumulated value of the totalizer. */
};
#endif

View File

@@ -23,6 +23,12 @@
#include <ModbusRTU.h> // Or your specific Modbus RTU library
#endif
/**
* @defgroup ModbusCategoryCodes Modbus Point Category Codes
* @brief Integer constants used in the `modbusMap` to identify the type of Modbus point.
* These codes determine which `ModbusPoint` subclass is created by the factory.
* @{
*/
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 */
@@ -33,6 +39,7 @@ 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
@@ -47,10 +54,16 @@ struct modbusMap
};
/**
* @brief The main loop previous milliseconds.
* @brief Timestamp for managing the main application loop interval.
* Used in the main `.cpp` file to control the frequency of the `EquipmentInstance.update()` call.
*/
unsigned long previousMillis = 0;
/**
* @defgroup GlobalInstances Global Instances
* @brief Globally accessible objects for the Modbus server and Equipment.
* @{
*/
/**
* @brief Global Modbus object instance.
* The type is determined at compile time based on the USE_MODBUS_IP flag.
@@ -64,6 +77,6 @@ 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