### Example: Get and Print MAC Address (String Version) Source: https://github.com/esp8266/arduino/blob/master/doc/esp8266wifi/station-class.md Demonstrates retrieving the MAC address as a formatted string and printing it when connected to WiFi. ```cpp if (WiFi.status() == WL_CONNECTED) { Serial.printf("Connected, mac address: %s\n", WiFi.macAddress().c_str()); } ``` -------------------------------- ### Setup for Web Browser OTA Updates Source: https://github.com/esp8266/arduino/blob/master/doc/ota_updates/readme.md This code initializes mDNS, sets up the HTTP update server, and starts the web server. Ensure the ESP and computer are on the same network. ```cpp MDNS.begin(host); httpUpdater.setup(&httpServer); httpServer.begin(); MDNS.addService("http", "tcp", 80); ``` -------------------------------- ### List Available Examples Source: https://github.com/esp8266/arduino/blob/master/tests/host/README.txt Run this command to display a list of all available example sketches for the ESP8266 Arduino core. ```bash make list ``` -------------------------------- ### Build WiFiClient Example Source: https://github.com/esp8266/arduino/blob/master/tests/host/README.txt Compile the WiFiClient example for network connectivity. 'D=1' enables debug messages. ```bash make D=1 ../../libraries/ESP8266WiFi/examples/WiFiClient/WiFiClient ``` -------------------------------- ### Example: Get and Print MAC Address Source: https://github.com/esp8266/arduino/blob/master/doc/esp8266wifi/station-class.md Demonstrates how to retrieve the MAC address using a pointer and print it to the serial monitor when connected to WiFi. ```cpp if (WiFi.status() == WL_CONNECTED) { uint8_t macAddr[6]; WiFi.macAddress(macAddr); Serial.printf("Connected, mac address: %02x:%02x:%02x:%02x:%02x:%02x\n", macAddr[0], macAddr[1], macAddr[2], macAddr[3], macAddr[4], macAddr[5]); } ``` -------------------------------- ### Initialize Soft AP with Custom Configuration Source: https://github.com/esp8266/arduino/blob/master/doc/esp8266wifi/soft-access-point-class.md This example demonstrates how to configure the soft AP's network interface with a specific IP address, gateway, and subnet, then starts the soft AP, and prints its IP address. ```cpp #include IPAddress local_IP(192,168,4,22); IPAddress gateway(192,168,4,9); IPAddress subnet(255,255,255,0); void setup() { Serial.begin(115200); Serial.println(); Serial.print("Setting soft-AP configuration ... "); Serial.println(WiFi.softAPConfig(local_IP, gateway, subnet) ? "Ready" : "Failed!"); Serial.print("Setting soft-AP ... "); Serial.println(WiFi.softAP("ESPsoftAP_01") ? "Ready" : "Failed!"); Serial.print("Soft-AP IP address = "); Serial.println(WiFi.softAPIP()); } void loop() {} ``` -------------------------------- ### Example: Get and Print Gateway IP Address Source: https://github.com/esp8266/arduino/blob/master/doc/esp8266wifi/station-class.md Illustrates how to retrieve and print the gateway IP address to the serial monitor. ```cpp Serial.printf("Gataway IP: %s\n", WiFi.gatewayIP().toString().c_str()); ``` -------------------------------- ### Example: Get and Print DNS IP Addresses Source: https://github.com/esp8266/arduino/blob/master/doc/esp8266wifi/station-class.md Shows how to retrieve and print the IP addresses of the first and second DNS servers to the serial monitor. ```cpp Serial.print("DNS #1, #2 IP: "); WiFi.dnsIP().printTo(Serial); Serial.print(", "); WiFi.dnsIP(1).printTo(Serial); Serial.println(); ``` -------------------------------- ### Build HelloServer Example Source: https://github.com/esp8266/arduino/blob/master/tests/host/README.txt Compile the basic HelloServer example for the ESP8266 web server. 'D=1' enables debug messages. ```bash make D=1 ../../libraries/ESP8266WebServer/examples/HelloServer/HelloServer ``` -------------------------------- ### Example: Get and Print Local IP Address Source: https://github.com/esp8266/arduino/blob/master/doc/esp8266wifi/station-class.md Shows how to obtain and print the ESP station's local IP address to the serial monitor when connected to WiFi. ```cpp if (WiFi.status() == WL_CONNECTED) { Serial.print("Connected, IP address: "); Serial.println(WiFi.localIP()); } ``` -------------------------------- ### Build and Run a Specific Example Source: https://github.com/esp8266/arduino/blob/master/tests/host/README.txt Compile a specific example sketch, such as 'Blink', and then run the compiled executable. 'D=1' enables debug messages. ```bash make D=1 ../../libraries/esp8266/examples/Blink/Blink ./bin/Blink/Blink -h ``` -------------------------------- ### Build UDP Example Source: https://github.com/esp8266/arduino/blob/master/tests/host/README.txt Compile the UDP networking example. 'D=1' enables debug messages. ```bash make D=1 ../../libraries/ESP8266WiFi/examples/udp/udp ``` -------------------------------- ### Example: Get and Print Subnet Mask Source: https://github.com/esp8266/arduino/blob/master/doc/esp8266wifi/station-class.md Demonstrates retrieving and printing the subnet mask of the station's interface to the serial monitor. ```cpp Serial.print("Subnet mask: "); Serial.println(WiFi.subnetMask()); ``` -------------------------------- ### Build mDNS Web Server Example Source: https://github.com/esp8266/arduino/blob/master/tests/host/README.txt Compile the mDNS_Web_Server example, which integrates mDNS for network discovery. 'D=1' enables debug messages. ```bash make D=1 ../../libraries/ESP826mDNS/examples/mDNS_Web_Server/mDNS_Web_Server ``` -------------------------------- ### Build AdvancedWebServer Example Source: https://github.com/esp8266/arduino/blob/master/tests/host/README.txt Compile the AdvancedWebServer example, showcasing more complex web server functionalities. 'D=1' enables debug messages. ```bash make D=1 ../../libraries/ESP8266WebServer/examples/AdvancedWebServer/AdvancedWebServer ``` -------------------------------- ### Server Lifecycle Methods Source: https://github.com/esp8266/arduino/blob/master/libraries/ESP8266WebServer/README.rst Methods for starting, handling, and stopping the web server. ```cpp void begin(); ``` ```cpp void handleClient(); ``` ```cpp void close(); void stop(); ``` -------------------------------- ### Basic ESP8266 Web Server Setup Source: https://github.com/esp8266/arduino/blob/master/libraries/ESP8266WebServer/examples/Graph/readme.md This is a minimal setup for an ESP8266 web server. It includes basic WiFi connection and a handler for serving files from the filesystem. The `index.htm` file is served by default when no specific filename is requested. ```c++ void setup() { Serial.begin(115200); Serial.println("Booting..."); // Initialize SPIFFS or other filesystem if (!SPIFFS.begin(true)){ Serial.println("SPIFFS Mount Failed"); return; } // Connect to WiFi WiFi.begin(STASSID, STAPSK); while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); } Serial.println("WiFi connected"); Serial.println("IP address: " + WiFi.localIP()); // Serve files from filesystem server.on("/", HTTP_GET, []() { server.send(200, "text/html", "Hello from ESP8266!"); }); // Start server server.begin(); Serial.println("HTTP server started"); } void loop() { server.handleClient(); } ``` -------------------------------- ### Serial Monitor Output Examples Source: https://github.com/esp8266/arduino/blob/master/doc/esp8266wifi/station-examples.md Example logs showing the ESP8266 connection lifecycle, including initial connection and switching between access points. ```default f r0, scandone f r0, scandone state: 0 -> 2 (b0) state: 2 -> 3 (0) state: 3 -> 5 (10) add 0 aid 1 cnt chg_B1:-40 connected with sensor-net-1, channel 1 dhcp client start... ip:192.168.1.10,mask:255.255.255.0,gw:192.168.1.9 ``` ```default bcn_timout,ap_probe_send_start ap_probe_send over, rest wifi status to disassoc state: 5 -> 0 (1) rm 0 f r-40, scandone f r-40, scandone f r-40, scandone state: 0 -> 2 (b0) state: 2 -> 3 (0) state: 3 -> 5 (10) add 0 aid 1 cnt connected with sensor-net-2, channel 11 dhcp client start... ip:192.168.1.102,mask:255.255.255.0,gw:192.168.1.234 ``` ```default bcn_timout,ap_probe_send_start ap_probe_send over, rest wifi status to disassoc state: 5 -> 0 (1) rm 0 f r-40, scandone f r-40, scandone f r-40, scandone state: 0 -> 2 (b0) state: 2 -> 3 (0) state: 3 -> 5 (10) add 0 aid 1 cnt connected with sensor-net-1, channel 6 dhcp client start... ip:192.168.1.10,mask:255.255.255.0,gw:192.168.1.9 ``` -------------------------------- ### Start GDB on Linux Source: https://github.com/esp8266/arduino/blob/master/doc/gdb.md Navigate to the ESP8266 toolchain directory and run this command to start the GDB executable for debugging on Linux. ```bash ~/.arduino15/packages/esp8266/tools/xtensa-lx106-elf-gcc/2.5.0-4-b40a506/bin/xtensa-lx106-elf-gdb ``` -------------------------------- ### Initialize GDB Stub in Setup Source: https://github.com/esp8266/arduino/blob/master/doc/gdb.md Ensure the serial port is initialized and call gdbstub_init() within your void setup() function to prepare for GDB debugging. ```cpp Serial.begin(115200); gdbstub_init(); ``` -------------------------------- ### Example Sketch Implementation Source: https://github.com/esp8266/arduino/blob/master/doc/faq/a06-global-build-options.md A sample sketch demonstrating the use of globally defined macros. ```cpp #include // has prototype for umm_free_heap_size_min() void setup() { Serial.begin(115200); delay(200); #ifdef MYTITLE1 Serial.printf("\r\n" MYTITLE1 MYTITLE2 "\r\n"); #else Serial.println("ERROR: MYTITLE1 not present"); #endif Serial.printf("Heap Low Watermark %u\r\n", umm_free_heap_size_min()); } void loop() {} ``` -------------------------------- ### Start GDB on Windows (Git) Source: https://github.com/esp8266/arduino/blob/master/doc/gdb.md Navigate to the ESP8266 toolchain directory and run this command to start the GDB executable for debugging on Windows using the Git version. ```bash %userprofile%\Documents\Arduino\hardware\esp8266com\esp8266\tools\xtensa-lx106-elf\bin\xtensa-lx106-elf-gdb.exe ``` -------------------------------- ### Python Setup and Teardown for WiFiClient Test Source: https://github.com/esp8266/arduino/blob/master/tests/README.md Use the `@setup` and `@teardown` decorators to bind Python functions to specific test cases. These functions can create resources like TCP servers and manage environment variables passed to the device test. Ensure environment variables are correctly set and validated. ```python from mock_decorators import setup, teardown, setenv, request_env @setup('WiFiClient test') def setup_wificlient_test(e): # create a TCP server # pass environment variable to the test setenv(e, 'SERVER_PORT', '10000') setenv(e, 'SERVER_IP', repr(server_ip)) @teardown('WiFiClient test') def teardown_wificlient_test(e): # delete TCP server # request environment variable from the test, compare to the expected value read_bytes = request_env(e, 'READ_BYTES') assert(read_bytes == '4096') ``` -------------------------------- ### Launch ESP8266 GDB Source: https://github.com/esp8266/arduino/blob/master/doc/gdb.md Start the ESP8266-specific GDB instance. ```bash earle@server:~$ ~/.arduino15/packages/esp8266/hardware/xtensa-lx106-elf/bin/xtensa-lx106-elf-gdb GNU gdb (GDB) 8.2.50.20180723-git Copyright (C) 2018 Free Software Foundation, Inc. License GPLv3+: GNU GPL version 3 or later This is free software: you are free to change and redistribute it. There is NO WARRANTY, to the extent permitted by law. Type "show copying" and "show warranty" for details. This GDB was configured as "--host=x86_64-linux-gnu --target=xtensa-lx106-elf". Type "show configuration" for configuration details. For bug reporting instructions, please see: . Find the GDB manual and other documentation resources online at: . For help, type "help". Type "apropos word" to search for commands related to "word". (gdb) ``` -------------------------------- ### Restore Legacy Boot WiFi Behavior Source: https://github.com/esp8266/arduino/blob/master/doc/esp8266wifi/generic-class.md Example of using enableWiFiAtBootTime to restore automatic WiFi startup at boot. ```cpp #include void setup () { #ifdef WIFI_IS_OFF_AT_BOOT enableWiFiAtBootTime(); // can be called from anywhere with the same effect #endif .... } ``` -------------------------------- ### Basic Mesh Network Example Source: https://github.com/esp8266/arduino/blob/master/libraries/ESP8266WiFiMesh/README.md Upload this example to multiple ESP8266 devices to create a working mesh network. Modify `useLED` to visualize message propagation, `floodingMesh.broadcast` to change transmitted data, and `meshMessageHandler` to alter node reactions. ```cpp int useLED = false; floodingMesh.broadcast("Hello Mesh!"); void meshMessageHandler(uint32_t from, String &from_node, String &message) { // Modify how mesh nodes react to received transmissions } ``` -------------------------------- ### Format Release Notes Example Source: https://github.com/esp8266/arduino/blob/master/package/README.md Structure for organizing breaking changes and library updates in the changelog. ```markdown Breaking Changes ================ API xyz changed #1234 ... Library - xyz ============= API xyz changed #1234 (Breaking change) ... ``` -------------------------------- ### Start GDB on Windows (Board Manager) Source: https://github.com/esp8266/arduino/blob/master/doc/gdb.md Navigate to the ESP8266 toolchain directory and run this command to start the GDB executable for debugging on Windows using the Board Manager version. ```bash %userprofile%\AppData\Local\Arduino15\packages\esp8266\tools\xtensa-lx106-elf-gcc\2.5.0-3-20ed2b9\bin\xtensa-lx106-elf-gdb.exe ``` -------------------------------- ### Initialize Soft AP Source: https://github.com/esp8266/arduino/blob/master/doc/esp8266wifi/soft-access-point-examples.md Core function call to start the access point. ```cpp boolean result = WiFi.softAP("ESPsoftAP_01", "pass-to-soft-AP"); ``` -------------------------------- ### Initialize GDBStub in Arduino Sketch Source: https://github.com/esp8266/arduino/blob/master/doc/gdb.md Include the GDBStub library and initialize it in the setup function to enable debugging. ```cpp #include void setup() { Serial.begin(115200); gdbstub_init(); Serial.printf("Starting...\n"); } void loop() { static uint32_t cnt = 0; Serial.printf("%d\n", cnt++); delay(100); } ``` -------------------------------- ### Serial and Network Data Transfer Example Source: https://github.com/esp8266/arduino/blob/master/doc/reference.md This example demonstrates transferring data between a Telnet client and the UART (Serial). It shows byte-by-byte transfer from network to serial and buffered transfer from serial to network, including availability checks. ```cpp //check clients for data //get data from the telnet client and push it to the UART while (serverClient.available()) { Serial.write(serverClient.read()); } //check UART for data if (Serial.available()) { size_t len = Serial.available(); uint8_t sbuf[len]; Serial.readBytes(sbuf, len); //push UART data to all connected telnet clients if (serverClient && serverClient.connected()) { serverClient.write(sbuf, len); } } ``` -------------------------------- ### Serial Monitor Output Example Source: https://github.com/esp8266/arduino/blob/master/doc/esp8266wifi/station-examples.md Sample output showing the connection status monitoring process. ```default Looking for WiFi ..... connected to sensor-net-1 Looking for WiFi ....... connected to sensor-net-2 Looking for WiFi .... connected to sensor-net-1 ``` -------------------------------- ### Configuring Access Points Source: https://github.com/esp8266/arduino/blob/master/doc/esp8266wifi/station-examples.md Examples of adding multiple access points to the wifiMulti instance. ```cpp wifiMulti.addAP("primary-network-name", "pass-to-primary-network"); wifiMulti.addAP("secondary-network-name", "pass-to-secondary-network"); ``` ```cpp wifiMulti.addAP("tertiary-network-name", "pass-to-tertiary-network"); ... ``` -------------------------------- ### SoftAP Setup Source: https://github.com/esp8266/arduino/blob/master/doc/esp8266wifi/soft-access-point-class.md Functions to set up and configure the ESP8266 in soft access point (soft-AP) mode. ```APIDOC ## POST /esp8266/arduino/softAP ### Description Sets up a soft access point to establish a Wi-Fi network. Can be used to create an open network or a protected network with a pre-shared key. ### Method POST ### Endpoint /esp8266/arduino/softAP ### Parameters #### Query Parameters - **ssid** (string) - Required - Character string containing network SSID (max. 32 characters). - **psk** (string) - Optional - Character string with a pre-shared key (minimum 8 characters, maximum 64 characters). If not specified, the access point will be open. - **channel** (integer) - Optional - Wi-Fi channel from 1 to 13. Defaults to 1. - **hidden** (boolean) - Optional - If set to `true`, the SSID will be hidden. - **max_connection** (integer) - Optional - Maximum simultaneous connected stations, from 0 to 8. Defaults to 4. ### Request Example ```json { "ssid": "MyESP8266AP", "psk": "MyPassword123", "channel": 6, "hidden": false, "max_connection": 8 } ``` ### Response #### Success Response (200) - **success** (boolean) - Indicates if the soft-AP setup was successful. #### Response Example ```json { "success": true } ``` ``` ```APIDOC ## POST /esp8266/arduino/softAPConfig ### Description Configures the soft access point's network interface with a specific IP address, gateway, and subnet mask. ### Method POST ### Endpoint /esp8266/arduino/softAPConfig ### Parameters #### Request Body - **local_ip** (IPAddress) - Required - The IP address of the soft access point. - **gateway** (IPAddress) - Required - The gateway IP address. - **subnet** (IPAddress) - Required - The subnet mask. ### Request Example ```json { "local_ip": "192.168.4.22", "gateway": "192.168.4.1", "subnet": "255.255.255.0" } ``` ### Response #### Success Response (200) - **success** (boolean) - Indicates if the configuration was successful. #### Response Example ```json { "success": true } ``` ``` -------------------------------- ### Asynchronous Scan Implementation Example Source: https://github.com/esp8266/arduino/blob/master/doc/esp8266wifi/scan-class.md Demonstrates using scanNetworksAsync with a callback function to process scan results. ```cpp #include "ESP8266WiFi.h" void prinScanResult(int networksFound) { Serial.printf("%d network(s) found\n", networksFound); for (int i = 0; i < networksFound; i++) { Serial.printf("%d: %s, Ch:%d (%ddBm) %s\n", i + 1, WiFi.SSID(i).c_str(), WiFi.channel(i), WiFi.RSSI(i), WiFi.encryptionType(i) == ENC_TYPE_NONE ? "open" : ""); } } void setup() { Serial.begin(115200); Serial.println(); WiFi.mode(WIFI_STA); WiFi.disconnect(); delay(100); WiFi.scanNetworksAsync(prinScanResult); } void loop() {} ``` -------------------------------- ### Initialize ESP8266WebServer Source: https://github.com/esp8266/arduino/blob/master/libraries/ESP8266WebServer/README.rst Creates an instance of the web server on a specified port. ```cpp ESP8266WebServer server(80); ``` -------------------------------- ### begin(port) Source: https://github.com/esp8266/arduino/blob/master/doc/esp8266wifi/server-class.md Initializes the server on a specific port. If no port is provided, it defaults to port 23. ```APIDOC ## begin(uint16_t port) ### Description Starts the server on the specified port. If the port is not specified in the constructor or begin method, the server defaults to port 23. ### Parameters #### Method Parameters - **port** (uint16_t) - Optional - The TCP port number to listen on. ``` -------------------------------- ### Initialize and Fetch Data Source: https://github.com/esp8266/arduino/blob/master/libraries/ESP8266WebServer/examples/Graph/data/index.htm Initializes the digital chart and fetches the first sample of data to start the visualization process. ```javascript // Configure the digital chart initDigitalChart(); // Get first sample fetchNewData(); ``` -------------------------------- ### WiFi.begin() Source: https://github.com/esp8266/arduino/blob/master/doc/esp8266wifi/station-class.md Initializes the ESP8266 in station mode and establishes a connection to an access point using various configuration options. ```APIDOC ## WiFi.begin() ### Description Initializes the ESP8266 station mode. Multiple overloads allow for connecting to a specific SSID, reconnecting to the last saved access point, or providing detailed network parameters. ### Parameters #### Request Body - **ssid** (string) - Optional - SSID of the Access Point (up to 32 characters). - **password** (string) - Optional - Password for the Access Point (8-64 characters). - **channel** (int) - Optional - Specific channel of the AP. - **bssid** (string) - Optional - MAC address of the AP. - **connect** (boolean) - Optional - If false, saves parameters without establishing an immediate connection. ### Request Example WiFi.begin("mySSID", "myPassword", 6, "AA:BB:CC:DD:EE:FF", true) ``` -------------------------------- ### Error Message for Generic ESP8266 Module Source: https://github.com/esp8266/arduino/blob/master/doc/faq/a04-board-generic-is-unknown.md This is an example of the error message encountered when the Arduino IDE cannot recognize the 'Generic ESP8266 Module'. This typically happens after package installation issues. ```default Board generic (platform esp8266, package esp8266) is unknown Error compiling for board Generic ESP8266 Module. ``` -------------------------------- ### Error Message for Adafruit HUZZAH ESP8266 Source: https://github.com/esp8266/arduino/blob/master/doc/faq/a04-board-generic-is-unknown.md This is an example of the error message when the 'Adafruit HUZZAH ESP8266' board is not recognized. This error is related to the esp8266 package installation within the Arduino IDE. ```default Board huzzah (platform esp8266, package esp8266) is unknown Error compiling for board Adafruit HUZZAH ESP8266. ``` -------------------------------- ### Error Message for WeMos D1 R2 & mini Source: https://github.com/esp8266/arduino/blob/master/doc/faq/a04-board-generic-is-unknown.md This is an example of the error message when the 'WeMos D1 R2 & mini' board is not recognized by the Arduino IDE. It indicates a problem with the esp8266 package installation. ```default Board d1_mini (platform esp8266, package esp8266) is unknown Error compiling for board WeMos D1 R2 & mini. ``` -------------------------------- ### Initialize WiFiServer Source: https://github.com/esp8266/arduino/blob/master/doc/esp8266wifi/server-examples.md Create a server object listening on port 80, the standard port for web traffic. ```cpp WiFiServer server(80); ``` -------------------------------- ### Initialize Git Submodules Source: https://github.com/esp8266/arduino/blob/master/doc/installing.md After cloning the repository, run this command to fetch external libraries required by the ESP8266 core. Failure to do so may result in build errors. ```bash cd esp8266 git submodule update --init ``` -------------------------------- ### Build BearSSL Validation Example Source: https://github.com/esp8266/arduino/blob/master/tests/host/README.txt Compile the BearSSL_Validation example, used for testing SSL/TLS certificate validation. 'D=1' enables debug messages. ```bash make D=1 ../../libraries/ESP8266WiFi/examples/BearSSL_Validation/BearSSL_Validation ``` -------------------------------- ### Complete ESP8266 WiFi Connection and Event Handling Example Source: https://github.com/esp8266/arduino/blob/master/doc/esp8266wifi/generic-examples.md This code sets up Wi-Fi connection with event handlers for IP acquisition and disconnection. It also blinks an LED in the main loop, demonstrating asynchronous task handling. ```cpp #include const char* ssid = "********"; const char* password = "********"; WiFiEventHandler gotIpEventHandler, disconnectedEventHandler; bool ledState; void setup() { Serial.begin(115200); Serial.println(); pinMode(LED_BUILTIN, OUTPUT); gotIpEventHandler = WiFi.onStationModeGotIP([](const WiFiEventStationModeGotIP& event) { Serial.print("Station connected, IP: "); Serial.println(WiFi.localIP()); }); disconnectedEventHandler = WiFi.onStationModeDisconnected([](const WiFiEventStationModeDisconnected& event) { Serial.println("Station disconnected"); }); Serial.printf("Connecting to %s ...\n", ssid); WiFi.begin(ssid, password); } void loop() { digitalWrite(LED_BUILTIN, ledState); ledState = !ledState; delay(250); } ``` -------------------------------- ### Create an HTTP Web Server Source: https://context7.com/esp8266/arduino/llms.txt Implements a basic web server with route handlers for GET requests and LED control. Requires the ESP8266WebServer library. ```cpp #include #include ESP8266WebServer server(80); int ledState = LOW; void handleRoot() { String html = "ESP8266 Web Server"; html += "

