DIYables Web Apps Library Reference

DIYables WebApps Library - API Reference

Overview

The DIYables WebApps library provides a comprehensive modular solution for creating WebSocket-based web applications on Arduino Uno R4 WiFi and DIYables STEM V4 IoT. It includes multiple pre-built web applications and a flexible framework for creating custom applications. Specially optimized for the DIYables STEM V4 IoT educational platform with enhanced IoT capabilities and built-in sensor integration.

The library uses a modular architecture where you only include the web applications you need, saving memory and improving performance.

Features

  • Modular Architecture: Add only the web apps you need to optimize memory usage
  • Memory Efficient: Each web app can be enabled/disabled independently
  • 11+ Ready-to-Use Web Applications: Complete Arduino control without web programming knowledge
  • Custom Web App Framework: Create your own applications using the base class system
  • Real-time Communication: WebSocket-based for instant updates
  • Responsive Design: Works on desktop, tablet, and mobile devices
  • Easy Integration: Simple callback-based API
  • Multiple App Support: Support adding multiple web apps simultaneously
  • Platform Extensible: Currently implemented for Arduino Uno R4 WiFi, but can be extended for other hardware platforms. See DIYables_WebApps_ESP32

Core Classes

DIYablesWebAppServer

The main server class that manages web applications, HTTP requests, and WebSocket communication.

Constructor
DIYablesWebAppServer(int httpPort = 80, int websocketPort = 81)

Creates a web app server instance.

  • httpPort: HTTP server port (default: 80)
  • websocketPort: WebSocket server port (default: 81)
Methods

##### Setup and Connection

bool begin()

Initializes network connection (for Ethernet or pre-configured connections) and starts the web server.

  • Returns: true if successful, false if failed
  • Use case: For future Ethernet support or when WiFi credentials are pre-configured
bool begin(const char* ssid, const char* password)

Initializes WiFi connection and starts the web server.

  • ssid: WiFi network name
  • password: WiFi password
  • Returns: true if successful, false if failed
  • Use case: Standard WiFi connection with credentials
void loop()

Handles HTTP requests and WebSocket communication. Must be called in the main loop.

bool isConnected()

Returns true if WiFi is connected.

String getIPAddress()

Returns the Arduino's IP address as a string.

##### Application Management

void addApp(DIYablesWebAppPageBase* app)

Adds a web application to the server.

  • app: Pointer to a web application instance
void removeApp(const String& path)

Removes a web application by its URL path.

  • path: URL path of the application (e.g., "/chat")
DIYablesWebAppPageBase* getApp(const String& path)

Gets a web application by its URL path.

  • path: URL path of the application
  • Returns: Pointer to the app or nullptr if not found
void setNotFoundPage(const DIYablesNotFoundPage& page)

Sets the 404 Not Found page (optional).

  • page: 404 page instance

##### Specialized App Access

DIYablesWebDigitalPinsPage* getWebDigitalPinsPage()

Gets the digital pins page instance if added.

  • Returns: Pointer to the digital pins page or nullptr
DIYablesWebSliderPage* getWebSliderPage()

Gets the slider page instance if added.

  • Returns: Pointer to the slider page or nullptr
DIYablesWebJoystickPage* getWebJoystickPage()

Gets the joystick page instance if added.

  • Returns: Pointer to the joystick page or nullptr

Base Classes

DIYablesWebAppPageBase

Abstract base class that all web applications inherit from. Provides common functionality for HTTP handling, WebSocket communication, and page management.

Constructor
DIYablesWebAppPageBase(const String& pagePath)

Creates a base page instance with the specified URL path.

  • pagePath: URL path for the page (e.g., "/web-joystick")
Virtual Methods (Must be implemented by derived classes)
virtual void handleHTTPRequest(IWebClient& client) = 0

Handles HTTP requests for this page. Pure virtual method.

  • client: Web client interface for sending response
virtual void handleWebSocketMessage(IWebSocket& ws, const char* message, uint16_t length) = 0

Handles WebSocket messages for this page. Pure virtual method.

  • ws: WebSocket connection interface
  • message: Received message content
  • length: Message length
virtual const char* getPageInfo() const = 0

Returns page identification string used in connection info display. Pure virtual method.

  • Returns: Page info string (e.g., "đŸ•šī¸ Web Joystick: ")
virtual String getNavigationInfo() const = 0

Returns HTML for home page navigation button. Pure virtual method.

  • Returns: HTML string for navigation card
