Skip to main content

Overview

AutoLight V3 includes a built-in AsyncWebServer with RESTful API for remote LED control. The system supports both Access Point (AP) and Station (STA) WiFi modes with automatic IP configuration.

Quick Start

1

Enable WiFi Support

The WiFi module is automatically included with AutoLight V3:
#define ENABLE_ADDONS_AUTOLIGHT_V3
#include "Kinematrix.h"

using namespace AutoLight;
2

Initialize with Web Server

BaseChannel led;
BaseConfig config;

void setup() {
    Serial.begin(115200);
    
    // Configure LED system
    config.setDynamicConfig(12, 2);
    led.attachConfig(config.getConfigData());
    led.initialize();
    
    // Enable integrated web server
    led.enableWebServer(true);
}
3

Connect and Control

The device creates a WiFi access point:
  • SSID: AutoLight-XXXX (check serial output)
  • IP Address: 192.168.4.1
  • API Port: 8000
  • Web Port: 80 (if SD card available)

Complete Web-Enabled Example

#define ENABLE_ADDONS_AUTOLIGHT_V3
#include "Kinematrix.h"

using namespace AutoLight;

BaseChannel led;
BaseConfig config;

void setup() {
    Serial.begin(115200);
    Serial.println("AutoLight V3 - Web Control Example");
    
    // Configure 24 LED channels across 3 PCF8574 devices
    config.setDynamicConfig(24, 3);
    
    // Set initial pattern and speed
    led.setInitSequence(2);   // Start with Blink All
    led.setInitDelay(50);     // 50ms timing
    
    // Attach configuration
    led.attachConfig(config.getConfigData());
    
    // Initialize LED system
    if (led.initialize()) {
        Serial.println("✓ LED system initialized");
    }
    
    // Enable web server with automatic FreeRTOS task
    led.enableWebServer(true);
    
    Serial.println("==============================");
    Serial.println("Web Server Ready");
    Serial.println("Default IP: 192.168.4.1:8000");
    Serial.println("==============================");
}

void loop() {
    led.runAutoLight();
    delay(10);
}

REST API Endpoints

Device Information

Retrieve device configuration and status:
# Get device name
curl http://192.168.4.1:8000/api/v1/data/get/device/name
# Response: "AutoLight-A1B2C3"

# Get channel count
curl http://192.168.4.1:8000/api/v1/data/get/device/ch
# Response: "24"

# Get device serial number
curl http://192.168.4.1:8000/api/v1/data/get/device/serial
# Response: "AL3-2024-001"

LED Mode Control

Control sequence modes (0-15):
# Get current mode
curl http://192.168.4.1:8000/api/v1/data/get/mode
# Response: "2"

# Set mode to 5 (Fill In pattern)
curl "http://192.168.4.1:8000/api/v1/data/set/mode?value=5"
# Response: "Berhasil Set Mode : 5"

Timing Control

Adjust LED animation speed:
# Get current delay time
curl http://192.168.4.1:8000/api/v1/data/get/delay
# Response: "50"

# Set delay to 100ms (slower animation)
curl "http://192.168.4.1:8000/api/v1/data/set/delay?value=100"
# Response: "Berhasil Set delay : 100"

Device Configuration

Update device settings:
# Change device name
curl "http://192.168.4.1:8000/api/v1/data/set/device/name?value=MyAutoLight"
# Response: "Berhasil Set device : MyAutoLight"

API Endpoint Reference

EndpointMethodParametersDescription
/api/v1/data/get/device/nameGET-Get device name
/api/v1/data/get/device/chGET-Get channel count
/api/v1/data/get/device/serialGET-Get serial number
/api/v1/data/get/modeGET-Get current sequence mode
/api/v1/data/get/delayGET-Get delay time (ms)
/api/v1/data/set/modeGETvalue=0-15Set sequence mode
/api/v1/data/set/delayGETvalue=30-300Set delay time
/api/v1/data/set/device/nameGETvalue=stringSet device name