ESP8266 Control Panel

"; html += "

LED State: " + String(ledState ? "ON" : "OFF") + "

"; html += ""; html += ""; html += ""; server.send(200, "text/html", html); } void handleLedOn() { ledState = HIGH; digitalWrite(LED_BUILTIN, LOW); // LED is active-low server.sendHeader("Location", "/"); server.send(303); } void handleLedOff() { ledState = LOW; digitalWrite(LED_BUILTIN, HIGH); server.sendHeader("Location", "/"); server.send(303); } void handleNotFound() { String message = "404 Not Found\n\n"; message += "URI: " + server.uri() + "\n"; message += "Method: " + String((server.method() == HTTP_GET) ? "GET" : "POST") + "\n"; message += "Arguments: " + String(server.args()) + "\n"; for (uint8_t i = 0; i < server.args(); i++) { message += " " + server.argName(i) + ": " + server.arg(i) + "\n"; } server.send(404, "text/plain", message); } void setup() { Serial.begin(115200); pinMode(LED_BUILTIN, OUTPUT); digitalWrite(LED_BUILTIN, HIGH); WiFi.mode(WIFI_STA); WiFi.begin("your-ssid", "your-password"); while (WiFi.status() != WL_CONNECTED) { delay(500); } Serial.print("Server IP: "); Serial.println(WiFi.localIP()); // Define routes server.on("/", HTTP_GET, handleRoot); server.on("/led/on", HTTP_GET, handleLedOn); server.on("/led/off", HTTP_GET, handleLedOff); server.onNotFound(handleNotFound); server.begin(); Serial.println("HTTP server started"); } void loop() { server.handleClient(); } ``` -------------------------------- ### Configure Filesystem Parameters Source: https://github.com/esp8266/arduino/blob/master/doc/filesystem.md Use setConfig to define filesystem behavior before mounting. This must be called before begin() to override default settings like auto-formatting. ```cpp SPIFFSConfig cfg; cfg.setAutoFormat(false); SPIFFS.setConfig(cfg); ``` -------------------------------- ### Install Python SSL Certificates on macOS Source: https://github.com/esp8266/arduino/blob/master/doc/installing.md If you encounter SSL certificate verification errors when running 'python3 get.py' on macOS, use this command to install the required certificates. ```bash cd "/Applications/Python 3.7/" && sudo "./Install Certificates.command" ``` -------------------------------- ### Manual Binary Signing Setup Source: https://github.com/esp8266/arduino/blob/master/doc/ota_updates/readme.md Integrate these declarations and function call in your main code before enabling any update methods to enable manual signature verification for OTA updates. ```cpp BearSSL::PublicKey signPubKey( ... key contents ... ); BearSSL::HashSHA256 hash; BearSSL::SigningVerifier sign( &signPubKey ); ... Update.installSignature( &hash, &sign ); ``` -------------------------------- ### TCP/IP Mesh Backend Example Callbacks Source: https://github.com/esp8266/arduino/blob/master/libraries/ESP8266WiFiMesh/README.md Key functions to modify in the TcpIpMeshBackend example for customizing network behavior. These include handling incoming requests, managing responses, filtering networks, and updating transmission outcomes. ```cpp manageRequest(requestHandler); manageResponse(responseHandler); networkFilter; exampleTransmissionOutcomesUpdateHook; ``` -------------------------------- ### Connect with Advanced Parameters Source: https://github.com/esp8266/arduino/blob/master/doc/esp8266wifi/station-class.md This overload of `begin` allows specifying additional parameters such as channel, BSSID, and a flag to control immediate connection. Use this for fine-grained control over the connection process. ```cpp WiFi.begin(ssid, password, channel, bssid, connect) ``` -------------------------------- ### Make HTTP GET and POST Requests Source: https://context7.com/esp8266/arduino/llms.txt Perform HTTP GET and POST requests to web APIs using the ESP8266HTTPClient library. Handles connection management, headers, and response parsing. Ensure WiFi is connected before making requests. ```cpp #include #include #include void setup() { Serial.begin(115200); WiFi.mode(WIFI_STA); WiFi.begin("your-ssid", "your-password"); while (WiFi.status() != WL_CONNECTED) { delay(500); } } void loop() { if (WiFi.status() == WL_CONNECTED) { WiFiClient client; HTTPClient http; // GET request Serial.println("[HTTP] GET request..."); if (http.begin(client, "http://httpbin.org/get")) { http.addHeader("Accept", "application/json"); int httpCode = http.GET(); if (httpCode > 0) { Serial.printf("Response code: %d\n", httpCode); if (httpCode == HTTP_CODE_OK) { String payload = http.getString(); Serial.println(payload); } } else { Serial.printf("GET failed: %s\n", http.errorToString(httpCode).c_str()); } http.end(); } delay(2000); // POST request with JSON Serial.println("[HTTP] POST request..."); if (http.begin(client, "http://httpbin.org/post")) { http.addHeader("Content-Type", "application/json"); String jsonPayload = "{\"sensor\":\"temperature\",\"value\":23.5}"; int httpCode = http.POST(jsonPayload); if (httpCode > 0) { Serial.printf("Response code: %d\n", httpCode); String response = http.getString(); Serial.println(response); } http.end(); } } delay(30000); } ``` -------------------------------- ### WiFi.hostname Source: https://github.com/esp8266/arduino/blob/master/doc/esp8266wifi/station-class.md Get or set the DHCP hostname for the ESP station. ```APIDOC ## GET/SET WiFi.hostname ### Description Retrieves the current DHCP hostname or sets a new one. The default format is ESP_24xMAC. ### Parameters #### Request Body - **aHostname** (String/char*) - Optional - The new hostname to set (max 32 characters). ### Response - **Return Value** (String/bool) - Returns the current hostname as a String, or a boolean indicating success/failure when setting a new one. ``` -------------------------------- ### Initialize and Configure Ace Editor Source: https://github.com/esp8266/arduino/blob/master/libraries/ESP8266WebServer/examples/FSBrowser/data/edit/index.htm Sets up the Ace editor instance, including language detection, theme configuration, and custom command bindings. ```javascript function createEditor(element, file, lang, theme, type){ function getLangFromFilename(filename){ var lang = "plain"; var ext = /(?:\\.(\\.[^.]+))?$/.exec(filename)[1]; if (ext !== undefined){ switch(ext){ case "txt": lang = "plain"; break; case "htm": lang = "html"; break; case "js": lang = "javascript"; break; case "c": lang = "c_cpp"; break; case "cpp": lang = "c_cpp"; break; case "css": case "scss": case "php": case "html": case "json": case "xml": lang = ext; } } return lang; } if (typeof file === "undefined") file = "/index.htm"; if (typeof lang === "undefined"){ lang = getLangFromFilename(file); } if (typeof theme === "undefined") theme = "textmate"; if (typeof type === "undefined"){ type = "text/"+lang; if (lang === "c_cpp") type = "text/plain"; } var xmlHttp = null; var editor = ace.edit(element); function filePosted(){ setLoading(false); if (xmlHttp.status != 200) showHttpError(xmlHttp); tree.refreshPath(getParentFolder(file)); // to update size in tree refreshStatus(); } function postFile(path, data, type){ setLoading(true, "Saving '" + path + "'..."); xmlHttp = new XMLHttpRequest(); xmlHttp.onload = filePosted; var formData = new FormData(); formData.append("data", new Blob([data], { type: type }), path); xmlHttp.open("POST", "/edit"); xmlHttp.send(formData); } function fileLoaded(){ setLoading(false); document.getElementById("preview").style.display = "none"; document.getElementById("editor").style.display = "block"; document.getElementById("editorButtons").style.display = "inline"; if (xmlHttp.status == 200) { editor.setValue(xmlHttp.responseText); editor.clearSelection(); enableSaveDiscardBtns(false); } else tree.clearMainPanel(); } function loadFile(path){ setLoading(true, "Loading '" + path + "'..."); xmlHttp = new XMLHttpRequest(); xmlHttp.onload = fileLoaded; xmlHttp.open("GET", path, true); xmlHttp.send(null); } if (lang !== "plain") editor.getSession().setMode("ace/mode/"+lang); editor.setTheme("ace/theme/"+theme); editor.$blockScrolling = Infinity; editor.getSession().setUseSoftTabs(true); editor.getSession().setTabSize(2); editor.setHighlightActiveLine(true); editor.setShowPrintMargin(false); editor.commands.addCommand({ name: 'save', bindKey: {win: 'Ctrl-S', mac: 'Command-S'}, exec: function(editor) { editor.save(); }, readOnly: false }); editor.commands.addCommand({ name: "showKeyboardShortcuts", bindKey: {win: "Ctrl-Alt-h", mac: "Command-Alt-h"}, exec: function(editor) { editor.showShortcuts(); } }) editor.session.on('change', function(delta) { enableSaveDiscardBtns(true); }); editor.loadUrl = function(path){ document.getElementById("pathInput").value = path; enableSaveDiscardBtns(false); file = path; lang = getLangFromFilename(file); type = "text/"+lang; if (lang !== "plain") editor.getSession().setMode("ace/mode/"+lang); loadFile(file); } editor.save = function() { enableSaveDiscardBtns(false); postFile(file, editor.getValue()+"", type); } editor.discard = function() { editor.loadUrl(file); enableSaveDiscardBtns(false); } editor.showShortcuts = function() { ace.config.loadModule("ace/ext/keybinding_menu", function(module) { module.init(editor); editor.showKeyboardShortcuts() }); } loadFile(file); return editor; } ``` -------------------------------- ### Get File Size Source: https://github.com/esp8266/arduino/blob/master/doc/filesystem.md Returns the total size of the file in bytes. ```cpp file.size() ``` -------------------------------- ### Python Virtual Environment Setup Source: https://github.com/esp8266/arduino/blob/master/tests/README.md Command to prepare the Python virtual environment for the test runner. This should be run once on each machine where tests are executed. ```makefile make virtualenv ``` -------------------------------- ### WiFi.scanNetworksAsync Source: https://github.com/esp8266/arduino/blob/master/doc/esp8266wifi/scan-class.md Starts an asynchronous scan and executes a callback function upon completion. ```APIDOC ## scanNetworksAsync ### Description Start scanning for available Wi-Fi networks. On completion execute another function. ### Parameters #### Request Body - **onComplete** (function) - Required - The event handler executed when the scan is done. - **show_hidden** (boolean) - Optional - Set to true to scan for hidden networks. ``` -------------------------------- ### Get Short File Name Source: https://github.com/esp8266/arduino/blob/master/doc/filesystem.md Retrieves the filename without the path component. ```cpp String name = file.name(); ``` -------------------------------- ### Initialize Wi-Fi Connection Source: https://github.com/esp8266/arduino/blob/master/doc/esp8266wifi/readme.md Initiates the connection to a specified Wi-Fi network using the provided network name and password. ```cpp WiFi.begin("network-name", "pass-to-network"); ``` -------------------------------- ### Get File Position Source: https://github.com/esp8266/arduino/blob/master/doc/filesystem.md Retrieves the current byte offset within the file. ```cpp file.position() ``` -------------------------------- ### Download Binary Tools for ESP8266 Core Source: https://github.com/esp8266/arduino/blob/master/doc/installing.md Navigate to the tools directory within the cloned ESP8266 Arduino core and execute the get.py script to download necessary binary tools. ```bash cd tools python3 get.py ``` -------------------------------- ### Get Current WiFi Mode Source: https://github.com/esp8266/arduino/blob/master/doc/esp8266wifi/generic-class.md Retrieves the current active WiFi mode. ```cpp WiFiMode_t getMode() ``` -------------------------------- ### ESP8266 WiFiClient: Status Source: https://github.com/esp8266/arduino/blob/master/doc/esp8266wifi/client-class.md Get the current status of the WiFi client connection. ```cpp uint8_t status () ``` -------------------------------- ### Writing Firmware via Stream Interface Source: https://github.com/esp8266/arduino/blob/master/doc/ota_updates/readme.md Demonstrates how to use the Update class to write firmware from a stream source. ```cpp Update.begin(firmwareLengthInBytes); Update.writeStream(streamVar); Update.end(); ``` -------------------------------- ### Create a TCP Server Source: https://context7.com/esp8266/arduino/llms.txt Set up a TCP server to listen for incoming client connections on a specified port. Useful for custom protocols or raw socket communication. Ensure to disable the Nagle algorithm for low latency. ```cpp #include WiFiServer server(23); // Telnet port void setup() { Serial.begin(115200); WiFi.mode(WIFI_STA); WiFi.begin("your-ssid", "your-password"); while (WiFi.status() != WL_CONNECTED) { delay(500); } server.begin(); server.setNoDelay(true); // Disable Nagle algorithm for low latency Serial.print("Telnet server started at "); Serial.print(WiFi.localIP()); Serial.println(":23"); } void loop() { // Check for new clients WiFiClient client = server.accept(); if (client) { Serial.println("Client connected"); client.println("Welcome to ESP8266 Telnet Server!"); while (client.connected()) { // Echo received data while (client.available()) { char c = client.read(); Serial.write(c); client.write(c); // Echo back } // Send serial input to client while (Serial.available()) { char c = Serial.read(); client.write(c); } yield(); // Allow background tasks } client.stop(); Serial.println("Client disconnected"); } } ``` -------------------------------- ### Prepare HTML Page Content Source: https://github.com/esp8266/arduino/blob/master/doc/esp8266wifi/server-examples.md Construct the HTTP response string including headers and the analog input reading. ```cpp String prepareHtmlPage() { String htmlPage; htmlPage.reserve(1024); // prevent ram fragmentation htmlPage = F("HTTP/1.1 200 OK\r\n" "Content-Type: text/html\r\n" "Connection: close\r\n" // the connection will be closed after completion of the response "Refresh: 5\r\n" // refresh the page automatically every 5 sec "\r\n" "" "" "Analog input: "); htmlPage += analogRead(A0); htmlPage += F("" "\r\n"); return htmlPage; } ``` -------------------------------- ### Get MFLN Status Source: https://github.com/esp8266/arduino/blob/master/doc/esp8266wifi/bearssl-client-secure-class.md Returns the success status of MFLN negotiation after a connection is established. ```cpp bool getMFLNStatus() ``` -------------------------------- ### Configure Filesystem for Web Server Source: https://github.com/esp8266/arduino/blob/master/libraries/ESP8266WebServer/examples/Graph/readme.md Uncomment one of these directives to select the ESP filesystem for storing the index.htm file. Ensure WiFi credentials are provided. ```c++ #define USE_SPIFFS // #define USE_LITTLEFS // #define USE_SDFS ``` -------------------------------- ### Filesystem Configuration and Lifecycle Source: https://github.com/esp8266/arduino/blob/master/doc/filesystem.md Methods for configuring, mounting, unmounting, and formatting SPIFFS or LittleFS filesystems on the ESP8266. ```APIDOC ## setConfig ### Description Configures filesystem parameters before mounting. Must be called before begin(). ### Parameters - **cfg** (Object) - Required - A filesystem-specific config object (e.g., SPIFFSConfig, SDFSConfig). ### Request Example ```cpp SPIFFSConfig cfg; cfg.setAutoFormat(false); SPIFFS.setConfig(cfg); ``` ## begin ### Description Mounts the filesystem. Must be called before any other FS APIs are used. ### Response - **return** (boolean) - Returns true if mounted successfully, false otherwise. ## end ### Description Unmounts the filesystem. Recommended before performing OTA updates. ## format ### Description Formats the filesystem. Can be called before or after begin(). ### Response - **return** (boolean) - Returns true if formatting was successful. ``` -------------------------------- ### Initializing String with Flash Content Source: https://github.com/esp8266/arduino/blob/master/doc/PROGMEM.md Example of initializing a String object using the F macro. ```cpp String mystring(F("This string is stored in flash")); ``` -------------------------------- ### Binary Generation Recipes Source: https://github.com/esp8266/arduino/blob/master/platform.txt Recipes for generating binary files, signing, and calculating sizes. ```text recipe.objcopy.hex.1.pattern="{runtime.tools.python3.path}/python3" -I "{runtime.tools.elf2bin}" --eboot "{runtime.tools.eboot}" --app "{build.path}/{build.project_name}.elf" --flash_mode {build.flash_mode} --flash_freq {build.flash_freq} --flash_size {build.flash_size} --path "{runtime.tools.xtensa-lx106-elf-gcc.path}/bin" --out "{build.path}/{build.project_name}.bin" recipe.objcopy.hex.2.pattern="{runtime.tools.python3.path}/python3" -I "{runtime.tools.signing}" --mode sign --privatekey "{build.source.path}/private.key" --bin "{build.path}/{build.project_name}.bin" --out "{build.path}/{build.project_name}.bin.signed" --legacy "{build.path}/{build.project_name}.bin.legacy_sig" recipe.objcopy.hex.3.pattern="{runtime.tools.python3.path}/python3" -X utf8 -I "{runtime.tools.sizes}" --elf "{build.path}/{build.project_name}.elf" --path "{runtime.tools.xtensa-lx106-elf-gcc.path}/bin" --mmu "{build.mmuflags}" ``` -------------------------------- ### Initialize Main Application Entry Point Source: https://github.com/esp8266/arduino/blob/master/libraries/ESP8266WebServer/examples/FSBrowser/data/edit/index.htm Handles page load events and dynamic loading of the Ace editor script if not already present. ```javascript function onBodyLoad(){ var vars = {}; var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) { vars[key] = value; }); if (typeof ace != "undefined") { var editor = createEditor("editor", vars.file, vars.lang, vars.theme); } tree = createTree("tree", editor); createHeader("header", tree, editor); refreshStatus(); }; if (typeof ace == "undefined") { console.log("Cannot load ace.js from the web, trying local copy"); var script = document.createElement('script'); script.src = "/edit/ace.js"; script.async = false; document.head.appendChild(script); } ``` -------------------------------- ### Serial Monitor Output Source: https://github.com/esp8266/arduino/blob/master/doc/esp8266wifi/scan-examples.md Example output displayed in the serial monitor after running the scan sketch. ```default Scan start ... 5 network(s) found Tech_D005107 HP-Print-A2-Photosmart 7520 ESP_0B09E3 Hack-4-fun-net UPC Wi-Free ``` -------------------------------- ### Get Full File Path Source: https://github.com/esp8266/arduino/blob/master/doc/filesystem.md Retrieves the full path of the file including directory structure. ```cpp // Filesystem: // testdir/ // file1 Dir d = LittleFS.openDir("testdir/"); File f = d.openFile("r"); // f.name() == "file1", f.fullName() == "testdir/file1" ```