docs - mb

This commit is contained in:
lovebird 2025-06-04 16:43:41 +02:00
parent ffed55be4f
commit eeb1c1cb45
8 changed files with 547 additions and 5 deletions

File diff suppressed because one or more lines are too long

71
docs-c/modbus/Modbus.md Normal file
View File

@ -0,0 +1,71 @@
# Modbus
**Path**: [src/modbus/Modbus.h](src/modbus/Modbus.h)
**Revision History**: Initial documentation
A header file providing standardized macros for initializing Modbus communication blocks in ESP-32 industrial applications.
## Requirements
- ESP-32 microcontroller
- PlatformIO development environment
- C++17 support
## Provides
- **INIT_MODBUS_BLOCK_TCP**: Macro for initializing Modbus blocks with TCP base address
- **INIT_MODBUS_BLOCK**: Macro for initializing standard Modbus blocks
- **LOW_WORD / HIGH_WORD**: Macros for handling 32-bit word operations
## Features
- Standardized initialization of Modbus communication blocks
- Automated address calculations based on specified offsets
- Consistent parameter setting for both TCP and standard interfaces
- Streamlined documentation and organization through group identifiers
## Dependencies
- [ModbusTypes.h](src/modbus/ModbusTypes.h)
```mermaid
graph TD
Modbus[Modbus.h] --> ModbusTypes[ModbusTypes.h]
```
## Behaviour
The Modbus header provides initialization macros that ensure consistent formatting and values when setting up Modbus blocks. These macros handle address calculations, function codes, and access permissions.
```mermaid
graph TD
Start[Application code] --> UsesMacros[Uses INIT_MODBUS_BLOCK macros]
UsesMacros --> TCP{Is TCP?}
TCP -->|Yes| TCPMACRO[INIT_MODBUS_BLOCK_TCP]
TCP -->|No| STDMACRO[INIT_MODBUS_BLOCK]
TCPMACRO --> ModbusBlock[Initialized Modbus Block]
STDMACRO --> ModbusBlock
```
## TODOs
### Performance
- Consider pre-computing constant addresses at compile time where possible to reduce runtime calculations
### Security
- Add validation macros to ensure proper function code and access flag combinations
- Implement range checking for addresses to prevent potential buffer overflows
### Compliance
- Validate against Modbus specifications for both RTU and TCP implementations
- Ensure error handling complies with industrial standards
### Recommendations
- Use these macros consistently across the codebase to maintain uniformity
- Document the address range and offset enumerations carefully to avoid address conflicts
- Consider adding specific macros for different function types (read vs. write operations)

126
docs-c/modbus/ModbusRTU.md Normal file
View File

