cotestatnt / async-esp-fs-webserver

ESP32/ESP8266 WebServer, WiFi manager and ACE web editor Arduino library. Based on ESPAsyncWebServer
Apache License 2.0
33 stars 10 forks source link

nice to see some recent activity on a an esp page #28

Open ldijkman opened 4 months ago

ldijkman commented 4 months ago

Like the fsbrowser example maybe add a discussions tab to this github page (under settings add discussions tab) i have issues but not direct related to this fsbrowser

i have been playing for years with ace because of esp fsbrower ace editor https://ldijkman.github.io/Ace_Seventh_Heaven/Hell.html

trying to make an timed switch program for ESP , easy to edit / change https://codepen.io/ldijkman/full/LYaOgvW

ESP wifi connect always worked good on raspberry pi arm arduino editor now i use linux mint x86 ide1 ide2 and wiffi will not connect to the linksys i used for years when esp is loaded for arm wifi works ok when esp is loadd from x86 ide1 ide2 wifi is not working for linksys router but it works if i use ziggo router

can connect to this ap 8.8.8.8 strange when i select from your wifi scanner it will not connect

sure when i try this program uploaded from my arduino rasberry pi400 ide1 it will work, it will connect to selected

i would say wifi.h or esptool.py uploader is different as raspberry arm version

ace editor and visual timeslots schedule easy view edit intended for future use on an ESP8266 / ESP32 wifi switch

Screenshot from 2024-02-05 03-29-27

Screenshot from 2024-02-05 03-29-55

ldijkman commented 4 months ago

better give a bit more info in arduino comments that it start as an wifi accespoint where you have to connect to with a wifi broadcasted name "ESP32-API1234" and password "123456789"??? i removed it to blank if connected then browse to 8.8.8.8 give links to edit and setup on page at adres 8.8.8.8

maybe use mdns for a name for 8.8.8.8 (does not work on my old android phone) or add a field for mDNS configurable parameter. so that user can create http://kitchen.local instead of an ip

i use an app "BonjourBrowser" to see scanned mdns .local adresses https://play.google.com/store/apps/details?id=de.wellenvogel.bonjourbrowser&pli=1 that shows a mdns scan of all esp devices

x86 ide1 ide2 strange thing is connect to ziggo works x86 ide1 ide2 connect to Bangert does not x86 ide1 ide2 when i program ESP32 from my raspberry pi400 arm ide1 it works

Screenshot from 2024-02-05 03-51-47

ldijkman commented 4 months ago

scheduler.html served from ESP espasyncFSbrowser webserver with your program ;-)

Screenshot from 2024-02-05 04-16-59

edit scheduler.html in ace editor and save it on esp webserver (copy paste from codepen.io example)

Screenshot from 2024-02-05 04-19-22

ldijkman commented 4 months ago

do not realy understand it all but scheduler on / off switchtimes array websocket seems to get to the ESP and also on serial monitor

const ws = new WebSocket('ws://8.8.8.8/ws');

maybe i should use someting variable from ws:// window.location /ws like

// Create a WebSocket URL using the current location's hostname and protocol
const protocol = window.location.protocol === 'https:' ? 'wss' : 'ws'; // Choose ws or wss based on current protocol
const host = window.location.hostname; // Get the current host (domain or IP)
const wsPath = '/ws'; // The endpoint where the WebSocket server is listening
const wsPort = ':80'; // Specify the WebSocket server port if it's different from the web server's port

const wsUrl = `${protocol}://${host}${wsPort}${wsPath}`;

// Create a new WebSocket connection using the constructed URL
const ws = new WebSocket(wsUrl);

Screenshot from 2024-02-05 17-46-55

ldijkman commented 4 months ago

trying to figure out how it works

my simple server ino with custom websocket listener

// Init with custom WebSocket event handler and start server server.init(onWsEvent);

added when server on index added NTP time


// starts as an wifi accespoint AP
// wifi name broadcasted in the air "ESP32_AP1234"
// no password used
// connect to it 
// if connected browse to http://8.8.8.8/setup
// or browse to http://8.8.8.8/edit
// create a file index or scheduler.html in ace editor FS browsser
// copy the code from https://codepen.io/ldijkman/pen/LYaOgvW
// paste and save in ace editor FSbrowser
// browse to http://8.8.8.8/scheduler.html 
//   or when made index.html 
//       browse to http://8.8.8.8/  or http://8.8.8.8/index.html
// see when times are changed result in serial monitor
// now need to do someting with the times on the ESP

#include <FS.h>
#include <LittleFS.h>
#include <AsyncFsWebServer.h> // https://github.com/cotestatnt/async-esp-fs-webserver
                              // Arduino IDE => Sketch => include library => Manage Libraries -> 
                              // search for "cotestatnt AsyncEspFSWebserver" and install

#include <ArduinoJson.h>
#include "time.h"

// NTP server settings
const char* ntpServer = "time.google.com";
const long  gmtOffset_sec = 0;  // Adjust according to your timezone
const int   daylightOffset_sec = 3600; // Typically 3600 for 1 hour, or 0 if not using DST