WiFi Configuration Modes

Access Point Mode (Default)

Device creates its own WiFi network:
void setup() {
    Serial.begin(115200);
    
    config.setDynamicConfig(12, 2);
    led.attachConfig(config.getConfigData());
    led.initialize();
    
    // AP mode is default
    led.enableWebServer(true);
    
    // Check serial output for:
    // - SSID: AutoLight-XXXXXX
    // - Password: (shown in serial)
    // - IP: 192.168.4.1
}

Station Mode

Connect to existing WiFi network:
void setup() {
    Serial.begin(115200);
    
    // Configure WiFi credentials before enabling web server
    ConfigManager::getInstance().setWiFiMode(AUTOLIGHT_WIFI_MODE_STA);
    ConfigManager::getInstance().updateCredentials(
        "YourWiFiSSID",
        "YourWiFiPassword"
    );
    
    config.setDynamicConfig(12, 2);
    led.attachConfig(config.getConfigData());
    led.initialize();
    led.enableWebServer(true);
    
    // Device IP will be assigned by your router
    // Check serial output for assigned IP
}

Web Client Integration

AutoLight V3 includes a Next.js web client for browser-based control.

JavaScript Fetch Example

// Device configuration
const baseURL = 'http://192.168.4.1:8000/api/v1';

// Get current mode
async function getCurrentMode() {
    try {
        const response = await fetch(`${baseURL}/data/get/mode`);
        const mode = await response.text();
        console.log('Current mode:', mode);
        return parseInt(mode);
    } catch (error) {
        console.error('Error fetching mode:', error);
    }
}

// Set new mode
async function setMode(modeValue) {
    try {
        const response = await fetch(
            `${baseURL}/data/set/mode?value=${modeValue}`
        );
        const result = await response.text();
        console.log('Mode changed:', result);
    } catch (error) {
        console.error('Error setting mode:', error);
    }
}

// Set delay time
async function setDelay(delayMs) {
    try {
        const response = await fetch(
            `${baseURL}/data/set/delay?value=${delayMs}`
        );
        const result = await response.text();
        console.log('Delay changed:', result);
    } catch (error) {
        console.error('Error setting delay:', error);
    }
}

// Usage
await setMode(5);      // Set to mode 5 (Fill In)
await setDelay(100);   // Set to 100ms timing

React Component Example

import { useState, useEffect } from 'react';

function AutoLightController() {
    const [mode, setMode] = useState(0);
    const [delay, setDelay] = useState(50);
    const [deviceName, setDeviceName] = useState('');
    const baseURL = 'http://192.168.4.1:8000/api/v1';

    // Fetch current state on mount
    useEffect(() => {
        const fetchState = async () => {
            try {
                const [modeRes, delayRes, nameRes] = await Promise.all([
                    fetch(`${baseURL}/data/get/mode`),
                    fetch(`${baseURL}/data/get/delay`),
                    fetch(`${baseURL}/data/get/device/name`)
                ]);
                
                setMode(parseInt(await modeRes.text()));
                setDelay(parseInt(await delayRes.text()));
                setDeviceName(await nameRes.text());
            } catch (error) {
                console.error('Failed to fetch device state:', error);
            }
        };
        
        fetchState();
        
        // Poll every 2 seconds
        const interval = setInterval(fetchState, 2000);
        return () => clearInterval(interval);
    }, []);

    const handleModeChange = async (newMode) => {
        try {
            await fetch(`${baseURL}/data/set/mode?value=${newMode}`);
            setMode(newMode);
        } catch (error) {
            console.error('Failed to set mode:', error);
        }
    };

    const handleDelayChange = async (newDelay) => {
        try {
            await fetch(`${baseURL}/data/set/delay?value=${newDelay}`);
            setDelay(newDelay);
        } catch (error) {
            console.error('Failed to set delay:', error);
        }
    };

    return (
        <div className="autolight-controller">
            <h2>AutoLight Control: {deviceName}</h2>
            
            <div className="mode-selector">
                <label>Mode: {mode}</label>
                <input
                    type="range"
                    min="0"
                    max="15"
                    value={mode}
                    onChange={(e) => handleModeChange(e.target.value)}
                />
            </div>
            
            <div className="delay-selector">
                <label>Delay: {delay}ms</label>
                <input
                    type="range"
                    min="30"
                    max="300"
                    value={delay}
                    onChange={(e) => handleDelayChange(e.target.value)}
                />
            </div>
            
            <div className="quick-modes">
                <button onClick={() => handleModeChange(0)}>OFF</button>
                <button onClick={() => handleModeChange(1)}>ON</button>
                <button onClick={() => handleModeChange(2)}>Blink</button>
                <button onClick={() => handleModeChange(5)}>Fill In</button>
            </div>
        </div>
    );
}

