### Start AutoConnect Update Server Example Source: https://hieromon.github.io/AutoConnect/otaserver.html Example command to start the `updateserver.py` script, specifying the port, bind IP address, catalog directory, and log level. Assumes binary files are in the 'bin' directory. ```bash python updateserver.py --port 8080 --bind 172.16.1.10 --catalog bin --log debug ``` -------------------------------- ### begin Source: https://hieromon.github.io/AutoConnect/api.html Starts the WiFi connection process and initializes the web server. ```APIDOC ## begin ### Description Starts establishing the WiFi connection. If connection fails, it switches to SoftAP mode and starts the captive portal. ### Parameters - **ssid** (const char*) - Optional - SSID to connect to. - **passphrase** (const char*) - Optional - Password for the connection. - **timeout** (unsigned long) - Optional - Timeout in milliseconds. ### Return Value - **bool** - true if connected, false if captive portal started. ``` -------------------------------- ### Full AutoConnect Sketch Example Source: https://hieromon.github.io/AutoConnect/achandling.html A complete Arduino sketch demonstrating AutoConnect setup, custom page definitions, and handler functions for an addition form. ```cpp #include #include #include #include const char PAGE_ADD[] PROGMEM = R"( { "uri": "/add", "title": "Adder", "menu": true, "element": [ { "name": "valueA", "type": "ACInput", "label": "Value A", "apply": "number" }, { "name": "valueB", "type": "ACInput", "label": "Value B", "apply": "number" }, { "name": "add", "type": "ACSubmit", "value": "ADD", "uri": "/results" } ] } )"; const char PAGE_RESULTS[] PROGMEM = R"( { "uri": "/results", "title": "Adder", "menu": false, "element": [ { "name": "results", "type": "ACText" } ] } )"; AutoConnect portal; AutoConnectAux page_add; AutoConnectAux page_results; String onAdd(AutoConnectAux& aux, PageArgument& args) { aux["valueA"].as().value = "0"; aux["valueB"].as().value = "0"; return String(); } String onResults(AutoConnectAux& aux, PageArgument& args) { int valueA = args.arg("valueA").toInt(); int valueB = args.arg("valueB").toInt(); aux["results"].as().value = String(valueA) + " + " + String(valueB) + " = " + String(valueA + valueB); return String(); } void setup() { delay(1000); page_add.load(PAGE_ADD); page_results.load(PAGE_RESULTS); portal.join({ page_add, page_results }); portal.on("/add", onAdd); portal.on("/results", onResults); portal.begin(); } void loop() { portal.handleClient(); } ``` -------------------------------- ### Register Handler and Start Camera Server Source: https://hieromon.github.io/AutoConnect/esp32cam.html Register the custom page handler for the root path and start the camera streaming server. Check for `ESP_OK` to confirm the server started successfully. ```cpp portal.on("/", viewer); if (webcam.startCameraServer() == ESP_OK) { Serial.printf("ESP32WebCam server ready: %s\n", WiFi.localIP().toString().c_str()); } else { Serial.println("ESP32WebCam server start failed"); } ``` -------------------------------- ### Start Camera Server with Default Settings Source: https://hieromon.github.io/AutoConnect/esp32cam.html Begins the HTTP server task with default configurations. ```c esp_err_t startCameraServer(void) ``` -------------------------------- ### Initialize Sensor and Create Instance Source: https://hieromon.github.io/AutoConnect/esp32cam.html Example demonstrating how to initialize the sensor and create an ESP32Cam instance. ```c++ ESP32WebCam webcam(); webcam.sensorInit(); ``` -------------------------------- ### AutoConnectUploadFS Example Implementation Source: https://hieromon.github.io/AutoConnect/acupload.html An example implementation of `AutoConnectUploadHandler` that uses SPIFFS for file storage. ```APIDOC ## Class: AutoConnectUploadFS ### Description An implementation of `AutoConnectUploadHandler` that utilizes SPIFFS (or a similar filesystem) to store uploaded files. ### Inheritance Inherits from `AutoConnectUploadHandler`. ### Constructor - `explicit AutoConnectUploadFS(SPIFFST& media)`: Constructor that takes a reference to the SPIFFS media object. ### Destructor - `~AutoConnectUploadFS()`: Ensures the file is closed upon object destruction. ### Protected Member Functions (Overrides) #### `_open(const char* filename, const char* mode)` - Opens the file using the provided `SPIFFST` object. - Returns `true` if the file is opened successfully, `false` otherwise. #### `_write(const uint8_t* buf, const size_t size)` - Writes data from the buffer to the opened file. - Returns the number of bytes written, or -1 if the file is not open. #### `_close(void)` - Closes the file and ends the SPIFFS media connection. ### Private Members - `SPIFFST* _media`: Pointer to the SPIFFS media object. - `SPIFileT _file`: Represents the opened file handle. ``` -------------------------------- ### Start Camera Server with Port Source: https://hieromon.github.io/AutoConnect/esp32cam.html Begins the HTTP server task. Specifies the server port. ```c esp_err_t startCameraServer(const uint16_t port) ``` -------------------------------- ### Configure and Start AutoConnect Source: https://hieromon.github.io/AutoConnect/apiconfig.html This snippet configures AutoConnect with various settings such as SoftAP name, IP addresses, gateway, auto-reconnect, credential saving, EEPROM reservation, portal timeout, and home URI. It then starts the captive portal. ```cpp AutoConnect Portal; AutoConnectConfig Config("", "passpass"); // SoftAp name is determined at runtime Config.apid = ESP.hostname(); // Retrieve host name to SotAp identification Config.apip = IPAddress(192,168,10,101); // Sets SoftAP IP address Config.gateway = IPAddress(192,168,10,1); // Sets WLAN router IP address Config.netmask = IPAddress(255,255,255,0); // Sets WLAN scope Config.autoReconnect = true; // Enable auto-reconnect Config.autoSave = AC_SAVECREDENTIAL_NEVER; // No save credential Config.boundaryOffset = 64; // Reserve 64 bytes for the user data in EEPROM. Config.portalTimeout = 60000; // Sets timeout value for the captive portal Config.retainPortal = true; // Retains the portal function after timed-out Config.homeUri = "/index.html"; // Sets home path of Sketch application Config.title ="My menu"; // Customize the menu title Config.staip = IPAddress(192,168,10,10); // Sets static IP Config.staGateway = IPAddress(192,168,10,1); // Sets WiFi router address Config.staNetmask = IPAddress(255,255,255,0); // Sets WLAN scope Config.dns1 = IPAddress(192,168,10,1); // Sets primary DNS address Portal.config(Config); // Configure AutoConnect Portal.begin(); // Starts and behaves captive portal ``` -------------------------------- ### Start AutoConnect Portal and Load View Page Source: https://hieromon.github.io/AutoConnect/esp32cam.html Start the AutoConnect portal and load the main view page. `CAMERA_VIEWER` is a predefined page for camera display. ```cpp portal.begin(); portal.load(CAMERA_VIEWER); ``` -------------------------------- ### Initialize AutoConnectFile Source: https://hieromon.github.io/AutoConnect/acelements.html Example usage of the AutoConnectFile constructor for file upload configuration. ```cpp AutoConnectFile file("file", "", "Upload:", AC_File_FS) ``` ```cpp AutoConnectFile(const char* name, const char* value, const char* label, const ACFile_t store, const ACPosterior_t post) ``` -------------------------------- ### Example implementation of AutoConnectUploadFS Source: https://hieromon.github.io/AutoConnect/acupload.html A concrete implementation of AutoConnectUploadHandler that uses SPIFFS for file storage. ```cpp class AutoConnectUploadFS : public AutoConnectUploadHandler { public: explicit AutoConnectUploadFS(SPIFFST& media) : _media(&media) {} ~AutoConnectUploadFS() { _close(); } protected: bool _open(const char* filename, const char* mode) override { if (_media->begin()) { _file = _media->open(filename, mode); return _file != false; } return false; } size_t _write(const uint8_t* buf, const size_t size) override { if (_file) return _file.write(buf, size); else return -1; } void _close(void) override { if (_file) _file.close(); _media->end(); } private: SPIFFST* _media; SPIFileT _file; }; ``` -------------------------------- ### Register connection callback Source: https://hieromon.github.io/AutoConnect/adconnection.html Example of registering a standard function to handle WiFi connection events. ```cpp AutoConnect Portal; void onConnect(IPAddress& ipaddr) { Serial.print("WiFi connected with "); Serial.print(WiFi.SSID()); Serial.print(", IP:"); Serial.println(ipaddr.toString()); } void setup() { Serial.begin(115200); Portal.onConnect(onConnect); // Register the ConnectExit function Portal.begin(); } void loop() { Portal.handleClient(); } ``` -------------------------------- ### Example: Setting Initial Values and Appending HTML Source: https://hieromon.github.io/AutoConnect/achandling.html This example demonstrates registering two handlers for an AutoConnectAux page: one to set initial input values before HTML generation (`AC_AHEAD`) and another to append custom HTML after generation (`AC_LATER`). ```cpp // AutoConnect object declarations ACInput(input1); AutoConnectAux aux("/aux", { input1 }); AutoConnect portal; // Pre-declare handlers String initialize(AutoConnectAux&, PageArgument&); String append(AutoConnectAux&, PageArgument&); // Register handlers and launch the portal. aux.on(initialize, AC_AHEAD); aux.on(append, AC_LATER); portal.join(aux); portal.begin(); // Some code here... // The handler called before HTML generating String initialize(AutoConnectAux& aux, PageArgument& args) { AutoConnectInput& input1 = aux.getElement("input1"); // Set initial value for the input box in a custom Web page. input1.value = "Initial value"; // Nothing appendix for a generated HTML. return String(); } // The handler called after HTML generated String append(AutoConnectAux& aux, PageArgument& args) { // Append an HTML return String("