// Define the GPIO pin you want to control
//const int controlPin = D1; // Example GPIO pin

AsyncFsWebServer server(80, LittleFS, "myServer");
int testInt = 150;
float testFloat = 123.456;

#ifndef LED_BUILTIN
#define LED_BUILTIN 2
#endif
uint8_t ledPin = LED_BUILTIN;

// FILESYSTEM INIT
bool startFilesystem(){
  if (LittleFS.begin()){
      File root = LittleFS.open("/", "r");
      File file = root.openNextFile();
      while (file){
          Serial.printf("FS File: %s, size: %d\n", file.name(), file.size());
          file = root.openNextFile();
      }
      return true;
  }
  else {
      Serial.println("ERROR on mounting filesystem. It will be formmatted!");
      LittleFS.format();
      ESP.restart();
  }
  return false;
}

/*
* Getting FS info (total and free bytes) is strictly related to
* filesystem library used (LittleFS, FFat, SPIFFS etc etc) and ESP framework
*/
#ifdef ESP32
void getFsInfo(fsInfo_t* fsInfo) {
    fsInfo->totalBytes = LittleFS.totalBytes();
    fsInfo->usedBytes = LittleFS.usedBytes();
    strcpy(fsInfo->fsName, "LittleFS");
}
#endif

//---------------------------------------
void handleLed(AsyncWebServerRequest *request) {
  static int value = false;
  // http://xxx.xxx.xxx.xxx/led?val=1
  if(request->hasParam("val")) {
    value = request->arg("val").toInt();
    digitalWrite(ledPin, value);
  }
  String reply = "LED is now ";
  reply += value ? "ON" : "OFF";
  request->send(200, "text/plain", reply);
}

// Global variables to store the on and off times
unsigned long onTime = 0;
unsigned long offTime = 0;
bool ledState = false;

// In this example a custom websocket event handler is used instead default
void onWsEvent(AsyncWebSocket* server, AsyncWebSocketClient* client, AwsEventType type, void* arg, uint8_t* data, size_t len) {
  switch (type) {
    case WS_EVT_CONNECT:
      client->printf("{\"Websocket connected\": true, \"clients\": %u}", client->id());
      Serial.printf("luberth Websocket client %u connected\n", client->id());
      break;

    case WS_EVT_DISCONNECT:
      Serial.printf("luberth Websocket client %u connected\n", client->id());
      break;

case WS_EVT_DATA:
      {
        AwsFrameInfo* info = (AwsFrameInfo*)arg;
        if (info->opcode == WS_TEXT) {
          data[len] = '\0'; // Null-terminate the data to parse as string
          Serial.printf("luberth Received message \"%s\"\n", data);

          // Parse JSON message
          DynamicJsonDocument doc(1024); // Adjust size according to your expected message size
          DeserializationError error = deserializeJson(doc, data);
          if (error) {
            // Handle the error, e.g., send an error message back to the client
            Serial.println("Failed to parse JSON!");
            return;
          }

          // Assuming the JSON structure is an array of objects like [{"on":60,"off":75}, ...]
          JsonArray array = doc.as<JsonArray>();
          for (JsonObject obj : array) {
            int onTime = obj["on"]; // Get ON time in minutes
            int offTime = obj["off"]; // Get OFF time in minutes

            // Now you would use onTime and offTime to schedule the GPIO pin control
            // This is where you would add your timing logic
            // For simplicity, let's assume we toggle the pin immediately as an example
            //digitalWrite(controlPin, HIGH); // Turn ON the GPIO pin
            //delay(onTime * 60000); // Wait for ON time duration (convert minutes to milliseconds)
            //digitalWrite(controlPin, LOW); // Turn OFF the GPIO pin
            //delay(offTime * 60000); // Wait for OFF time duration (convert minutes to milliseconds)
          }
        }
      }
      break;

    default:
      break;
  }
}  