export default AutoLightController;

CORS Configuration

AutoLight V3 API includes CORS headers for cross-origin requests:
void APIServerManager::setDefaultHeaders() {
    DefaultHeaders::Instance().addHeader(
        "Access-Control-Allow-Headers", "content-type"
    );
    DefaultHeaders::Instance().addHeader(
        "Access-Control-Allow-Origin", "*"
    );
}
This allows web clients from any origin to access the API.

Manual Web Server Mode

For custom task management:
void setup() {
    Serial.begin(115200);
    
    config.setDynamicConfig(12, 2);
    led.attachConfig(config.getConfigData());
    led.initialize();
    
    // Enable web server without automatic FreeRTOS task
    led.enableWebServerManual();
}

void loop() {
    led.runAutoLight();
    
    // Manually run web server in main loop
    led.runWebServer();
    
    delay(10);
}

WebClient Pattern Builder

The AutoLight V3 WebClient provides a visual Pattern Builder: Features:
  • Visual grid-based pattern creation
  • C++ code generation for BaseChannelSequence
  • JavaScript simulator with high-precision timing
  • Expression builder for mathematical patterns
  • Real-time device synchronization
Access the WebClient:
cd lib/addons/AutoLightv3/WebClient
npm install
npm run dev
Open browser to http://localhost:3001 and connect to your device at 192.168.4.1:8000.

Advanced: Custom API Endpoints

Extend the API with custom endpoints:
class CustomAPIManager : public APIServerManager {
public:
    CustomAPIManager(BaseChannel* led, BaseConfig* config)
        : APIServerManager(led, config) {}
    
    void setupCustomRoutes() {
        // Add custom endpoint
        api_.on("/api/v1/custom/pattern", HTTP_GET, 
            [this](AsyncWebServerRequest *request) {
                if (request->hasArg("id")) {
                    int patternId = request->arg("id").toInt();
                    activateCustomPattern(patternId);
                    request->send(200, "text/plain", 
                        "Pattern activated: " + String(patternId));
                } else {
                    request->send(400, "text/plain", 
                        "Missing pattern ID");
                }
            });
    }
    
private:
    void activateCustomPattern(int id) {
        // Your custom pattern logic
    }
};

Troubleshooting

Cannot Connect to WiFi

  1. Check serial output for WiFi credentials
  2. Ensure device is in AP mode (default)
  3. Verify IP address (usually 192.168.4.1)

API Not Responding

  1. Confirm web server is enabled: led.enableWebServer(true)
  2. Check API port (8000, not 80)
  3. Test with curl: curl http://192.168.4.1:8000/api/v1/data/get/mode

CORS Errors in Browser

// CORS is enabled by default
// If issues persist, verify browser console for specific error

Performance Considerations

  • API server runs on FreeRTOS Task (Core 0)
  • LED control runs in main loop (Core 1)
  • Minimal latency between API commands and LED response
  • Supports concurrent API requests

Next Steps

Pattern Sequences

Learn about the 16 built-in LED sequence patterns

Basic LED Control

Review fundamental AutoLight setup and configuration

Build docs developers (and LLMs) love