docs : core raw

This commit is contained in:
lovebird 2025-06-04 16:50:34 +02:00
parent eeb1c1cb45
commit da734afe6d
21 changed files with 1663 additions and 11 deletions

File diff suppressed because one or more lines are too long

82
docs-c/core/Addon.md Normal file
View File

@ -0,0 +1,82 @@
# Addon
**Path**: [`src/modbus/Addon.h`](../src/modbus/Addon.h)
**Revision History**: Initial documentation
Addon is a base class that extends the Component class, providing a foundation for creating modular extensions within the modbus system. It serves as a backward compatibility layer while ensuring consistent behavior across different types of add-ons.
## REQUIREMENTS
- ESP-32 microcontroller
- Platform.io development environment
## PROVIDES
- `Addon` class: Base class for creating modular components
- `Addons` type: A Vector container for storing Addon pointers
- `AddonFnPtr` type: Function pointer type for addon methods
- `byId()` utility function: Find an addon by its ID in a collection
## FEATURES
- Inheritance from Component class for consistent behavior
- Default run flags for standard execution modes
- Support for identifying addons through unique IDs
- Vector-based storage and retrieval of addons
## DEPENDENCIES
- [Component.h](../src/modbus/Component.h)
- [enums.h](../src/modbus/enums.h)
- [error_codes.h](../src/modbus/error_codes.h)
- [macros.h](../src/modbus/macros.h)
- [WString.h](https://github.com/espressif/arduino-esp32/blob/master/cores/esp32/WString.h)
- [Vector.h](https://github.com/janelia-arduino/Vector)
- [Arduino.h](https://github.com/espressif/arduino-esp32/blob/master/cores/esp32/Arduino.h)
```mermaid
graph TD
Addon --> Component
Addon --> enums
Addon --> error_codes
Addon --> macros
Addon --> WString
Addon --> Vector
```
## BEHAVIOUR
The Addon class extends Component, inheriting its lifecycle methods and adding specific functionality for modular components.
```mermaid
graph TD
Start[Initialize Addon] --> Construct[Constructor sets name, id, flags]
Construct --> Setup[Setup phase]
Setup --> Loop[Loop function execution]
Loop --> Info[Info reporting]
Info --> Loop
```
## TODOS
### PERFORMANCE
- Consider optimizing the `byId()` function for large collections using more efficient data structures or search algorithms
- Evaluate memory usage when multiple addons are instantiated
### SECURITY
- Add validation for addon IDs to prevent duplication
- Consider implementing access control mechanisms for sensitive addons
### COMPLIANCE
- Ensure compatibility with industrial Modbus-485 specifications
- Maintain backward compatibility with existing addon implementations
### RECOMMENDATIONS
- Use meaningful, unique IDs for each addon to simplify management
- Consider implementing a registration system to avoid manual management of addon collections
- Document specific addon implementations with clear usage examples

95
docs-c/core/App.md Normal file
View File

@ -0,0 +1,95 @@
---
title: "App - Application Component"
description: "The App class is the main application component that manages the lifecycle and interactions of all components in the system."
keywords: ["ESP32", "App", "Component", "PlatformIO", "ModbusRTU", "embedded system"]
---
## App
**Path**: [`src/App.cpp`](src/App.cpp)
**Revision History**: Initial documentation
The App class serves as the main application component responsible for managing the lifecycle and execution of all components in the system. It is derived from the Component base class and provides functionality for setting up, running the main loop, debugging, and retrieving information about the application and its components. The App acts as a container and orchestrator for all child components.
## REQUIREMENTS
- ESP32 microcontroller
- PlatformIO build environment
- C++17 support
## PROVIDES
- `App` class that manages the application lifecycle
- Component management functionality
- Component registration with Bridge for communication
- Debugging infrastructure
## FEATURES
- Component management (adding, retrieving, and querying components)
- Application lifecycle management (setup, loop)
- Component setup and execution orchestration
- Debug facilities with configurable intervals
- Component registration with Bridge for communication
- Component filtering by flags
## DEPENDENCIES
- [Component](./Component.md)
- [Bridge](./Bridge.md)
- [Vector](./Vector.md)
- [xtypes](./xtypes.md)
- [xtimer](./xtimer.md)
```mermaid
graph TD
App --> Component
App --> Bridge
App --> Vector
App --> xtypes
App --> xtimer
```
## BEHAVIOUR
The App class follows a standard application lifecycle pattern:
```mermaid
graph TD
Start[Start] --> Constructor[Constructor]
Constructor --> Setup[Setup]
Setup --> RegisterComponents[Register Components]
RegisterComponents --> OnRun[onRun]
OnRun --> Loop[Loop]
Loop --> Debug[Debug if interval passed]
Debug --> Loop
Loop --> End[End]
```
## TODOS
### PERFORMANCE
- Consider implementing component prioritization for the main loop
- Optimize component lookup by ID using a hashmap instead of linear search
- Implement a more efficient mechanism for component flag filtering
### SECURITY
- Implement component access control or validation mechanisms
- Add proper error handling for component operations
- Consider adding checks for component validity before operations
### COMPLIANCE
- Ensure memory management follows best practices for embedded systems
- Validate that the application meets real-time requirements for industrial settings
### RECOMMENDATIONS
- Use the `byId` method to retrieve components when you know their IDs
- Configure appropriate debug intervals based on the application's performance requirements
- Group related components with similar flags for easier management
- Implement a more structured approach for component initialization and dependency management
- Consider implementing a component health monitoring system

99
docs-c/core/Bridge.md Normal file
View File

@ -0,0 +1,99 @@
# Bridge
**Path**: [src/modbus/Bridge.h](../../../src/modbus/Bridge.h)
**Revision History**:
- Initial documentation
A Bridge component that enables inter-component messaging and remote method invocation in an ESP32-based system. It allows components to register member functions that can be called via a message passing mechanism, typically triggered by Modbus commands.
## REQUIREMENTS
- No specific hardware pins required
- Software dependencies for messaging and component management
## PROVIDES
- `SComponentInfo`: A structure that stores information about registered component methods
- Stores component key, instance pointer, method name, and function pointer
- `Bridge`: Main class that manages component method registration and message handling
- Inherits from `Component` base class
## FEATURES
- Register component member functions for remote invocation
- Message routing between components
- Method lookup by component ID and method name
- Debug support for listing registered methods
- Support for component discovery for Modbus management
## DEPENDENCIES
- [Component](./Component.md): Base class for all components
- [WString](https://github.com/espressif/arduino-esp32): String manipulation
- [xtypes](./xtypes.md): Type definitions
- [enums](./enums.md): Enumeration definitions
- [macros](./macros.md): Macro definitions
- [Vector](./Vector.md): Container for storing component information
- [Streaming](./Streaming.md): Stream output utilities
```mermaid
graph TD
Bridge --> Component
Bridge --> WString
Bridge --> xtypes
Bridge --> enums
Bridge --> macros
Bridge --> Vector
Bridge --> Streaming
```
## BEHAVIOUR
The Bridge acts as a message router between components. It maintains a registry of component methods and handles method invocation based on message parameters.
```mermaid
sequenceDiagram
participant Caller
participant Bridge
participant Component
Caller->>Bridge: onMessage(id, verb, flags, user, src)
alt EC_METHOD verb
Bridge->>Bridge: Parse method parameters
Bridge->>Bridge: hasMethod(id, methodName)
alt Method found
Bridge->>Component: Invoke method
Component-->>Bridge: Return result
Bridge-->>Caller: Return result
else Method not found
Bridge-->>Caller: Return E_NOT_FOUND
end
else Other verbs
Bridge-->>Caller: Return E_OK
end
```
## TODOS
### PERFORMANCE
- The current implementation uses dynamic memory allocation for component registration which could lead to heap fragmentation. Consider using a fixed-size pool for `SComponentInfo` objects.
- Message parsing could be optimized for cases with large numbers of registered components.
### SECURITY
- There is no authentication mechanism for method invocation. Consider adding a permission system.
- Method invocation through Modbus should be validated to prevent buffer overflows and other security issues.
### COMPLIANCE
- Ensure proper memory management to comply with embedded system best practices.
- Test for compliance with industrial communication standards when used with Modbus.
### RECOMMENDATIONS
- Use descriptive method names and consistent component IDs to make debugging easier.
- Keep registered method count below the `MAX_COMPONENTS` limit (defined in configuration).
- When adding new components, always register their methods during initialization.
- Consider implementing an unregister mechanism for dynamically loaded/unloaded components.

View File

@ -0,0 +1,93 @@
---
title: "CommandMessage Class - Message Parsing System"
description: "Documentation for the CommandMessage class used to parse and structure messages in a Modbus system"
keywords: ["ESP-32", "Modbus", "communication", "command parsing", "messaging"]
---
## CommandMessage
**Path**: [src/modbus/command_message.h](../src/modbus/command_message.h)
**Revision History**: Initial documentation
The CommandMessage class provides a structured approach to parse, validate, and manage command messages within the system. It supports message serialization and deserialization with defined start/end markers and delimiters. This class is designed for efficient messaging in industrial Modbus-485 communications.
## REQUIREMENTS
- No specific hardware pins required
- Requires StringUtils and enums support
## PROVIDES
- **CommandMessage**: The main class for message handling
- **DEBUG_MESSAGES_PARSE**: Conditional compilation flag for verbose message parsing output
- **DEBUG_MESSAGES_PARSER**: Macro for debug logging of message parsing operations
- **MESSAGE_TOKENS**: Constant defining the expected number of tokens in a valid message
## FEATURES
- Structured message storage with ID, verb, flags, and payload
- Timestamp tracking for message receipt
- Validation of message format with start/end markers
- Parsing of delimited message content
- Clear method for resetting message state
- Match checking for message format validation
## DEPENDENCIES
- [Vector](../src/Vector.h)
- [ArduinoLog](../src/ArduinoLog.h)
- [StringUtils](../src/StringUtils.h)
- [Enums](../src/modbus/enums.h)
```mermaid
graph TD
CommandMessage --> StringUtils
CommandMessage --> ArduinoLog
CommandMessage --> Vector
CommandMessage --> Enums
```
## BEHAVIOUR
```mermaid
sequenceDiagram
participant Client
participant CommandMessage
Client->>CommandMessage: Create message with id, verb, flags
Client->>CommandMessage: parse(message)
CommandMessage->>CommandMessage: clear()
CommandMessage->>CommandMessage: Extract content between markers
CommandMessage->>CommandMessage: Split by delimiters
CommandMessage->>CommandMessage: Validate token count
CommandMessage->>CommandMessage: Assign id, verb, flags, payload
CommandMessage->>CommandMessage: Set timestamp
CommandMessage-->>Client: Return success/failure
```
## TODOS
### PERFORMANCE
- Consider pre-allocating memory for the message parsing to avoid heap fragmentation
- Evaluate the use of String vs. char arrays for payload handling in memory-constrained environments
- Potential for optimizing token parsing with a more efficient approach than strtok
### SECURITY
- Consider implementing message integrity checking (checksums or CRC)
- Add length validation to prevent buffer overflows
- Implement validation of message payload content based on expected verb/command
### COMPLIANCE
- Ensure all message processing complies with Modbus protocol standards where applicable
- Consider adding support for standard industrial message formats
### RECOMMENDATIONS
- Add support for binary payloads for more efficient communication
- Consider implementing a message queue system to handle multiple messages
- Add methods to serialize a CommandMessage back to a string for bidirectional communication
- Consider adding timeout functionality for message handling

97
docs-c/core/Component.md Normal file
View File

@ -0,0 +1,97 @@
---
title: "Component Class"
description: "A generic component class for embedded systems"
keywords: ["component", "ESP-32", "modbus", "industrial application"]
---
## Component
**Path**: [`src/modbus/Component.h`](../src/modbus/Component.h)
**Revision History**: Initial documentation
The Component class represents a generic component for industrial applications. It provides a foundation for creating various types of components with consistent behavior and interface. These components can be integrated into a modbus-based industrial control system.
## REQUIREMENTS
- ESP-32 platform
- No specific hardware pins required as this is a base class
## PROVIDES
- `Component` class - A base class for creating components in an industrial application
- Constants:
- `COMPONENT_DEFAULT` - Default run flags for a component
- `COMPONENT_NO_ID` - Default ID for a component
## FEATURES
- Name-based component identification
- ID-based component identification
- Configurable run flags
- Support for owner-child relationship between components
- Type identification through enumeration
- Integration with Modbus communication
## DEPENDENCIES
- [`WString.h`](../src/WString.h) - String handling
- [`ArduinoLog.h`](../src/ArduinoLog.h) - Logging functionality
- [`Vector.h`](../src/Vector.h) - Dynamic array implementation
- [`enums.h`](../src/modbus/enums.h) - Enumeration definitions
- [`constants.h`](../src/modbus/constants.h) - Constant definitions
- [`error_codes.h`](../src/modbus/error_codes.h) - Error code definitions
- [`macros.h`](../src/modbus/macros.h) - Macro definitions
- [`xtypes.h`](../src/modbus/xtypes.h) - Extended type definitions
```mermaid
graph TD
Component --> WString
Component --> ArduinoLog
Component --> Vector
Component --> enums
Component --> constants
Component --> error_codes
Component --> macros
Component --> xtypes
ModbusBlock[ModbusBlockView] --> Component
ModbusTCP --> Component
RS485 --> Component
Bridge --> Component
```
## BEHAVIOUR
The Component class operates as a base class that defines common behavior for various industrial components.
```mermaid
graph TD
Init[Initialize Component] --> Setup[Setup Component]
Setup --> Loop[Run Loop]
Loop --> |Run Flags| Loop
Loop --> |End of loop| Cleanup[Cleanup]
```
## TODOS
### PERFORMANCE
- Consider implementing lazy initialization for components with high initialization costs
- Evaluate the memory footprint of components in resource-constrained environments
### SECURITY
- Implement access control mechanisms for sensitive components
- Ensure proper validation of component IDs and types to prevent misuse
### COMPLIANCE
- Review compliance with industrial standards for component interfaces
- Ensure compatibility with Modbus protocol specifications
### RECOMMENDATIONS
- Extend this base class for specific component types rather than modifying the base class
- Use meaningful names and IDs for components to improve system maintainability
- Set appropriate run flags based on the component's intended behavior
- Organize components in a logical hierarchy using the owner-child relationship

108
docs-c/core/Logger.md Normal file
View File

@ -0,0 +1,108 @@
---
title: "CircularLogPrinter - In-Memory Logging with Optional Output"
description: "A circular buffer for storing log messages with ESP-IDF integration"
keywords: ["ESP32", "logging", "circular buffer", "ESP-IDF", "modbus"]
---
## CircularLogPrinter
**Path**: [`src/modbus/circular_log_printer.h`](../../src/modbus/circular_log_printer.h)
**Revision History**:
- 2023-11-15: Initial documentation
CircularLogPrinter is an Arduino-compatible Print implementation that stores the last N log lines in a circular buffer. It can optionally mirror all output to another stream (like Serial). The component is designed to be 100% reinterpret-cast-free for MISRA/CPPCHECK compliance, making it suitable for industrial applications.
## REQUIREMENTS
- FreeRTOS (for optional thread safety)
- ESP32 IDF framework
- Global Serial object (when using default constructor)
## PROVIDES
- `using LogRingBuffer = char[LOG_BUFFER_LINES][LOG_BUFFER_LINE_LENGTH]`
- `class CircularLogPrinter`: A Print implementation storing log lines in a circular buffer
## FEATURES
- Configurable circular buffer size via macros
- Thread-safe operation (optional)
- Ability to attach to ESP-IDF's logging system
- No pointer type casting (MISRA compliant)
- Retrieves log history by line number
- Optional mirroring to any Print-compatible output
- Efficient multi-byte writes
## DEPENDENCIES
- [Arduino.h](https://github.com/espressif/arduino-esp32)
- [Print.h](https://github.com/espressif/arduino-esp32)
- [esp_log.h](https://docs.espressif.com/projects/esp-idf/en/latest/esp32/api-reference/system/log.html)
```mermaid
graph TD
CircularLogPrinter --> Arduino
CircularLogPrinter --> Print
CircularLogPrinter --> ESP_Log
```
## BEHAVIOUR
```mermaid
stateDiagram-v2
[*] --> Ready
Ready --> Accumulating: write(byte)
Accumulating --> Accumulating: write non-newline
Accumulating --> CommittingLine: write newline
CommittingLine --> Ready: Store line & update indices
Ready --> Cleared: clear()
Cleared --> Ready: write(byte)
```
## TODOS
### PERFORMANCE
- Consider using a more efficient buffer strategy for high-volume logging
- Potential optimization by pre-allocating buffer space when attaching to ESP-IDF log
### SECURITY
- No direct security concerns as this is an output-only component
- Consider adding sanitization for control characters that could affect terminal displays
### COMPLIANCE
- Already designed for MISRA/CPPCHECK compliance with no reinterpret casts
- Consider adding formal verification of buffer access bounds
### RECOMMENDATIONS
- Adjust `LOG_BUFFER_LINES` and `LOG_BUFFER_LINE_LENGTH` based on available memory and application needs
- For performance-critical applications, consider disabling thread safety with `LOG_BUFFER_THREAD_SAFE=0`
- When using with Modbus, attach to ESP-IDF logging to capture all system messages including Modbus communication logs
## Example
```cpp
#include "circular_log_printer.h"
// Create logger with default output (Serial)
CircularLogPrinter logger;
void setup() {
Serial.begin(115200);
// Attach to ESP-IDF logging system
logger.attachToEspLog();
// Log some messages
logger.println("System initializing...");
// Later, retrieve historical logs
for (size_t i = 0; i < logger.lines(); i++) {
Serial.println(logger.getLine(i));
}
}
```

View File

@ -0,0 +1,97 @@
---
title: "SerialMessage - Serial Communication Component"
description: "A component that handles serial communication over a stream, providing methods for reading and parsing command messages."
keywords: "SerialMessage, serial communication, command parsing, ESP32, modbus"
---
## SerialMessage
**Path**: [`src/modbus/SerialMessage.h`](../src/modbus/SerialMessage.h)
**Revision History**: Initial documentation
SerialMessage is a component that handles serial communication over a provided Stream. It is responsible for reading incoming data from the serial port, parsing it into structured command messages, and forwarding these messages to its owner component. The class periodically checks for new messages on the configured serial interface.
## REQUIREMENTS
- A valid Stream object (like Serial, Serial1, etc.) for communication
- Sufficient memory for the receive buffer (SERIAL_RX_BUFFER_SIZE, defaults to 256 bytes)
## PROVIDES
- **SerialMessage class**: Main component for handling serial communication
## FEATURES
- Periodic checking for new serial commands (configurable interval)
- Parsing of raw serial data into structured CommandMessage objects
- Event-based message handling through owner component notification
- Configurable message delimiter (default: newline)
- Debug capabilities for troubleshooting communication issues
## DEPENDENCIES
- [Vector](../src/Vector.h)
- [ArduinoLog](../src/ArduinoLog.h)
- [Arduino.h](https://www.arduino.cc/reference/en/)
- [xtypes.h](../src/xtypes.h)
- [Component.h](../src/Component.h)
- [CommandMessage.h](../src/CommandMessage.h)
- [config.h](../src/config.h)
```mermaid
graph TD
SerialMessage --> Component
SerialMessage --> CommandMessage
SerialMessage --> Vector
SerialMessage --> ArduinoLog
SerialMessage --> xtypes
SerialMessage --> config
```
## BEHAVIOUR
The SerialMessage component operates on a time-based polling mechanism:
```mermaid
graph TD
Start([Start]) --> Setup[Setup SerialMessage]
Setup --> Loop[Loop]
Loop --> CheckInterval{Time to check?}
CheckInterval -->|No| Loop
CheckInterval -->|Yes| ReadSerial[Read from serial]
ReadSerial --> DataAvailable{Data available?}
DataAvailable -->|No| UpdateTime[Update lastRead time]
DataAvailable -->|Yes| ParseMessage[Parse to CommandMessage]
ParseMessage --> ValidMessage{Valid message?}
ValidMessage -->|No| UpdateTime
ValidMessage -->|Yes| NotifyOwner[Notify owner component]
NotifyOwner --> UpdateTime
UpdateTime --> Loop
```
## TODOS
### PERFORMANCE
- Consider implementing interrupt-driven serial reading rather than polling for high-throughput applications
- Optimize buffer handling for memory-constrained environments
- Evaluate the impact of the polling interval on application responsiveness
### SECURITY
- Add input validation to prevent buffer overflow attacks
- Consider implementing message authentication for secure applications
- Evaluate the need for encryption for sensitive data transmission
### COMPLIANCE
- Ensure compliance with relevant industrial communication standards when used in Modbus-485 applications
- Verify error handling mechanisms meet application reliability requirements
### RECOMMENDATIONS
- Set an appropriate SERIAL_COMMAND_PARSE_INTERVAL based on your application's requirements
- For debugging communication issues, enable DEBUG_SERIAL_MESSAGES in your build configuration
- When extending this component, consider implementing additional message validation logic
- For applications with multiple serial interfaces, create separate SerialMessage instances for each interface

View File

@ -0,0 +1,89 @@
---
title: "StringUtils - String Manipulation Utilities"
description: "A utility class for string manipulation and type conversion for ESP-32 applications"
keywords: "ESP-32, C++17, string utilities, type conversion, industrial application, Modbus"
---
## StringUtils
**Path**: [`src/modbus/StringUtils.h`](../src/modbus/StringUtils.h)
**Revision History**: Initial documentation
StringUtils provides a set of utility functions for string manipulation and type conversion in an industrial ESP-32 application. It enables parsing and converting string values to native C types, which is particularly useful for configuration and communication scenarios in Modbus applications.
## REQUIREMENTS
No specific hardware pins are required as this is a software utility helper.
## PROVIDES
- `E_VALUE_TYPE` enumeration for representing different value types
- Template function `convertTo<T>` for converting strings to various native types
- Type detection functions (`isInteger`, `isFloat`, `detectType`)
- Hex data printing utility
## FEATURES
- Specialized template implementations for converting strings to:
- Integer types (`int`, `short`, `long int`)
- Floating-point (`float`)
- Boolean values (`bool`)
- Type detection to determine if a string represents a valid integer or floating-point value
- Platform-specific adaptations for string tokenization across different compilers
- Hex data visualization for debugging
## DEPENDENCIES
- [`./xtypes.h`](../src/modbus/xtypes.h)
- Standard C libraries: `<stdio.h>`, `<string.h>`, `<ctype.h>`, `<stdlib.h>`
```mermaid
graph TD
StringUtils --> xtypes
StringUtils --> "Standard C Libraries"
```
## BEHAVIOUR
The StringUtils component follows a simple conversion and detection workflow:
```mermaid
graph LR
Input[Input String] --> Detect[Detect Type]
Detect --> |Integer| ConvertInt[Convert to Integer]
Detect --> |Float| ConvertFloat[Convert to Float]
Detect --> |Boolean| ConvertBool[Convert to Boolean]
Detect --> |Text| HandleText[Handle as String]
ConvertInt --> Result[Native Type Result]
ConvertFloat --> Result
ConvertBool --> Result
HandleText --> Result
```
## TODOS
### PERFORMANCE
- Consider using `strtol`, `strtof`, etc. for all conversions to provide better error handling
- Optimize the string scanning operations for large strings
- Add string length validation to avoid buffer overruns
### SECURITY
- Add input validation to prevent exploitation through malformed strings
- Consider adding bounds checking for numeric conversions
- Implement sanitization for strings that will be used in sensitive contexts
### COMPLIANCE
- Ensure compatibility with C17 standard
- Verify that all functions work correctly in the target ESP-32 environment
- Audit for potential compliance issues with industrial standards
### RECOMMENDATIONS
- Extend type support to include additional numeric types as needed
- Add more robust error handling for conversion failures
- Consider adding string formatting utilities for consistent output generation
- For improved performance, use static or cached conversions for frequently used values

View File

@ -0,0 +1,96 @@
---
title: "ValueWrapper Template Class"
description: "A templated class for managing values with threshold-based notifications through Modbus"
keywords: "ValueWrapper, Modbus, threshold, notification, embedded systems, ESP32"
---
## ValueWrapper
**Path**: [`src/modbus/ValueWrapper.h`](../src/modbus/ValueWrapper.h)
**Revision History**: Initial documentation
A template class that wraps values of any type with threshold-based update notifications through Modbus. This class monitors changes in a value and sends notifications to the owner component when changes exceed specified thresholds, using different comparison modes. It helps reduce network traffic by only sending updates when significant changes occur.
## REQUIREMENTS
- An owning Component instance that receives notifications
- A Modbus address space for notifications
- Function code configuration for the Modbus messages
## PROVIDES
- `ValueWrapper<T>` - Template class for wrapping values of any type
- `ThresholdMode` enumeration:
- `DIFFERENCE` - Triggers when absolute difference between old and new values exceeds threshold
- `INTERVAL_STEP` - Triggers when values cross step boundaries defined by the threshold
- Macros:
- `DEFAULT_VW_POST_NOTIFY_LAMBDA` - Helper for creating standard post-notification logging lambdas
- `INIT_COMPONENT_VALUE_WRAPPER` - Simplifies ValueWrapper initialization
## FEATURES
- Wraps any data type, including enums, with transparent type conversion
- Provides automatic threshold-based notifications through Modbus
- Supports different threshold modes for different types of data
- Handles both arithmetic types and enumerations correctly
- Provides callbacks when notifications are sent
- Automatic typecasting for Modbus message values
## DEPENDENCIES
- [`Component.h`](../src/Component.md)
- [`modbus/ModbusTypes.h`](../src/modbus/ModbusTypes.md)
- [`enums.h`](../src/enums.md)
- [`Logger.h`](../src/Logger.md)
```mermaid
graph TD
ValueWrapper --> Component
ValueWrapper --> ModbusTypes
ValueWrapper --> enums
ValueWrapper --> Logger
```
## BEHAVIOUR
The ValueWrapper monitors changes to a value and sends notifications when thresholds are exceeded.
```mermaid
stateDiagram-v2
[*] --> Initialized: Constructor
Initialized --> Comparing: update(newValue)
Comparing --> ThresholdNotMet: Below threshold
Comparing --> ThresholdExceeded: Above threshold
ThresholdNotMet --> ValueUpdated: Update value without notification
ThresholdExceeded --> NotifyOwner: Send Modbus update
NotifyOwner --> CallbackExecution: Execute post-notification callback
CallbackExecution --> ValueUpdated: Value updated
ValueUpdated --> Initialized: Ready for next update
```
## TODOS
### PERFORMANCE
- Consider providing specialized implementations for common types to avoid template instantiation overhead
- Investigate using std::variant for better type safety and potentially reduced memory footprint
- Add an optional hysteresis parameter to prevent rapid oscillations around threshold values
### SECURITY
- Add bounds checking for Modbus addresses to prevent accidental overwrites
- Consider adding validation callbacks to ensure values remain within acceptable ranges
### COMPLIANCE
- Ensure all Modbus messages conform to the Modbus specification requirements
- Consider adding support for additional Modbus function codes as needed
### RECOMMENDATIONS
- Use the `INIT_COMPONENT_VALUE_WRAPPER` macro to simplify instance creation
- Choose appropriate threshold values to balance responsiveness and network traffic
- For enum types, use threshold value of 1 to notify on any state change
- For float values, consider the INTERVAL_STEP mode to create logical boundaries for notifications

58
docs-c/core/constants.md Normal file
View File

@ -0,0 +1,58 @@
# Constants
**Path**: [`src/modbus/constants.h`](../src/modbus/constants.h)
**Revision History**: Initial documentation
This file defines global constants used throughout the application, particularly for component management and debug settings.
## REQUIREMENTS
No specific hardware requirements. This is a header-only file that provides constant values.
## PROVIDES
- Global constant definitions:
- `MAX_COMPONENTS`: Maximum number of components in the system
- `DEFAULT_DEBUG_INTERVAL`: Default interval for debug operations in milliseconds
## FEATURES
- Defines system-wide constants for configuration
- Sets limits for component management
- Establishes default timing values
## DEPENDENCIES
None. This is a standalone header file.
```mermaid
graph TD
Constants["Constants"]
```
## BEHAVIOUR
This component doesn't have behavior as it only provides constant definitions.
## TODOS
### PERFORMANCE
- Consider evaluating if `MAX_COMPONENTS` is appropriately sized for the application's needs
- Review if any constants should be configurable at compile time based on target hardware
### SECURITY
- No direct security concerns as these are compile-time constants
### COMPLIANCE
- Ensure constant values comply with any relevant industrial standards or specifications
- Consider documenting the reasoning behind specific values for future reference
### RECOMMENDATIONS
- Use these constants throughout the application rather than hard-coding values
- Consider moving to a more structured configuration system if the number of constants grows substantially
- Document the impact of changing these values on system behavior and resource usage

87
docs-c/core/enums.md Normal file
View File

@ -0,0 +1,87 @@
---
title: "Modbus Enums and Constants"
description: "Documentation for the Modbus enumerations and constants used in the industrial control application"
keywords: "Modbus, ESP32, Industrial Control, Enumerations, Constants, Error Codes"
---
## Modbus Enumerations and Constants
**Path**: [/src/modbus/enums.h](../../../src/modbus/enums.h)
**Revision History**: Initial documentation
This file defines the core enumerations and constants used throughout the industrial control application, particularly for Modbus communications, component management, and error handling.
## REQUIREMENTS
- No direct hardware requirements
- Consistent implementation across the codebase
## PROVIDES
- `COMPONENT_KEY_BASE` - Base key identifiers for system components
- `COMPONENT_TYPE` - Component type classification
- Error Code Constants - System-wide error definitions
- `OBJECT_RUN_FLAGS` - Runtime behavior flags for components
- `OBJECT_NET_CAPS` - Network capability flags
- `MB_REGISTER_MODE` - Modbus register access modes
- `E_CALLS` - Call type definitions
- `E_MessageFlags` - Message processing flags
- `MB_FC` - Modbus function codes
- `MODBUS_ERRORS` - Standard Modbus error codes
- `E_ModbusType` - Modbus data type definitions
- `E_ModbusAccess` - Modbus access permissions
## FEATURES
- Comprehensive error code system with reserved ranges for subsystems
- Modbus protocol constants aligned with industry standards
- Component type classification for system organization
- Runtime behavior flags for component lifecycle management
- Message handling flags for inter-component communication
## DEPENDENCIES
- No direct dependencies on other components
```mermaid
graph TD
Enums[Modbus Enumerations and Constants]
OtherComponents[Other System Components]
OtherComponents --> Enums
```
## BEHAVIOUR
The enumerations and constants in this file define the protocol and behavior parameters used by other components in the system.
```mermaid
graph TD
Constants[Constants Definition] --> Usage[Used by Components]
Usage --> ComponentInteraction[Component Interaction]
Usage --> ErrorHandling[Error Handling]
Usage --> ModbusProtocol[Modbus Protocol Execution]
```
## TODOS
### PERFORMANCE
- Consider using more compact types for memory-constrained applications
- Evaluate if any enumerations could be consolidated to reduce memory usage
### SECURITY
- Ensure error codes don't leak sensitive information in production environments
- Consider adding authentication/authorization related constants for secure Modbus implementations
### COMPLIANCE
- Maintain alignment with Modbus specification for all Modbus-related constants
- Consider adding comments with references to specific sections of the Modbus specification
### RECOMMENDATIONS
- When extending error codes, maintain the hierarchical structure
- When adding new component types, ensure they follow the established naming convention
- Consider adding range validation macros alongside the constants

View File

@ -0,0 +1,75 @@
# Error Codes
**Path**: [`src/modbus/error_codes.h`](../../src/modbus/error_codes.h)
**Revision History**: Initial documentation
A comprehensive collection of error codes used throughout the Modbus implementation. This header defines specific error code enumerations for different types of errors that can occur during Modbus operations.
## REQUIREMENTS
No specific hardware pins required. This is a pure software component providing error code definitions.
## PROVIDES
- `ModbusErrorCode` - Enumeration for general Modbus error codes
- `ModbusDeviceErrorCode` - Enumeration for device-specific Modbus error codes
- `ModbusExceptionCode` - Enumeration for standard Modbus exception codes
## FEATURES
- Standardized error code definitions for Modbus protocol implementation
- Clear separation between different categories of errors
- Compliance with standard Modbus exception codes
- Error codes to handle both protocol-level and device-specific errors
## DEPENDENCIES
None. This is a standalone header file defining error code enumerations.
```mermaid
graph TD
ErrorCodes[Error Codes]
```
## BEHAVIOUR
The error codes are used to report and handle various error conditions throughout the Modbus implementation.
```mermaid
graph TD
Start[Operation Start] --> Operation[Modbus Operation]
Operation --> CheckError{Error?}
CheckError -->|No| Success[Operation Successful]
CheckError -->|Yes| Identify[Identify Error Type]
Identify -->|Protocol Error| ProtocolError[ModbusErrorCode]
Identify -->|Device Error| DeviceError[ModbusDeviceErrorCode]
Identify -->|Exception| Exception[ModbusExceptionCode]
ProtocolError --> Handle[Handle Error]
DeviceError --> Handle
Exception --> Handle
Handle --> End[End Operation]
Success --> End
```
## TODOS
### PERFORMANCE
- Consider optimizing error handling mechanisms for minimal runtime overhead
### SECURITY
- Review error codes to ensure they don't expose sensitive system information
- Consider adding error codes for security-related issues (authentication failures, access violations)
### COMPLIANCE
- Verify that all Modbus exception codes match the latest Modbus specification
- Consider adding compliance with IEC 61131-3 error handling recommendations
### RECOMMENDATIONS
- Use appropriate error codes consistently across the codebase
- Consider extending error codes with additional information for debugging purposes
- Implement comprehensive error logging using these error codes

81
docs-c/core/json.md Normal file
View File

@ -0,0 +1,81 @@
---
title: "JSON Utilities"
description: "Utility functions for parsing JSON data in embedded applications"
keywords: ["JSON", "ArduinoJson", "parsing", "ESP32", "embedded"]
---
## JSON Utilities
**Path**: [`src/utils/json_utils.h`](../../src/utils/json_utils.h)
**Revision History**:
- Initial documentation
A collection of inline utility functions for parsing JSON data in embedded applications. These functions provide a consistent way to extract values from JSON objects, with built-in type validation and error reporting.
## REQUIREMENTS
- ArduinoJson library
- ArduinoLog library
## PROVIDES
- `JsonUtils` namespace containing utility functions:
- `parseJsonFieldUint32`: Parses a 32-bit unsigned integer from JSON
- `parseJsonFieldUint8`: Parses an 8-bit unsigned integer from JSON
- `parseJsonFieldBool`: Parses a boolean value from JSON
## FEATURES
- Type validation for JSON field parsing
- Maintains default values when fields are missing or of incorrect type
- Debug logging for parsing errors
- Consistent parsing interface across different data types
## DEPENDENCIES
- [ArduinoJson](https://arduinojson.org/)
- [ArduinoLog](https://github.com/thijse/Arduino-Log)
```mermaid
graph TD
JsonUtils --> ArduinoJson
JsonUtils --> ArduinoLog
```
## BEHAVIOUR
```mermaid
graph TD
Start([Parse JSON Field]) --> CheckField{Field exists?}
CheckField -- Yes --> CheckType{Correct type?}
CheckField -- No --> UseDefault[Use default value]
CheckType -- Yes --> AssignValue[Assign parsed value]
CheckType -- No --> LogWarning[Log warning] --> UseDefault
AssignValue --> End([End])
UseDefault --> End
```
## TODOS
### PERFORMANCE
- Consider providing batch parsing functions to reduce parsing overhead for multiple fields
- Evaluate memory usage when parsing large JSON objects
### SECURITY
- Currently no validation for value ranges; consider adding range validation options
- Implement protection against malformed JSON that could lead to buffer overflows
### COMPLIANCE
- Ensure all error messages follow consistent formatting standards
- Consider adding more documentation for compliance with project coding standards
### RECOMMENDATIONS
- Add support for additional data types (e.g., float, string)
- Consider a more structured approach to error handling (e.g., error codes or exceptions)
- Add functions for array parsing and nested object traversal
- Provide examples of common JSON parsing scenarios

87
docs-c/core/macros.md Normal file
View File

@ -0,0 +1,87 @@
---
title: "Macros Utility Header"
description: "Documentation for the macros utility header which provides various helper macros for ESP32 C17 development"
keywords: "ESP32, C17, macros, utilities, embedded, industrial"
---
# Macros Utility
**Path**: [`src/modbus/macros.h`](../src/modbus/macros.h)
**Revision History**: Initial documentation
A comprehensive collection of utility macros for ESP-32 development. This header provides macro definitions for commonly used operations in embedded systems programming, avoiding the use of the standard library. It includes macros for type manipulation, bit operations, mathematical functions, array handling, compile-time optimizations, and more.
## Requirements
- ESP-32 platform
- C17 compliant compiler
- No standard library dependencies
## Provides
- **Incrementation/Decrementation**: `INC_X`, `DEC_X`, `INCREMENT`, `DECREMENT`
- **Compiler Optimizations**: `FORCE_INLINE`, `_UNUSED`, `NOOP`
- **Argument Counting/Testing**: `NUM_ARGS`, `TWO_ARGS`
- **String Helpers**: `CAT`, `_CAT`
- **Conditional Compilation**: `ENABLED`, `DISABLED`, `ANY`, `ALL`, `NONE`
- **Bit Manipulation**: `__BV`, `TEST`, `SBI`, `CBI`, `SET_BIT_TO`
- **Math Operations**: `WITHIN`, `RADIANS`, `DEGREES`, `NEAR_ZERO`
- **Time Helpers**: `PENDING`, `ELAPSED`, `HOUR_MS`, `MIN_MS`
- **Array Initialization**: `ARRAY_N`, `ARRAY_1` through `ARRAY_6`
- **C++11 Template Utilities**: Min/Max templates, SFINAE helpers
## Features
- Preprocessor macros for common calculations and operations
- Bit manipulation utilities
- Compile-time optimizations
- Safe type conversion helpers
- Template-based compile-time checks
- Time management utilities
- Array initialization helpers
- Conditional execution based on feature flags
## Dependencies
- [`./xtypes.h`](../src/modbus/xtypes.h)
```mermaid
graph TD
Macros --> XTypes
```
## Behavior
The macros in this header provide utility functions that are used throughout the codebase. They do not have state or flow by themselves but enable cleaner, more efficient code.
```mermaid
graph LR
Application[Application Code] -->|Uses macros| Macros
Macros -->|Expand at compile time| Optimized[Optimized Binary]
```
## TODOs
### Performance
- Consider separating into multiple headers for faster compilation
- Add pre-processor optimization for frequently used macro combinations
### Security
- No direct security concerns as these are compile-time macros
- Ensure macros don't introduce unintended behaviors when used with user input
### Compliance
- Compatible with C17 standard
- Designed for ESP-32 and industrial Modbus applications
- No use of standard library functions
### Recommendations
- Group related macros when using in implementation files
- Use the ENABLED/DISABLED macros for feature toggling
- Prefer the template-based MIN/MAX over macro versions when in C++ code
- Consider the resource constraints of ESP-32 when using complex macro expansions

View File

@ -0,0 +1,84 @@
---
title: "Cassandra 650 Test Data Constants"
description: "Reference constants and verified test data for the Cassandra 650 hot-plate system"
keywords: ["modbus", "cassandra", "hotplate", "test data", "constants"]
---
## Cassandra 650 Test Data
**Path**: [`src/modbus/cassandra650_testdata.h`](../../../src/modbus/cassandra650_testdata.h)
**Revision History**:
- 2025-05-01: Initial verified version with full equation markup.
This header file provides verified test data constants for the Cassandra 650 hot-plate system, serving as a reference for simulation, testing, and validation of the hot-plate control system.
The constants follow specific notation:
- Values ending in `_X100` are stored multiplied by 100 (e.g., 1.25 becomes 125)
- Dimensions are in millimeters unless otherwise noted
- Time units: s = seconds, min = minutes
- Frequency: mHz = milli-hertz (10⁻³ Hz)
## REQUIREMENTS
- No specific hardware pins required as this is a constants-only header
- Compatible with C17 standard
- ESP-32 platform as target
## PROVIDES
- **Heat-plate geometry constants**: Dimensions of the heat plate
- **Heater configuration constants**: Specifications for the heating elements
- **Cooling performance constants**: Natural cooling rates
- **Temperature-loop precision constants**: Control precision specifications
- **Oscillation constants**: Timing parameters for temperature holding
- **Heating performance constants**: Rate of temperature increase under different conditions
- **Derived thermodynamic properties**: Calculated constants based on measured data
- **Sequential heating constants**: Parameters for multi-partition heating systems
## FEATURES
- Comprehensive set of validated constants for the Cassandra 650 hot-plate system
- Clear organization of constants by functional category
- Documented equations showing relationships between constants
- Scaled values (×100) to maintain precision with integer constants
## DEPENDENCIES
None - this is a self-contained constants header
```mermaid
graph TD
cassandra650_testdata[cassandra650_testdata.h]
style cassandra650_testdata fill:#f9f,stroke:#333,stroke-width:2px
```
## BEHAVIOUR
As a constants header file, this component doesn't have behavior or state transitions.
## TODOS
### PERFORMANCE
- Consider adding temperature gradient constants across the plate surface
- Add thermal profile constants for different materials/loads
### SECURITY
- No security concerns for constant definitions
### COMPLIANCE
- Constants should be verified periodically against actual measurements to ensure continued accuracy
- Consider adding IEC or other industrial standards references for measurement methodologies
### RECOMMENDATIONS
- When updating constant values, maintain the equation references to document the relationships
- Consider adding a table or graph representation of heating/cooling curves in documentation
- To extend this module, consider adding constants for:
- Different material loads (e.g., glass, metal, ceramic)
- Energy consumption metrics
- Wear and aging factors

83
docs-c/core/xmath.md Normal file
View File

@ -0,0 +1,83 @@
---
title: "XMath - Utility Functions for Mathematical Operations"
description: "Lightweight mathematical functions including template-based clamping and range checking"
keywords: ["ESP-32", "math", "clamp", "range", "normalize"]
---
## XMath
**Path**: [`src/modbus/xmath.h`](../src/modbus/xmath.h)
**Revision History**:
- Initial documentation
A lightweight utility header that provides essential mathematical operations for embedded systems. It includes a template-based clamp function and macros for range checking and normalized clamping.
## REQUIREMENTS
- C++17 compiler support
- No hardware-specific requirements
## PROVIDES
- `clamp<T>()` - Template function for clamping values within specified bounds
- `RANGE()` - Macro for checking if a value is within a specified range
- `NCLAMP()` - Macro for normalizing a value within a range to [0.0, 1.0]
## FEATURES
- Type-generic clamping through template implementation
- Range checking for value validation
- Value normalization to a [0.0, 1.0] range
- Conditional compilation for C++ environments
- No standard library dependencies
## DEPENDENCIES
- None
```mermaid
graph TD
Application --> XMath
```
## BEHAVIOUR
The XMath utilities provide deterministic mathematical operations:
```mermaid
graph LR
A[Input Value] --> B{clamp}
B --> |value < low| C[Return low]
B --> |value > high| D[Return high]
B --> |low ≤ value ≤ high| E[Return value]
F[Input Value] --> G{RANGE}
G --> |min < value < max| H[Return true]
G --> |else| I[Return false]
J[Input Value] --> K{NCLAMP}
K --> L[Normalize to 0.0-1.0 range]
```
## TODOS
### PERFORMANCE
- Consider specialized implementations for common numeric types to avoid template instantiation overhead
- Evaluate potential for SIMD optimizations on compatible platforms
### SECURITY
- No known security concerns as the utilities perform pure mathematical operations without side effects
### COMPLIANCE
- Ensure all mathematical operations maintain expected precision for safety-critical applications
- Verify behavior with edge cases (e.g., handling of NaN, Inf values)
### RECOMMENDATIONS
- Use `clamp<T>()` when working with specific types to leverage compile-time type checking
- Prefer the NCLAMP macro when normalizing sensor readings or other input values to a standardized range
- Consider adding additional mathematical utilities as needed for specific application domains

View File

@ -0,0 +1,90 @@
---
title: "XStatistics Class - Statistical Analysis Toolkit"
description: "A lightweight C++ class for statistical analysis, providing functionality for calculating mean, min/max, variance, and standard deviation of numerical datasets"
keywords: ["ESP32", "statistics", "C++", "industrial", "standard deviation", "variance", "average"]
---
## XStatistics
**Path**: [`src/modbus/xstatistics.h`](../src/modbus/xstatistics.h)
**Revision History**: Initial documentation
The XStatistics module provides a lightweight statistical analysis toolkit for numerical datasets. It is designed for use in industrial applications on ESP32 platforms where standard C++ libraries might not be available. The Statistic class enables efficient calculation of basic statistical measures like average, minimum, maximum, variance, and standard deviations without requiring dynamic memory allocation.
## REQUIREMENTS
- No specific hardware requirements
- C++ compiler supporting C++11 features
- Arduino core for ESP32
## PROVIDES
- `Statistic` class for collecting and analyzing numerical datasets
- Template functions for basic operations (`MIN`, `MAX`, `ABS`)
- Conditional compilation for standard deviation functionality using the `STAT_USE_STDEV` flag
## FEATURES
- Calculation of basic statistical measures (count, sum, min, max, average)
- Optional calculation of variance and standard deviation
- Memory-efficient implementation suitable for embedded systems
- No dynamic memory allocation required
- Incremental calculation methods that avoid storing the entire dataset
## DEPENDENCIES
- [Arduino.h](https://www.arduino.cc/reference/en/)
- [math.h](https://en.cppreference.com/w/cpp/header/cmath)
```mermaid
graph TD
XStatistics --> Arduino
XStatistics --> Math
```
## BEHAVIOUR
The Statistic class collects numerical data points one at a time and maintains running calculations of statistical measures.
```mermaid
graph TD
Start[Create Statistic object] --> Clear[Initialize counters]
Clear --> Add[Add data point]
Add --> Calculate[Calculate statistics]
Add --> |More data points| Add
Calculate --> |mean/average| Mean
Calculate --> |min/max| MinMax
Calculate --> |count| Count
Calculate --> |sum| Sum
subgraph "Optional functionality"
Calculate --> |STAT_USE_STDEV| Variance
Variance --> PopStdev[Population standard deviation]
Variance --> UnbiasedStdev[Unbiased standard deviation]
end
```
## TODOS
### PERFORMANCE
- The code includes an optimization comment indicating a 10% faster calculation method for standard deviation, but it limits samples to 65K due to potential overflow. Consider implementing a version that handles larger datasets.
- For larger datasets, consider adding functionality to discard outliers or implement online algorithms that require less memory.
### SECURITY
- No significant security concerns as this is a mathematical utility class without I/O operations.
- Consider adding bounds checking to prevent potential numerical overflows in extreme use cases.
### COMPLIANCE
- The implementation follows standard computational formulas for statistical measures.
- The class might need additional methods like confidence intervals or hypothesis testing for compliance with specific industrial data analysis standards.
### RECOMMENDATIONS
- Use this class when you need to monitor trends and statistics for sensor data or control variables.
- When using on systems with limited floating-point performance, consider monitoring the computational overhead.
- The optional standard deviation features can be disabled by removing the `STAT_USE_STDEV` definition to reduce code size and execution time.
- Consider extending the class with additional statistical functions like median, mode, or quartile calculations for more comprehensive analysis.

93
docs-c/core/xtimer.md Normal file
View File

@ -0,0 +1,93 @@
---
title: "XTimer - A Lightweight Timer Implementation"
description: "A template-based timer utility for scheduling tasks at specific intervals or times"
keywords: ["timer", "ESP-32", "embedded", "C++", "scheduling", "task management"]
---
## XTimer
**Path**: [`src/modbus/xtimer.h`](../src/modbus/xtimer.h)
**Revision History**:
- Initial documentation
A lightweight, template-based timer implementation designed for embedded systems, specifically targeting ESP-32. The timer provides functionality for scheduling tasks to run after a delay, at a specific time, or at regular intervals. It avoids using the standard library, making it suitable for resource-constrained environments.
## REQUIREMENTS
- No specific hardware pins required
- C++17 support
- Arduino framework or equivalent (`millis()` function)
## PROVIDES
- `Timer<size_t max_tasks, unsigned long (*time_func)()>` - Main timer class template
- `handler_t` - Function pointer type for task callbacks
- `timer_create_default()` - Utility function to create a timer with default settings
- `task` struct - Internal structure to represent scheduled tasks
## FEATURES
- Schedule tasks to run after a specified delay
- Schedule tasks to run at specific time points
- Schedule recurring tasks at regular intervals
- Configurable number of maximum concurrent tasks
- Customizable time function (defaults to `millis()`)
- Small memory footprint with fixed-size task array
- No dynamic memory allocation
## DEPENDENCIES
- [`src/modbus/macros.h`](../src/modbus/macros.h)
- Arduino core (`Arduino.h` or `WProgram.h` for older versions)
```mermaid
graph TD
XTimer --> Macros
XTimer --> Arduino["Arduino Core"]
```
## BEHAVIOUR
The timer operates by tracking tasks and their scheduled execution times:
```mermaid
graph TD
Start[Initialize Timer] --> AddTask[Add Task to Queue]
AddTask --> Tick[Timer Tick]
Tick --> CheckTasks[Check Task Expiry]
CheckTasks --> TaskExpired{Task Expired?}
TaskExpired -- Yes --> Execute[Execute Task Handler]
TaskExpired -- No --> Tick
Execute --> IsRepeat{Is Recurring?}
IsRepeat -- Yes --> ResetTask[Reset Timer for Next Run]
ResetTask --> Tick
IsRepeat -- No --> RemoveTask[Remove Task from Queue]
RemoveTask --> Tick
```
## TODOS
### PERFORMANCE
- Consider a more efficient data structure than a simple array for tasks, especially for systems with many scheduled tasks
- Implement a priority queue to optimize the `tick()` function when handling many tasks
- Provide options to reduce memory usage for systems with very limited RAM
### SECURITY
- No major security concerns as this is a local timer implementation
- Ensure task handlers do not introduce timing vulnerabilities in security-critical applications
### COMPLIANCE
- Review for MISRA C++ compliance if used in safety-critical applications
- Ensure thread safety if used in multi-threaded environments
### RECOMMENDATIONS
- Keep task handlers lightweight to avoid blocking the main loop
- Avoid using too many concurrent tasks as it may impact performance
- For time-critical operations, consider using hardware timers instead
- When using the `every()` function for periodic tasks, be aware of potential timing drift over long periods
- Consider implementing a task ID return value to allow for cancellation of scheduled tasks

64
docs-c/core/xtypes.md Normal file
View File

@ -0,0 +1,64 @@
# Types
**Path**: [`src/modbus/types.h`](../src/modbus/types.h)
**Revision History**:
- Initial documentation
A core utility header that defines fundamental type aliases used throughout the codebase. This file provides standardized type definitions to ensure consistent data type usage across the application.
## REQUIREMENTS
No specific hardware requirements. This is a pure software utility.
## PROVIDES
- `cchar`: A type alias for constant character data
- `uchar`: A type alias for unsigned character data
- `millis_t`: A type alias for millisecond time representations
- `ushort`: A type alias for unsigned short integers
- `ulong`: A type alias for unsigned long integers
- `lint`: A type alias for long integers
- `llint`: A type alias for long long integers
## FEATURES
- Simple, standardized type definitions
- Cross-platform compatibility
- Consistent naming convention for derived types
- Avoids usage of standard library types
## DEPENDENCIES
- [`<stdint.h>`](https://en.cppreference.com/w/c/types/integer) - Standard C library for integer types
```mermaid
graph TD
Types --> stdint
```
## BEHAVIOUR
This component is a passive header-only utility that doesn't have runtime behavior.
## TODOS
### PERFORMANCE
- No specific performance considerations as these are basic type aliases
### SECURITY
- Consider defining overflow-safe numeric types for sensitive operations
### COMPLIANCE
- Verify that these type definitions are consistent with the target hardware architecture
- Ensure compliance with C17 standard
### RECOMMENDATIONS
- Use these type aliases consistently throughout the codebase
- Consider adding more explicit sizing (e.g., `uint32_t`) for architecture-dependent types where exact bit sizes are critical
- When adding new types, maintain the established naming convention
- Document the expected size (in bits) for each type to avoid platform-specific issues

View File

@ -1,10 +1,9 @@
kbot-d --model=anthropic/claude-3.7-sonnet \
--prompt=./scripts/docs-m.md \
--each=./src/modbus/*.h \
--each=./src/*.h \
--globExtension=match-cpp \
--mode=completion \
--filters=markdown \
--preferences=none \
--exclude='./docs-c/modbus/Modbus.h' \
--exclude='./docs-c/modbus/${SRC_NAME}.md' \
--dst='./docs-c/modbus/${SRC_NAME}.md'
--exclude='./docs-c/core/${SRC_NAME}.md' \
--dst='./docs-c/core/${SRC_NAME}.md'