This text has been added.

"); } ``` -------------------------------- ### Start Camera Server with Stream Path and Port Source: https://hieromon.github.io/AutoConnect/esp32cam.html Begins the HTTP server task. Specifies the stream endpoint path and the server port. ```c esp_err_t startCameraServer(const char* streamPath, const uint16_t port) ``` -------------------------------- ### Start Camera Server with Stream, Capture, and Prompt Paths Source: https://hieromon.github.io/AutoConnect/esp32cam.html Begins the HTTP server task. Specifies paths for stream, capture, and prompt endpoints. ```c esp_err_t startCameraServer(const char* streamPath, const char* capturePath, const char* promptPath) ``` -------------------------------- ### Initialize AutoConnectInput Source: https://hieromon.github.io/AutoConnect/acelements.html Example usage of the AutoConnectInput constructor for text input configuration. ```cpp AutoConnectInput input("input", "", "Server", "MQTT broker server"); ``` ```cpp AutoConnectInput(const char* name, const char* value, const char* label, const char* pattern, const char* placeholder, const ACPosterior_t post, const ACInput_t apply) ``` -------------------------------- ### Start WiFi Connection with Credentials Source: https://hieromon.github.io/AutoConnect/api.html Initiates the WiFi connection process using the provided SSID and passphrase. The captive portal activates if the initial connection fails. ```cpp bool begin(const char* ssid, const char* passphrase) ``` -------------------------------- ### AutoConnectRadio Constructor Sample Source: https://hieromon.github.io/AutoConnect/acelements.html Example of initializing an AutoConnectRadio element with a name, values, label, arrangement, and checked state. ```cpp AutoConnectRadio radio("radio", { "30 sec.", "60 sec.", "180 sec." }, "Update period", AC_Vertical, 1); ``` -------------------------------- ### Start Camera Server with Stream Path Source: https://hieromon.github.io/AutoConnect/esp32cam.html Begins the HTTP server task to make the endpoint interface available. Specifies the path for the stream endpoint. ```c esp_err_t startCameraServer(const char* streamPath) ``` -------------------------------- ### Access ESP8266WebServer Instance Source: https://hieromon.github.io/AutoConnect/adothers.html Instantiate AutoConnect without parameters to create an ESP8266WebServer. Use Portal.host() after Portal.begin() to get a reference to the server instance. ```cpp AutoConnect Portal; Portal.begin(); ESP8266WebServer& server = Portal.host(); server.send(200, "text/plain", "Hello, world"); ``` -------------------------------- ### AutoConnectText Sample Usage Source: https://hieromon.github.io/AutoConnect/acelements.html Example of instantiating an AutoConnectText object with name, value, and style parameters. ```cpp AutoConnectText text("text", "Publishing the WiFi signal strength to MQTT channel. RSSI value of ESP8266 to the channel created on ThingSpeak", "font-family:serif;color:#4682b4;"); ``` -------------------------------- ### Register OTA Start Handler Source: https://hieromon.github.io/AutoConnect/api.html Registers a routine called once when an OTA update begins. ```cpp void onOTAStart(OTAStartExit_ft fn) ``` ```cpp typedef std::function OTAStartExit_ft ``` -------------------------------- ### Register connection callback with lambda Source: https://hieromon.github.io/AutoConnect/adconnection.html Example of using a lambda expression to handle connection events and optionally shut down SoftAP. ```cpp AutoConnect Portal; void setup() { Serial.begin(115200); Portal.onConnect([](IPAddress& ipaddr){ Serial.printf("WiiFi connected with %s, IP:%s\n", WiFi.SSID().c_str(), ipaddr.toString().c_str()); if (WiFi.getMode() & WIFI_AP) { WiFi.softAPdisconnect(true); WiFi.enableAP(false); Serial.printf("SoftAP:%s shut down\n", WiFi.softAPSSID().c_str()); } }); Portal.begin(); } void loop() { Portal.handleClient(); } ``` -------------------------------- ### Example Usage of AutoConnectAux::on Source: https://hieromon.github.io/AutoConnect/achandling.html Demonstrates how to register and implement handler functions for initializing page elements and appending custom HTML content. ```APIDOC ## Example: Custom Web Page Handlers ### Description This example shows how to use `AutoConnectAux::on` to register two handlers: one to set initial values for input elements before the page is rendered (`initialize`) and another to append custom HTML after the page is rendered (`append`). ### Method `void on(const AuxHandlerFunctionT handler, const AutoConnectExitOrder_t order)` ### Endpoint This example assumes an `AutoConnectAux` object named `aux` has been created and joined with the `AutoConnect` portal. ### Parameters None directly for the `on` function call in this example, but the handlers themselves take parameters. ### Request Example ```cpp // AutoConnect object declarations ACInput(input1); AutoConnectAux aux("/aux", { input1 }); AutoConnect portal; // Pre-declare handlers String initialize(AutoConnectAux&, PageArgument&); String append(AutoConnectAux&, PageArgument&); // Register handlers and launch the portal. aUX.on(initialize, AC_EXIT_AHEAD); aux.on(append, AC_EXIT_LATER); portal.join(aux); portal.begin(); // Some code here... // The handler called before HTML generating String initialize(AutoConnectAux& aux, PageArgument& args) { AutoConnectInput& input1 = aux.getElement("input1"); // Set initial value for the input box in a custom Web page. input1.value = "Initial value"; // Nothing appendix for a generated HTML. return String(); } // The handler called after HTML generated String append(AutoConnectAux& aux, PageArgument& args) { // Append an HTML return String("

