--- title: "REST Server Component Documentation" description: "Documentation for the RESTServer component which provides HTTP and WebSocket APIs for Modbus communication" keywords: ["REST", "API", "WebSocket", "Modbus", "ESP32"] --- ## REST Server **Path**: [`src/components/RestServer.cpp`](../src/components/RestServer.cpp) **Revision History**: Initial documentation The RESTServer component provides a RESTful API and WebSocket interface for interacting with the Modbus system, allowing remote monitoring and control of registers and coils. It serves static files from the filesystem and implements a comprehensive API for system monitoring and Modbus operations. ## REQUIREMENTS - WiFi or Ethernet connectivity - ESP32 with sufficient memory for web server operation - LittleFS filesystem for serving static files (optional, enabled via `ENABLE_LITTLEFS`) - WebSocket support (optional, enabled via `ENABLE_WEBSOCKET`) ## FEATURES - RESTful API for Modbus operations (read/write registers and coils) - WebSocket interface for real-time updates and commands - Serves static files from the filesystem (HTML, CSS, JS) - System information and status endpoint - Log level control - RTU operation queue monitoring - CORS support for cross-origin requests - Pagination support for large datasets - JSON-based communication format ## DEPENDENCIES - [ESPAsyncWebServer](https://github.com/me-no-dev/ESPAsyncWebServer) - Asynchronous web server library - [AsyncJson](https://github.com/me-no-dev/ESPAsyncWebServer) - JSON support for the async web server - [ArduinoJson](https://arduinojson.org/) - JSON parsing and serialization - [ArduinoLog](https://github.com/thijse/Arduino-Log) - Logging utility - [AsyncTCP](https://github.com/me-no-dev/AsyncTCP) - Asynchronous TCP library - [Component](../src/Component.h) - Base component class - [Bridge](../src/Bridge.h) - System bridge - [ModbusTCP](../src/modbus/ModbusTCP.h) - Modbus TCP implementation - [LittleFS](https://arduino-esp8266.readthedocs.io/en/latest/filesystem.html) - Filesystem for static files ```mermaid graph TD RESTServer --> ESPAsyncWebServer RESTServer --> AsyncJson RESTServer --> ArduinoJson RESTServer --> ArduinoLog RESTServer --> AsyncTCP RESTServer --> Component RESTServer --> Bridge RESTServer --> ModbusTCP RESTServer --> LittleFS[LittleFS "optional"] RESTServer --> WebSocket[AsyncWebSocket "optional"] ``` ## BEHAVIOUR The RESTServer handles API requests and WebSocket communications for interfacing with the Modbus system. ```mermaid stateDiagram-v2 [*] --> Initialize Initialize --> SetupRoutes SetupRoutes --> Ready Ready --> HandleHTTPRequest: HTTP Request HandleHTTPRequest --> ServeStaticFile: File Request HandleHTTPRequest --> ProcessAPICall: API Request HandleHTTPRequest --> Ready Ready --> HandleWebSocket: WebSocket Event HandleWebSocket --> ProcessCommand: Message Received HandleWebSocket --> NotifyClient: Client Connected HandleWebSocket --> CleanupClient: Client Disconnected HandleWebSocket --> Ready Ready --> BroadcastUpdate: Modbus Data Changed BroadcastUpdate --> Ready ProcessAPICall --> ReadModbusData: GET Request ProcessAPICall --> WriteModbusData: POST Request ProcessCommand --> ReadModbusData: Read Command ProcessCommand --> WriteModbusData: Write Command ``` ## TODOS ### PERFORMANCE - Consider implementing message compression for WebSocket communications to reduce bandwidth usage - Optimize JSON serialization for large datasets to reduce memory usage - Implement caching mechanisms for frequently accessed static files - Add pagination for all resource-intensive endpoints to prevent memory issues ### SECURITY - Implement authentication for API endpoints and WebSocket connections - Add rate limiting to prevent abuse - Consider using HTTPS for encrypted communications - Validate all input parameters more strictly - Implement token-based authentication for long-lived WebSocket connections ### COMPLIANCE - Ensure compliance with REST API best practices - Implement proper error handling and status codes according to HTTP standards - Ensure WebSocket implementation complies with RFC 6455 - Consider implementing OpenAPI/Swagger documentation for API endpoints - Add proper CORS configuration for security ### RECOMMENDATIONS - Keep WebSocket messages below the maximum size limit (currently 12KB) - Use pagination for large datasets to avoid memory issues - Monitor memory usage during operation, especially with large JSON responses - Consider implementing a websocket message queue for high-traffic systems - Add graceful disconnection handling for WebSocket clients ## EXAMPLE This is how you would initialize and mount a RESTServer component: ```cpp #ifdef ENABLE_WIFI // Create REST server component restServer = new RESTServer( WiFi.localIP(), // Local IP address from WiFi 80, // HTTP port &modbusTCP, // Modbus TCP manager this // Owner component (Bridge) ); if (restServer) { components.push_back(restServer); Log.infoln(F("REST Server initialized on port 80")); } else { Log.errorln(F("REST Server initialization failed")); } #endif ``` ### References - [ESPAsyncWebServer Documentation](https://github.com/me-no-dev/ESPAsyncWebServer) - [RFC 6455 - The WebSocket Protocol](https://tools.ietf.org/html/rfc6455) - [RESTful API Design Guide](https://restfulapi.net/) - [ArduinoJson Documentation](https://arduinojson.org/v6/doc/)