Virtual Methods (Optional overrides)
virtual void onWebSocketConnection(IWebSocket& ws)

Called when a new WebSocket connection is established.

  • ws: New WebSocket connection
virtual void onWebSocketClose(IWebSocket& ws)

Called when a WebSocket connection is closed.

  • ws: Closed WebSocket connection
Common Methods
const char* getPagePath() const

Gets the URL path for this page.

  • Returns: Page path string
bool isEnabled() const

Checks if the page is currently enabled.

  • Returns: true if enabled, false if disabled
void setEnabled(bool enable)

Enables or disables the page.

  • enable: true to enable, false to disable
Utility Methods
void sendHTTPHeader(IWebClient& client, const char* contentType = "text/html")

Sends standard HTTP headers to client.

  • client: Web client interface
  • contentType: MIME type (default: "text/html")
void sendWebSocketMessage(IWebSocket& ws, const char* message)

Sends a message to specific WebSocket client.

  • ws: Target WebSocket connection
  • message: Message to send
void broadcastToAllClients(const char* message)

Broadcasts a message to all connected WebSocket clients.

  • message: Message to broadcast
void sendLargeHTML(IWebClient& client, const char* html)

Sends large HTML content using chunked transfer encoding.

  • client: Web client interface
  • html: HTML content to send
Usage Example
class CustomPage : public DIYablesWebAppPageBase { public: CustomPage() : DIYablesWebAppPageBase("/custom") {} void handleHTTPRequest(IWebClient& client) override { sendHTTPHeader(client); client.println("<html><body>Custom Page</body></html>"); } void handleWebSocketMessage(IWebSocket& ws, const char* message, uint16_t length) override { // Handle WebSocket messages sendWebSocketMessage(ws, "Response: " + String(message)); } const char* getPageInfo() const override { return " 🔧 Custom Page: "; } String getNavigationInfo() const override { return "<a href=\"/custom\" class=\"app-card custom\">" "<h3>🔧 Custom</h3><p>Custom functionality</p></a>"; } };

Web Application Classes

DIYablesHomePage

Central navigation hub providing links to all enabled applications.

Constructor
DIYablesHomePage()
URL Path
  • Path: / (root)

DIYablesWebChatPage

Interactive chat interface for two-way communication with Arduino.

Constructor
DIYablesWebChatPage()
URL Path
  • Path: /webchat
Methods
void onWebChatMessage(std::function<void(const String&)> callback)

Sets callback for incoming chat messages.

void sendToWebChat(const String& message)

Sends a message to the web chat interface.

DIYablesWebMonitorPage

Web-based serial monitor for real-time output and command input.

Constructor
DIYablesWebMonitorPage()
URL Path
  • Path: /webmonitor
Methods
void onWebMonitorMessage(std::function<void(const String&)> callback)

Sets callback for incoming monitor messages.

void sendToWebMonitor(const String& message)

Sends a message to the web monitor interface.

DIYablesWebDigitalPinsPage

Control and monitor digital pins 0-13 through web interface.

Constructor
DIYablesWebDigitalPinsPage()
URL Path
  • Path: /webdigitalpins
Methods
void enablePin(int pin, int mode)

Enables a pin for web control.

  • pin: Pin number (0-13)
  • mode: WEB_PIN_OUTPUT or WEB_PIN_INPUT
void onPinWrite(std::function<void(int, int)> callback)

Sets callback for pin write operations (output pins).

void onPinRead(std::function<int(int)> callback)

Sets callback for pin read operations (input pins).

void onPinModeChange(std::function<void(int, int)> callback)

Sets callback for pin mode changes.

void updatePinState(int pin, int state)

Updates pin state in real-time for web clients.

DIYablesWebSliderPage

Dual slider control for analog/PWM applications.

Constructor
DIYablesWebSliderPage()
URL Path
  • Path: /webslider
Methods
void onSliderValueFromWeb(std::function<void(int, int)> callback)

Sets callback for slider value changes from web.

  • Parameters: slider1 (0-255), slider2 (0-255)
void onSliderValueToWeb(std::function<void()> callback)

Sets callback for web client requesting current values.

void sendToWebSlider(int slider1, int slider2)

Sends slider values to web interface.

DIYablesWebJoystickPage

2D joystick control for robotics and positioning applications.

Constructor
DIYablesWebJoystickPage(bool autoReturn = true, float sensitivity = 10.0)
  • autoReturn: Whether joystick returns to center automatically
  • sensitivity: Minimum movement percentage to trigger updates
URL Path
  • Path: /webjoystick
Methods
void onJoystickValueFromWeb(std::function<void(int, int)> callback)

Sets callback for joystick movement from web.