This text has been added.

"); } ``` ### Response None. This example focuses on handler registration and implementation. ``` -------------------------------- ### Register OTA Start Callback Source: https://hieromon.github.io/AutoConnect/api.html Register a callback function that is executed once when the Over-The-Air (OTA) update process begins. ```APIDOC ## void onOTAStart(OTAStartExit_ft fn) ### Description Register the on-start exit routine that is called only once when the OTA has been started. ### Method void ### Endpoint N/A (Callback registration) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response None ### Callback Signature ```c++ typedef std::function OTAStartExit_ft ``` ### Callback Parameters None ``` -------------------------------- ### GET /prompt Source: https://hieromon.github.io/AutoConnect/esp32cam.html The prompt endpoint allows users to trigger image captures, manage timer-based recording, and save or load sensor settings to NVS. ```APIDOC ## GET /prompt ### Description Triggers specific camera actions such as one-shot capture, timer-based capture, or NVS configuration management. ### Method GET ### Endpoint http://{HOST}:{PORT}{PATH} ### Parameters #### Query Parameters - **mf** (string) - Required - The function to execute: oneshot, timershot, distimer, entimer, load, save. - **fs** (string) - Optional - File system type: sd or mmc. - **filename** (string) - Optional - The target filename for saved images. - **period** (integer) - Optional - Interval in seconds for timer-shot mode. ### Response #### Success Response (202) - Request accepted. #### Error Response (400) - Syntax error or fatal error occurred. ``` -------------------------------- ### AutoConnectSubmit Sample Usage Source: https://hieromon.github.io/AutoConnect/acelements.html Example of creating an AutoConnectSubmit button with the label 'Save' that submits to the '/mqtt_save' URI. ```cpp AutoConnectSubmit submit("submit", "Save", "/mqtt_save"); ``` -------------------------------- ### PlatformIO Compilation Error Logs Source: https://hieromon.github.io/AutoConnect/faq.html Example error logs indicating missing SPIFFS.h or LittleFS.h header files during the build process. ```text In file included from C:\Users\\Documents\Arduino\libraries\AutoConnect\src\AutoConnect.h:30:0, from src/main.cpp:28: C:\Users\\Documents\Arduino\libraries\PageBuilder\src\PageBuilder.h:88:27: fatal error: SPIFFS.h: No such file or directory ``` ```text In file included from C:\Users\\Documents\Arduino\libraries\AutoConnect\src\AutoConnect.h:30, from src/main.cpp:28: C:\Users\\Documents\Arduino\libraries\PageBuilder\src\PageBuilder.h:93:17: fatal error: LittleFS.h: No such file or directory ``` -------------------------------- ### AutoConnectRange Constructor Sample Source: https://hieromon.github.io/AutoConnect/acelements.html Example of initializing an AutoConnectRange element with a name, default value, label, min/max range, step, position, and posterior tag. ```cpp AutoConnectRange range("bri", 0, "Brightness", -2, 2, 1, AC_Infront); ``` -------------------------------- ### Configure Partial Authentication Scope Source: https://hieromon.github.io/AutoConnect/adauthentication.html Example setup for using AC_AUTHSCOPE_PARTIAL with specific credentials. ```cpp AutoConnect portal(server); AutoConnectConfig config; void setup() { // It's a default value but has no meaning in the AC_AUTHSCOPE_PARTIAL setting. // config.auth = AC_AUTH_NONE; config.authScope = AC_AUTHSCOPE_PARTIAL; config.username = "user"; config.password = "password"; portal.config(config); portal.load(FPSTR(PAGE_HELLO)); portal.load(FPSTR(PAGE_AUTH)); portal.begin(); } void loop() { portal.handleClient(); } ``` -------------------------------- ### Capture Endpoint Request Source: https://hieromon.github.io/AutoConnect/esp32cam.html This is an example of an HTTP GET request to the capture endpoint. The endpoint responds with a captured image in image/jpeg format. ```http GET http://{HOST}:{PORT}{PATH} ``` -------------------------------- ### Embed AutoConnectOTA in Sketch Source: https://hieromon.github.io/AutoConnect/otabrowser.html This example demonstrates the basic steps to embed the AutoConnectOTA class into your sketch for Over-The-Air updates. Ensure all required libraries are included and follow the setup and loop function procedures. ```cpp #include #include #include ESP8266WebServer server; AutoConnect portal(server); AutoConnectConfig config; AutoConnectAux hello; static const char HELLO_PAGE[] PROGMEM = R"( {\"title\": \"Hello world\", \"uri\": \"/\", \"menu\": true, \"element\": [ { \"name\": \"caption\", \"type\": \"ACText\", \"value\": \"

Hello, world

\", \"style\": \"text-align:center;color:#2f4f4f;padding:10px;\" }, { \"name\": \"content\", \"type\": \"ACText\", \"value\": \"In this page, place the custom web page handled by the Sketch application.\" } ] } )"; void setup() { config.ota = AC_OTA_BUILTIN; portal.config(config); hello.load(HELLO_PAGE); portal.join({ hello }); portal.begin(); } void loop() { portal.handleClient(); } ``` -------------------------------- ### Format Image Stream URL Source: https://hieromon.github.io/AutoConnect/esp32cam.html Example of using `printf` with a format string to construct the image stream URL. This is an alternative to dynamic string concatenation. ```c printf("", "localhost:3000/_stream"); ``` -------------------------------- ### Start Camera Server with Stream, Capture, Prompt Paths, and Port Source: https://hieromon.github.io/AutoConnect/esp32cam.html Begins the HTTP server task. Specifies paths for stream, capture, and prompt endpoints, along with the server port. ```c esp_err_t startCameraServer(const char* streamPath, const char* capturePath, const char* promptPath, const uint16_t port) ``` -------------------------------- ### Minimal AutoConnectCore Implementation Source: https://hieromon.github.io/AutoConnect/basicusage.html A basic example demonstrating the initialization of an AutoConnect instance using the core header. Note that custom web page and OTA features are unavailable when using this header. ```cpp #include #include #include WebServer Server; AutoConnect Portal(Server); void rootPage() { char content[] = "Hello, World"; Server.send(200, "text/plain", content); } void setup() { delay(1000); Serial.begin(115200); Serial.println(); Server.on("/", rootPage); Portal.begin(); Serial.println("Web Server started:" + WiFi.localIP().toString()); } void loop() { Portal.handleClient(); } ``` -------------------------------- ### Accessing POST Arguments with JSON and PageArgument Source: https://hieromon.github.io/AutoConnect/achandling.html This example uses a JSON string to define web pages and accesses arguments via PageArgument within a custom handler. It achieves similar functionality to the previous example. ```cpp const static char auxPage[] PROGMEM = R"raw( [ { "title":"Hello", "uri":"/hello", "menu":true, "element":[ { "name":"input1", "type": "ACInput", "label": "INPUT" }, { "name":"send", "type":"ACSubmit", "value":"HELLO", "uri":"/echo" }] }, { "title":"Echo", "uri":"/echo", "menu":false, "element":[ { "name":"echo", "type":"ACText" }] } ])raw"; AutoConnect portal; portal.load(auxPage); portal.on("/echo", [](AutoConnectAux& aux, PageArgument& args) { AutoConnectText& ac_echo = aux.getElement("echo"); ac_echo.value = args.arg("input1"); return String(); }); portal.begin(); ``` -------------------------------- ### Loading Custom Web Pages from String, PROGMEM, and Stream Source: https://hieromon.github.io/AutoConnect/acjson.html Demonstrates loading custom web page JSON documents into AutoConnect from a String, PROGMEM, and a Stream (file). Ensure JSON syntax is valid for ArduinoJson parsing. ```cpp AutoConnect portal; // Loading from String const String aux = String("{\"title\":\"Page 1 title\",\"uri\":\"/page1\",\"menu\":true,\"element\":[{\"name\":\"caption\",\"type\":\"ACText\",\"value\":\"hello, world\"}]"); portal.load(aux); // Loading from PROGMEM const char aux[] PROGMEM = R"raw( { "title" : "Page 1 title", "uri" : "/page1", "menu" : true, "element" : [ { "name" : "caption", "type" : "ACText", "value" : "hello, world" } ] } )raw"; portal.load(FPSTR(aux)); // Loading from Stream assumes "aux.json" file should be store in SPIFFS. File aux = SPIFFS.open("aux.json", "r"); portal.load(aux); aux.close(); ``` -------------------------------- ### GET /capture Source: https://hieromon.github.io/AutoConnect/esp32cam.html Captures an image from the sensor and serves it via HTTP. ```APIDOC ## GET /capture ### Description Captures an image from the sensor and serves it via HTTP. ### Method GET ### Endpoint /capture (Default path, configurable via getCapturePath) ``` -------------------------------- ### Initialize Camera Sensor Source: https://hieromon.github.io/AutoConnect/esp32cam.html Initialize the camera sensor using `ESP32WebCam::sensorInit`. Check for `ESP_OK` to confirm successful initialization. ```cpp ESP32WebCam webcam(ESP32Cam::CAMERA_MODEL_AI_THINKER); if (webcam.sensorInit() != ESP_OK) { Serial.println("Camera initialize failed"); } ``` -------------------------------- ### Start WiFi Connection Source: https://hieromon.github.io/AutoConnect/api.html Initiates the WiFi connection process. If SSID and passphrase are not provided, WiFi.begin() is called without credentials. The captive portal activates if the initial connection fails. ```cpp bool begin() ``` -------------------------------- ### GET /stream Source: https://hieromon.github.io/AutoConnect/esp32cam.html The stream endpoint provides a live MJPEG feed from the ESP32-CAM. ```APIDOC ## GET /stream ### Description Returns a live stream of captured images in image/jpeg format using multipart/x-mixed-replace. ### Method GET ### Endpoint http://{HOST}:{PORT}{PATH} ### Response #### Success Response (200) - Content body contains captured image data with multipart boundary. ``` -------------------------------- ### Handle Web Server Client Source: https://hieromon.github.io/AutoConnect/api.html Demonstrates how to obtain a reference to the AutoConnect-managed web server and handle incoming client requests. This can be done by directly calling the method or by assigning the reference to a variable first. ```cpp ESP8266WebServer& server = portal.host(); server.handleClient(); ``` ```cpp portal.host().handleClient(); ``` -------------------------------- ### GET /_capture Source: https://hieromon.github.io/AutoConnect/esp32cam.html The capture endpoint responds with a captured image in image/jpeg format. ```APIDOC ## GET /_capture ### Description Responds with a captured image from the sensor. ### Method GET ### Endpoint http://{HOST}:{PORT}/_capture ### Parameters #### Path Parameters - **HOST** (string) - Required - Host address of ESP32-CAM. - **PORT** (uint16_t) - Optional - Port number of HTTP server (Default: 3000). ### Response #### Success Response (200) - **Body** (image/jpeg) - Captured image data. ``` -------------------------------- ### Get current AutoConnectRadio value Source: https://hieromon.github.io/AutoConnect/apielements.html Returns the currently selected option string. ```cpp const String& value(void) const ``` -------------------------------- ### Start WiFi Connection with Credentials and Timeout Source: https://hieromon.github.io/AutoConnect/api.html Initiates the WiFi connection process with credentials and a specified timeout. The captive portal activates if the connection cannot be established within the timeout period. ```cpp bool begin(const char* ssid, const char* passphrase, unsigned long timeout) ``` -------------------------------- ### ESP32WebCam Server Control Source: https://hieromon.github.io/AutoConnect/esp32cam.html Functions to start and stop the internal HTTP server task. ```APIDOC ## startCameraServer ### Description Begins the HTTP server task and starts the endpoint service. ### Parameters - **streamPath** (const char*) - Optional - Path of the stream endpoint. - **capturePath** (const char*) - Optional - Path of the capture endpoint. - **promptPath** (const char*) - Optional - Path of the prompt endpoint. - **port** (uint16_t) - Optional - Port number (Default: 3000). ### Response - **ESP_OK** - Server started successfully. - **ESP_ERR_HTTPD_HANDLERS_FULL** - URI handlers full. - **ESP_ERR_HTTPD_ALLOC_MEM** - Memory allocation failed. - **ESP_ERR_HTTPD_TASK** - Failed to launch task. - **ESP_FAIL** - Other error. ## stopCameraServer ### Description Stops the HTTP server task and frees resources. ``` -------------------------------- ### AutoConnectSelect Sample Usage Source: https://hieromon.github.io/AutoConnect/acelements.html Example of initializing an AutoConnectSelect element with timezone options and a label. ```cpp AutoConnectSelect select("select", { String("Europe/London"), String("Europe/Berlin"), String("Europe/Helsinki"), String("Europe/Moscow"), String("Asia/Dubai") }, "Select TZ name"); ``` -------------------------------- ### Get Number of Credential Entries Source: https://hieromon.github.io/AutoConnect/credit.html Returns the total count of stored credential entries. ```cpp uint8_t entries(void) ``` -------------------------------- ### Register onStart callback Source: https://hieromon.github.io/AutoConnect/apiupdate.html Registers a routine to be called once when the update process begins. ```cpp void AutoConnectUpdate::onStart(HTTPUpdateStartCB fn) ``` ```cpp using HTTPUpdateStartCB = std::function; ``` -------------------------------- ### Include AutoConnect Full Component Source: https://hieromon.github.io/AutoConnect/basicusage.html This example demonstrates how to include the full AutoConnect component for use with WebServer. Ensure this is used when custom web pages or OTA updates are needed. ```cpp #include #include #include static const char PAGE_HELLO[] = R"( { "uri": "/", "title": "Hello", "menu": false, "element": [ { "name": "caption", "type": "ACText", "value": "Hello, World" }, ] } )"; WebServer Server; AutoConnect Portal(Server); AutoConnectConfig Config; void setup() { delay(1000); Serial.begin(115200); Serial.println(); Config.ota = AC_OTA_BUILTIN; Portal.config(Config); portal.load(PAGE_HELLO); Portal.begin(); Serial.println("Web Server started:" + WiFi.localIP().toString()); } void loop() { Portal.handleClient(); } ``` -------------------------------- ### Check if Server is Started Source: https://hieromon.github.io/AutoConnect/esp32cam.html Returns a boolean indicating if the HTTP server task is currently running. ```c++ bool isServerStarted(void) ``` -------------------------------- ### Initialize AutoConnectButton Source: https://hieromon.github.io/AutoConnect/acelements.html Sample initialization for an AutoConnectButton. ```cpp AutoConnectButton button("button", "OK", "myFunction()"); ``` -------------------------------- ### Disable Captive Portal Source: https://hieromon.github.io/AutoConnect/adcpcontrol.html Prevents the captive portal from starting by setting autoRise to false in the configuration. ```cpp AutoConnect portal; AutoConnectConfig acConfig; acConfig.autoRise = false; portal.config(acConfig); portal.begin(); ``` -------------------------------- ### Instantiate ESP32WebCam Source: https://hieromon.github.io/AutoConnect/esp32cam.html Instantiates the ESP32WebCam class, which also initializes ESP32Cam. The camera is not initialized and the HTTP server is not started at this point; these require separate function calls. Specify the camera model if it's not the default. ```cpp ESP32WebCam(const uint16_t port = ESP32CAM_DEFAULT_HTTPPORT) ``` ```cpp ESP32WebCam(const ESP32Cam::CameraId model, const uint16_t port = ESP32CAM_DEFAULT_HTTPPORT) ``` -------------------------------- ### Initialize AutoConnectCheckbox Source: https://hieromon.github.io/AutoConnect/acelements.html Sample initialization for an AutoConnectCheckbox. ```cpp AutoConnectCheckbox checkbox("checkbox", "uniqueapid", "Use APID unique", false); ``` -------------------------------- ### Get Stream Path Source: https://hieromon.github.io/AutoConnect/esp32cam.html Retrieves the path for streaming URLs. The default path is defined by ESP32CAM_DEFAULT_PATH_STREAM. ```c++ const char* getStreamPath(void) ``` -------------------------------- ### Common Sketch for SPIFFS and LittleFS Source: https://hieromon.github.io/AutoConnect/filesystem.html This code demonstrates how to write a sketch that is compatible with both SPIFFS and LittleFS file systems. It uses preprocessor directives to select the appropriate file system based on the AUTOCONNECT_USE_LITTLEFS macro. Ensure the correct file system header is included and the FlashFS instance is assigned. ```cpp #include #ifdef AUTOCONNECT_USE_LITTLEFS #include #if defined(ARDUINO_ARCH_ESP8266) FS& FlashFS = LittleFS; #elif defined(ARDUINO_ARCH_ESP32) fs::LittleFSFS& FlashFS = LittleFS; #endif #else #include #include fs::SPIFFSFS& FlashFS = SPIFFS; #endif void setup() { ... FlashFS.begin(); ... } ``` -------------------------------- ### Get AutoConnectRadio option count Source: https://hieromon.github.io/AutoConnect/apielements.html Returns the total number of options contained in the radio element. ```cpp size_t size(void) ``` -------------------------------- ### Get request source URI Source: https://hieromon.github.io/AutoConnect/api.html Returns the URI of the AutoConnectAux page that triggered the current request. ```cpp String where(void) ``` -------------------------------- ### Get Referer Reference Source: https://hieromon.github.io/AutoConnect/apiaux.html Returns a reference to the AutoConnectAux instance that triggered the current page transition. ```cpp AutoConnectAux& referer(void) ``` -------------------------------- ### Configure Filesystem via PlatformIO build_flags Source: https://hieromon.github.io/AutoConnect/filesystem.html Use build_flags in platformio.ini to define the filesystem without modifying library source files. ```ini [env:esp_wroom_02] platform = espressif8266 board = esp_wroom_02 framework = arduino lib_extra_dirs = ~/Documents/Arduino/libraries lib_ldf_mode = deep+ build_flags = -DAC_USE_SPIFFS -DPB_USE_SPIFFS upload_speed = 921600 monitor_speed = 115200 ``` -------------------------------- ### Batch Clear All Credentials Source: https://hieromon.github.io/AutoConnect/credit.html Example implementation to clear all saved credentials by iterating through entries and deleting them individually. ```cpp void deleteAllCredentials(void) { AutoConnectCredential credential; station_config_t config; uint8_t ent = credential.entries(); while (ent--) { credential.load(0, &config); credential.del((const char*)&config.ssid[0]); } } ``` -------------------------------- ### Define an AutoConnectRadio event handler Source: https://hieromon.github.io/AutoConnect/acinteract.html Example of a function signature for handling change events on an AutoConnectRadio element. ```cpp void onChangeRadio(AutoConnectRadio& me, AutoConnectAux& aux) ``` -------------------------------- ### File System Configuration (ESP8266/ESP32) Source: https://hieromon.github.io/AutoConnect/acjson.html Information on configuring file systems (SPIFFS/LittleFS) for file storage with AutoConnect. ```APIDOC ## File System Configuration (ESP8266/ESP32) ### Description AutoConnect supports SPIFFS and LittleFS for storing uploaded files on ESP8266/ESP32 modules. The choice between them is determined by the `AC_USE_SPIFFS` macro in `AutoConnectDefs.h`. ### File Systems: - **SPIFFS**: Supported by older ESP8266 Arduino core versions. - **LittleFS**: Supported since ESP8266 Arduino core v2.7.0 and is the default for newer AutoConnect versions. ### Configuration: - Ensure the `AC_USE_SPIFFS` macro in `AutoConnectDefs.h` matches the file system implemented in your Sketch. - If `AC_USE_SPIFFS` is enabled, AutoConnect assumes SPIFFS. - If `AC_USE_SPIFFS` is disabled, AutoConnect assumes LittleFS. - Mismatched configurations can lead to file writing errors. ``` -------------------------------- ### Entries and Loading Credentials Source: https://hieromon.github.io/AutoConnect/credit.html Functions to get the number of stored credentials and to load them into a station configuration structure. ```APIDOC ### __entries ```cpp uint8_t entries(void) ``` Returns number of entries as contained credentials. **Return value** Number of entries as contained credentials. ### __load (by SSID) ```cpp int8_t load(const char* ssid, station_config_t* config) ``` Load a credential entry and store to **config**. **Parameters** ssid SSID to be loaded. config station_config_t **Return value** Save the specified SSID's credential entry to `station_config_t` pointed to by the parameter as **config**. -1 is returned if the SSID is not saved. ### __load (by entry index) ```cpp bool load(int8_t entry, station_config_t* config) ``` Load a credential entry and store to **config**. **Parameters** entry Specifies the index number based 0 to be loaded. config station_config_t **Return value** Save the specified credential entry to `station_config_t` pointed to by the parameter as **config**. -1 is returned if specified number is not saved. ``` -------------------------------- ### ESP32WebCam Utility Methods Source: https://hieromon.github.io/AutoConnect/esp32cam.html Methods to retrieve configuration paths and server handles. ```APIDOC ## Utility Methods ### getCapturePath Returns the current endpoint URL path for capturing images. ### getPromptPath Returns the current endpoint URL path for prompting. ### getServerHandle Returns the httpd_handle_t of the internal HTTP server. Returns nullptr if the server is not running. ``` -------------------------------- ### Launch Captive Portal On-Demand Source: https://hieromon.github.io/AutoConnect/adcpcontrol.html Enable `retainPortal` and `autoRise` to launch SoftAP and DNS when a WiFi disconnect is detected during the handleClient loop. This behavior occurs even if the WiFi mode is STA. ```cpp AutoConnect Portal; AutoConnectConfig Config; void setup() { Config.autoRise = true; // It's the default, no setting is needed explicitly. Config.retainPortal = true; Portal.config(Config); Portal.begin(); } void loop() { Portal.handleClient(); } ``` -------------------------------- ### Integrate mDNS with AutoConnect Source: https://hieromon.github.io/AutoConnect/adnetwork.html Enable mDNS responder after the AutoConnect portal has successfully started to allow hostname-based access. ```cpp #include #include #include AutoConnect Portal; void setup() { if (Portal.begin()) { if (MDNS.begin("esp8266")) { MDNS.addService("http", "tcp", 80); } } } void loop() { Portal.handleClient(); } ``` -------------------------------- ### void onConnect(ConnectExit_ft fn) Source: https://hieromon.github.io/AutoConnect/api.html Registers a callback function to be executed when the WiFi connection is established. ```APIDOC ## void onConnect(ConnectExit_ft fn) ### Description Register the function which will be called from AutoConnect when the WiFi connection is established. ### Parameters #### Request Body - **fn** (ConnectExit_ft) - Required - Function prototype: void(IPAddress& localIP). ``` -------------------------------- ### Configure ESP32 Partition Scheme Source: https://hieromon.github.io/AutoConnect/faq.html Specify a custom partition table in platformio.ini to manage flash memory usage. ```ini [env:esp32dev] board_build.partitions = min_spiffs.csv ``` -------------------------------- ### Access element members after casting Source: https://hieromon.github.io/AutoConnect/achandling.html Example of loading a JSON configuration and accessing a specific element's value. ```cpp const String auxJson = String("{\"title\":\"Page 1 title\",\"uri\":\"/page1\",\"menu\":true,\"element\":[{\"name\":\"caption\",\"type\":\"ACText\",\"value\":\"hello, world\"}]}"); AutoConnect portal; portal.load(auxJson); AutoConnectAux* aux = portal.aux("/page1"); // Identify the AutoConnectAux instance with uri AutoConnectText& text = aux->getElement("caption"); // Cast to real type and access members Serial.println(text.value); ``` -------------------------------- ### Retrieve element by pointer or reference Source: https://hieromon.github.io/AutoConnect/achandling.html Example showing how to retrieve an element using reinterpret_cast or template-based reference retrieval. ```cpp AutoConnectAux aux; aux.load("SOME_JSON_DOCUMENT"); // Retrieve the pointer of the AutoConnectText AutoConnectText* text = reinterpret_cast(aux.getElement("TEXT_ELEMENT_NAME")); // Retrieve the reference of the AutoConnectText AutoConnectText& text = aux.getElement("TEXT_ELEMENT_NAME"); ``` -------------------------------- ### Include AutoConnect Headers Source: https://hieromon.github.io/AutoConnect/api.html Use AutoConnect.h for full functionality or AutoConnectCore.h to reduce binary size by excluding OTA and custom web page features. ```cpp #include ``` ```cpp #include ``` -------------------------------- ### Define the upload entry point Source: https://hieromon.github.io/AutoConnect/acupload.html The public virtual upload function serves as the entry point for handling file upload chunks. ```cpp public virtual void upload(const String& requestUri, const HTTPUpload& upload) ``` -------------------------------- ### Get Content Count of AutoConnectAux Source: https://hieromon.github.io/AutoConnect/apiaux.html Returns the total number of AutoConnectElements currently registered within the AutoConnectAux object. ```cpp size_t content(void) ``` -------------------------------- ### Accessing POST Arguments with ESP8266WebServer Source: https://hieromon.github.io/AutoConnect/achandling.html This sketch demonstrates how to handle a custom web page and echo back an input value using ESP8266WebServer::arg and ESP8266WebServer::send. ```cpp ESP8266WebServer server; AutoConnect portal(server); ACInput(input1, "", "INPUT"); ACSubmit(send, "HELLO", "/echo"); AutoConnectAux aux("/hello", { input1, send }); server.on("/echo", []() { String echo = server.arg("input1"); Serial.println(echo); server.send(200, "text/plain", echo); }); portal.join(aux); portal.begin(); ```