### Initialize Homie Setup Source: https://github.com/labodj/homie-esp8266/blob/develop/docs/others/cpp-api-reference.md This function must be called once in your sketch's setup() function to initialize Homie. ```c++ void setup(); ``` -------------------------------- ### Run OTA Updater Script Example Source: https://github.com/labodj/homie-esp8266/blob/develop/scripts/ota_updater/README.md Example command to send an OTA firmware update to a Homie device. Replace placeholders with your specific MQTT broker details, base topic, device ID, and firmware path. ```bash python3 ota_updater.py -l localhost -u admin -d secure -t "homie/" -i "device-id" /path/to/firmware.bin ``` -------------------------------- ### Example Configuration JSON Source: https://github.com/labodj/homie-esp8266/blob/develop/docs/others/ota-configuration-updates.md This is an example of a Homie for ESP8266 configuration file. Sensitive information like Wi-Fi passwords is not included when published to the `$implementation/config` topic. ```json { "name": "Kitchen light", "wifi": { "ssid": "Network_1", "password": "I'm a Wi-Fi password!" }, "mqtt": { "host": "192.168.1.20", "port": 1883 }, "ota": { "enabled": false }, "settings": { } } ``` -------------------------------- ### Serial Logging Setup Source: https://github.com/labodj/homie-esp8266/blob/develop/docs/others/upgrade-guide-from-v1-to-v2.md If Serial logging is enabled, `Serial.begin()` must be called explicitly in your sketch. ```cpp Serial.begin() ``` -------------------------------- ### Global Input Handler Setup Source: https://github.com/labodj/homie-esp8266/blob/develop/docs/advanced-usage/input-handlers.md Implement this handler to manage all changed settable properties for all nodes. It must be set before Homie.setup(). ```c++ bool globalInputHandler(const HomieNode& node, const HomieRange& range, const String& property, const String& value) { } ``` ```c++ void setup() { Homie.setGlobalInputHandler(globalInputHandler); // before Homie.setup() // ... } ``` -------------------------------- ### Set Custom Setup Function Source: https://github.com/labodj/homie-esp8266/blob/develop/docs/others/cpp-api-reference.md Provide a custom function to be executed when Homie operates in normal mode. ```c++ Homie& setSetupFunction(std::function callback); ``` -------------------------------- ### Homie Core Setup and Loop Source: https://context7.com/labodj/homie-esp8266/llms.txt Essential functions for any Homie sketch. Homie_setFirmware must be called before Homie.setup(), and Homie.loop() must be called within the Arduino loop() function to handle all Homie operations. ```cpp #include void setup() { Serial.begin(115200); Serial << endl << endl; Homie_setFirmware("bare-minimum", "1.0.0"); // Required: set firmware name and version Homie.setup(); // Initialize Homie } void loop() { Homie.loop(); // Handle all Homie operations } ``` -------------------------------- ### Basic Light Node Example Source: https://github.com/labodj/homie-esp8266/blob/develop/README.md This sketch demonstrates how to set up a simple light node using the Homie library. It includes handling the 'on' property to control a relay and reporting the status. Ensure the PIN_RELAY is correctly defined for your hardware. ```c++ #include const int PIN_RELAY = 5; HomieNode lightNode("light", "Light", "switch"); bool lightOnHandler(const HomieRange& range, const String& value) { if (value != "true" && value != "false") return false; bool on = (value == "true"); digitalWrite(PIN_RELAY, on ? HIGH : LOW); lightNode.getProperty("on").send(value); Homie.getLogger() << "Light is " << (on ? "on" : "off") << endl; return true; } void setup() { Serial.begin(115200); Serial << endl << endl; pinMode(PIN_RELAY, OUTPUT); digitalWrite(PIN_RELAY, LOW); Homie_setFirmware("awesome-relay", "1.0.0"); lightNode.advertise("on").setName("On").setDatatype("boolean").settable(lightOnHandler); Homie.setup(); } void loop() { Homie.loop(); } ``` -------------------------------- ### Set up and Loop Functions for Sensor Data Source: https://github.com/labodj/homie-esp8266/blob/develop/docs/quickstart/getting-started.md Abstract network and mode checks for setup and loop functions. `setupHandler` runs once when the device is in normal mode and connected, while `loopHandler` runs repeatedly under the same conditions. ```cpp Homie.setSetupFunction(setupHandler); Homie.setLoopFunction(loopHandler); ``` -------------------------------- ### JSON Configuration for Custom Setting Source: https://github.com/labodj/homie-esp8266/blob/develop/docs/advanced-usage/custom-settings.md Example JSON configuration to provide a value for the 'percentage' setting. This setting is optional because a default value was provided. ```json { "settings": { "percentage": 75 } } ``` -------------------------------- ### Install Dependencies for OTA Updater Source: https://github.com/labodj/homie-esp8266/blob/develop/scripts/ota_updater/README.md Installs the necessary Python packages required for the OTA updater script. Ensure you have Python 3 installed. ```bash python3 -m pip install -r requirements.txt ``` -------------------------------- ### GET /device-info Source: https://github.com/labodj/homie-esp8266/blob/develop/docs/configuration/http-json-api.md Get some information on the device. ```APIDOC ## GET /device-info ### Description Get some information on the device. ### Method GET ### Endpoint /device-info ### Response #### Success Response (200) (application/json) ```json { "hardware_device_id": "52a8fa5d", "homie_esp8266_version": "3.1.0", "firmware": { "name": "awesome-device", "version": "1.0.0" }, "nodes": [ { "id": "light", "type": "light" } ], "settings": [ { "name": "timeout", "description": "Timeout in seconds", "type": "ulong", "required": false, "default": 10 } ] } ``` #### Type Definitions `type` can be one of the following: * `bool`: a boolean * `ulong`: an unsigned long * `long`: a long * `double`: a double * `string`: a string #### Note If a setting is not required, the `default` field will always be set. ``` -------------------------------- ### Property Input Handler Setup Source: https://github.com/labodj/homie-esp8266/blob/develop/docs/advanced-usage/input-handlers.md This handler manages changes for a specific settable property of a specific node. It is set using the .settable() method on an advertised property before Homie.setup(). ```c++ bool propertyInputHandler(const HomieRange& range, const String& value) { } ``` ```c++ HomieNode node("id", "type"); void setup() { node.advertise("property").settable(propertyInputHandler); // before Homie.setup() // ... } ``` -------------------------------- ### PUT /wifi/connect Source: https://github.com/labodj/homie-esp8266/blob/develop/docs/configuration/http-json-api.md Initiates the connection of the device to the Wi-Fi network while in configuration mode. This request is not synchronous and the result (Wi-Fi connected or not) must be obtained by with GET /wifi/status. ```APIDOC ## PUT /wifi/connect ### Description Initiates the connection of the device to the Wi-Fi network while in configuration mode. This request is not synchronous and the result (Wi-Fi connected or not) must be obtained by with `GET /wifi/status`. ### Method PUT ### Endpoint /wifi/connect ### Request Body (application/json) ```json { "ssid": "My_SSID", "password": "my-passw0rd" } ``` ### Response #### Success Response (202) Accepted (application/json) ```json { "success": true } ``` #### Error Response (400) In case of error in the payload (application/json) ```json { "success": false, "error": "Reason why the payload is invalid" } ``` ``` -------------------------------- ### Install Homie with PlatformIO Source: https://context7.com/labodj/homie-esp8266/llms.txt Add Homie to your ESP32/ESP8266 project by specifying the git dependency in your platformio.ini file. Optionally, increase the MQTT ACK queue size for high-volume advertisement bursts. ```ini [env:esp32dev] platform = https://github.com/pioarduino/platform-espressif32/releases/download/stable/platform-espressif32.zip framework = arduino board = esp32dev lib_deps = https://github.com/labodj/homie-esp8266.git#develop ; Optional: Increase MQTT ACK queue for large advertisement bursts build_flags = -D HOMIE_PENDING_MQTT_ACK_QUEUE_SIZE=64 ``` -------------------------------- ### Homie Configuration JSON Source: https://context7.com/labodj/homie-esp8266/llms.txt Example of the JSON file used for device configuration, including Wi-Fi, MQTT, OTA, and custom settings. This file is typically stored at `/homie/config.json`. ```json { "name": "Kitchen light", "device_id": "kitchen-light", "device_stats_interval": 60, "wifi": { "ssid": "Network_1", "password": "I'm a Wi-Fi password!", "bssid": "DE:AD:BE:EF:BA:BE", "channel": 1, "ip": "192.168.1.5", "mask": "255.255.255.0", "gw": "192.168.1.1", "dns1": "8.8.8.8", "dns2": "8.8.4.4" }, "mqtt": { "host": "192.168.1.10", "port": 1883, "base_topic": "homie/", "auth": true, "username": "user", "password": "pass", "ssl": true, "ssl_fingerprint": "a27992d3420c89f293d351378ba5f5675f74fe3c" }, "ota": { "enabled": true }, "settings": { "temperatureInterval": 600 } } ``` -------------------------------- ### Device Control Functions Source: https://github.com/labodj/homie-esp8266/blob/develop/docs/others/cpp-api-reference.md Functions to control the Homie device's state after setup, including reset, sleep, and status checks. ```APIDOC ## POST /device/reset ### Description Flags the device for reset. ### Method POST ### Endpoint /device/reset ### Parameters None ### Request Example None ### Response #### Success Response (200) None #### Response Example None ``` ```APIDOC ## POST /device/setIdle ### Description Sets the device as idle or not. Useful at runtime to prevent resets when other operations are in progress. ### Method POST ### Endpoint /device/setIdle ### Parameters #### Request Body - **idle** (boolean) - Required - Device in an idle state or not. ### Request Example ```json { "idle": true } ``` ### Response #### Success Response (200) None #### Response Example None ``` ```APIDOC ## POST /device/prepareToSleep ### Description Prepares the device for deep sleep. Ensures messages are sent and disconnects cleanly from the MQTT broker, triggering a `READY_TO_SLEEP` event when done. ### Method POST ### Endpoint /device/prepareToSleep ### Parameters None ### Request Example None ### Response #### Success Response (200) None #### Response Example None ``` ```APIDOC ## POST /device/doDeepSleep ### Description Puts the device into deep sleep. Ensures the Serial is flushed. ### Method POST ### Endpoint /device/doDeepSleep ### Parameters #### Query Parameters - **time_us** (uint64_t) - Optional - Duration in microseconds for deep sleep. Defaults to 0 (indefinite sleep). - **mode** (RFMode) - Optional - RF mode for deep sleep. Defaults to `RF_DEFAULT`. ### Request Example None ### Response #### Success Response (200) None #### Response Example None ``` ```APIDOC ## GET /device/isConfigured ### Description Checks if the device is in `normal` mode and configured. ### Method GET ### Endpoint /device/isConfigured ### Parameters None ### Request Example None ### Response #### Success Response (200) - **configured** (boolean) - True if the device is configured, false otherwise. #### Response Example ```json { "configured": true } ``` ``` ```APIDOC ## GET /device/isConnected ### Description Checks if the device is in `normal` mode, configured, and connected to the MQTT broker. ### Method GET ### Endpoint /device/isConnected ### Parameters None ### Request Example None ### Response #### Success Response (200) - **connected** (boolean) - True if the device is connected, false otherwise. #### Response Example ```json { "connected": true } ``` ``` ```APIDOC ## GET /device/configuration ### Description Retrieves the device's configuration struct. Use with caution; do not attempt to modify this struct directly. ### Method GET ### Endpoint /device/configuration ### Parameters None ### Request Example None ### Response #### Success Response (200) - **configuration** (ConfigStruct) - The device's configuration structure. #### Response Example ```json { "configuration": { "field1": "value1", "field2": 123 } } ``` ``` ```APIDOC ## GET /device/mqttClient ### Description Gets the underlying `AsyncMqttClient` object. ### Method GET ### Endpoint /device/mqttClient ### Parameters None ### Request Example None ### Response #### Success Response (200) - **mqttClient** (AsyncMqttClient) - The `AsyncMqttClient` object. #### Response Example ```json { "mqttClient": "" } ``` ``` ```APIDOC ## GET /device/logger ### Description Gets the underlying `Logger` object, which is a wrapper around `Serial` by default. ### Method GET ### Endpoint /device/logger ### Parameters None ### Request Example None ### Response #### Success Response (200) - **logger** (Logger) - The `Logger` object. #### Response Example ```json { "logger": "" } ``` ``` -------------------------------- ### HTTP API - Get Device Information Source: https://context7.com/labodj/homie-esp8266/llms.txt Retrieves detailed information about the device, including hardware ID, Homie version, firmware details, and configured nodes/settings. The response is in JSON format. ```bash curl http://192.168.123.1/device-info ``` -------------------------------- ### Node Input Handler Setup Source: https://github.com/labodj/homie-esp8266/blob/develop/docs/advanced-usage/input-handlers.md This handler manages changed settable properties for a specific node. It is defined when creating the HomieNode instance. ```c++ bool nodeInputHandler(const HomieRange& range, const String& property, const String& value) { } ``` ```c++ HomieNode node("id", "type", false, 0, 0, nodeInputHandler); ``` -------------------------------- ### Handle Homie Events Source: https://github.com/labodj/homie-esp8266/blob/develop/docs/advanced-usage/events.md Implement the `onHomieEvent` function to handle various Homie events. This example shows how to react when statistics are sent. ```cpp void onHomieEvent(const HomieEvent& event) { switch (event.type) { case HomieEventType::SENDING_STATISTICS: // Do whatever you want when statistics are sent in normal mode break; } } void setup() { Homie.onEvent(onHomieEvent); // before Homie.setup() // ... } ``` -------------------------------- ### Get Device Info Source: https://github.com/labodj/homie-esp8266/blob/develop/docs/configuration/http-json-api.md Retrieve information about the device, including hardware ID, firmware version, and node details. The response is in JSON format. ```json { "hardware_device_id": "52a8fa5d", "homie_esp8266_version": "3.1.0", "firmware": { "name": "awesome-device", "version": "1.0.0" }, "nodes": [ { "id": "light", "type": "light" } ], "settings": [ { "name": "timeout", "description": "Timeout in seconds", "type": "ulong", "required": false, "default": 10 } ] } ``` -------------------------------- ### MQTT Topic Structure for Range Properties Source: https://github.com/labodj/homie-esp8266/blob/develop/docs/advanced-usage/range-properties.md When using range properties, Homie automatically structures MQTT topics to reflect the device type and properties, including the defined range. This example shows the expected topic and property structure for an LED strip. ```text homie//strip/$type strip homie//strip/$properties led[1-100]:settable ``` -------------------------------- ### Add Homie to PlatformIO Project Source: https://github.com/labodj/homie-esp8266/blob/develop/README.md Include the Homie library as a git dependency in your PlatformIO project configuration file (`platformio.ini`). This example shows how to add the maintained fork for ESP32. ```ini [env:myboard] platform = https://github.com/pioarduino/platform-espressif32/releases/download/stable/platform-espressif32.zip board = ... framework = arduino lib_deps = https://github.com/labodj/homie-esp8266.git#develop ``` -------------------------------- ### Get Node Type Source: https://github.com/labodj/homie-esp8266/blob/develop/docs/others/cpp-api-reference.md Returns the type of the HomieNode. ```c++ const char* getType() const; ``` -------------------------------- ### Get Node ID Source: https://github.com/labodj/homie-esp8266/blob/develop/docs/others/cpp-api-reference.md Returns the ID of the HomieNode. ```c++ const char* getId() const; ``` -------------------------------- ### GET /networks Source: https://github.com/labodj/homie-esp8266/blob/develop/docs/configuration/http-json-api.md Retrieve the Wi-Fi networks the device can see. ```APIDOC ## GET /networks ### Description Retrieve the Wi-Fi networks the device can see. ### Method GET ### Endpoint /networks ### Response #### Success Response (200) (application/json) ```json { "networks": [ { "ssid": "Network_2", "rssi": -82, "encryption": "wep" }, { "ssid": "Network_1", "rssi": -57, "encryption": "wpa" }, { "ssid": "Network_3", "rssi": -65, "encryption": "wpa2" }, { "ssid": "Network_5", "rssi": -94, "encryption": "none" }, { "ssid": "Network_4", "rssi": -89, "encryption": "auto" } ] } ``` #### Error Response (503) In case the initial Wi-Fi scan is not finished on the device (application/json) ```json { "error": "Initial Wi-Fi scan not finished yet" } ``` ``` -------------------------------- ### GET /heart Source: https://github.com/labodj/homie-esp8266/blob/develop/docs/configuration/http-json-api.md This endpoint is useful to ensure we are connected to the device AP. ```APIDOC ## GET /heart ### Description This is useful to ensure we are connected to the device AP. ### Method GET ### Endpoint /heart ### Response #### Success Response (204) No Content ``` -------------------------------- ### Send Full Configuration via HTTP PUT Source: https://context7.com/labodj/homie-esp8266/llms.txt Use this command to send the entire device configuration to the Homie device. Ensure the config.json file exists and is correctly formatted. ```bash curl -X PUT http://192.168.123.1/config \ -H "Content-Type: application/json" \ -d @config.json ``` -------------------------------- ### Get Logger Source: https://github.com/labodj/homie-esp8266/blob/develop/docs/others/cpp-api-reference.md Retrieves the underlying `Logger` object, which defaults to wrapping `Serial`. ```c++ Logger& getLogger(); ``` -------------------------------- ### Homie_setFirmware Function Source: https://github.com/labodj/homie-esp8266/blob/develop/docs/others/upgrade-guide-from-v1-to-v2.md Replace `Homie.setFirmware(name, version)` with `Homie_setFirmware(name, version)` for firmware information. ```cpp Homie_setFirmware(name, version) ``` -------------------------------- ### Get MQTT Client Source: https://github.com/labodj/homie-esp8266/blob/develop/docs/others/cpp-api-reference.md Retrieves the underlying `AsyncMqttClient` object for advanced MQTT operations. ```c++ AsyncMqttClient& getMqttClient(); ``` -------------------------------- ### Organize Homie Sketch Safely Source: https://github.com/labodj/homie-esp8266/blob/develop/docs/advanced-usage/miscellaneous.md Structure your sketch using Homie's provided setupHandler() and loopHandler() functions for safe operation. Avoid placing significant code directly in the main loop() to prevent MCU crashes. setupHandler() runs after WiFi connection, while loopHandler() runs in the main loop after setupHandler() completes. ```c++ #include void setupHandler() { // Code which should run AFTER the WiFi is connected. } void loopHandler() { // Code which should run in normal loop(), after setupHandler() finished. } void setup() { Serial.begin(115200); Serial << endl << endl; Homie_setFirmware("bare-minimum", "1.0.0"); // The underscore is not a typo! See Magic bytes Homie.setSetupFunction(setupHandler).setLoopFunction(loopHandler); // Code which should run BEFORE the WiFi is connected. Homie.setup(); } void loop() { Homie.loop(); } ``` -------------------------------- ### Set Standalone Mode Source: https://github.com/labodj/homie-esp8266/blob/develop/docs/others/cpp-api-reference.md Configure Homie to boot in standalone mode. The device must be reset to enter configuration mode. ```c++ Homie& setStandalone(); ``` -------------------------------- ### Get Configuration Struct Source: https://github.com/labodj/homie-esp8266/blob/develop/docs/others/cpp-api-reference.md Retrieves the configuration struct. Use with caution; never attempt to modify it directly. ```c++ const ConfigStruct& getConfiguration() const; ``` -------------------------------- ### GET /wifi/status Source: https://github.com/labodj/homie-esp8266/blob/develop/docs/configuration/http-json-api.md Returns the current Wi-Fi connection status. Helpful when monitoring Wi-Fi connectivity after PUT /wifi/connect. ```APIDOC ## GET /wifi/status ### Description Returns the current Wi-Fi connection status. Helpful when monitoring Wi-Fi connectivity after `PUT /wifi/connect`. ### Method GET ### Endpoint /wifi/status ### Response #### Success Response (200) (application/json) ```json { "status": "connected" } ``` #### Status Definitions `status` might be one of the following: * `idle` * `connect_failed` * `connection_lost` * `no_ssid_available` * `connected` along with a `local_ip` field * `disconnected` ``` -------------------------------- ### Set Firmware Name and Version Source: https://github.com/labodj/homie-esp8266/blob/develop/docs/others/cpp-api-reference.md Set the name and version of your firmware. This is mandatory for OTA updates and should be called before Homie.setup(). Note that this is a macro. ```c++ void Homie_setFirmware(const char* name, const char* version); ``` -------------------------------- ### Handle Homie Lifecycle Events Source: https://context7.com/labodj/homie-esp8266/llms.txt Hook into Homie lifecycle events such as Wi-Fi connection, MQTT status, and OTA updates. This must be called before Homie.setup(). ```cpp #include void onHomieEvent(const HomieEvent& event) { switch (event.type) { case HomieEventType::STANDALONE_MODE: Serial << "Standalone mode started" << endl; break; case HomieEventType::CONFIGURATION_MODE: Serial << "Configuration mode started" << endl; break; case HomieEventType::NORMAL_MODE: Serial << "Normal mode started" << endl; break; case HomieEventType::OTA_STARTED: Serial << "OTA started" << endl; break; case HomieEventType::OTA_PROGRESS: Serial << "OTA progress: " << event.sizeDone << "/" << event.sizeTotal << endl; break; case HomieEventType::OTA_FAILED: Serial << "OTA failed" << endl; break; case HomieEventType::OTA_SUCCESSFUL: Serial << "OTA successful" << endl; break; case HomieEventType::ABOUT_TO_RESET: Serial << "About to reset" << endl; break; case HomieEventType::WIFI_CONNECTED: Serial << "Wi-Fi connected, IP: " << event.ip << endl; break; case HomieEventType::WIFI_DISCONNECTED: Serial << "Wi-Fi disconnected, reason: " << (int8_t)event.wifiReason << endl; break; case HomieEventType::MQTT_READY: Serial << "MQTT connected" << endl; break; case HomieEventType::MQTT_DISCONNECTED: Serial << "MQTT disconnected, reason: " << (int8_t)event.mqttReason << endl; break; case HomieEventType::MQTT_PACKET_ACKNOWLEDGED: Serial << "MQTT packet acknowledged, packetId: " << event.packetId << endl; break; case HomieEventType::READY_TO_SLEEP: Serial << "Ready to sleep" << endl; break; case HomieEventType::SENDING_STATISTICS: Serial << "Sending statistics" << endl; break; } } void setup() { Serial.begin(115200); Serial << endl << endl; Homie.disableLogging(); Homie_setFirmware("events-test", "1.0.0"); Homie.onEvent(onHomieEvent); // Must be before Homie.setup() Homie.setup(); } void loop() { Homie.loop(); } ``` -------------------------------- ### Get Homie Setting Value Source: https://github.com/labodj/homie-esp8266/blob/develop/docs/others/cpp-api-reference.md Retrieves the value of a Homie setting. Returns the default value if optional and not provided, or the provided value. ```c++ T get() const; ``` -------------------------------- ### Define and Configure a Custom Setting Source: https://github.com/labodj/homie-esp8266/blob/develop/docs/advanced-usage/custom-settings.md Define a custom setting with a default value and a validator. The default value must be set before Homie.setup(). ```c++ HomieSetting percentageSetting("percentage", "A simple percentage"); // id, description void setup() { percentageSetting.setDefaultValue(50).setValidator([] (long candidate) { return (candidate >= 0) && (candidate <= 100); }); Homie.setup(); } ``` -------------------------------- ### Device Implementation and Version Source: https://github.com/labodj/homie-esp8266/blob/develop/docs/others/homie-implementation-specifics.md Information about the device implementation identifier and how to retrieve the fork version. ```APIDOC ## Device Implementation ### Description The `$implementation` identifier is platform-dependent. ### Method PUBLISH/SUBSCRIBE ### Endpoint `$implementation` ### Parameters #### Query Parameters - **implementation** (string) - Required - The platform identifier (`esp32` or `esp8266`). ## Version ### Description Retrieve the maintained fork version. ### Method SUBSCRIBE ### Endpoint `$implementation/version` ### Response Example ``` "2.0.0" ``` ``` -------------------------------- ### Get Wi-Fi Status Source: https://github.com/labodj/homie-esp8266/blob/develop/docs/configuration/http-json-api.md Retrieve the current Wi-Fi connection status. The response includes the status and optionally the local IP address if connected. ```json { "status": "connected" } ``` -------------------------------- ### Define Custom Configuration Settings with HomieSetting Source: https://context7.com/labodj/homie-esp8266/llms.txt Create custom configuration settings that can be managed via JSON or the Configuration API. Settings support validation and default values, making them optional if a default is provided. ```cpp #include const int DEFAULT_TEMPERATURE_INTERVAL = 300; unsigned long lastTemperatureSent = 0; HomieNode temperatureNode("temperature", "Temperature", "temperature"); HomieSetting temperatureIntervalSetting("temperatureInterval", "The temperature interval in seconds"); void loopHandler() { if (millis() - lastTemperatureSent >= temperatureIntervalSetting.get() * 1000UL || lastTemperatureSent == 0) { float temperature = 22.5; Homie.getLogger() << "Temperature: " << temperature << " C" << endl; temperatureNode.setProperty("degrees").send(String(temperature)); lastTemperatureSent = millis(); } } void setup() { Serial.begin(115200); Serial << endl << endl; Homie_setFirmware("temperature-setting", "1.0.0"); Homie.setLoopFunction(loopHandler); temperatureNode.advertise("degrees") .setDatatype("float") .setUnit("C"); // Set default value (makes setting optional) and validator temperatureIntervalSetting.setDefaultValue(DEFAULT_TEMPERATURE_INTERVAL) .setValidator([] (long candidate) { return candidate > 0; }); Homie.setup(); } void loop() { Homie.loop(); } // Update via MQTT: homie//$implementation/config/set // Payload: {"settings":{"temperatureInterval":600}} ``` -------------------------------- ### Check if Setting Was Provided Source: https://github.com/labodj/homie-esp8266/blob/develop/docs/others/cpp-api-reference.md Returns `true` if the Homie setting was provided by the user, `false` otherwise. ```c++ bool wasProvided() const; ``` -------------------------------- ### Device Reset Source: https://github.com/labodj/homie-esp8266/blob/develop/docs/others/homie-implementation-specifics.md Instructions on how to reset the device using MQTT. ```APIDOC ## Reset ### Description You can publish a `true` to this topic to reset the device. ### Method PUBLISH ### Endpoint `$implementation/reset` ### Request Body - **payload** (boolean) - Required - Set to `true` to trigger a device reset. ### Request Example ```json { "payload": true } ``` ``` -------------------------------- ### Configuration Management Source: https://github.com/labodj/homie-esp8266/blob/develop/docs/others/homie-implementation-specifics.md Details on how to retrieve and update the device configuration. ```APIDOC ## Configuration ### Description Manage the device configuration via MQTT topics. ### Method SUBSCRIBE/PUBLISH ### Endpoint `$implementation/config` and `$implementation/config/set` ### Parameters #### `$implementation/config` (SUBSCRIBE) - **Description**: The `config.json` is published here, with sensitive fields stripped. #### `$implementation/config/set` (PUBLISH) - **Description**: You can update the `config.json` by sending incremental JSON on this topic. ### Request Example (`$implementation/config/set`) ```json { "wifi": { "password": "new_wifi_password" } } ``` ### Response Example (`$implementation/config`) ```json { "name": "mydevice", "mqtt": { "host": "mqtt.local", "port": 1883 }, "wifi": { "ssid": "MyNetwork" } } ``` ``` -------------------------------- ### Redirect Homie Logging Output Source: https://github.com/labodj/homie-esp8266/blob/develop/docs/advanced-usage/logging.md Use `Homie.setLoggingPrinter()` before `Homie.setup()` to direct Homie's debug messages to a different `Print` instance, such as `Serial2`. You are responsible for initializing the target `Print` instance. ```c++ void setup() { Homie.setLoggingPrinter(&Serial2); // before Homie.setup() // ... } ``` -------------------------------- ### HTTP API - Get Available Wi-Fi Networks Source: https://context7.com/labodj/homie-esp8266/llms.txt Scans for and lists available Wi-Fi networks in the vicinity. The response includes SSID, signal strength (RSSI), and encryption type for each network. ```bash curl http://192.168.123.1/networks ``` -------------------------------- ### Check Device Configuration and Connectivity Source: https://github.com/labodj/homie-esp8266/blob/develop/docs/advanced-usage/miscellaneous.md Use Homie.isConfigured() and Homie.isConnected() within your loop() function to determine the device's operational state. This is useful for conditional logic based on whether the device is set up and has a network connection. ```c++ void loop() { if (Homie.isConfigured()) { // The device is configured, in normal mode if (Homie.isConnected()) { // The device is connected } else { // The device is not connected } } else { // The device is not configured, in either configuration or standalone mode } } ``` -------------------------------- ### OTA Firmware Update via MQTT Source: https://context7.com/labodj/homie-esp8266/llms.txt Initiate an Over-The-Air firmware update by publishing the firmware file to the specified MQTT topic. The topic includes the MD5 checksum of the firmware. Ensure firmware.bin is the correct file. ```bash mosquitto_pub -t "homie//$implementation/ota/firmware/" \ -f firmware.bin ``` -------------------------------- ### Logging and Feedback Control Source: https://github.com/labodj/homie-esp8266/blob/develop/docs/others/cpp-api-reference.md Functions to control Homie's logging and LED feedback. ```APIDOC ## Homie& disableLogging() ### Description Disable Homie logging. ### Method Homie& ### Endpoint N/A ### Parameters None ### Request Example ```c++ void setup() { Homie.disableLogging(); Homie.setup(); } ``` ### Response Returns the Homie instance for chaining. ``` ```APIDOC ## Homie& setLoggingPrinter(Print* printer) ### Description Set the Print instance used for logging. ### Method Homie& ### Endpoint N/A ### Parameters * **printer** (Print*) - Print instance to log to. By default, `Serial` is used. ### Request Example ```c++ void setup() { Serial.begin(115200); Homie.setLoggingPrinter(&Serial); Homie.setup(); } ``` ### Response Returns the Homie instance for chaining. ``` ```APIDOC ## Homie& disableLedFeedback() ### Description Disable the built-in LED feedback indicating the Homie for ESP8266 state. ### Method Homie& ### Endpoint N/A ### Parameters None ### Request Example ```c++ void setup() { Homie.disableLedFeedback(); Homie.setup(); } ``` ### Response Returns the Homie instance for chaining. ``` ```APIDOC ## Homie& setLedPin(uint8_t pin, uint8_t on) ### Description Set pin of the LED to control. ### Method Homie& ### Endpoint N/A ### Parameters * **pin** (uint8_t) - LED to control * **on** (uint8_t) - state when the light is on (HIGH or LOW) ### Request Example ```c++ void setup() { Homie.setLedPin(LED_BUILTIN, HIGH); Homie.setup(); } ``` ### Response Returns the Homie instance for chaining. ``` -------------------------------- ### Configuration and Handlers Source: https://github.com/labodj/homie-esp8266/blob/develop/docs/others/cpp-api-reference.md Functions for setting configuration options and custom handlers. ```APIDOC ## Homie& setConfigurationApPassword(const char* password) ### Description Set the configuration AP password. ### Method Homie& ### Endpoint N/A ### Parameters * **password** (const char*) - the configuration AP password ### Request Example ```c++ void setup() { Homie.setConfigurationApPassword("mySecurePassword"); Homie.setup(); } ``` ### Response Returns the Homie instance for chaining. ``` ```APIDOC ## Homie& setGlobalInputHandler(std::function handler) ### Description Set input handler for subscribed properties. ### Method Homie& ### Endpoint N/A ### Parameters * **handler** (std::function) - Global input handler * **node** (const HomieNode&) - Name of the node getting updated * **property** (const String&) - Property of the node getting updated * **range** (const HomieRange&) - Range of the property of the node getting updated * **value** (const String&) - Value of the new property ### Request Example ```c++ bool inputHandler(const HomieNode& node, const HomieRange& range, const String& property, const String& value) { // Handle input return true; } void setup() { Homie.setGlobalInputHandler(inputHandler); Homie.setup(); } ``` ### Response Returns the Homie instance for chaining. ``` ```APIDOC ## Homie& setBroadcastHandler(std::function handler) ### Description Set broadcast handler. ### Method Homie& ### Endpoint N/A ### Parameters * **handler** (std::function) - Broadcast handler * **level** (const String&) - Level of the broadcast * **value** (const String&) - Value of the broadcast ### Request Example ```c++ bool broadcastHandler(const String& level, const String& value) { // Handle broadcast return true; } void setup() { Homie.setBroadcastHandler(broadcastHandler); Homie.setup(); } ``` ### Response Returns the Homie instance for chaining. ``` ```APIDOC ## Homie& onEvent(std::function callback) ### Description Set the event handler. Useful if you want to hook to Homie events. ### Method Homie& ### Endpoint N/A ### Parameters * **callback** (std::function) - Event handler ### Request Example ```c++ void eventHandler(const HomieEvent& event) { // Handle event } void setup() { Homie.onEvent(eventHandler); Homie.setup(); } ``` ### Response Returns the Homie instance for chaining. ``` -------------------------------- ### Enable Standalone Mode in Homie for ESP8266 Source: https://github.com/labodj/homie-esp8266/blob/develop/docs/advanced-usage/standalone-mode.md Call `Homie.setStandalone()` before `Homie.setup()` to enable standalone mode. This prevents the device from booting into configuration mode on initial startup. ```c++ void setup() { Homie.setStandalone(); // before Homie.setup() // ... } ``` -------------------------------- ### Get Wi-Fi Networks Source: https://github.com/labodj/homie-esp8266/blob/develop/docs/configuration/http-json-api.md Retrieve a list of available Wi-Fi networks. The response includes SSID, RSSI, and encryption type. A '503 Service Unavailable' error is returned if the initial Wi-Fi scan is not finished. ```json { "networks": [ { "ssid": "Network_2", "rssi": -82, "encryption": "wep" }, { "ssid": "Network_1", "rssi": -57, "encryption": "wpa" }, { "ssid": "Network_3", "rssi": -65, "encryption": "wpa2" }, { "ssid": "Network_5", "rssi": -94, "encryption": "none" }, { "ssid": "Network_4", "rssi": -89, "encryption": "auto" } ] } ``` ```json { "error": "Initial Wi-Fi scan not finished yet" } ``` -------------------------------- ### Core Homie Functions Source: https://github.com/labodj/homie-esp8266/blob/develop/docs/others/cpp-api-reference.md Essential functions for initializing and running Homie. ```APIDOC ## void setup() ### Description Setup Homie. ### Method void ### Endpoint N/A ### Parameters None ### Request Example ```c++ void setup() { Homie.setup(); } ``` ### Response None ``` ```APIDOC ## void loop() ### Description Handle Homie work. ### Method void ### Endpoint N/A ### Parameters None ### Request Example ```c++ void loop() { Homie.loop(); } ``` ### Response None ``` -------------------------------- ### PlatformIO Configuration for Homie ESP32 Fork Source: https://github.com/labodj/homie-esp8266/blob/develop/docs/quickstart/getting-started.md This configuration is for PlatformIO and uses a git dependency for the Homie ESP8266 fork, primarily targeting ESP32. Ensure you have the correct platform and framework specified. ```ini platform = https://github.com/pioarduino/platform-espressif32/releases/download/stable/platform-espressif32.zip framework = arduino board = esp32dev lib_deps = https://github.com/labodj/homie-esp8266.git#develop ``` -------------------------------- ### Enable Transparent Proxy Mode via HTTP PUT Source: https://context7.com/labodj/homie-esp8266/llms.txt This command enables transparent proxy mode on the Homie device. The request body must be a JSON object with an 'enable' property set to true. ```bash curl -X PUT http://192.168.123.1/proxy/control \ -H "Content-Type: application/json" \ -d '{"enable": true}' ``` -------------------------------- ### JSON Configuration File Source: https://context7.com/labodj/homie-esp8266/llms.txt Details the structure and content of the `config.json` file used for device configuration, including Wi-Fi, MQTT, OTA, and custom settings. ```APIDOC ## JSON Configuration File ### Description The device configuration is stored at `/homie/config.json` on the filesystem. Configure Wi-Fi, MQTT, OTA, and custom settings. ### File Path `/homie/config.json` ### Structure ```json { "name": "Kitchen light", "device_id": "kitchen-light", "device_stats_interval": 60, "wifi": { "ssid": "Network_1", "password": "I'm a Wi-Fi password!", "bssid": "DE:AD:BE:EF:BA:BE", "channel": 1, "ip": "192.168.1.5", "mask": "255.255.255.0", "gw": "192.168.1.1", "dns1": "8.8.8.8", "dns2": "8.8.4.4" }, "mqtt": { "host": "192.168.1.10", "port": 1883, "base_topic": "homie/", "auth": true, "username": "user", "password": "pass", "ssl": true, "ssl_fingerprint": "a27992d3420c89f293d351378ba5f5675f74fe3c" }, "ota": { "enabled": true }, "settings": { "temperatureInterval": 600 } } ``` ``` -------------------------------- ### Connect to Wi-Fi Source: https://github.com/labodj/homie-esp8266/blob/develop/docs/configuration/http-json-api.md Initiate a connection to a Wi-Fi network. Requires SSID and password in the request body. Success returns '202 Accepted', while errors return '400 Bad Request'. ```json { "ssid": "My_SSID", "password": "my-passw0rd" } ``` ```json { "success": true } ``` ```json { "success": false, "error": "Reason why the payload is invalid" } ``` -------------------------------- ### Set Custom LED Pin for Feedback Source: https://github.com/labodj/homie-esp8266/blob/develop/docs/advanced-usage/built-in-led.md Use `Homie.setLedPin(pin, state)` before `Homie.setup()` to specify a different pin for LED feedback and its active state. The second parameter indicates the state of the pin when the LED is on. ```c++ void setup() { Homie.setLedPin(16, HIGH); // before Homie.setup() -- 2nd param is the state of the pin when the LED is o // ... } ``` -------------------------------- ### Save Configuration Source: https://github.com/labodj/homie-esp8266/blob/develop/docs/configuration/http-json-api.md Save the device configuration. A successful response is '200 OK', while errors return '400 Bad Request' or '403 Forbidden' with a reason. ```json { "success": true } ``` ```json { "success": false, "error": "Reason why the payload is invalid" } ``` ```json { "success": false, "error": "Device already configured" } ``` -------------------------------- ### HTTP API - Test Wi-Fi Connection Source: https://context7.com/labodj/homie-esp8266/llms.txt Initiates a Wi-Fi connection attempt using the provided SSID and password. Expects a '202 Accepted' response upon successful request submission. ```bash curl -X PUT http://192.168.123.1/wifi/connect \ -H "Content-Type: application/json" \ -d '{"ssid": "Network_1", "password": "my-password"}' ``` -------------------------------- ### Advertise and Handle Range Properties for LED Strip Source: https://github.com/labodj/homie-esp8266/blob/develop/docs/advanced-usage/range-properties.md Use `advertiseRange` to declare a property that applies to a range of devices. The `settable` handler function is called when a value is published to a specific device within the range. Ensure this is called before `Homie.setup()`. ```c++ HomieNode stripNode("strip", "strip"); bool ledHandler(const HomieRange& range, const String& value) { Homie.getLogger() << "LED " << range.index << " set to " << value << endl; // Now, let's update the actual state of the given led stripNode.setProperty("led").setRange(range).send(value); } void setup() { stripNode.advertiseRange("led", 1, 100).settable(ledHandler); // before Homie.setup() } ``` -------------------------------- ### Check if Device is Configured Source: https://github.com/labodj/homie-esp8266/blob/develop/docs/others/cpp-api-reference.md Checks if the device is in `normal` mode and has been configured. ```c++ bool isConfigured() const; ``` -------------------------------- ### Access Device Configuration Structure Source: https://github.com/labodj/homie-esp8266/blob/develop/docs/advanced-usage/miscellaneous.md Define and access the configuration structure of the Homie device. This struct provides access to details like device name, WiFi credentials, MQTT settings, and OTA status. ```c++ struct ConfigStruct { char* name; char* deviceId; struct WiFi { char* ssid; char* password; } wifi; struct MQTT { struct Server { char* host; uint16_t port; } server; char* baseTopic; bool auth; char* username; char* password; } mqtt; struct OTA { bool enabled; } ota; }; // Example usage: // Homie.getConfiguration().wifi.ssid; ``` -------------------------------- ### Device Configuration API Source: https://github.com/labodj/homie-esp8266/blob/develop/docs/configuration/http-json-api.md This API allows for configuring device settings, such as enabling or disabling features. It is crucial to keep requests and responses minimal due to limited RAM. ```APIDOC ## POST /device/config ### Description Allows for configuration of device settings. Due to memory limitations, payloads should be as small as possible. ### Method POST ### Endpoint /device/config ### Request Body - **enable** (boolean) - Required - Specifies whether to enable or disable a feature. ### Request Example ```json { "enable": true } ``` ### Response #### Success Response (200) - **success** (boolean) - Indicates if the operation was successful. #### Response Example ```json { "success": true } ``` #### Error Response (400) - **success** (boolean) - Indicates if the operation was successful. - **error** (string) - Reason why the payload is invalid. #### Response Example ```json { "success": false, "error": "Reason why the payload is invalid" } ``` ``` -------------------------------- ### Control LED Strips with Homie Range Properties Source: https://context7.com/labodj/homie-esp8266/llms.txt Use range properties to control multiple LEDs in a strip through indexed MQTT topics. Ensure the index is within the valid range and the value is 'on' or 'off'. ```cpp #include const unsigned int NUMBER_OF_LED = 4; const unsigned char LED_PINS[NUMBER_OF_LED] = { 16, 5, 4, 0 }; // Create range node: id, name, type, isRange=true, lower=1, upper=4 HomieNode stripNode("strip", "Strip", "strip", true, 1, NUMBER_OF_LED); bool stripLedHandler(const HomieRange& range, const String& value) { if (!range.isRange) return false; if (range.index < 1 || range.index > NUMBER_OF_LED) return false; if (value != "on" && value != "off") return false; bool on = (value == "on"); digitalWrite(LED_PINS[range.index - 1], on ? HIGH : LOW); stripNode.setProperty("led").setRange(range).send(value); Homie.getLogger() << "Led " << range.index << " is " << value << endl; return true; } void setup() { for (int i = 0; i < NUMBER_OF_LED; i++) { pinMode(LED_PINS[i], OUTPUT); digitalWrite(LED_PINS[i], LOW); } Serial.begin(115200); Serial << endl << endl; Homie_setFirmware("awesome-ledstrip", "1.0.0"); stripNode.advertise("led") .setName("Led") .setDatatype("boolean") .settable(stripLedHandler); Homie.setup(); } void loop() { Homie.loop(); } // Control LED 1: homie//strip/led_1/set -> "on" // Control LED 3: homie//strip/led_3/set -> "off" ```