@ -0,0 +1,126 @@
---
title: "ModbusRTU - Industrial Modbus-485 RTU Interface"
description: "A robust Modbus RTU interface for ESP32 industrial applications"
keywords: ["modbus", "modbus-rtu", "rs485", "industrial", "esp32", "communication"]
---
## ModbusRTU
**Path**: [`src/modbus/ModbusRTU.h`](../../src/modbus/ModbusRTU.h)
**Revision History**: Initial documentation
ModbusRTU is a comprehensive class that provides a robust interface for Modbus RTU communication over RS-485. It is designed for industrial applications on ESP32, offering efficient queue management, adaptive timeouts, and extensive error handling capabilities.
## REQUIREMENTS
- Hardware:
- ESP32 microcontroller
- RS-485 transceiver (with DE/RE pin for direction control)
- Serial interface for communication
- Software:
- Arduino framework
- ModbusClientRTU library
- HardwareSerial for serial communication
- ArduinoLog for logging
## PROVIDES
- **Enumerations**:
- `E_InitState`: Tracks initialization states (`INIT_NOT_STARTED`, `INIT_SERIAL_STARTED`, `INIT_CLIENT_STARTED`, `INIT_READY`, `INIT_FAILED`)
- **Classes**:
- `ModbusRTU`: Main class for Modbus RTU communication
- `Manager`: Device management class for handling multiple Modbus slave devices
## FEATURES
- Non-blocking initialization and operation
- Flexible queue management with priority levels
- Read/write operations for coils and registers (single and multiple)
- Automatic value caching with synchronization status tracking
- Comprehensive error handling and retry mechanisms
- Adaptive minimum operation interval to adjust for network conditions
- Filter chain for operation validation and duplicate prevention
- Callback system for register changes, write completions, and error handling
- Status reporting and debugging utilities
## DEPENDENCIES
- [Arduino.h](https://www.arduino.cc/reference/en/)
- [ModbusClientRTU.h](https://github.com/eModbus/eModbus)
- [HardwareSerial.h](https://www.arduino.cc/reference/en/language/functions/communication/serial/)
- [ArduinoLog.h](https://github.com/thijse/Arduino-Log)
- [ModbusTypes.h](../../src/modbus/ModbusTypes.h)
```mermaid
graph TD
ModbusRTU --> Arduino
ModbusRTU --> ModbusClientRTU
ModbusRTU --> HardwareSerial
ModbusRTU --> ArduinoLog
ModbusRTU --> ModbusTypes
Manager --> ArduinoLog
Manager --> ModbusTypes
Manager --> ModbusRTU
```
## BEHAVIOUR
```mermaid
stateDiagram-v2
[*] --> INIT_NOT_STARTED
INIT_NOT_STARTED --> INIT_SERIAL_STARTED: begin()
INIT_SERIAL_STARTED --> INIT_CLIENT_STARTED: Serial init delay elapsed
INIT_CLIENT_STARTED --> INIT_READY: Client init delay elapsed
INIT_READY --> [*]: end()
INIT_NOT_STARTED --> INIT_FAILED: Error
INIT_SERIAL_STARTED --> INIT_FAILED: Error
INIT_CLIENT_STARTED --> INIT_FAILED: Error
state Operations {
[*] --> Idle
Idle --> QueueOperation: Read/Write request
QueueOperation --> FilterOperation: Apply filters
FilterOperation --> ExecuteOperation: If passed filters
FilterOperation --> Idle: If rejected
ExecuteOperation --> WaitForResponse: Operation sent
WaitForResponse --> ProcessResponse: Response received
WaitForResponse --> HandleError: Timeout/Error
ProcessResponse --> Idle: Update cache
HandleError --> Retry: If retries < max
HandleError --> Idle: If max retries exceeded
Retry --> ExecuteOperation: After backoff
}
INIT_READY --> Operations: Ready for operations
```
## TODOS
### PERFORMANCE
- Consider buffer pooling for multiple register operations to reduce memory fragmentation
- Implement batch processing for adjacent registers to reduce number of transactions
- Explore more granular timeouts for different device types or operation types
### SECURITY
- Implement authentication mechanisms for secure Modbus communication
- Add validation for incoming data values to prevent exploitation
- Consider adding packet encryption for sensitive industrial applications
### COMPLIANCE
- Ensure full compliance with Modbus RTU protocol specification
- Add support for additional function codes to cover all Modbus operations
- Implement proper exception code handling according to the standard
### RECOMMENDATIONS
- Monitor operation success rates and adjust retry limits based on network reliability
- Configure adaptive timeouts based on device response characteristics
- Implement device-specific wrappers for common industrial equipment
- Use high priority flag for critical operations (safety or timing-sensitive commands)

134
docs-c/modbus/ModbusTCP.md Normal file
View File

@ -0,0 +1,134 @@
---
title: "ModbusTCP Class Documentation"
description: "Documentation for the ModbusTCP class that manages Modbus TCP communication in an industrial environment"
keywords: ["ESP32", "ModbusTCP", "Modbus Server", "Industrial", "Communication"]
---
## ModbusTCP
**Path**: [`src/modbus/ModbusTCP.h`](../src/modbus/ModbusTCP.h)
**Revision History**: Initial documentation
The ModbusTCP class manages Modbus TCP communication, acting as a Server/Slave. It listens for Modbus TCP requests, finds the target component, and uses the Component's network interface (read/mb_tcp_write) to process the request.
## REQUIREMENTS
- ESP32 with TCP/IP connectivity
- ModbusServerTCPasync instance (from eModbus library)
- Component hierarchy with a parent owner component (typically PHApp)
## PROVIDES
- **ModbusTCP Class**: Main class for managing Modbus TCP server functionality
- **Address Mapping Functionality**: Maps Modbus addresses to component functions
## FEATURES
- Handles Modbus TCP slave/server functionality
- Supports standard Modbus function codes:
- Read Coils (01)
- Read Holding Registers (03)
- Write Single Coil (05)
- Write Single Register (06)
- Write Multiple Coils (15)
- Write Multiple Registers (16)
- Manages address mapping between Modbus addresses and components
- Routes Modbus requests to appropriate component handlers
- Provides component registration system for Modbus address ranges
- Maps internal errors to Modbus exception codes
## DEPENDENCIES
- [Component.h](../src/core/Component.h)
- [enums.h](../src/util/enums.h)
- [config-modbus.h](../src/config/config-modbus.h)
- [ArduinoLog.h](../lib/ArduinoLog/ArduinoLog.h)
- [Vector.h](../lib/Vector/Vector.h)
- [ModbusServerTCPasync.h](../lib/eModbus/ModbusServerTCPasync.h)
- [ModbusTypes.h](../src/modbus/ModbusTypes.h)
```mermaid
graph TD
ModbusTCP --> Component
ModbusTCP --> enums
ModbusTCP --> ModbusTypes
ModbusTCP --> ModbusServerTCPasync
ModbusTCP --> Vector
ModbusTCP --> ArduinoLog
ModbusTCP --> configmodbus[config-modbus.h]
```
## BEHAVIOUR
```mermaid
sequenceDiagram
participant Client as Modbus TCP Client
participant Server as ModbusTCP Server
participant Component as Component
Client->>Server: TCP Connection
Client->>Server: Modbus Request (Function Code + Address)
Server->>Server: Find component for address
alt Component found
Server->>Component: mb_tcp_read() or mb_tcp_write()
Component->>Server: Return data/status
Server->>Client: Modbus Response with data
else No component or mapping found
Server->>Client: Exception Response
end
```
## EXAMPLE
```cpp
#include "ModbusTCP.h"
// Create ModbusServerTCPasync instance
ModbusServerTCPasync mbTCPServer;
// Create and initialize ModbusTCP
ModbusTCP modbusTCP(appComponent, &mbTCPServer);
// Register component with Modbus address block
MB_Registers tempSensorRegisters = {
.startAddress = 1000,
.count = 10,
.type = FN_READ_HOLD_REGISTER,
.access = MB_ACCESS_READ_WRITE,
.componentId = 0 // Will be filled by ModbusTCP
};
modbusTCP.registerModbus(temperatureComponent, tempSensorRegisters);
// Setup and start the Modbus TCP manager
modbusTCP.setup();
// Call this regularly in the main loop
modbusTCP.loop();
```
## TODOS
### PERFORMANCE
- Consider implementing a more efficient lookup method for address mappings (e.g., hash map) for projects with many components
- Add optional caching for frequently read values to reduce component calls
- Optimize byte packing/unpacking for multi-coil operations
### SECURITY
- Add IP filtering capability to restrict access to authorized clients
- Implement authentication mechanism for Modbus TCP connections
- Consider adding encrypted Modbus TCP support for sensitive applications
### COMPLIANCE
- Ensure full compliance with Modbus Application Protocol Specification V1.1b3
- Add support for other function codes (Read Input Registers, Read Discrete Inputs) if needed
### RECOMMENDATIONS
- Create unit tests to validate mapping and routing functionality
- Maintain detailed logs of Modbus communications for debugging
- Implement a strict mode that returns exceptions for unmapped addresses (currently configurable)
- Consider adding diagnostic counters for monitoring communication quality

View File

@ -0,0 +1,131 @@
---
title: "ModbusTypes Reference"
description: "Comprehensive reference for the ModbusTypes component used in Modbus RS-485 industrial applications"
keywords: ["modbus", "industrial", "esp32", "rs485", "communication"]
---
# ModbusTypes
**Path**: [`src/modbus/ModbusTypes.h`](../../../src/modbus/ModbusTypes.h)
**Revision History**: Initial documentation
A collection of enumerations, structures, and classes that define the foundational types used by the Modbus implementation. This component provides the core data types and interfaces for working with Modbus communication in industrial applications.
## REQUIREMENTS
- ESP32 microcontroller
- Platform.io development environment
- C++17 compatible compiler
## PROVIDES
- **Enumerations**:
- `E_FN_CODE`: Modbus function codes
- `E_MB_OpType`: Modbus operation types
- `E_MB_OpStatus`: Operation status
- `MB_Error`: Error codes
- `E_FilterType`: Filter types for operation filtering
- `E_ModbusAccess`: Access types (from config-modbus.h)
- **Structures**:
- `MB_Registers`: Register definition structure
- `ModbusBlockView`: Non-owning view of register blocks
- `MB_UpdateData`: RTU update data
- `ModbusOperation`: Modbus operation structure
- `ModbusValueEntry`: Register or coil value entry
- `SlaveData`: Modbus slave data
- `ModbusReadBlock`: Mandatory read block definition
- **Classes**:
- `ModbusOperationFilter`: Base class for operation filters
- `DuplicateOperationFilter`: Filter to remove duplicate operations
- `RateLimitFilter`: Filter to limit operation rates
- `PriorityFilter`: Filter for prioritizing operations
- `OperationLifecycleFilter`: Filter for managing operation lifecycle
- `RegisterState`: Class for register state management
- `RTU_Base`: Base class for RTU devices
- **Callback Types**:
- `ResponseCallback`: Callback for slave responses
- `OnRegisterChangeCallback`: Callback for register changes
- `OnWriteCallback`: Callback for write operations
- `OnErrorCallback`: Callback for error handling
- `OperationExistsCallback`: Callback for checking if operation exists
## FEATURES
- Comprehensive Modbus function code support
- Error handling with detailed error codes
- Operation filtering system for queue management
- Register state management
- Device state management through RTU_Base
- Support for mandatory read blocks
- Priority-based operation scheduling
- Callback systems for events
## DEPENDENCIES
- [Arduino.h](https://www.arduino.cc/reference/en/)
- [ArduinoLog.h](https://github.com/thijse/Arduino-Log)
- [Component.h](../../../src/Component.h)
- [Vector.h](../../../src/Vector.h)
- [enums.h](../../../src/enums.h)
- [macros.h](../../../src/macros.h)
- [constants.h](../../../src/constants.h)
- [config-modbus.h](../../../src/config-modbus.h)
```mermaid
graph TD
ModbusTypes --> ArduinoLog
ModbusTypes --> Component
ModbusTypes --> Vector
ModbusTypes --> macros
ModbusTypes --> constants
ModbusTypes --> config-modbus
ModbusTypes --> enums
ModbusRTU --> ModbusTypes
RTUDevices --> ModbusTypes
RS485 --> ModbusTypes
```
## BEHAVIOUR
```mermaid
stateDiagram-v2
[*] --> UNINITIALIZED
UNINITIALIZED --> INITIALIZING: initialize()
INITIALIZING --> IDLE: initialization complete
IDLE --> RUNNING: operations pending
RUNNING --> IDLE: operations complete
IDLE --> ERROR: timeout
RUNNING --> ERROR: timeout
ERROR --> IDLE: response received
```
## TODOS
### PERFORMANCE
- Consider more efficient data structures for queuing operations
- Optimize memory usage in filter chain implementations
- Implement operation batching for improved throughput
### SECURITY
- Add validation for input parameters to prevent buffer overflows
- Consider implementing authentication mechanisms for Modbus TCP
- Add checks for unauthorized register access
### COMPLIANCE
- Ensure full compliance with Modbus specification
- Review handling of exceptional responses
- Validate operation against industrial standards
### RECOMMENDATIONS
- Implement appropriate error handling strategies
- Set appropriate timeouts based on network characteristics
- Use the filter chain to customize operation processing
- Leverage the callback system for event-based programming

70
scripts/docs-m.md Normal file
View File

@ -0,0 +1,70 @@
# Context
- ESP-32, Platform.io, C17
- avoidance of std
- industrial application, using Modbus-485
## Instructions
- Generate documentation for a given class, its types, enumerations, in a new Markdown file located at `./docs/modbus/<filename>.md`.
- The documentation is intended for an Astro static site generator.
- Include frontmatter in the Markdown file with `title`, `description`, and `keywords` fields.
- You will be provided with the content of the component's header file (e.g., `src/modbus/<file-name>.h`).
- Ensure the generated Markdown adheres to standard linting rules.
- 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.
- Do not comment or add thoughts, just output plain Markdown
## Layout
The Markdown document must adhere to the following structure:
----------------------------
## COMPONENT NAME
**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 !
A detailed description of the component
## REQUIREMENTS
Detail the hardware pins and software dependencies required by the component.
## PROVIDES
- a list of all types, enumerations and classes
## FEATURES
List the key features and functionalities of the component.
## DEPENDENCIES
- Provide a list of dependencies as Markdown formatted links.
- Include a minimal Mermaid diagram illustrating the dependencies. The diagram node names should not contain braces or brackets.
## BEHAVIOUR
- Include a minimal Mermaid diagram illustrating the component's behaviour or state machine. The diagram node names should not contain braces or brackets.
## TODOS
### PERFORMANCE
Outline any performance considerations or areas for future optimization.
### SECURITY
Describe potential security vulnerabilities or hardening measures.
### COMPLIANCE
Note any compliance standards or requirements relevant to the component.
### RECOMMENDATIONS
Provide any recommendations for using or extending the component.

10
scripts/docs-m.sh Normal file
View File

@ -0,0 +1,10 @@
kbot-d --model=anthropic/claude-3.7-sonnet \
--prompt=./scripts/docs-m.md \
--each=./src/modbus/*.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'