doc scripts | component docs - inc

This commit is contained in:
lovebird 2025-06-03 21:27:49 +02:00
parent 766e1a1dd9
commit 362e2b2bbe
36 changed files with 23199 additions and 584 deletions

File diff suppressed because one or more lines are too long

File diff suppressed because it is too large Load Diff

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

132
docs/3PosAnalog.md Normal file
View File

@ -0,0 +1,132 @@
---
title: 3-Position Analog Switch
description: A component for handling 3-position analog switches with UP/MIDDLE/DOWN positions
keywords: [analog, switch, 3-position, input, modbus, ESP32]
---
# 3-Position Analog Switch
**Path**: [src/components/3PosAnalog.h](../src/components/3PosAnalog.h)
**Revision History**: Initial documentation
The 3-Position Analog Switch (`Pos3Analog`) component provides an interface to hardware switches with three positions (UP, MIDDLE, DOWN). It reads from two analog input pins and determines the current position. The component supports both local (physical) and remote (Modbus) control modes, making it suitable for industrial automation applications that require flexible control mechanisms.
## Requirements
### Hardware
- ESP32 microcontroller
- Two analog input pins for position detection (upPin and downPin)
### Software
- Arduino framework
- ArduinoLog library
- Modbus TCP support
## Features
- Three-position state detection (UP, MIDDLE, DOWN)
- Dual control modes:
- LOCAL: Position determined by physical input readings
- REMOTE: Position controlled via Modbus
- Modbus integration with read/write capabilities
- Configurable sampling interval
- State change notifications
- Comprehensive error handling and validation
## Dependencies
- [Component](../src/Component.h): Base component class providing core functionality
- [ModbusTCP](../src/modbus/ModbusTCP.h): Modbus TCP protocol implementation
- [Bridge](../src/Bridge.h): Serial command bridge for component communication
- [App](../src/App.h): Application framework integration
```mermaid
graph TD
Pos3Analog --> Component
Pos3Analog --> ModbusTCP
Pos3Analog --> Bridge
Component --> App
```
## Behaviour
The component operates in one of two modes (LOCAL or REMOTE) and has three possible positions (UP, MIDDLE, DOWN).
```mermaid
stateDiagram-v2
[*] --> LOCAL
LOCAL --> REMOTE: Modbus Write
REMOTE --> LOCAL: Modbus Write
state LOCAL {
[*] --> MIDDLE
MIDDLE --> UP: upPin Active
MIDDLE --> DOWN: downPin Active
UP --> MIDDLE: No pins Active
DOWN --> MIDDLE: No pins Active
}
state REMOTE {
[*] --> REMOTE_MIDDLE
REMOTE_MIDDLE --> REMOTE_UP: Modbus Write
REMOTE_MIDDLE --> REMOTE_DOWN: Modbus Write
REMOTE_UP --> REMOTE_MIDDLE: Modbus Write
REMOTE_DOWN --> REMOTE_MIDDLE: Modbus Write
}
```
## TODOs
### Performance
- Consider implementing debounce functionality for more stable readings
- Optimize analog reading frequency based on application requirements
### Security
- Implement authentication for remote control mode changes
- Add permission levels for Modbus write operations
### Compliance
- Ensure compliance with industrial control systems standards
- Verify compatibility with Modbus specification
### Recommendations
- Use pull-up or pull-down resistors on the analog inputs for more reliable readings
- Implement filtering for noisy environments
- Consider adding hysteresis to prevent rapid state changes near thresholds
## Example
Below is an example of how to initialize and use the 3-Position Analog Switch component:
```cpp
#ifdef AUX_ANALOG_3POS_SWITCH_0
analog3PosSwitch_0 = new Pos3Analog(
this, // owner
AUX_ANALOG_3POS_SWITCH_0, // upPin
AUX_ANALOG_3POS_SWITCH_0 + 1, // downPin (assuming sequential pins)
COMPONENT_KEY_ANALOG_3POS_SWITCH_0, // id
MB_ANALOG_3POS_SWITCH_0_ADDR // modbusAddress
);
if (analog3PosSwitch_0)
{
components.push_back(analog3PosSwitch_0);
Log.infoln(F("3-Position Analog Switch 0 initialized. UpPin:%d, DownPin:%d, ID:%d, MB:%d"),
AUX_ANALOG_3POS_SWITCH_0, AUX_ANALOG_3POS_SWITCH_0 + 1,
COMPONENT_KEY_ANALOG_3POS_SWITCH_0, MB_ANALOG_3POS_SWITCH_0_ADDR);
}
else
{
Log.errorln(F("3-Position Analog Switch 0 initialization failed."));
}
#endif
```
### References
- [Arduino Analog Input Documentation](https://www.arduino.cc/reference/en/language/functions/analog-io/analogread/)
- [Modbus Protocol Specification](https://modbus.org/specs.php)

126
docs/AnalogLevelSwitch.md Normal file
View File

@ -0,0 +1,126 @@
---
title: "AnalogLevelSwitch Component"
description: "Analog Level Switch Component for multi-position switch detection via analog input"
keywords: ["analog", "level", "switch", "ESP32", "voltage divider", "multi-position"]
---
# AnalogLevelSwitch
**Path**: [`src/components/AnalogLevelSwitch.h`](../src/components/AnalogLevelSwitch.h)
**Revision History**: Initial documentation
The AnalogLevelSwitch component interprets an analog voltage as a discrete position or slot. It enables reading an analog input as a multi-position switch by mapping voltage levels to specific slots or positions, with built-in smoothing and debouncing functionality.
## REQUIREMENTS
### Hardware
- An analog input pin on the ESP32
- A voltage divider circuit with different resistor values for each switch position
- Pull-down resistor (typically 10kΩ) connected to the analog pin
### Software
- Arduino framework
- ArduinoLog library
- ModbusTCP support
## FEATURES
- Maps analog voltage readings to discrete positions (slots)
- Configurable number of positions/slots (up to 32 positions)
- Adjustable ADC step size per slot
- Configurable ADC value offset for the first slot
- Built-in signal smoothing using moving average or EMA
- Debouncing algorithm to prevent spurious readings
- Hysteresis to prevent jitter between adjacent positions
- Modbus integration for industrial control systems
- Customizable reading interval
## DEPENDENCIES
- [Component](../src/Component.h) - Base component class
- [ModbusTCP](../src/modbus/ModbusTCP.h) - Modbus TCP communication
- [ArduinoLog](https://github.com/thijse/Arduino-Log) - Logging functionality
```mermaid
graph TD
AnalogLevelSwitch --> Component
AnalogLevelSwitch --> ModbusTCP
AnalogLevelSwitch --> ArduinoLog
```
## BEHAVIOUR
```mermaid
stateDiagram-v2
[*] --> Initialization
Initialization --> ReadAnalogValue
ReadAnalogValue --> SmoothValue
SmoothValue --> DetermineSlot
DetermineSlot --> CheckIfChanged
CheckIfChanged --> ConfirmChange: Slot different
CheckIfChanged --> ReadAnalogValue: Slot same
ConfirmChange --> UpdateSlot: Confirmed
ConfirmChange --> ReadAnalogValue: Not confirmed
UpdateSlot --> NotifyStateChange
NotifyStateChange --> ReadAnalogValue
```
## TODOS
### PERFORMANCE
- Consider optimizing the moving average calculation for better performance
- Evaluate if the current reading interval is optimal for the application
- Investigate using hardware filtering in addition to software smoothing
### SECURITY
- Implement range checking for analog readings to prevent unexpected behavior
- Add validation for Modbus register access
### COMPLIANCE
- Ensure compatibility with industrial standards for analog input processing
- Verify noise immunity meets requirements for industrial environments
### RECOMMENDATIONS
- Use 1% tolerance resistors in the voltage divider circuit for better accuracy
- Ensure the voltage divider resistance values create sufficient separation between positions
- Keep the overall equivalent resistance of the voltage divider in the 1kΩ to 100kΩ range
- Add appropriate ESD protection for the analog input pin in industrial environments
- When using mechanical switches, consider adding hardware debouncing in addition to software debouncing
## EXAMPLE
Here's an example of how to initialize and use the AnalogLevelSwitch component:
```cpp
#ifdef PIN_ANALOG_LEVEL_SWITCH_0
analogLevelSwitch_0 = new AnalogLevelSwitch(
this, // owner
PIN_ANALOG_LEVEL_SWITCH_0, // analogPin
ALS_0_NUM_LEVELS, // numLevels
ALS_0_ADC_STEP, // levelStep
ALS_0_ADC_OFFSET, // adcValueOffset
ID_ANALOG_LEVEL_SWITCH_0, // id
ALS_0_MB_ADDR // modbusAddress
);
if (analogLevelSwitch_0) {
components.push_back(analogLevelSwitch_0);
Log.infoln(F("AnalogLevelSwitch_0 initialized. Pin:%d, Levels:%d, Step:%d, Offset:%d, ID:%d, MB:%d"),
PIN_ANALOG_LEVEL_SWITCH_0, ALS_0_NUM_LEVELS,
ALS_0_ADC_STEP, ALS_0_ADC_OFFSET,
ID_ANALOG_LEVEL_SWITCH_0, ALS_0_MB_ADDR);
} else {
Log.errorln(F("AnalogLevelSwitch_0 initialization failed."));
}
#endif
```
### References
${DOXYGEN_PLACEHOLDER}
${VENDOR_PLACEHOLDER}

121
docs/Bridge.md Normal file
View File

@ -0,0 +1,121 @@
---
title: "Bridge Component"
description: "A communication bridge component for handling inter-component messaging and registering method calls"
keywords: ["bridge", "communication", "messaging", "inter-component", "method registry", "ESP-32", "industrial"]
---
# BRIDGE
**Path**: [src/Bridge.cpp](../../src/Bridge.cpp)
**Revision History**: Initial documentation
A communication bridge component that facilitates inter-component messaging and method registration. The Bridge acts as a central hub for communication between different system components and provides services for Modbus management.
## REQUIREMENTS
- No specific hardware pins required
- Component base class
- String manipulation capabilities
- Vector container support
## FEATURES
- Component method registration and management
- Inter-component message handling
- Component instance tracking and retrieval
- Debugging and listing capabilities
- Method delimiter-based parsing
- Integration with Modbus Manager
## DEPENDENCIES
- [Component](./Component.md)
- WString
- Vector
- Streaming
- xtypes
- enums
- macros
```mermaid
graph TD;
Bridge["Bridge"] -->|extends| Component["Component"];
Bridge -->|uses| WString["WString"];
Bridge -->|uses| Vector["Vector"];
Bridge -->|uses| Streaming["Streaming"];
Bridge -->|uses| xtypes["xtypes"];
Bridge -->|uses| enums["enums"];
```
## BEHAVIOUR
```mermaid
stateDiagram-v2
[*] --> INITIALIZATION
INITIALIZATION --> REGISTRATION : setup()
REGISTRATION --> READY : register components
READY --> MESSAGE_HANDLING : onMessage()
MESSAGE_HANDLING --> DEBUGGING : debug()
MESSAGE_HANDLING --> READY : return status
DEBUGGING --> READY
READY --> LISTING : getComponentList()
LISTING --> READY
```
## TODOS
### PERFORMANCE
- Implement component method caching for faster lookups
- Optimize memory usage by pre-allocating component storage
- Add method call frequency monitoring
- Consider asynchronous message processing
### SECURITY
- Implement access control for component method registration
- Implement message authentication and encryption
- Add signed message data integrity checks
- Enable inter-component communication logging
### COMPLIANCE
- Ensure error handling complies with industrial standards
- Implement message logging for audit requirements
- Validate time-critical communication performance
- Consider system failover and redundancy in communication
### RECOMMENDATIONS
- Use structured error codes for consistent message handling
- Maintain component hierarchies to maintain clear dependencies
- Implement event driven architecture for inter-component synchronization
- Add component lifecycle tracking
## EXAMPLE
Based on the available header file:
```cpp
#defdef ENABLE_BRIDGE_COMMUNICATION
bridge = new Bridge(
this // owner
);
if (bridge)
{
components.push_back(bridge);
Log.infoln(F("Bridge initialized."));
}
else
{
Log.errorln(F("Bridge initialization failed."));
}
#endif
```
### References
${DOXYGEN_PLACEHOLDER}
${VENDOR_PLACEHOLDER}

121
docs/CircularLogPrinter.md Normal file
View File

@ -0,0 +1,121 @@
---
title: CircularLogPrinter
description: A thread-safe circular buffer logger for ESP32 applications
keywords: [logger, esp32, circular buffer, thread-safe, logging]
---
# CircularLogPrinter
**Path**: [`src/Logger.h`](../src/Logger.h)
**Revision History**: Initial documentation
CircularLogPrinter is a high-performance, thread-safe logging utility designed for ESP32 applications. It maintains a configurable circular buffer of log messages in memory while optionally mirroring output to a Serial or other Print-compatible stream. The implementation is compliant with MISRA/CPPCHECK standards, avoiding reinterpret casts for improved safety.
## Requirements
### Hardware
- No specific hardware pins required
- Compatible with ESP32 platforms
### Software
- Arduino framework
- FreeRTOS (for thread-safety features)
- ESP-IDF (for ESP log integration)
## Features
- Configurable circular buffer for storing the last N log lines
- Thread-safe operation (optional via configuration)
- Ability to redirect ESP-IDF logging macros (ESP_LOGx) into this printer
- MISRA/CPPCHECK compliant implementation with no pointer type casting
- Memory-efficient design with fixed buffer sizes
- Optional output mirroring to any Arduino Print-compatible stream
## Dependencies
- [Arduino.h](https://github.com/arduino/ArduinoCore-avr/blob/master/cores/arduino/Arduino.h)
- [Print.h](https://github.com/arduino/ArduinoCore-avr/blob/master/cores/arduino/Print.h)
- [esp_log.h](https://github.com/espressif/esp-idf/blob/master/components/log/include/esp_log.h)
```mermaid
graph TD
CircularLogPrinter --> Print
CircularLogPrinter --> Arduino
CircularLogPrinter --> esp_log
```
## Behaviour
The CircularLogPrinter maintains a circular buffer of log lines. When the buffer is full, new log entries overwrite the oldest entries. Log entries are committed when a newline character is encountered or when the maximum line length is reached.
```mermaid
stateDiagram-v2
[*] --> Initialize: Constructor
Initialize --> Ready
Ready --> AppendChar: write(byte)
Ready --> AppendMultipleChars: write(buffer, size)
AppendChar --> CommitLine: If newline
AppendChar --> AppendChar: If not newline
AppendMultipleChars --> CommitLine: If newline encountered
AppendMultipleChars --> Ready: After processing
CommitLine --> Ready
Ready --> Clear: clear() called
Clear --> Ready
```
## TODOs
### Performance
- Consider using a more efficient memory layout for the circular buffer
- Evaluate the impact of thread-safety mechanisms on performance in high-frequency logging scenarios
- Add compile-time options to disable features not needed for specific applications
### Security
- Add configurable log level filtering to prevent sensitive information leakage
- Consider adding encryption options for logs containing sensitive information
- Implement log rotation to persistent storage for critical deployments
### Compliance
- The implementation is already MISRA/CPPCHECK compliant by avoiding pointer type casting
- Consider adding support for standardized log formats like RFC5424
### Recommendations
- Use reasonable buffer sizes to avoid excessive memory usage
- Consider the performance impact of thread-safety in high-frequency logging scenarios
- When using with ESP-IDF logging, ensure consistent configuration across components
- For production environments, implement a strategy for persistent log storage
## Example
This example shows how to initialize and use the CircularLogPrinter:
```cpp
// Create a CircularLogPrinter that mirrors to Serial
CircularLogPrinter logger(&Serial);
// Clear the buffer
logger.clear();
// Write some logs
logger.println("Starting application...");
logger.printf("System initialized with version: %s", VERSION);
// Attach to ESP-IDF logging
logger.attachToEspLog();
// Now ESP_LOGx macros will also be captured
ESP_LOGI("TAG", "This will be captured by the CircularLogPrinter");
// Retrieve a specific line from history (0 is most recent)
const char* lastLine = logger.getLine(0);
```
### References
- [ESP-IDF Logging Library](https://docs.espressif.com/projects/esp-idf/en/latest/esp32/api-reference/system/log.html)
- [Arduino Print Class](https://www.arduino.cc/reference/en/language/functions/communication/serial/print/)

139
docs/Component.md Normal file
View File

@ -0,0 +1,139 @@
---
title: Component Class
description: Base class for all firmware components with standard behavior and lifecycle management
keywords: component, base class, framework, firmware, modbus, ESP32
---
# Component
**Path**: [`src/Component.h`](../src/Component.h)
**Revision History**:
- Initial documentation
The Component class serves as the foundational building block for all firmware components in the system. It provides standardized interfaces for component initialization, execution, and communication via Modbus and other protocols. It's designed to work within an industrial application environment using Modbus-485.
## Requirements
- No specific hardware pins required as this is a base class
- Software dependencies:
- Arduino framework
- WString.h
- ArduinoLog.h
- Vector.h
## Features
- Standardized component lifecycle management (setup, loop)
- Configurable execution flags for controlling component behavior
- Modbus integration capabilities for industrial communication
- Component ownership hierarchy for resource management
- Component type categorization for organizational purposes
- Support for ESP32 platform
## Dependencies
- [WString.h](https://www.arduino.cc/reference/en/language/variables/data-types/string/)
- [ArduinoLog.h](https://github.com/thijse/Arduino-Log/)
- [Vector.h](https://github.com/janelia-arduino/Vector)
- [`enums.h`](../src/enums.h)
- [`constants.h`](../src/constants.h)
- [`error_codes.h`](../src/error_codes.h)
- [`macros.h`](../src/macros.h)
- [`xtypes.h`](../src/xtypes.h)
```mermaid
graph TD
Component --> WString
Component --> ArduinoLog
Component --> Vector
Component --> enums
Component --> constants
Component --> error_codes
Component --> macros
Component --> xtypes
Bridge --> Component
ModbusTCP --> Component
ModbusBlockView --> Component
MB_Registers --> Component
RS485 --> Component
```
## Behaviour
The Component class follows a standard lifecycle pattern controlled by flags:
```mermaid
stateDiagram-v2
Start --> Construct
Construct --> Setup: E_OF_SETUP flag
Setup --> Loop: E_OF_LOOP flag
Loop --> Loop: Main program loop
Loop --> Destruct: Program ends
Setup --> Destruct: No E_OF_LOOP flag
Construct --> Disabled: E_OF_DISABLED flag
Disabled --> Destruct
Destruct --> End
```
## TODOs
### Performance
- Consider memory optimization for resource-constrained ESP32 platforms
- Review constructor implementations for redundant operations
- Optimize Modbus-485 communication for industrial applications
### Security
- Implement validation for component IDs to prevent conflicts
- Consider access control mechanisms for critical components
- Ensure secure Modbus communication in industrial environments
### Compliance
- Ensure compliance with MISRA C++ coding standards
- Maintain compatibility with Arduino's component model
- Verify compliance with industrial Modbus protocol standards
### Recommendations
- Follow the component ownership hierarchy for proper resource management
- Use the appropriate flags to control component lifecycle
- Implement specific component types by extending this base class
- Ensure all derived components properly initialize the base class
- When using with ESP32, consider platform-specific optimizations
## Example
The Component class is typically extended rather than used directly. Here's an example of how a derived component might be constructed and mounted:
```cpp
#ifdef PIN_LED_FEEDBACK_0
ledFeedback_0 = new LEDFeedback(
this, // owner
PIN_LED_FEEDBACK_0, // pin
LED_PIXEL_COUNT_0, // pixelCount
ID_LED_FEEDBACK_0, // id
LED_FEEDBACK_0_MB_ADDR // modbusAddress
);
if (ledFeedback_0)
{
components.push_back(ledFeedback_0);
Log.infoln(F("LEDFeedback_0 initialized. Pin:%d, Count:%d, ID:%d, MB:%d"),
PIN_LED_FEEDBACK_0, LED_PIXEL_COUNT_0,
ID_LED_FEEDBACK_0, LED_FEEDBACK_0_MB_ADDR);
}
else
{
Log.errorln(F("LEDFeedback_0 initialization failed."));
}
#endif
```
### References
- Component flags are defined in the `OBJECT_RUN_FLAGS` enum in `enums.h`
- Component types are defined in the `COMPONENT_TYPE` enum in `enums.h`
- Error codes are defined in `error_codes.h`
- Default component configuration is specified with `COMPONENT_DEFAULT`

129
docs/Extruder.md Normal file
View File

@ -0,0 +1,129 @@
---
title: Extruder Component
description: Documentation for the Extruder component which manages VFD-controlled extrusion with joystick and potentiometer control
keywords: extruder, VFD, joystick, potentiometer, torque monitoring, jam detection
---
# Extruder
**Path**: [`src/components/Extruder.h`](../src/components/Extruder.h)
**Revision History**: Initial documentation
The Extruder component provides control over a SAKO VFD-driven extruder motor. It supports both manual and automatic extrusion modes, with configurable speed and overload protection via potentiometers. The component integrates with a joystick for manual control and features jam detection based on motor torque feedback.
## Requirements
### Hardware
- SAKO VFD (Variable Frequency Drive) for motor control
- Joystick for manual control (optional)
- Potentiometer for speed control (optional)
- Potentiometer for overload threshold control (optional)
### Pins
- No direct pin requirements (manages components that have their own pin requirements)
## Features
- Dual operating modes: manual (joystick-controlled) and auto (timed operation)
- Configurable extrusion speed via potentiometer
- Adjustable overload/jam detection threshold
- Automatic jam detection based on motor torque feedback
- Modbus TCP interface for remote control and monitoring
- Safety features including maximum runtime limits
- Auto-mode activation via joystick hold
## Dependencies
- [Component](../src/Component.h) - Base component class
- [SAKO_VFD](../src/components/SAKO_VFD.h) - VFD motor controller
- [Pos3Analog](../src/components/3PosAnalog.h) - 3-position analog input (joystick)
- [POT](../src/components/POT.h) - Potentiometer interface
- [ModbusTCP](../src/modbus/ModbusTCP.h) - Modbus interface
```mermaid
graph TD
Extruder --> Component
Extruder --> SAKO_VFD
Extruder --> Pos3Analog
Extruder --> POT
Extruder --> ModbusTCP
```
## Behaviour
The Extruder component implements a state machine with the following states:
```mermaid
stateDiagram-v2
[*] --> IDLE
IDLE --> EXTRUDING_MANUAL: Joystick UP
EXTRUDING_MANUAL --> EXTRUDING_AUTO: Hold joystick UP for set duration
EXTRUDING_MANUAL --> IDLE: Release joystick
EXTRUDING_AUTO --> STOPPING: Auto time complete or manual stop
EXTRUDING_MANUAL --> JAMMED: Torque exceeds threshold
EXTRUDING_AUTO --> JAMMED: Torque exceeds threshold
STOPPING --> IDLE: VFD stopped
JAMMED --> RESETTING_JAM: Reset command
RESETTING_JAM --> IDLE: Reset complete
```
## TODOs
### Performance
- Consider implementing acceleration/deceleration ramps for smoother operation
- Optimize VFD polling frequency based on system requirements
- Evaluate the potential for predictive jam detection using torque trend analysis
### Security
- Implement authentication for Modbus commands that control the extruder
- Consider adding physical emergency stop integration
- Validate input values from potentiometers to prevent unexpected behavior
### Compliance
- Ensure conformance with industrial safety standards for automated machinery
- Implement proper error handling and logging for diagnostic purposes
- Consider adding UL/CE compliance features if required for deployment environment
### Recommendations
- Add temperature monitoring to prevent motor overheating
- Consider implementing a material feed sensor to detect material availability
- Implement a maintenance tracking system based on operation hours
- Add visual feedback (e.g., LED indicators) for different states, especially jammed condition
## Example
The following example shows how to create and configure an Extruder component:
```cpp
#ifdef ENABLE_EXTRUDER
// First ensure required components exist
if (sakoVFD && joystick && speedPot && overloadPot) {
extruder = new Extruder(
this, // owner
sakoVFD, // VFD controller
joystick, // joystick for manual control
speedPot, // potentiometer for speed control
overloadPot // potentiometer for overload threshold
);
if (extruder) {
components.push_back(extruder);
Log.infoln(F("Extruder initialized"));
} else {
Log.errorln(F("Extruder initialization failed"));
}
} else {
Log.warningln(F("Extruder not initialized - missing dependencies"));
}
#endif
```
### References

123
docs/Joystick.md Normal file
View File

@ -0,0 +1,123 @@
---
title: Joystick Component
description: Documentation for the Joystick input component for ESP32 platform
keywords: [joystick, input device, ESP32, modbus, industrial]
---
## Joystick
**Path**: [`./src/components/Joystick.cpp`](../src/components/Joystick.cpp)
**Revision History**: Initial documentation
The Joystick component provides an interface for a 4-position digital joystick (Up, Down, Left, Right) with a center position. It supports both local physical input and remote control via Modbus, allowing for integration into industrial control systems.
## REQUIREMENTS
### Hardware
- 4 digital input pins connected to joystick switches
- ESP32 microcontroller
### Software
- Arduino framework
- ArduinoLog library
- Platform.io environment
## FEATURES
- 5-position detection (UP, DOWN, LEFT, RIGHT, CENTER)
- Local and remote operation modes
- Position override capability via Modbus
- Input debouncing for reliable operation
- Position hold time tracking
- State change notification system
- Modbus integration for industrial control systems
## DEPENDENCIES
- [Component](./Component.md) - Base component class
- [ModbusTCP](./ModbusTCP.md) - Modbus TCP protocol implementation
- [Bridge](./Bridge.md) - Serial communication bridge
- [config.h](./config.md) - System configuration
```mermaid
graph TD
Joystick --> Component
Joystick --> ModbusTCP
Joystick --> Bridge
Joystick --> Config
```
## BEHAVIOUR
The Joystick operates in two modes: LOCAL and REMOTE. In LOCAL mode, it reads physical inputs from pins. In REMOTE mode, it uses an override position set via Modbus.
```mermaid
stateDiagram-v2
[*] --> Setup
Setup --> Idle
Idle --> ReadPosition: If LOCAL mode
ReadPosition --> Debounce: Read inputs
Debounce --> UpdatePosition: Confirmed
Debounce --> Idle: Not confirmed
UpdatePosition --> Notify: Position changed
Notify --> Idle
Idle --> CheckRemote: If REMOTE mode
CheckRemote --> UpdatePosition: Override changed
CheckRemote --> Idle: No change
```
## TODOS
### PERFORMANCE
- Consider optimizing the debouncing algorithm for faster response in time-critical applications
- Evaluate interrupt-based approach instead of polling for reduced CPU overhead
### SECURITY
- Add input validation for Modbus commands to prevent unexpected behavior
- Consider adding authentication for remote control mode switching
### COMPLIANCE
- Ensure compliance with industrial standards for joystick controls
- Consider implementing emergency stop functionality
### RECOMMENDATIONS
- Use pull-up or pull-down resistors with the input pins to ensure stable readings
- When using in industrial environments, consider adding hardware debouncing
- Implement application-level validation for critical operations controlled by the joystick
## EXAMPLE
This example shows how to initialize and mount a Joystick component:
```cpp
#ifdef PIN_JOYSTICK_UP
joystick = new Joystick(
this, // owner
PIN_JOYSTICK_UP, // UP pin
PIN_JOYSTICK_DOWN, // DOWN pin
PIN_JOYSTICK_LEFT, // LEFT pin
PIN_JOYSTICK_RIGHT, // RIGHT pin
COMPONENT_KEY_JOYSTICK_0 // modbus address
);
if (joystick)
{
components.push_back(joystick);
Log.infoln(F("Joystick initialized. Pins: UP=%d, DOWN=%d, LEFT=%d, RIGHT=%d, ID=%d"),
PIN_JOYSTICK_UP, PIN_JOYSTICK_DOWN,
PIN_JOYSTICK_LEFT, PIN_JOYSTICK_RIGHT,
COMPONENT_KEY_JOYSTICK_0);
}
else
{
Log.errorln(F("Joystick initialization failed."));
}
#endif
```
### References

106
docs/LEDFeedback.md Normal file
View File

@ -0,0 +1,106 @@
---
title: LEDFeedback Component
description: LED-based visual feedback system for indicating device status
keywords: LED, visual feedback, NeoPixel, status indicator, ESP32
---
## LEDFeedback
**Path**: [src/LEDFeedback.cpp](../src/LEDFeedback.cpp)
**Revision History**: Initial documentation
The LEDFeedback component provides visual status indication through addressable LEDs (NeoPixels). It allows for controlling color, intensity, and pattern of LEDs to convey system status or feedback to users.
## REQUIREMENTS
### Hardware
- Addressable LED strip/array (NeoPixels)
- Data pin connected to ESP32 GPIO
- Appropriate power supply for LEDs
### Software
- Adafruit_NeoPixel library
## FEATURES
- Control of individual addressable LEDs
- Multiple color patterns for status indication
- Modbus integration for remote control
- Configurable update interval
- Support for various LED counts
## DEPENDENCIES
- [Component](../src/Component.h) - Base component class
- [Adafruit_NeoPixel](https://github.com/adafruit/Adafruit_NeoPixel) - Library for controlling NeoPixels
```mermaid
graph TD
LEDFeedback --> Component
LEDFeedback --> Adafruit_NeoPixel
```
## BEHAVIOUR
```mermaid
stateDiagram-v2
[*] --> Initialize
Initialize --> Idle
Idle --> UpdateLEDs: Update interval reached
UpdateLEDs --> Idle
Idle --> ChangePattern: Modbus command received
ChangePattern --> Idle
```
## TODOS
### PERFORMANCE
- Optimize LED update frequency to minimize CPU usage
- Consider implementing brightness scaling based on system load
### SECURITY
- None identified - LED feedback is output-only
### COMPLIANCE
- Ensure power consumption stays within device specifications
### RECOMMENDATIONS
- Consider adding support for more complex animation patterns
- Add power-saving modes that reduce brightness during idle periods
- Implement error indication patterns for system diagnostics
## EXAMPLE
The LEDFeedback component is constructed and mounted as follows:
```cpp
#ifdef PIN_LED_FEEDBACK_0
ledFeedback_0 = new LEDFeedback(
this, // owner
PIN_LED_FEEDBACK_0, // pin
LED_PIXEL_COUNT_0, // pixelCount
ID_LED_FEEDBACK_0, // id
LED_FEEDBACK_0_MB_ADDR // modbusAddress
);
if (ledFeedback_0)
{
components.push_back(ledFeedback_0);
Log.infoln(F("LEDFeedback_0 initialized. Pin:%d, Count:%d, ID:%d, MB:%d"),
PIN_LED_FEEDBACK_0, LED_PIXEL_COUNT_0,
ID_LED_FEEDBACK_0, LED_FEEDBACK_0_MB_ADDR);
}
else
{
Log.errorln(F("LEDFeedback_0 initialization failed."));
}
#endif
```
### References
- [NeoPixel Documentation](https://learn.adafruit.com/adafruit-neopixel-uberguide)

148
docs/ModbusLogicEngine.md Normal file
View File

@ -0,0 +1,148 @@
---
title: ModbusLogicEngine Component
description: A programmable logic rule engine that operates on Modbus registers to execute conditional commands
keywords: modbus, automation, rules engine, logic, conditional execution, industrial automation
---
# ModbusLogicEngine
**Path**: [`src/components/ModbusLogicEngine.h`](../src/components/ModbusLogicEngine.h)
**Revision History**: Initial documentation
The ModbusLogicEngine component provides a programmable logic rule engine that executes conditional actions based on Modbus register values. It functions similar to a basic PLC (Programmable Logic Controller), allowing the system to be configured with a set of if-then rules via Modbus registers without requiring firmware modifications.
## REQUIREMENTS
### Hardware
- No specific hardware pins required
- Operates entirely on Modbus data
### Software
- Requires `ENABLE_MB_SCRIPT` to be defined in the configuration
- Access to Modbus register data (holding registers, coils, etc.)
- PHApp instance to interact with other components
## FEATURES
- Supports up to 8 configurable logic rules (adjustable via `MAX_LOGIC_RULES`)
- Each rule includes:
- A condition based on Modbus register or coil values
- An action to execute when the condition is met
- Status tracking (trigger count, last execution time, etc.)
- Condition types: equal, not equal, less than, less or equal, greater than, greater or equal
- Action types:
- Write to a Modbus holding register
- Write to a Modbus coil
- Call a registered component method
- Rule debugging capabilities via flags
- Rules are fully configurable via Modbus registers
## DEPENDENCIES
- [Component](../src/Component.h)
- [ArduinoLog](https://github.com/thijse/Arduino-Log)
- [config.h](../src/config.h)
- [ModbusTypes.h](../src/modbus/ModbusTypes.h)
```mermaid
graph TD
ModbusLogicEngine --> Component
ModbusLogicEngine --> PHApp
ModbusLogicEngine --> ArduinoLog
ModbusLogicEngine --> ModbusTypes
```
## BEHAVIOUR
The ModbusLogicEngine evaluates rules at regular intervals (default 100ms). For each enabled rule:
```mermaid
graph TD
A[Check if rule enabled] -->|Yes| B[Read condition source value]
B --> C[Evaluate condition]
C -->|Condition true| D[Execute action]
D --> E[Update status registers]
C -->|Condition false| E
A -->|No| F[Skip rule]
F --> E
```
Each rule occupies a block of 13 consecutive Modbus registers with the following structure:
1. Enabled (0/1)
2. Condition Source Type (register type)
3. Condition Source Address (Modbus address)
4. Condition Operator (0=Equal, 1=Not Equal, 2=Less Than, etc.)
5. Condition Value (to compare against)
6. Command Type (2=Write Coil, 3=Write Register, 100=Call Method)
7. Command Target (address or component ID)
8. Command Parameter 1 (value or method ID)
9. Command Parameter 2 (additional argument)
10. Flags (debug settings)
11. Last Status (execution result code)
12. Last Trigger Timestamp
13. Trigger Count
## TODOS
### PERFORMANCE
- Consider optimizing the rule evaluation frequency based on application needs
- Implement priority levels for rules to ensure critical rules execute first
- Add rate limiting options for high-frequency triggers
### SECURITY
- Implement range checking on Modbus addresses to prevent unauthorized memory access
- Add authorization mechanism for registering and modifying component methods
- Consider adding CRC or checksum validation for rule configurations
### COMPLIANCE
- Document compatibility with IEC 61131-3 (PLC programming standard) concepts
- Add options for meeting real-time response requirements for industrial control systems
### RECOMMENDATIONS
- Use debug flags during initial rule setup and disable for production
- Organize rule addresses logically to group related functionality
- Implement a backup/restore mechanism for rule configurations
- Consider adding a web interface for easier rule configuration
## EXAMPLE
This section would typically show how the component is constructed and mounted, but the CPP file couldn't be located. However, based on the header file, a typical initialization would look like:
```cpp
#ifdef ENABLE_MB_SCRIPT
// Create the ModbusLogicEngine component
modbusLogicEngine = new ModbusLogicEngine(this); // 'this' is PHApp instance
if (modbusLogicEngine)
{
components.push_back(modbusLogicEngine);
// Register methods that can be called by logic rules
modbusLogicEngine->registerMethod(
COMPONENT_KEY_RELAY_0, // component ID
1, // method ID for toggle
[this](short arg1, short arg2) -> short {
// Method implementation
return 0; // Success
}
);
Log.infoln(F("ModbusLogicEngine initialized"));
}
else
{
Log.errorln(F("ModbusLogicEngine initialization failed"));
}
#endif
```
### References
- [Modbus Specification](https://modbus.org/specs.php)
- [PLC Programming Concepts](https://en.wikipedia.org/wiki/Programmable_logic_controller)

125
docs/OmronE5.md Normal file
View File

@ -0,0 +1,125 @@
---
title: OmronE5 Component
description: Modbus RTU interface for Omron E5 temperature controllers
keywords: omron, e5, temperature, controller, modbus, rtu, rs485
---
# OmronE5
**Path**: [`src/components/OmronE5.h`](../src/components/OmronE5.h)
**Revision History**: Initial documentation
The OmronE5 component provides a Modbus RTU interface for Omron E5 series temperature controllers. It enables reading current temperature values (PV), setting target temperatures (SP), and controlling the device operation through an RS485 interface.
## Requirements
### Hardware
- RS485 interface connected to ESP32
- Omron E5 series temperature controller(s) with Modbus RTU capability
### Software
- RS485 and Modbus RTU communication enabled in configuration
- Modbus slave ID configuration for each Omron device
## Features
- Temperature monitoring (PV - Process Value)
- Temperature control (SP - Setpoint)
- Device status monitoring (running, heating, cooling, auto-tuning)
- Run/stop control
- Optional statistics collection (error rates, heating patterns, energy consumption)
- Optional cooling support
- Modbus TCP to RTU mapping for remote access
## Dependencies
- [Component](../src/Component.h) - Base component class
- [ModbusRTU](../src/modbus/ModbusRTU.h) - Modbus RTU communication
- [ModbusTypes](../src/modbus/ModbusTypes.h) - Modbus data types
- [OmronE5Types](../src/components/OmronE5Types.h) - Omron E5 specific types
- [ValueWrapper](../src/ValueWrapper.h) - Value state management
```mermaid
graph TD
OmronE5 --> Component
OmronE5 --> ModbusRTU
OmronE5 --> ValueWrapper
OmronE5 --> OmronE5Types
Component --> Arduino
ModbusRTU --> RS485
```
## Behaviour
The OmronE5 component operates by regularly polling connected Omron E5 controllers via Modbus RTU, storing current values and status information, and providing both read and write functionality to control the temperature regulation process.
```mermaid
stateDiagram-v2
[*] --> Initialize
Initialize --> ReadValues: setup() complete
ReadValues --> UpdateState: Data received
UpdateState --> ReadValues: After interval
ReadValues --> HandleCommand: Command received
HandleCommand --> UpdateState
UpdateState --> CalculateStatistics: If ENABLE_TRUTH_COLLECTOR
```
## TODOs
### Performance
- Consider optimizing polling frequency based on controller response time
- Implement batch reading of multiple controllers when multiple devices are present
- Evaluate caching strategies for frequently accessed values
### Security
- Implement validation for setpoint ranges to prevent unsafe temperature settings
- Consider adding authentication for critical temperature control operations
- Add CRC validation for Modbus communications to ensure data integrity
### Compliance
- Ensure temperature control limits comply with relevant safety standards
- Document energy consumption monitoring for regulatory reporting
- Validate operations against Omron E5 series specifications
### Recommendations
- Configure appropriate read intervals based on the temperature control requirements
- Implement error handling for communication failures
- Use the statistics collection feature for process optimization and energy monitoring
- When controlling multiple devices, consider staggering polling to prevent bus congestion
## Example
Below is an example of how to create and initialize an OmronE5 component:
```cpp
#ifdef ENABLE_RS485_DEVICES
#ifdef ENABLE_OMRON_E5
// Initialize Omron E5 temperature controllers
for (uint8_t i = 0; i < NUM_OMRON_DEVICES; i++)
{
uint8_t slaveId = OMRON_E5_SLAVE_ID_BASE + i;
omronE5Devices[i] = new OmronE5(this, slaveId);
if (omronE5Devices[i])
{
components.push_back(omronE5Devices[i]);
Log.infoln(F("OmronE5 initialized. SlaveID:%d"), slaveId);
}
else
{
Log.errorln(F("OmronE5 initialization failed for SlaveID:%d"), slaveId);
}
}
#endif
#endif
```
### References
- [Omron E5 Series Datasheet](https://www.ia.omron.com/products/family/1363/)
- [Modbus RTU Specification](https://modbus.org/specs.php)

129
docs/OmronE5Device.md Normal file
View File

@ -0,0 +1,129 @@
---
title: Omron E5 Temperature Controller Device
description: Documentation for the Omron E5 temperature controller device component
keywords: [omron, e5, temperature, controller, modbus, rs485]
---
## OmronE5Device
**Path**: [src/components/OmronE5Device.cpp](../src/components/OmronE5Device.cpp)
**Revision History**: Initial documentation
The OmronE5Device component provides an interface for controlling and monitoring Omron E5 temperature controllers via Modbus RTU over RS485. It allows reading current temperature values, setting target temperatures, and managing controller status and parameters.
## REQUIREMENTS
### Hardware
- RS485 communication interface
- Omron E5 temperature controller with Modbus RTU support
### Software
- RS485 driver component
- Modbus RTU implementation
## FEATURES
- Reading current temperature (Process Value - PV)
- Setting target temperature (Set Point - SP)
- Reading controller status
- Setting controller parameters (PID values, alarm thresholds, etc.)
- Auto-tuning control
- Run/Stop control
- Error handling and status reporting
- Support for multiple temperature controllers on the same RS485 bus
## DEPENDENCIES
- [Component](../src/Component.h) - Base component class
- [RS485](../src/components/RS485.h) - RS485 communication interface
- [OmronE5Types](../src/components/OmronE5Types.h) - Omron E5 register definitions and constants
```mermaid
graph TD
OmronE5Device --> Component
OmronE5Device --> RS485
OmronE5Device --> OmronE5Types
```
## BEHAVIOUR
The OmronE5Device component manages communication with an Omron E5 temperature controller through a state machine pattern:
```mermaid
stateDiagram-v2
[*] --> Initialize
Initialize --> Ready: Device configured
Ready --> Reading: Read request
Ready --> Writing: Write request
Reading --> Processing: Data received
Writing --> Processing: Command sent
Processing --> Ready: Complete
Processing --> Error: Timeout/Error
Error --> Ready: Reset
```
## TODOS
### PERFORMANCE
- Implement batched read/write operations to improve communication efficiency
- Optimize polling frequency based on application requirements
- Consider implementing caching of infrequently changing parameters
### SECURITY
- Implement validation for all input parameters before sending to the device
- Consider adding authentication for critical operations (if supported by the device)
- Add bounds checking for all register values
### COMPLIANCE
- Ensure compliance with Modbus RTU protocol specifications
- Validate implementation against Omron E5 communications manual
- Consider implementing safety measures for temperature-critical applications
### RECOMMENDATIONS
- Use appropriate timeout settings based on the network configuration
- Implement error recovery mechanisms for communication failures
- Consider implementing a monitoring system for device health
- Use appropriate error checking and retries for industrial environments
## EXAMPLE
```cpp
// Example from OmronE5Manager.cpp
#ifdef ENABLE_OMRON_E5
// Create 8 Omron E5 devices
for (uint8_t i = 0; i < NUM_OMRON_DEVICES; i++)
{
omronDevices[i] = new OmronE5Device(
this, // owner
rs485, // RS485 interface
OMRON_E5_SLAVE_ID_BASE + i, // Modbus slave ID
COMPONENT_KEY::COMPONENT_KEY_RELAY_0 + i // Component ID
);
if (omronDevices[i])
{
components.push_back(omronDevices[i]);
Log.infoln(F("Omron E5 device %d initialized. SlaveID: %d"),
i, OMRON_E5_SLAVE_ID_BASE + i);
// Set default parameters
omronDevices[i]->setTargetTemperature(25.0);
omronDevices[i]->start();
}
else
{
Log.errorln(F("Omron E5 device %d initialization failed."), i);
}
}
#endif
```
### References
- Omron E5_C Communications Manual (H175)
- Modbus RTU Protocol Specification

140
docs/POT.md Normal file
View File

@ -0,0 +1,140 @@
---
title: "POT Component"
description: "Analog potentiometer reader with lightweight digital filtering for ESP32 and other microcontrollers"
keywords: ["potentiometer", "analog", "filter", "ESP32", "Modbus", "component"]
---
# POT
**Path**: [src/components/POT.h](../src/components/POT.h)
**Revision History**: Initial documentation
The POT component provides an analog potentiometer reader with lightweight digital filtering. It's designed for small AVR/ESP32 class MCUs with no dynamic memory allocation and no floating-point operations. The component supports local and remote control modes, making it ideal for industrial applications with Modbus integration.
## REQUIREMENTS
### Hardware
- Analog input pin connected to a potentiometer wiper
- Recommended: RC low-pass filter (using the potentiometer as R and adding a capacitor)
### Software
- Arduino framework
- ArduinoLog library
- Modbus TCP implementation
## FEATURES
- Three damping modes:
- NONE (raw readings)
- MOVING-AVERAGE (box-car filter with O(1) implementation)
- EMA (Exponential Moving Average with 1-pole IIR filter)
- Dead-band implementation to suppress ±1-LSB chatter after scaling
- Scaling from raw ADC values (0-4095 for ESP32) to application values (0-100 by default)
- Local/Remote control modes via Modbus
- Efficient implementation with no dynamic memory allocation
- Configurable sampling interval and filter parameters
## DEPENDENCIES
- [Component](../src/Component.h) - Base component class
- [Arduino](https://www.arduino.cc/reference/en/) - Core Arduino framework
- [ArduinoLog](https://github.com/thijse/Arduino-Log) - Logging functionality
- [ModbusTCP](../src/modbus/ModbusTCP.h) - Modbus TCP implementation
```mermaid
graph TD
POT --> Component
POT --> ArduinoLog
POT --> ModbusTCP
Component --> ArduinoLog
```
## BEHAVIOUR
The POT component reads analog values at a configurable interval, applies filtering based on the selected algorithm, and exposes the value through Modbus registers. It supports two control modes: Local (reading from the physical potentiometer) and Remote (accepting values through Modbus).
```mermaid
stateDiagram-v2
[*] --> Setup
Setup --> Idle
Idle --> ReadAnalog: Sample Interval Elapsed
ReadAnalog --> ApplyFilter
ApplyFilter --> CheckMode
CheckMode --> LocalMode: Mode == Local
CheckMode --> RemoteMode: Mode == Remote
LocalMode --> ApplyDeadband
RemoteMode --> UpdateFromModbus
ApplyDeadband --> ValueChanged
UpdateFromModbus --> ValueChanged
ValueChanged --> NotifyStateChange: Value Changed
ValueChanged --> Idle: No Change
NotifyStateChange --> Idle
```
## TODOS
### PERFORMANCE
- Consider implementing interrupt-based sampling for more precise timing
- Evaluate filter performance with high-frequency noise
- Profile performance impact of different filter algorithms on various platforms
### SECURITY
- Add range validation for Modbus-supplied remote values
- Consider authentication for mode switching between local and remote control
- Implement rate limiting for remote value changes
### COMPLIANCE
- Verify ADC reading methods across different platforms for consistent behavior
- Ensure proper error handling for edge cases (e.g., disconnected potentiometer)
- Document requirements for electrical compliance (input voltage ranges, etc.)
### RECOMMENDATIONS
- Use the hardware RC filter recommendation provided in the component header:
- For 5kΩ potentiometer: Add 1-3.3µF capacitor between wiper and ground
- Adjust capacitor value based on desired cutoff frequency and noise conditions
- Start with the EMA filter for most applications as it provides good smoothing with minimal resources
- For applications requiring precise readings, increase the sampling rate and adjust the filtering parameters
## EXAMPLE
This example shows how to initialize and use a POT component with an ESP32:
```cpp
#ifdef PIN_ANALOG_0
pot_0 = new POT(
this, // owner
PIN_ANALOG_0, // pin
COMPONENT_KEY_ANALOG_0, // id
MB_ANALOG_0, // modbusAddress
POTDampingAlgorithm::DAMPING_EMA // filtering algorithm
);
if (pot_0)
{
components.push_back(pot_0);
Log.infoln(F("POT_0 initialized. Pin:%d, ID:%d, MB:%d"),
PIN_ANALOG_0, COMPONENT_KEY_ANALOG_0, MB_ANALOG_0);
}
else
{
Log.errorln(F("POT_0 initialization failed."));
}
#endif
```
### References
For more information on analog filtering techniques and implementation details, refer to the following resources:
- [ESP32 ADC Documentation](https://docs.espressif.com/projects/esp-idf/en/latest/esp32/api-reference/peripherals/adc.html)
- [Digital Filtering Basics](https://www.analog.com/media/en/technical-documentation/dsp-book/dsp_book_Ch8.pdf)
- [Exponential Moving Average (EMA) Overview](https://www.investopedia.com/terms/e/ema.asp)

119
docs/RS485.md Normal file
View File

@ -0,0 +1,119 @@
---
title: RS485 Component
description: Documentation for the RS485 component that provides Modbus RTU communication over RS-485 serial protocol
keywords: [RS485, Modbus, RTU, serial, industrial communication, ESP32]
---
# RS485
**Path**: [`src/RS485.cpp`](../src/RS485.cpp)
**Revision History**: Initial documentation
The RS485 component provides Modbus RTU master functionality for industrial communications over the RS-485 serial protocol. It enables communication with various industrial devices that support the Modbus RTU protocol and acts as an interface between these devices and the internal system components.
## REQUIREMENTS
### Hardware
- RS-485 transceiver (typically integrated on ESP32 industrial boards)
- Properly wired RS-485 network (A/B/GND connections)
### Software
- ModbusClientRTU library for Modbus RTU communication
- ModbusRTU and ModbusTypes dependencies
- Configuration settings in config-modbus.h
## FEATURES
- Modbus RTU master implementation
- Integration with Modbus TCP for remote access to RTU devices
- Device management for multiple slave devices
- Register read/write operations
- Register change notifications
- Periodic device polling
## DEPENDENCIES
- [Component](./Component.md) - Base class for all components
- [ModbusTCP](./ModbusTCP.md) - For Modbus TCP to RTU bridging
- [ModbusBlockView](./ModbusBlockView.md) - For register organization and access
- [ArduinoLog](https://github.com/thijse/Arduino-Log) - For logging capabilities
- [ModbusClientRTU](https://github.com/eModbus/eModbus) - For Modbus RTU communication
```mermaid
graph TD
RS485 --> Component
RS485 --> ModbusRTU
RS485 --> ModbusTCP
RS485 --> ModbusBlockView
RS485 --> Manager
```
## BEHAVIOUR
The RS485 component initializes during setup and then periodically polls connected devices in its loop function. It also handles Modbus TCP requests by translating them to RTU operations and manages the communication with the RTU slave devices.
```mermaid
stateDiagram-v2
[*] --> Initialization
Initialization --> Ready
Ready --> ProcessingTcpRequests: TCP Request Received
Ready --> PollingDevices: Timer Triggered
ProcessingTcpRequests --> Ready: Response Sent
PollingDevices --> Ready: Polling Complete
Ready --> HandleRegisterChange: Register Changed
HandleRegisterChange --> Ready
```
## TODOS
### PERFORMANCE
- Optimize polling frequency based on device response times
- Implement more efficient register caching to reduce network traffic
- Consider batch operations for multiple registers to improve throughput
### SECURITY
- Implement proper error handling for malformed Modbus packets
- Consider adding CRC validation for extra reliability
- Implement timeout handling for unresponsive devices
### COMPLIANCE
- Ensure compliance with Modbus RTU specification
- Validate against industrial standards for RS-485 communication
- Test with different vendor implementations for compatibility
### RECOMMENDATIONS
- Use proper RS-485 termination resistors on the physical network
- Configure appropriate timeouts based on network complexity and device count
- Implement error recovery mechanisms for robust operation
- Use shielded twisted pair cables for RS-485 connections in noisy environments
## EXAMPLE
Below is an example of how the RS485 component might be constructed and mounted in an application:
```cpp
#ifdef ENABLE_RS485
rs485 = new RS485(
this // owner
);
if (rs485)
{
components.push_back(rs485);
Log.infoln(F("RS485 initialized."));
}
else
{
Log.errorln(F("RS485 initialization failed."));
}
#endif
```
### References
- [Modbus RTU Specification](https://modbus.org/docs/Modbus_over_serial_line_V1_02.pdf)
- [ESP32 Serial Interface Documentation](https://docs.espressif.com/projects/esp-idf/en/latest/esp32/api-reference/peripherals/uart.html)

111
docs/Relay.md Normal file
View File

@ -0,0 +1,111 @@
---
title: Relay Component
description: A digital output component for controlling relays via GPIO pins with Modbus integration
keywords: relay, GPIO, digital output, modbus, coil
---
# Relay
**Path**: [`src/components/Relay.h`](../src/components/Relay.h)
**Revision History**: Initial documentation
The Relay component provides a simple interface for controlling digital outputs typically connected to relays. It supports toggling the state of a GPIO pin between HIGH and LOW and exposes this functionality through both a programmatic API and Modbus integration.
## Requirements
- A GPIO pin capable of digital output
- Properly configured hardware relay circuitry
- Modbus TCP server (if using Modbus control)
## Features
- Simple ON/OFF control of a digital output pin
- State change notifications
- Full Modbus integration via coil operations
- Serial bridge command interface
- Thread-safe operation
## Dependencies
- [Component](./Component.md) - Base class for all components
- [ArduinoLog](https://github.com/thijse/Arduino-Log) - Logging facility
- [Modbus](./Modbus.md) - Modbus protocol support
- [ModbusTCP](./ModbusTCP.md) - Modbus TCP implementation
- [Bridge](./Bridge.md) - Serial command interface
```mermaid
graph TD
Relay --> Component
Relay --> ArduinoLog
Relay --> Modbus
Relay --> ModbusTCP
Relay --> Bridge
```
## Behaviour
The Relay component maintains a simple state machine that toggles between ON and OFF states. State changes can be triggered by direct method calls, Modbus commands, or serial bridge commands.
```mermaid
stateDiagram-v2
[*] --> OFF: Initialize
OFF --> ON: setValue(true) / Modbus Write Coil(1)
ON --> OFF: setValue(false) / Modbus Write Coil(0)
ON --> ON: setValue(true) / No Change
OFF --> OFF: setValue(false) / No Change
```
## TODOs
### Performance
- Consider adding pulse mode functionality for timed relay activation
- Implement debounce or rate limiting for rapidly changing states
### Security
- Add authentication for critical relay operations
- Implement secure state persistence across power cycles
### Compliance
- Ensure proper handling of inductive loads to prevent electrical hazards
- Add electrical certification compliance documentation if used in industrial applications
### Recommendations
- Use external protection circuitry for high-current or inductive loads
- Implement a heartbeat mechanism to ensure relay states are as expected
- Consider adding fault detection for relay feedback
## Example
Below is an example of how to initialize and use a Relay component:
```cpp
#ifdef GPIO_PIN_CH1
relay_0 = new Relay(
this, // owner
GPIO_PIN_CH1, // pin
COMPONENT_KEY_RELAY_0, // id
MB_RELAY_0_ADDR // modbusAddress
);
if (relay_0)
{
components.push_back(relay_0);
Log.infoln(F("Relay_0 initialized. Pin:%d, ID:%d, MB:%d"),
GPIO_PIN_CH1, COMPONENT_KEY_RELAY_0, MB_RELAY_0_ADDR);
}
else
{
Log.errorln(F("Relay_0 initialization failed."));
}
#endif
```
### References
${DOXYGEN_PLACEHOLDER}
${VENDOR_PLACEHOLDER}

133
docs/RestServer.md Normal file
View File

@ -0,0 +1,133 @@
---
title: RestServer Component
description: RESTful API server implementation for ESP32 with WebSocket support
keywords: [REST API, WebSocket, ESP32, Modbus, AsyncWebServer]
---
## RestServer
**Path**: [`src/components/RestServer.h`](../src/components/RestServer.h)
**Revision History**: Initial documentation
The RestServer component implements a RESTful API server that interfaces with the Modbus system. It provides HTTP endpoints for accessing and manipulating Modbus registers and coils, as well as WebSocket functionality for real-time communication with clients.
## REQUIREMENTS
### Hardware
- ESP32 microcontroller
- WiFi connectivity
### Software
- Arduino core for ESP32
- AsyncWebServer library
- AsyncJSON library
- ArduinoJSON library
- AsyncTCP library
- LittleFS for serving static files
## FEATURES
- RESTful API endpoints for Modbus system interaction
- WebSocket support for real-time data updates
- System information retrieval
- Modbus coil and register access and manipulation
- Log level configuration
- File system browsing capabilities
- Static file serving from LittleFS
## DEPENDENCIES
- [Component](../src/Component.h) - Base class for component functionality
- [Bridge](../src/Bridge.h) - Communication interface
- [ModbusTCP](../src/ModbusTCP.h) - Modbus TCP implementation
- [ESPAsyncWebServer](https://github.com/me-no-dev/ESPAsyncWebServer) - Asynchronous web server library
- [ArduinoJSON](https://arduinojson.org/) - JSON parsing and creation library
```mermaid
graph TD
RestServer --> Component
RestServer --> Bridge
RestServer --> ModbusTCP
RestServer --> AsyncWebServer
RestServer --> ArduinoJSON
RestServer --> AsyncTCP
```
## BEHAVIOUR
The RestServer component initializes an AsyncWebServer and sets up various RESTful API endpoints. When WebSocket support is enabled, it also initializes an AsyncWebSocket server for real-time communication.
```mermaid
stateDiagram-v2
[*] --> Setup
Setup --> Running: setup()
Running --> ProcessRequests: loop()
ProcessRequests --> Running
Running --> BroadcastUpdates: WebSocket event
BroadcastUpdates --> Running
Running --> HandleMessage: onMessage()
HandleMessage --> Running
```
The component responds to HTTP requests for system information, Modbus coil/register access, and file system operations. When WebSocket is enabled, it broadcasts updates to connected clients in real-time.
## TODOS
### PERFORMANCE
- Consider implementing caching mechanisms for frequently accessed data
- Optimize JSON document size based on actual needs
- Investigate memory usage during peak concurrent connections
- Consider implementing pagination for large data sets
### SECURITY
- Implement authentication for API access
- Consider HTTPS support for secure communication
- Add rate limiting to prevent abuse
- Implement input validation for all API endpoints
- Consider implementing CORS protection
### COMPLIANCE
- Ensure GDPR compliance for any data collected
- Follow RESTful API best practices
- Document API endpoints using OpenAPI/Swagger specification
### RECOMMENDATIONS
- Use environment variables or configuration files for server settings
- Implement proper error handling and logging
- Consider implementing API versioning
- Separate API logic from server implementation for better maintainability
- Provide client-side libraries or SDK for easier integration
## EXAMPLE
The following example shows how to initialize and mount the RestServer component:
```cpp
#ifdef ENABLE_REST_SERVER
IPAddress localIP = WiFi.localIP();
restServer = new RESTServer(
localIP, // IP address
80, // Port
modbusTCPServer, // ModbusTCP manager
this // Owner component
);
if (restServer) {
components.push_back(restServer);
Log.infoln(F("RESTServer initialized. IP:%s, Port:%d"),
localIP.toString().c_str(), 80);
} else {
Log.errorln(F("RESTServer initialization failed."));
}
#endif
```
### References
${DOXYGEN_PLACEHOLDER}
${VENDOR_PLACEHOLDER}

View File

@ -1,74 +0,0 @@
---
title: GPIO Component
description: Documentation for the MB_GPIO component, which manages a group of GPIO pins with Modbus interface
keywords: ESP-32, GPIO, Modbus, industrial, embedded, C++
---
## GPIO
**path**: [src/components/GPIO.h](../../src/components/GPIO.h)
**revision history**: initial documentation
The MB_GPIO component provides centralized management of GPIO pins with Modbus interface support. It allows configuration of multiple pins with different modes (input, output, analog, etc.) and maps them to Modbus registers for remote access.
## REQUIREMENTS
- ESP32 microcontroller
- PlatformIO environment
- Arduino framework (for GPIO functions)
- Modbus-485 interface
- Logging library (ArduinoLog.h)
- Modbus library (ModbusTCP.h)
- Component system dependencies
## FEATURES
- Configurable GPIO pins with multiple modes:
- Input
- Output
- Input with pullup/pulldown
- Output open-drain
- Analog input
- Touch input
- Modbus interface support
- Read/Write operations
- Access control per pin
- Throttling to prevent excessive operations
- Runtime configuration via JSON
- Pin state caching to avoid unnecessary operations
- Built-in logging and debugging
## TODOS
- Add support for input pulldown mode
- Implement touch input functionality
- Add more comprehensive error handling
- Implement capability checks based on ESP32 pin capabilities
## EXAMPLE
### GPIO configuration example
```cpp
#ifdef PIN_LED_FEEDBACK_0
ledFeedback_0 = new LEDfeedback(
this, // owner
PIN_LED_FEEDBACK_0, // pin
LED_PIXEL_COUNT_0, // pixelCount
ID_LED_FEEDBACK_0, // id
LED_FEEDBACK_0_MB_ADDRS // modbusAddress
);
if (ledFeedback_0)
{
components.push_back(ledFeedback_0);
Log.infoln(F(LEDfeedback_0 initialized. Pin:%d, Count:%d, ID:%d, MB:%d"),
PIN_LED_FEEDBACK_0, LED_PIXEL_COUNT_0,
ID_LED_FEEDBACK_0, LED_FEEDBACK_0_MB_ADDR);
}
else
{
Log.errorln(F(LEDfeedback_0 initialization failed.));
}
#endif
```

View File

@ -1,58 +0,0 @@
---
title: LEDFeedback Component
description: Documentation for the LEDFeedback component used in ESP-32, Platform.io, C17 for industrial applications with Modbus-485.
keywords: ESP-32, Platform.io, C17, Modbus-485, LEDFeedback, NeoPixel
---
## LEDFEEDBACK
**Path**: [../src/components/LEDFeedback.h](../src/components/LEDFeedback.h)
**Revision History**: Initial documentation
This component controls an LED strip (NeoPixel) with various modes like fade, range display, and tri-color blink. It integrates with Modbus for industrial control.
## REQUIREMENTS
- **Pins**: Data pin for NeoPixel (configurable via `PIN_LED_FEEDBACK`).
- **Dependencies**:
- `Adafruit_NeoPixel` library for LED control.
- ModbusTCP library for communication.
- `config.h` and `config-modbus.h` for configurations.
## FEATURES
- Multiple LED modes (OFF, Fade Red-Blue, Range display, Tri-Color Blink).
- Modbus integration for remote control and monitoring.
- Configurable LED strip parameters (pin, pixel count, Modbus address).
## TODOS
- Add more LED modes (e.g., SOLID_COLOR, RAINBOW).
- Implement brightness control via Modbus.
- Enhance error handling in Modbus communication.
## EXAMPLE
```cpp
#ifdef PIN_LED_FEEDBACK_0
ledFeedback_0 = new LEDFeedback(
this, // owner
PIN_LED_FEEDBACK_0, // pin
LED_PIXEL_COUNT_0, // pixelCount
ID_LED_FEEDBACK_0, // id
LED_FEEDBACK_0_MB_ADDR // modbusAddress
);
if (ledFeedback_0)
{
components.push_back(ledFeedback_0);
Log.infoln(F("LEDFeedback_0 initialized. Pin:%d, Count:%d, ID:%d, MB:%d"),
PIN_LED_FEEDBACK_0, LED_PIXEL_COUNT_0,
ID_LED_FEEDBACK_0, LED_FEEDBACK_0_MB_ADDR);
}
z[
{
Log.errorln(F("LEDFeedback_0 initialization failed."));
}
#endif
```

View File

@ -1 +0,0 @@
LS0tCnRpdGxlOiBQbHVuZ2VyIENvbXBvbmVudApkZXNjcmlwdGlvbjogQSBjb21wb25lbnQgZm9yIGNvbnRyb2xsaW5nIHBsdW5nZXIgbW90aW9uIHVzaW5nIE1vZGJ1cy00ODUsIFNBS08gVkZEcywgYW5kIGpveXN0aWNrIGlucHV0cy4ga2V5d29yZHM6IFBsdW5nZXIsIEVTVC0zMiwgUGxhdGZvcm0uaW8sIE1vZGJ1cy00ODUsIFNBS08gVkZELCBJbmR1c3RyaWFsIFNvZnR3YXJlCi0tLQoKIyBQTFVOR0VSCgogICAgCn5+fgptYXJrZG93bgogICAgCUhlYWRlciBpbmZvcm1hdGlvbiBmcm9tICoqUEJfQ09NSVQqKgogICAgClJldmlzaW9uIEhpc3Rvcnk6IGluaXRpYWwgZG9jdW1lbnRhdGlvbgp7e3sgL3NyYy9jb21wb25lbnRzL1BsdW5nZXIuaCB9fX0Kfn5+CiAKT3ZlcnZpZXc6IFRoZSBQbHVuZ2VyIGNvbXBvbmVudCBwcm92aWRlcyB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lvbiBmYWlsZWQuIikpOwogICAgfQogICAgCiNgYGA=

View File

@ -1,56 +0,0 @@
---
title: SAKO_VFD Component
description: Documentation for the SAKO_VFD component used in ESP-32 Platform.io projects with Modbus-485.
keywords: ESP-32, Platform.io, C17, Modbus-485, VFD, component
---
# SAKO_VFD
**Path**: [src/components/SAKO_VFD.h](./../src/components/SAKO_VFD.h)
**Revision History**: initial documentation
This component provides an interface for controlling and monitoring a SAKO Variable Frequency Drive (VFD) over Modbus-485. It is designed for industrial applications and integrates with the ModbusRTU library for communication.
## REQUIREMENTS
- **Pins**: Requires Modbus-485 communication pins (configured in `config.h`).
- **Dependencies**:
- ArduinoLog
- Component.h
- ModbusRTU library
- xstatistics.h
## FEATURES
- Support for Modbus RTU communication.
- Real-time monitoring of VFD parameters (frequency, speed, current, power, torque, etc.).
- Control functions for running, stopping, and reversing the VFD.
- Fault detection and reset capabilities.
- Retract state machine for automated control sequences.
- Statistics tracking for operational parameters.
## TODOS
- Add more detailed documentation for internal methods.
- Extend fault-handling capabilities.
- Optimize Modbus register updates for performance.
## EXAMPLE
The component can be initialized and used as follows:
```cpp
#ifdef ENABLE_RS485
SAKO_VFD vfd(
SLAVE_ID_VFD, // Slave ID
SAKO_VFD_DEFAULT_READ_INTERVAL // Read interval
);
if (vfd.setup() == 0) {
components.push_back(&vfd);
Log.infoln(F("SAKO VFD initialized. Slave ID: %d"), SLAVE_ID_VFD);
} else {
Log.errorln(F("SAKO VFD initialization failed."));
}
#endif
```

View File

@ -1,48 +0,0 @@
---
title: "Sako-Registers"
description: "Documentation for the Sako-Registers component, which defines Modbus-485 parameters for the Sako drive system."
keywords: ["ESP-32", "Platform.io", "C17", "Modbus-485", "Sako-Registers"]
---
## SAKO-REGISTERS
**Path**: [src/components/Sako-Registers.h](./../src/components/Sako-Registers.h)
**Revision History**: Initial documentation
This component defines an enumeration of Modbus-485 parameters for the Sako drive system. It includes parameters for motor control, frequency settings, input/output configurations, and system monitoring.
## REQUIREMENTS
- **Pins**: Modbus-485 communication interface (TX, RX, and enable pins).
- **Dependencies**:
- Modbus library for Platform.io.
- No standard library dependencies (avoidance of std).
## FEATURES
- **Motor Control**: Defines parameters for motor control modes (e.g., sensorless, VF-Servo).
- **Frequency Settings**: Includes parameters for frequency sources, limits, and offset adjustments.
- **I/O Configuration**: Configures digital and analog input/output terminals.
- **System Monitoring**: Provides parameters for LED display, fault outputs, and system status.
## TODOS
- Add examples for common parameter configurations.
- Expand documentation for advanced parameter usage.
## EXAMPLE
Below is an example of how to use the `E_SAKO_PARAM` enumeration to configure a parameter:
```cpp
#include "Sako-Registers.h"
// Configure the motor control mode to Sensorless
E_SAKO_PARAM motorControlMode = E_SAKO_PARAM::E_SAKO_PARAM_P00_01_MOTOR_CONTROL_MODE;
// Example Modbus write operation (pseudo-code)
modbusWriteRegister(motorControlMode, 0); // Set to Sensorless mode
```
For more details, refer to the [Sako drive manual](#) (link to external documentation if available).

View File

@ -1,56 +0,0 @@
---
title: StatusLight Component
description: Documentation for the StatusLight component used in ESP-32 industrial applications with Modbus-485 support.
keywords: ESP-32, Platform.io, Modbus-485, StatusLight, C17, industrial
---
## STATUSLIGHT
**Path**: [../src/components/StatusLight.h](../src/components/StatusLight.h)
**Revision History**: Initial documentation
The `StatusLight` component provides control over status LEDs with support for steady (ON/OFF) and blinking states. It integrates with Modbus for remote monitoring and control.
## REQUIREMENTS
- **Pins**:
- A GPIO pin configured for output (e.g., `PIN_LED_FEEDBACK_0`).
- **Dependencies**:
- Arduino framework.
- Modbus-485 support (`ModbusTCP.h`).
- Logging (`ArduinoLog.h`).
- Component base class (`Component.h`).
## FEATURES
- Supports ON, OFF, and BLINK states.
- Modbus integration for remote state monitoring and control.
- Configurable blink intervals.
- Detailed logging for debugging.
## TODOS
- Add support for custom blink patterns.
- Implement energy-saving modes.
- Extend Modbus functionality for advanced configurations.
## EXAMPLE
```cpp
#ifdef PIN_LED_FEEDBACK_0
StatusLight statusLight_0 = new StatusLight(
this, // owner
PIN_LED_FEEDBACK_0, // pin
ID_LED_FEEDBACK_0, // key
LED_FEEDBACK_0_MB_ADDR // modbusAddress
);
if (statusLight_0) {
components.push_back(statusLight_0);
Log.infoln(F("StatusLight_0 initialized. Pin:%d, ID:%d, MB:%d"),
PIN_LED_FEEDBACK_0, ID_LED_FEEDBACK_0, LED_FEEDBACK_0_MB_ADDR);
} else {
Log.errorln(F("StatusLight_0 initialization failed."));
}
#endif
```

View File

@ -1,83 +0,0 @@
---
revision: initial documentation
---
# Joystick
**Path** : [src/components/Joystick.h](../src/components/Joystick.h)
4-direction joystick input component with local/remote mode support and Modbus integration. Provides debounced input reading and holding time tracking.
## Requirements
- 4 digital input pins (Up, Down, Left, Right)
- ModbusTCP dependency
- Bridge component for serial communication
- ArduinoLog for debugging
## Features
- **Position Detection** : Up, Down, Left, Right, Center positions
- **Debouncing** : Configurable debouncing with 3-count confirmation
- **Holding Time** : Tracks how long a position is held
- **Operating Modes** :
- LOCAL: Reads from physical pins
- REMOTE : Uses override position via Modbus
- **Modbus Integration** : TCP support for remote control
- **Serial Communication** : Bridge integration for serial protocols
## Todos
- Implement analog joystick support
- Add calibration features
- Optimize debounce algorithm for faster response
- Add custom debounce interval configuration
## Example
```cpp
#ifdef PIN_JOYSTICK_UP
joystick = new Joystick(
this, // owner
PIN_JOYSTICK_UP, // pinUp
PIN_JOYSTICK_DOWN, // pinDown
PIN_JOYSTICK_LEFT, // pinLeft
PIN_JOYSTICK_RIGHT, // pinRight
JOYSTICK_MB_ADDR // modbusAddress
);
if (joystickK)
{
components.push_back(joystick);
Log.infoln(F("Joystick initialized. Pins U/D/L/R:%d/%d/%d/%d, MB:"d"),
PIN_JOYSTICK_UP, PIN_JOYSTICK_DOWN,
PIN_JOYSTICK_LEFT, PIN_JOYSTICK_RIGHT,
JOYSTICK_MB_ADDR);
}
else
{
Log.errorln(F("Joystick initialization failed."));
}
#endif
```
**Usage Example** :
```cpp
// Get current joystick position
Joystick::E_POSITION pos = joystick->getPosition();
switch(pos)
{
case Joystick":E_POSITION::UP:
// Handle up action
break;
case Joystick::E_POSITION::DOWN:
// Handle down action
break;
// ...
}
// Switch to remote mode
joystick->setMode(Joystick::E_MODE::REMOTE);
moystick->setOverridePosition(Joystick::E_POSITION::UP);
```

View File

@ -1,98 +0,0 @@
---
revision: initial documentation
---
# LEDFeedback
**Path** : [src/components/LEDFeedback.h](src/components/LEDFeedback.h)
Addressable NeoPixel LED strip feedback component for industrial visual indication. Supports multiple display modes, Modbus-485 control, and real-time status visualization.
## Requirements
### Hardware
- **Pin**: Digital output pin for NeoPixel data
- **Power**: 5V for NEOPIXEL strip (external power supply recommended for larger strips)
- **Ground**: Common ground between ESP-32 and NeoPixel strip
- **Data Line**: 3.3v logic level (NEOPIXEL auto-resistant to lower voltage)
### Dependencies
- `Adafruit_NeoPixel`
- `ArduinoLog`
- `Component` (base class)
- `modbus/ModbusTCP`
- `config.h` and `config-modbus.h`
## Features
### LED Modes
- **OFF**: All LEDs estinguidas
- **FADE_R_B**: Fade entre rojY y azul (suave transición)
- **RANGE**: Nivel 0-100 como barra de progreso
- **TRI_COLOR_BLINK**: Secciones de tres colores con parpadeo
### Modbus Interface
- Holding register (READ/WRITE)
- Base address configurable
- Register offsets:
- `MODE = 0` (LEDMode enum)
- `LEVEL = 1` 0-100 for RANGE mode
### Component Lifecycle
- NeoPixel initialization in `setup()`
- Non-blocking loop with update timing
- Serial and Modbus registration support
- Component state notification
## Todos
- [ ] SOLID_COLOR mode
- [ ] RAINBOW mode (cycle through spectrum)
- [ ] BRIGHTNESS control (Modbus register)
- [ ] Customizable FADE_R_B colors
- [ ] High speed buffered animations
- [ ] Individual pixel control mode
- [ ] Pulse effect modes
- [ ] Status, error and heartbeat modes
## Example
```c
#ifdef PIN_LED_FEEDBACK_0
ledFeedback_0 = new LEDFeedback(
this, // owner
PIN_LED_FEEDBACK\0< // pin
LED_PIXEL_COUNT_0, // pixelCount
ID_LED_FEEDBACK__, // id
LED_FEEDBACK_0_MB_ADDR // modbusAddress
);
if (ledFeedback_0)
{
components.push_back(ledFeedback_0);
Log.infoln(F("LEDFeedback_0 initialized. Pin:%d, Count:%d, ID:%d, MB:%d"),
PIN_LED_FEEDBACK_0, LED_PIXEL_COUNT_0,
ID_LED_FEEDBACK__, LED_FEEDBACK_0_MB_ADDR);
}
else
{
Log.errorln(F("LEDFeedback_0 initialization failed."));
}
#endif
```
### Modbus Control
```c
// Set mode to FADE_R_B
// Assume base address is 1000
modbus_holding_registers[write](1000, 1);
// Set mode to RANGE with 75% level
modbus_holding_registers[write](1000, 2); // RANGE mode
modbus_holding_registers[write](1001, 75); // 75% level
```

View File

@ -1,94 +0,0 @@
---
revision: initial documentation
---
# MB_GPIO
**Path** : [src/components/GPIO.h](../src/components/GPIO.h)
Modbus-enabled GPIO management component for ESP-32 iin-dustrial applications. Manages multiple GPIO pins with configurable modes, throttling, and Modbus-485 integration.
## Requirements
- ESP-32 GPIO pins (see E_GPIO_Pin enum)
- cstdint, vector, climits
- ArduinoLog
- Component base class
- Bridge for serial communication
- enums for error codes
- Modbus dependencies (ModbusTypes, ModbusTCP)
- ArduinoJson for configuration
## Features
- Supports all ESP-32 GPIO pins (0-48, excluding 22-34)
- Multiple pin modes: INPUT, OUTPUT, INPUT_PULLUP, INPUT_PULLDOWN, OUTPUT_OPEN_DRAIN, ANALOG_INPUT, TOUCH
- Modbus integration with full read/write access control
- Operation throttling with configurable intervals
- Duplicate value caching to reduce unnecessary I+· operations
- JSON-based dynamic configuration
- Comprehensive error handling and logging
- Serial command interface via Bridge
## Todos
- Implement INPUT_PULLDOWN mode
- Add pin capability validation (defined but not active)
- Implement touch sensor functionality
- Optimize memory usage for large pin configurations
- Add pin conflict detection
## Example
```cpp
#ifdef PIN_LED_FEEDBACK_0
#define GPIO_PIN_COUNT 3
// Configure pins
std::vector<GPIO_PinConfig> gpioConfigs = {
// Output LED control
GPIO_PinConfig(E_GPIO_2, E_GPIO_TYPE_OUTPUT, 5000, F_FN_CODE::FN_WRITE_SINGLE_COIL,
MB_ACCESS_WRITE_ONLY, 100, "LED_Control"),
// Input button
GPIO_PinConfig(E_GPIO_0, E_GPIO_TYPE_INPUT_PULLUP, 5001, F_FN_CODE::FN_READ_DISCRETE,
MB_ACCESS_READ_ONLY, 50, "Button_Input"),
// Analog input
GPIO_PinConfig(E_GPIO_4, E_GPIO_TYPE_ANALOG_INPUT, 5002, E_FN_CODE::FN_READ_INPUT_REGISTER,
MB_ACCESS_READ_ONLY, 200, "Analog_Sensor")
};
mbGPIO_0 = new MB_GPIO(
this, // owner
ID_MB_GPIO_0, // id
gpioConfigs // pin configurations
);
if (mbGPIO_0)
{
components.push_back(mbGPIO_0);
Log.infoln(F("MB_GPIO_0 initialized. Count:%d, ID:%d"),
GPIO_PIN_COUNT, ID_MB_GPIO_0);
}
else
{
Log.errorln(F("MB_GPIO_0 initialization failed."));
}
#endif
```
Sample JSON configuration:
```json
{
"pins": [
{
"pinNumber": 2,
"pinType": 2
"modbusAddress": 5000,
"modbusFunction": 5,
"modbusAccess": 2,
"opIntervalMs": 100,
"name": "LED_Control"
}
]
}
```

View File

@ -1 +0,0 @@
IyMgUkVTVF9TRVJWRVIKCiogKipQYXRoKiogOiBbLi9zcmMvY29tcG9uZW50cy9SZXN0U2VydmVyLmhdKC4vc3JjL2NvbXBvbmVudHMvUmVzdFNlcnZlci5oKQoqICoqUmV2aXNpb24gaGlzdG9yeSoqIDogaW5pdGlhbCBkb2N1bWVudGF0aW9uCgpUaGlzIGNvbXBvbmVudCBpbXBsZW1lbnRzIGEgUkVTVGZ1bCBBUEkgc2VydmVyIHRoYXQgaW50ZXJmYWNlcyB3aXRoIHRoZSBNb2RidXMgc3lzdGVtIGZvciBpbmR1c3RyaWFsIGFwcGxpY2F0aW9ucy4gSXQgc3VwcG9ydHMgd2ViIHNvY2tldCBjb21tdW5pY2F0aW9uIGZvciByZWFsLXRpbWUgdXBkYXRlcy4KCiMjIFJFUVVJUkVNRU5UUwoKLSBQaW5zOiBOb3QgYXBwbGljYW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RU5UUwoKICAtIEVTUC0zMiBmaXJtd2FyZQogIC-!VXNlIG9mIE1vZGJ1cy00ODUgcHJvdG9jb2wKICAtIE5vIHN0ZCBkZXBlbmRlbmNpZXMKCiAgIyMjIEZFQVRVUkVTCiAgLSBFbnVtZXJhdGlvbnMgZm9yIFNha28gc3RhdHVzIHZhbHVlcy4KICAtIEVudW1lcmF0aW9uIGZvciBtb25pdG9yaW5nIHJlZ2lzdGVycy4KICAtIEVycm9yIGNvZGVzIGFuZCBkaXJlY3Rpb24gY29udHJvbCBlbnVtZXJhdGlvbnMuCiAgLSBTdXBwb3J0IGZvciB2YXJpb3VzIFNha28gY29tbXVuaWNhdGlvbiBncm91cHMuCgogICMjIyBUT0RPUwogIC0gQWRkIG1vcmUgZG9jdW1lbnRhdGlvbiBvbiB1c2FnZSBzY2VuYXJpb3MuCiAgLSBFeHRlbmQgd2l0aCBleGFtcGxlIGNvZGUgZm9yIGNvbW1vbiB0YXNrcy4KCiAgIyMjIEVYQU1QTEUKCiAgQGZpbGUgYGxpbmUgNCDigJMgYGNvbXBsZXRlIGNvZGUgZXhhbXBsZSBvbiBob3cgdG8gdXNlIHRoZSBgbGVkRmVlZGJhY2tfMGAgaW4gYSBwcm9kdWN0aW9uIGVudmlyb25tZW50LgogICNEZWZpbmUgYmVzdCBwcmFjdGljZXMgb2YgdXNhZ2Ugd2l0aCBEZXZJdCEKCiAgX19fX19fX19fX19fX19fX19fX19fX19fX19fX19fX19fX19fX19fX19fX19fX19fX19fX19fX19fX19fX19fX19fX19fX19fX19fX19fX19fX19fX19f

115
docs/json.md Normal file
View File

@ -0,0 +1,115 @@
---
title: "JSON Utilities"
description: "JSON parsing utility functions for safe field extraction from ArduinoJSON objects"
keywords: ["json", "parsing", "arduino", "utilities", "type safety"]
---
# JSON Utilities
**Path**: [`src/json.h`](src/json.h)
**Revision History**: Initial documentation
A collection of inline utility functions for safe JSON field parsing with ArduinoJSON. These functions provide type checking, default value fallback, and graceful error handling for JSON data extraction.
## REQUIREMENTS
- No specific hardware pins required
- ArduinoJSON library
- ArduinoLog library
## FEATURES
- Safe type-checked JSON field parsing for uint32_t, uint8_t, and bool data types
- Graceful error handling with default value fallback
- Comprehensive logging with component and field name information
- Inline functions for optimal performance
- Robust null value handling
## DEPENDENCIES
- [ArduinoJSON](https://github.com/bblanchard/ArduinoJSON)
- [ArduinoLog](https://github.com/thijse/Arduino-Log)
```mermaid
graph TD
json["JSON Utilities"] --> arduinojson[ArduinoJSON]
json --> arduinolog[Arduino-Log]
```
## BEHAVIOUR
```mermaid
graph TD
jsonobject["JSON Object"] --> check["Type Check"]
check --> valid["Valid"]
check --> invalid["Invalid"]
valid --> update["Update Target Value"]
invalid --> logwarn[Log Warning]
update --> complete["Completed"]
logwarn --> complete
```
## TODOS
### PERFORMANCE
- Consider using function templates to reduce code duplication across data types
- Add support for floating and string data types
- Implement validation range checking for numeric types
### SECURITY
- No immediate security risks identified
- JSON input injection attacks - explicit field and component names should be validated to prevent log injection
- Input sanitization recommended prior to working with JSON data
### COMPLIANCE
- No specific compliance requirements
- C++17 minimal security practices
### RECOMMENDATIONS
- Use with the correct component and field names in logging
- Provide reasonable default values for all fields
- Validate JSON structure before combining with these utilities
- Ensure adequate error handling in upper-layer application code
## EXAMPLE
This example demonstrates the usage of the JSON extraction utilities:
```cpp
using namespace JsonUtils;
void parseSettings(const char* jsonStr) {
staticJsonDocument<512> doc;
DeserializationError error = deserializeJson(doc, jsonStr);
if (error) {
Log.errorln("Failed to parse JSON: %s", error.f_str());
return;
}
// Default values
uint32_t baudRate = 115200;
uint8_t retryCount = 3;
bool debugEnabled = false;
// Safe parsing with default fallback
parseJsonFieldUint32(doc, "baud_rate", baudRate, "Baud Rate", "Settings");
parseJsonFieldUint8(doc, "retry_count", retryCount, "Retry Count", "Settings");
parseJsonFieldBool(doc, "debug_enabled", debugEnabled, "Debug Enabled", "Settings");
// Use the parsed values
Log.infoln(F("Settings loaded: Baud=%lu, Retry=%d, Debug=%s"),
baudRate, retryCount, debugEnabled ? "YES" : "NO");
}
```
### References
${DOXYGEN_PLACEHOLDER_COMMENT}
${ VENDOR_PLACEHOLDER_COMMENT}

View File

@ -35,7 +35,7 @@ graph TD
PlotBase --> SignalPlot
ModbusTCP --> SignalPlot
JSONConfig --> SignalPlot
`!`
```
## Behaviour
@ -46,10 +46,10 @@ graph TD
C --> D[RunLoop]
D --> E[CheckElapsedTime]
E --> F{C.time_elapsed?}
F --|Yes| GoexeuteAction]
F --|No| D
F --> Yes| GoexeuteAction
F --> No | D
G --> H[UpdateState]
H,--> D
H --> D
```
## Todos

View File

@ -16,6 +16,7 @@
- When using a tool to write the documentation file, ensure the file content is base64 encoded and provide the relative path to the file.
- The generated Markdown document must follow the specific layout provided below.
- The component's C++ source file will contain an example of how it is constructed and mounted; use this as a basis for the "Example" section in the documentation.
- To read files, use the read_file tool, JSON payload : {"path":"relative path"}
## Layout
@ -27,7 +28,7 @@ The Markdown document must adhere to the following structure:
**Path**: `relative/path/to/component-name.cpp` (as a Markdown link)
**Revision History**: Add a file revision entry in the header to track modifications. For the initial documentation, use "Initial documentation". Skip this if a revision history already exists.
**Revision History**: Add a file revision entry in the header to track modifications. For the initial documentation, use "Initial documentation". Skip this if a revision history already exists !
A short description of the component.

View File

@ -1,10 +1,20 @@
kbot-d --router2=openai --model=anthropic/claude-3.7-sonnet:thinking \
--prompt=./scripts/docs.md \
--each=./src/*.h \
--each=./src/components/*.h \
--include=../polymech-fw-apps/cassandra-rc2/src/config.h \
--include=./src/Component.h \
--wrap=meta \
--mode=tools --preferences=none \
--mode=tools \
--preferences=none \
--disableTools=read_files,list_files,file_exists,modify_project_files \
--tools="fs" \
--filters=code
--filters=code \
--exclude=./src/components/ModbusLogicEngine.h \
--exclude=./src/components/Extruder.h \
--exclude=./src/components/Sako-Registers.h \
--exclude=./src/components/OmronE5_Ex.h \
--exclude=./src/components/PlungerSettings.h \
--exclude=./src/components/OmronE5Types.h \
--exclude=./src/components/SakoTypes.h