void setup() {
    //pinMode(controlPin, OUTPUT); // Set the GPIO pin as an output

    pinMode(ledPin, OUTPUT);
    Serial.begin(115200);
    delay(1000);
    if (startFilesystem()) {
        Serial.println("LittleFS filesystem ready!");
        File config = server.getConfigFile("r");
        if (config) {
            DynamicJsonDocument doc(config.size() * 1.33);
            deserializeJson(doc, config);
            testInt = doc["Test int variable"];
            testFloat = doc["Test float variable"];
        }
        Serial.printf("Stored \"testInt\" value: %d\n", testInt);
        Serial.printf("Stored \"testFloat\" value: %3.2f\n", testFloat);
    }
    else
        Serial.println("LittleFS error!");

    IPAddress myIP = server.startWiFi(15000, "ESP32_AP1234", "");
    WiFi.setSleep(WIFI_PS_NONE);
    server.addOptionBox("Custom options");
    server.addOption("Test int variable", testInt);
    server.addOption("Test float variable", testFloat);
    server.setSetupPageTitle("Simple Async ESP FS WebServer");

    // Enable ACE FS file web editor and add FS info callback fucntion
    server.enableFsCodeEditor();
    #ifdef ESP32
    server.setFsInfoCallback(getFsInfo);
    #endif

  // Server index.html at the root path
  server.on("/", HTTP_GET, [](AsyncWebServerRequest *request){
    request->send(LittleFS, "/index.html", "text/html");
  });

    server.on("/led", HTTP_GET, handleLed);

    // Start server
   // Init with custom WebSocket event handler and start server
  server.init(onWsEvent);

    Serial.print(F("Async ESP Web Server started on IP Address: "));
    Serial.println(myIP);
    Serial.println(F(
        "This is \"simpleServer.ino\" example.\n"
        "Open /setup page to configure optional parameters.\n"
        "Open /edit page to view, edit or upload example or your custom webserver source files."
    ));

  // Check if we are in station mode before starting NTP
  if (WiFi.getMode() == WIFI_STA) {
    // Initialize NTP
    configTime(gmtOffset_sec, daylightOffset_sec, ntpServer);
    Serial.println("NTP client started");
  }

}

void loop() {
  static unsigned long lastPrintTime = 0;
  const unsigned long printInterval = 10000; // Print every 10000 milliseconds (10 seconds)

  unsigned long currentTime = millis();
  if (currentTime - lastPrintTime >= printInterval) {
    // Save the last time you printed the time
    lastPrintTime = currentTime;

    // Check WiFi connection and print the time
    if (WiFi.status() == WL_CONNECTED) {
      printLocalTime();
    }
  }

}

void printLocalTime() {
  struct tm timeinfo;
  if (!getLocalTime(&timeinfo)) {
    Serial.println("Failed to obtain time");
    return;
  }
  // Print the local time
  Serial.println(&timeinfo, "%A, %B %d %Y %H:%M:%S");
}

http://8.8.8.8./scheduler.html arduino serial monitor chrome chromium inspect network WS

Screenshot from 2024-02-06 05-47-22

cotestatnt commented 4 months ago

Hi @ldijkman Thank you for your interest in this project. I'm sorry, but I didn't quite understand what your request or issue is :flushed:

ldijkman commented 4 months ago

my ESP32 wifi connection problem to old linksys solved

when ESP32 programmed from raspberry pi arm

when ESP32 programmed from linux mint x86

like the way it gives the link when switching from AccesPoint to Station only user should have inputfield to set an mDNS adres in setup (http://garden.local) and maybe an mDNS scanner for a list of used mDNS . local ardesses

Screenshot from 2024-02-07 03-39-09

ldijkman commented 4 months ago

treid it on ESP8266 looked like connection change from ap to sta did not go well on ESP8266 did not get an link popup / but error that it did not connect and later it says it is connected allready not nice if there was user defined mdns input field, i would now the adres "http://toilet.local" now i have to look ip up in router

Screenshot from 2024-02-08 18-28-09

ldijkman commented 4 months ago

install SimpleWebServer from WebBrowser on ESP32

4Mb ESP32 Easy Install

https://ldijkman.github.io/async-esp-fs-webserver/

after succesfull installation connect to wifi accespoint "ESP32_AP1234" then browse to http://8.8.8.8/setup configure your wifi ip adres /edit for Ace editor

Screenshot from 2024-02-09 17-37-47

Screenshot from 2024-02-09 17-38-59

Screenshot from 2024-02-09 17-39-27

ldijkman commented 4 months ago

Flash 4Mb ESP32 InBrowser, The Art of Time Controlled

video https://youtu.be/eUbzEOBtTrU

Screenshot from 2024-02-10 07-12-01

video https://youtu.be/eUbzEOBtTrU

ldijkman commented 4 months ago

ok maybe it is not so hard to add mDNS adres and relais gpio pin

possible to change mdns adres now garage makes http://garage.local

https://github.com/ldijkman/async-esp-fs-webserver/tree/master/docs

Screenshot from 2024-02-11 11-16-47

ldijkman commented 4 months ago

https://youtu.be/jqXlJuNNpxE

ldijkman commented 4 months ago

added esp8266 4mb 12E / 12F flash from browser but connection switch form ap to station is not flawless https://ldijkman.github.io/async-esp-fs-webserver/

ldijkman commented 4 months ago

ace editor browser bookmarklet toggle show hide tree menu cq full screen editor

https://github.com/ldijkman/async-esp-fs-webserver/discussions/3

browser add bookmark Name: Toggle for URL:
next code

javascript:(function() {
    var editor = document.getElementById('editor');
    if (editor.style.left === '20%') {
        editor.style.left = '0%';
    } else {
        editor.style.left = '20%';
    }
})();

Ace editor options , change the looks ctrl+, = ctrl+comma

Screenshot from 2024-02-17 04-20-40

Screenshot from 2024-02-17 04-20-56


Ace editor options , change the looks ctrl+, = ctrl+comma

Screenshot from 2024-02-17 04-27-23