ESP32-Strobe-Master.ino

Arduino (C++) · 285 lines

#include <Arduino.h>
#include <WiFi.h>
#include <ESPAsyncWebServer.h>
#include <AsyncTCP.h>
#include <LittleFS.h>
#include <ArduinoJson.h>
#include "index_html_gz.h"

// ==========================================
// CONFIGURATION & CONSTANTS
// ==========================================
#define AP_SSID          "ESP32-Strobe-Master"
#define AP_PASS          "strobe1234"

#define LEDC_TIMER_RES   14          // 14-bit resolution (0 - 16383)
#define LEDC_MAX_DUTY    16383.0f

// Expanded Safe Output Pins Array (Input-only and Flash pins removed)
const uint8_t SAFE_PINS[] = {2, 4, 5, 12, 13, 14, 15, 16, 17, 18, 19, 21, 22, 23, 25, 26, 27, 32, 33};
const uint8_t NUM_SAFE_PINS = sizeof(SAFE_PINS) / sizeof(SAFE_PINS[0]);

// System State
uint8_t  activeLedPin  = 19;
double   currentFreq   = 60.0;     // Hz
float    currentDuty   = 1.5;      // Percent (0.1% to 100%)
bool     strobeEnabled = true;

// Web Server & WebSocket
AsyncWebServer server(80);
AsyncWebSocket ws("/ws");

// Telemetry timer
unsigned long lastTelemetryMs = 0;

// ==========================================
// HARDWARE PWM FUNCTIONS
// ==========================================
bool isPinSafe(uint8_t pin) {
    for (uint8_t i = 0; i < NUM_SAFE_PINS; i++) {
        if (SAFE_PINS[i] == pin) return true;
    }
    return false;
}

void applyStrobeHardwareSettings() {
    if (!isPinSafe(activeLedPin)) activeLedPin = 19; // Fallback to 19

    // Core 3.x LEDC API
    ledcDetach(activeLedPin);
    ledcAttach(activeLedPin, (uint32_t)currentFreq, LEDC_TIMER_RES);

    if (strobeEnabled) {
        uint32_t dutyRaw = (uint32_t)((currentDuty / 100.0f) * LEDC_MAX_DUTY);
        ledcWrite(activeLedPin, dutyRaw); // Use PIN, not channel
    } else {
        ledcWrite(activeLedPin, 0);
    }
}

// ==========================================
// LITTLEFS PROFILE MANAGEMENT
// ==========================================
String listProfilesJSON() {
    DynamicJsonDocument doc(2048);
    JsonArray array = doc.to<JsonArray>();

    File root = LittleFS.open("/profiles");
    if (root && root.isDirectory()) {
        File file = root.openNextFile();
        while (file) {
            String fileName = String(file.name());
            if (fileName.endsWith(".json")) {
                array.add(fileName);
            }
            file = root.openNextFile();
        }
    }

    String output;
    serializeJson(doc, output);
    return output;
}

void saveProfile(const char* filename, const String& jsonContent) {
    if (!LittleFS.exists("/profiles")) {
        LittleFS.mkdir("/profiles");
    }
    String path = "/profiles/";
    path += filename;
    if (!path.endsWith(".json")) path += ".json";

    File f = LittleFS.open(path, "w");
    if (f) {
        f.print(jsonContent);
        f.close();
    }
}

String loadProfile(const char* filename) {
    String path = "/profiles/";
    path += filename;
    if (!path.endsWith(".json")) path += ".json";

    if (!LittleFS.exists(path)) return "{}";

    File f = LittleFS.open(path, "r");
    if (!f) return "{}";

    String content = f.readString();
    f.close();
    return content;
}

void deleteProfile(const char* filename) {
    String path = "/profiles/";
    path += filename;
    if (!path.endsWith(".json")) path += ".json";
    if (LittleFS.exists(path)) {
        LittleFS.remove(path);
    }
}

// ==========================================
// TELEMETRY & SYSTEM METRICS GENERATOR
// ==========================================
void sendSystemTelemetry() {
    if (ws.count() == 0) return;

    DynamicJsonDocument doc(1024);
    doc["type"]        = "telemetry";
    doc["heap_free"]   = ESP.getFreeHeap();
    doc["cpu_mhz"]     = ESP.getCpuFreqMHz();
    doc["uptime_sec"]  = millis() / 1000;
    doc["fs_total"]    = LittleFS.totalBytes();
    doc["fs_used"]     = LittleFS.usedBytes();
    doc["active_pin"]  = activeLedPin;
    doc["freq"]        = currentFreq;
    doc["duty"]        = currentDuty;
    doc["enabled"]     = strobeEnabled;

    String jsonStr;
    serializeJson(doc, jsonStr);
    ws.textAll(jsonStr);
}