  • Parameters: x (-100 to 100), y (-100 to 100)
void onJoystickValueToWeb(std::function<void()> callback)

Sets callback for web client requesting current position.

void sendToWebJoystick(int x, int y)

Sends joystick position to web interface.

void setAutoReturn(bool autoReturn)

Sets auto-return behavior.

void setSensitivity(float sensitivity)

Sets movement sensitivity (percentage).

DIYablesWebPlotterPage

Real-time data visualization with multiple data series support.

Constructor
DIYablesWebPlotterPage()
URL Path
  • Path: /webplotter
Methods
void setPlotTitle(const String& title)

Sets the plot title.

void setAxisLabels(const String& xLabel, const String& yLabel)

Sets axis labels.

void enableAutoScale(bool enable)

Enables or disables automatic Y-axis scaling.

void setMaxSamples(int maxSamples)

Sets maximum number of data points to display.

void addDataPoint(const String& seriesName, float x, float y)

Adds a data point to a series.

void clearPlot()

Clears all data from the plot.

DIYablesNotFoundPage

Optional 404 error page for better user experience.

Constructor
DIYablesNotFoundPage()

Basic Usage Example

#include <DIYablesWebApps.h> // WiFi credentials const char* ssid = "YOUR_WIFI_SSID"; const char* password = "YOUR_WIFI_PASSWORD"; // Create server and web applications DIYablesWebAppServer webAppsServer(80, 81); DIYablesHomePage homePage; DIYablesWebChatPage chatPage; DIYablesWebMonitorPage monitorPage; void setup() { Serial.begin(9600); // Add only the applications you need webAppsServer.addApp(&homePage); webAppsServer.addApp(&chatPage); webAppsServer.addApp(&monitorPage); // Optional: Add 404 page webAppsServer.setNotFoundPage(DIYablesNotFoundPage()); // Start server if (webAppsServer.begin(ssid, password)) { Serial.println("Server started successfully"); Serial.print("IP: "); Serial.println(webAppsServer.getIPAddress()); } // Setup callbacks chatPage.onWebChatMessage([](const String& message) { Serial.println("Chat: " + message); chatPage.sendToWebChat("Arduino received: " + message); }); } void loop() { webAppsServer.loop(); delay(10); }

Web Applications Overview

Home Page

  • URL: http://[arduino-ip]/
  • Purpose: Central navigation hub
  • Features: Links to all enabled applications, connection status

WebChat Application

  • URL: http://[arduino-ip]/webchat
  • Purpose: Two-way communication interface
  • Features: Real-time messaging, message history, WebSocket status

Web Monitor

  • URL: http://[arduino-ip]/webmonitor
  • Purpose: Serial monitor replacement
  • Features: Real-time serial output, command input, dark theme

Web Digital Pins Control

  • URL: http://[arduino-ip]/webdigitalpins
  • Purpose: Control digital pins 0-13
  • Features: Individual pin control, bulk operations, real-time status

Web Slider Control

  • URL: http://[arduino-ip]/webslider
  • Purpose: Dual analog/PWM control
  • Features: Two independent sliders (0-255), preset values, real-time feedback

Web Joystick Control

  • URL: http://[arduino-ip]/webjoystick
  • Purpose: 2D position control for robots/vehicles
  • Features: Touch/mouse control, coordinate display, sensitivity adjustment

Web Plotter

  • URL: http://[arduino-ip]/webplotter
  • Purpose: Real-time data visualization
  • Features: Multiple data series, auto-scaling, configurable titles and axes

WebSocket Communication

All applications use WebSocket on port 81 for real-time communication:

  • WebSocket URL: ws://[arduino-ip]:81
  • Connection: Automatic reconnection on disconnect
  • Protocol: Text-based message format

Message Formats

WebChat Messages
  • From Web: Direct text message
  • To Web: Direct text message
Web Monitor Messages
  • From Web: Direct text message
  • To Web: Direct text message
Web Digital Pin Messages
  • From Web: JSON format: {"pin": 13, "state": 1}
  • To Web: JSON format: {"pin": 13, "state": 1}
Web Slider Messages
  • From Web: JSON format: {"slider1": 128, "slider2": 255}
  • To Web: JSON format: {"slider1": 128, "slider2": 255}
Web Joystick Messages
  • From Web: JSON format: {"x": 50, "y": -25}
  • To Web: JSON format: {"x": 50, "y": -25}
Web Plotter Messages
  • From Web: Not applicable (display only)
  • To Web: JSON format: {"series": "temp", "x": 10.5, "y": 23.4}

Error Handling

The library includes automatic error handling for:

  • WiFi connection failures
  • WebSocket disconnections
  • Invalid message formats
  • Client connection limits

Memory Usage

Modular Architecture Benefits: Include only the web applications you need to optimize memory usage.

Approximate memory usage per component:

  • DIYablesWebAppServer: ~8KB Flash, ~2KB RAM
  • DIYablesHomePage: ~3KB Flash, ~1KB RAM
  • DIYablesWebChatPage: ~6KB Flash, ~1.5KB RAM
  • DIYablesWebMonitorPage: ~5KB Flash, ~1.5KB RAM
  • DIYablesWebDigitalPinsPage: ~8KB Flash, ~2KB RAM
  • DIYablesWebSliderPage: ~6KB Flash, ~1.5KB RAM
  • DIYablesWebJoystickPage: ~7KB Flash, ~1.5KB RAM
  • DIYablesWebPlotterPage: ~10KB Flash, ~2KB RAM
  • WebSocket Buffer: ~1KB RAM per connection

Total if all apps enabled: ~53KB Flash, ~12KB RAM

Minimal setup (server + home + 1 app): ~17KB Flash, ~4.5KB RAM

Browser Compatibility

Supported browsers:

  • Chrome 50+
  • Firefox 45+
  • Safari 10+
  • Edge 79+
  • Mobile browsers (iOS Safari, Chrome Mobile)

Security Notes

  • No authentication implemented (suitable for local networks only)
  • Use in trusted networks only
  • Consider adding authentication for public deployments

Troubleshooting

Common Issues

  1. Cannot connect to WiFi

- Check SSID and password

- Verify network is 2.4GHz (not 5GHz)

- Check signal strength

  1. WebSocket connection fails

- Verify IP address is correct

- Check firewall settings

- Try different browser

  1. High memory usage

- Disable unused applications

- Limit concurrent connections

- Restart Arduino if memory fragmentation occurs

  1. Slow response

- Check WiFi signal strength

- Reduce WebSocket message frequency

- Use shorter callback functions

Example Projects

Example Applications

The DIYables WebApps library includes comprehensive examples designed for Arduino Uno R4 WiFi and DIYables STEM V4 IoT educational platform:

Available Examples

  • Chat Example: Two-way communication interface
  • WebMonitor Example: Serial monitor replacement with enhanced features
  • WebDigitalPins Example: Control all digital pins with visual feedback
  • WebSlider Example: Dual analog/PWM control with presets
  • WebJoystick Example: 2D position control for robotics projects
  • MultipleWebApps Example: All applications running simultaneously

Hardware Compatibility

  • Recommended: DIYables STEM V4 IoT (enhanced features, built-in sensors)
  • Compatible: Arduino Uno R4 WiFi

Tutorial Resources

Complete step-by-step tutorials available at:

  • Newbiely.com/tutorials/arduino/arduino-uno-r4-wifi-web-apps
  • DIYables STEM V4 IoT specific guides and sensor integration examples

See the examples/ folder for complete projects and docs/ folder for detailed setup instructions.

Platform Abstraction Interfaces

The DIYables WebApps library uses a platform abstraction layer with interfaces that enable support for multiple hardware platforms. These interfaces separate the core WebApp functionality from platform-specific implementations.

Core Interfaces

IWebClient

Interface for HTTP client connections.

class IWebClient { public: virtual ~IWebClient() = default; // Stream interface methods virtual int available() = 0; virtual int read() = 0; virtual int peek() = 0; virtual size_t write(uint8_t data) = 0; virtual size_t write(const uint8_t* buffer, size_t size) = 0; virtual void flush() = 0; // Connection management virtual bool connected() = 0; virtual void stop() = 0; // Convenience methods virtual void print(const String& str) = 0; virtual void println(const String& str) = 0; };
IWebSocket

Interface for WebSocket connections with bidirectional communication support.

class IWebSocket { public: enum DataType { TEXT = 1, BINARY = 2 }; enum CloseCode { NORMAL_CLOSURE = 1000, GOING_AWAY = 1001, PROTOCOL_ERROR = 1002, UNSUPPORTED_DATA = 1003, POLICY_VIOLATION = 1008, MESSAGE_TOO_BIG = 1009, INTERNAL_ERROR = 1011 }; virtual ~IWebSocket() = default; // Message handling virtual void sendText(const char* message) = 0; virtual void sendBinary(const uint8_t* data, size_t length) = 0; virtual bool isConnected() const = 0; virtual void close(CloseCode code = NORMAL_CLOSURE, const char* reason = nullptr) = 0; // Event callbacks virtual void onMessage(std::function<void(IWebSocket*, DataType, const char*, uint16_t)> callback) = 0; virtual void onClose(std::function<void(IWebSocket*, CloseCode, const char*, uint16_t)> callback) = 0; };
IWebServer

Interface for HTTP server functionality.

class IWebServer { public: virtual ~IWebServer() = default; // Server lifecycle virtual bool begin() = 0; virtual void stop() = 0; virtual IWebClient* available() = 0; // Configuration virtual void setPort(uint16_t port) = 0; virtual uint16_t getPort() const = 0; };
IWebSocketServer

Interface for WebSocket server with connection management.

class IWebSocketServer { public: using ConnectionCallback = std::function<void(IWebSocket*)>; using MessageCallback = std::function<void(IWebSocket*, IWebSocket::DataType, const char*, uint16_t)>; virtual ~IWebSocketServer() = default; // Server lifecycle virtual bool begin() = 0; virtual void stop() = 0; virtual void listen() = 0; // Event handling virtual void onConnection(ConnectionCallback callback) = 0; virtual void onMessage(MessageCallback callback) = 0; // Broadcasting virtual void broadcastText(const char* message) = 0; virtual void broadcastBinary(const uint8_t* data, size_t length) = 0; // Configuration virtual void setPort(uint16_t port) = 0; virtual uint16_t getPort() const = 0; };
INetworkProvider

Interface for network connectivity management.

class INetworkProvider { public: virtual ~INetworkProvider() = default; // Network lifecycle virtual bool begin(const char* ssid, const char* password) = 0; virtual void end() = 0; virtual bool isConnected() = 0; // Network information virtual String getLocalIP() = 0; virtual String getSSID() = 0; virtual int32_t getRSSI() = 0; };
IServerFactory

Factory interface for creating platform-specific implementations.

class IServerFactory { public: virtual ~IServerFactory() = default; // Factory methods virtual INetworkProvider* createNetworkProvider() = 0; virtual IWebServer* createWebServer(uint16_t port) = 0; virtual IWebSocketServer* createWebSocketServer(uint16_t port) = 0; // Platform information virtual String getPlatformName() const = 0; };

Platform Implementation Example

For Arduino Uno R4 WiFi, the interfaces are implemented using the UnoR4WiFi_WebServer library:

class UnoR4ServerFactory : public IServerFactory { public: INetworkProvider* createNetworkProvider() override { return new UnoR4NetworkProvider(); } IWebServer* createWebServer(uint16_t port) override { return new UnoR4WebServer(port); } IWebSocketServer* createWebSocketServer(uint16_t port) override { return new UnoR4WebSocketServer(port); } String getPlatformName() const override { return "Arduino Uno R4 WiFi"; } };

Adding New Platform Support

To add support for a new platform (e.g., ESP32):

  1. Implement all interfaces for the target platform
  2. Create a ServerFactory that instantiates your implementations
  3. Handle platform-specific networking and WebSocket protocols
  4. Test with existing WebApp classes (no changes needed)

Example usage with different platforms:

// Arduino Uno R4 WiFi UnoR4ServerFactory factory; DIYablesWebAppServer server(factory, 80, 81); // ESP32 (hypothetical) ESP32ServerFactory esp32Factory; DIYablesWebAppServer esp32Server(esp32Factory, 80, 81);

Benefits of Interface-Based Design

  • Platform Independence: Core WebApp logic works on any platform
  • Extensibility: Easy to add new hardware support
  • Maintainability: Platform-specific code is isolated
  • Testability: Interfaces can be mocked for unit testing
  • Consistency: Same API across all supported platforms

Current Platform Support

  • ✅ Arduino Uno R4 WiFi: Fully implemented and tested
  • 🔄 ESP32: Available as separate extension - DIYables_WebApps_ESP32
  • 🚀 Future Platforms: Can be added using the same interface pattern

※ OUR MESSAGES

  • As freelancers, We are AVAILABLE for HIRE. See how to outsource your project to us
  • Please feel free to share the link of this tutorial. However, Please do not use our content on any other websites. We invested a lot of effort and time to create the content, please respect our work!