// ==========================================
// WEBSOCKET COMMAND DISPATCHER
// ==========================================
void handleWebSocketMessage(void *arg, uint8_t *data, size_t len, AsyncWebSocketClient *client) {
    AwsFrameInfo *info = (AwsFrameInfo*)arg;
    if (info->final && info->index == 0 && info->len == len && info->opcode == WS_TEXT) {
        data[len] = 0;

        DynamicJsonDocument doc(1024);
        DeserializationError error = deserializeJson(doc, (char*)data);
        if (error) return;

        const char* cmd = doc["cmd"] | "";

        if (strcmp(cmd, "set_strobe") == 0) {
            if (doc.containsKey("freq"))    currentFreq = doc["freq"].as<double>();
            if (doc.containsKey("duty"))    currentDuty = doc["duty"].as<float>();
            if (doc.containsKey("enabled")) strobeEnabled = doc["enabled"].as<bool>();
            if (doc.containsKey("pin")) {
                uint8_t newPin = doc["pin"].as<uint8_t>();
                if (isPinSafe(newPin)) activeLedPin = newPin;
            }
            applyStrobeHardwareSettings();
            sendSystemTelemetry();
        }
        else if (strcmp(cmd, "reboot") == 0) {
            client->text("{\"type\":\"alert\",\"message\":\"Rebooting ESP32...\"}");
            delay(500); // Give time for message to send
            ESP.restart();
        }
        else if (strcmp(cmd, "get_system_info") == 0) {
            sendSystemTelemetry();
        }
        else if (strcmp(cmd, "save_profile") == 0) {
            const char* profileName = doc["name"] | "default";
            String profileData = doc["data"].as<String>();
            saveProfile(profileName, profileData);

            // Notify client with updated list
            DynamicJsonDocument resp(1024);
            resp["type"] = "profile_list";
            resp["profiles"] = serialized(listProfilesJSON());
            String respStr;
            serializeJson(resp, respStr);
            client->text(respStr);
        }
        else if (strcmp(cmd, "list_profiles") == 0) {
            DynamicJsonDocument resp(1024);
            resp["type"] = "profile_list";
            resp["profiles"] = serialized(listProfilesJSON());
            String respStr;
            serializeJson(resp, respStr);
            client->text(respStr);
        }
        else if (strcmp(cmd, "load_profile") == 0) {
            const char* profileName = doc["name"] | "";
            String content = loadProfile(profileName);

            DynamicJsonDocument resp(2048);
            resp["type"] = "profile_data";
            resp["name"] = profileName;
            resp["data"] = serialized(content);
            String respStr;
            serializeJson(resp, respStr);
            client->text(respStr);
        }
        else if (strcmp(cmd, "delete_profile") == 0) {
            const char* profileName = doc["name"] | "";
            deleteProfile(profileName);

            DynamicJsonDocument resp(1024);
            resp["type"] = "profile_list";
            resp["profiles"] = serialized(listProfilesJSON());
            String respStr;
            serializeJson(resp, respStr);
            client->text(respStr);
        }
        else if (strcmp(cmd, "format_littlefs") == 0) {
            LittleFS.format();
            LittleFS.mkdir("/profiles");
            sendSystemTelemetry();
        }
    }
}

void onEvent(AsyncWebSocket *server, AsyncWebSocketClient *client, AwsEventType type, void *arg, uint8_t *data, size_t len) {
    switch (type) {
        case WS_EVT_CONNECT:
            sendSystemTelemetry();
            break;
        case WS_EVT_DISCONNECT:
        case WS_EVT_PONG:
        case WS_EVT_ERROR:
            break;
        case WS_EVT_DATA:
            handleWebSocketMessage(arg, data, len, client);
            break;
    }
}

// ==========================================
// MAIN SETUP & LOOP
// ==========================================
void setup() {
    Serial.begin(115200);

    if (!LittleFS.begin(true)) {
        Serial.println("[ERROR] LittleFS Mount Failed");
    }

    WiFi.mode(WIFI_AP_STA);
    WiFi.softAP(AP_SSID, AP_PASS);

    applyStrobeHardwareSettings();

    ws.onEvent(onEvent);
    server.addHandler(&ws);

    server.on("/", HTTP_GET, [](AsyncWebServerRequest *request) {
        AsyncWebServerResponse *response = request->beginResponse_P(200, "text/html", index_html_gz, index_html_gz_len);
        response->addHeader("Content-Encoding", "gzip");
        request->send(response);
    });

    server.onNotFound([](AsyncWebServerRequest *request) {
        AsyncWebServerResponse *response = request->beginResponse_P(200, "text/html", index_html_gz, index_html_gz_len);
        response->addHeader("Content-Encoding", "gzip");
        request->send(response);
    });
    
    server.begin();
}

void loop() {
    ws.cleanupClients();
    if (millis() - lastTelemetryMs >= 500) {
        lastTelemetryMs = millis();
        sendSystemTelemetry();
    }
}