├── README.md ├── img ├── arduino-board-flashing.png ├── arduino-board-install.png ├── arduino-board-manager-link.png ├── arduino-board-select.png ├── arduino-sketch-edit.png ├── arduino-sketch-ota-option.png └── arduino-upload-speed.png └── ota-mqtt └── ota-mqtt.ino /README.md: -------------------------------------------------------------------------------- 1 | # ota-mqtt 2 | ESP8266 sketch that sends data via MQTT protocol. The sketch is updateable via OTA. 3 | 4 | For basic OTA update sketch or more OTA info see [ota-basic sketch](https://github.com/esp8266-examples/ota-basic) 5 | 6 | #Contents 7 | * [Prerequisites and limitations](#prerequisites-and-limitations) 8 | * [Installing software with Boards Manager](#installing-software-with-boards-manager) 9 | * [Flashing the esp8266 for the first time](#flashing-the-esp8266-for-the-first-time) 10 | * [OTA programming](#ota-programming) 11 | * [Issues and support](#issues-and-support) 12 | * [Contributing](#contributing) 13 | * [License and credits](#license-and-credits) 14 | 15 | 16 | 17 | #Prerequisites and limitations: 18 | To use this sketch you need: 19 | - An esp8266 board 20 | - Arduino software 1.6.7 or later [Download here](https://www.arduino.cc/en/Main/Software) 21 | - An esp8266 programmer (only to flash the esp8266 the first time) 22 | 23 | If you edit this sketch, you must consider that, to make OTA work: 24 | - The sketch compiled size cannot be greater than 50% of the esp8266 memory 25 | - If you use File System Wrapper, you maximun sketch size must be: (TotalMemory-FilesystemSize)/2 26 | 27 | #Installing software with Boards Manager 28 | * Install the Arduino Software (1.6.7 version or later) 29 | * Update Board Manager with custom URL:Open up Arduino, then go to the Preferences (**File > Preferences**). Then, towards the bottom of the window, copy this URL into the “Additional Board Manager URLs” text box: 30 | 31 | http://arduino.esp8266.com/stable/package_esp8266com_index.json 32 | 33 |

34 | 35 | Note: You can add multiple URLs, separating them with commas. 36 | 37 | * Open Boards Manager from **Tools > Board** menu and install esp8266 platform (and don't forget to select your ESP8266 board from **Tools > Board** menu after installation). 38 | 39 |

40 |

41 | 42 | #Flashing the esp8266 for the first time 43 | To make the esp8266 OTA ready we need to flash de initial firmware with a esp8266 flashing circuit. For example: 44 | 45 |

46 | 47 | You'll need to edit the sketch to set some parametres: 48 | * WIFI configuration: Change the 'ssid' and 'password' value to match your WIFI settings 49 | * MQTT server/client configuration: 50 | * mqtt_server: IP of yout MQTT server 51 | * mqtt_user: Client username 52 | * mqtt_password:Client password 53 | * MQTT message configuration: 54 | * mqtt_client_id: Client Id 55 | * mqtt_base_topic:Root for topics 56 | 57 |

58 | 59 | And set the configutarion of your programming circuit: 60 | - Board: If you don't know which is yours then select 'Generic ESP8266 module' 61 | - Port: The COM port of your programmer 62 | - Speed: 115200 63 | 64 |

65 | 66 | Now, we can upload the sketch to de esp8266. 67 | 68 | #OTA programming 69 | Once we have flashed the firmware of the esp8266 with an OTA enabled firmware we need to restart Arduino Software and you can dissconect the programmer serial port (or maintain it connected to use serial port for debugging, for example). 70 | Now, in the **Tools > Port** menu we'll find a new option, starting with 'esp8266' and including a local IP address. We must select that serial port. After that, go to **Tools > Upload using** and select **OTA** option. 71 | 72 |

73 | 74 | Just try to upload de sketch and it'll upload over WIFI. **Note that WIFI programming is A LOT faster than serial programming**. 75 | 76 | #Issues and support 77 | 78 | If you encounter an issue, you are welcome to submit it here on Github: [https://github.com/esp8266-examples/ota-basic/issues](https://github.com/esp8266-examples/ota-basic/issues). Please provide as much context as possible: version which you are using (you can check it in Boards Manager), your sketch code, serial output, board model, IDE settings (board selection, flash size, etc). 79 | 80 | #Contributing 81 | 82 | For minor fixes of code and documentation, go ahead and submit a pull request. 83 | 84 | Larger changes (rewriting parts of existing code from scratch, adding new functions to the core, adding new libraries) should generally be discussed in the chat first. 85 | 86 | Feature branches with lots of small commits (especially titled "oops", "fix typo", "forgot to add file", etc.) should be squashed before opening a pull request. At the same time, please refrain from putting multiple unrelated changes into a single pull request. 87 | 88 | #License and credits 89 | 90 | Arduino IDE is developed and maintained by the Arduino team. The IDE is licensed under GPL. 91 | 92 | ESP8266 core includes an xtensa gcc toolchain, which is also under GPL. 93 | 94 | Esptool written by Christian Klippel is licensed under GPLv2, currently maintained by Ivan Grokhotkov: [https://github.com/igrr/esptool-ck](https://github.com/igrr/esptool-ck). 95 | 96 | Espressif SDK included in this build is under Espressif MIT License. 97 | 98 | ESP8266 core files are licensed under LGPL. 99 | 100 | SPI Flash File System (SPIFFS) written by Peter Andersson is used in this project. It is distributed under MIT license. 101 | -------------------------------------------------------------------------------- /img/arduino-board-flashing.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/esp8266-examples/ota-mqtt/b05427c96aabd61b88abd15b4283f03dded2ef62/img/arduino-board-flashing.png -------------------------------------------------------------------------------- /img/arduino-board-install.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/esp8266-examples/ota-mqtt/b05427c96aabd61b88abd15b4283f03dded2ef62/img/arduino-board-install.png -------------------------------------------------------------------------------- /img/arduino-board-manager-link.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/esp8266-examples/ota-mqtt/b05427c96aabd61b88abd15b4283f03dded2ef62/img/arduino-board-manager-link.png -------------------------------------------------------------------------------- /img/arduino-board-select.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/esp8266-examples/ota-mqtt/b05427c96aabd61b88abd15b4283f03dded2ef62/img/arduino-board-select.png -------------------------------------------------------------------------------- /img/arduino-sketch-edit.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/esp8266-examples/ota-mqtt/b05427c96aabd61b88abd15b4283f03dded2ef62/img/arduino-sketch-edit.png -------------------------------------------------------------------------------- /img/arduino-sketch-ota-option.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/esp8266-examples/ota-mqtt/b05427c96aabd61b88abd15b4283f03dded2ef62/img/arduino-sketch-ota-option.png -------------------------------------------------------------------------------- /img/arduino-upload-speed.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/esp8266-examples/ota-mqtt/b05427c96aabd61b88abd15b4283f03dded2ef62/img/arduino-upload-speed.png -------------------------------------------------------------------------------- /ota-mqtt/ota-mqtt.ino: -------------------------------------------------------------------------------- 1 | #include //For ESP8266 2 | #include //For MQTT 3 | #include //For OTA 4 | #include //For OTA 5 | #include //For OTA 6 | 7 | //WIFI configuration 8 | #define wifi_ssid "MY_SSID" 9 | #define wifi_password "MY_PASSWORD" 10 | 11 | //MQTT configuration 12 | #define mqtt_server "192.168.0.15" 13 | #define mqtt_user "esp8266" 14 | #define mqtt_password "esp8266password" 15 | String mqtt_client_id="ESP8266-"; //This text is concatenated with ChipId to get unique client_id 16 | //MQTT Topic configuration 17 | String mqtt_base_topic="/sensor/"+mqtt_client_id+"/data"; 18 | #define humidity_topic "/humidity" 19 | #define temperature_topic "/temperature" 20 | 21 | //MQTT client 22 | WiFiClient espClient; 23 | PubSubClient mqtt_client(espClient); 24 | 25 | //Necesary to make Arduino Software autodetect OTA device 26 | WiFiServer TelnetServer(8266); 27 | 28 | void setup_wifi() { 29 | delay(10); 30 | Serial.print("Connecting to "); 31 | Serial.print(wifi_ssid); 32 | WiFi.begin(wifi_ssid, wifi_password); 33 | while (WiFi.status() != WL_CONNECTED) { 34 | delay(500); 35 | Serial.print("."); 36 | } 37 | Serial.println("OK"); 38 | Serial.print(" IP address: "); 39 | Serial.println(WiFi.localIP()); 40 | } 41 | 42 | void setup() { 43 | Serial.begin(115200); 44 | Serial.println("\r\nBooting..."); 45 | 46 | setup_wifi(); 47 | 48 | Serial.print("Configuring OTA device..."); 49 | TelnetServer.begin(); //Necesary to make Arduino Software autodetect OTA device 50 | ArduinoOTA.onStart([]() {Serial.println("OTA starting...");}); 51 | ArduinoOTA.onEnd([]() {Serial.println("OTA update finished!");Serial.println("Rebooting...");}); 52 | ArduinoOTA.onProgress([](unsigned int progress, unsigned int total) {Serial.printf("OTA in progress: %u%%\r\n", (progress / (total / 100)));}); 53 | ArduinoOTA.onError([](ota_error_t error) { 54 | Serial.printf("Error[%u]: ", error); 55 | if (error == OTA_AUTH_ERROR) Serial.println("Auth Failed"); 56 | else if (error == OTA_BEGIN_ERROR) Serial.println("Begin Failed"); 57 | else if (error == OTA_CONNECT_ERROR) Serial.println("Connect Failed"); 58 | else if (error == OTA_RECEIVE_ERROR) Serial.println("Receive Failed"); 59 | else if (error == OTA_END_ERROR) Serial.println("End Failed"); 60 | }); 61 | ArduinoOTA.begin(); 62 | Serial.println("OK"); 63 | 64 | Serial.println("Configuring MQTT server..."); 65 | mqtt_client_id=mqtt_client_id+ESP.getChipId(); 66 | mqtt_base_topic="/sensor/"+mqtt_client_id+"/data"; 67 | mqtt_client.setServer(mqtt_server, 1883); 68 | Serial.printf(" Server IP: %s\r\n",mqtt_server); 69 | Serial.printf(" Username: %s\r\n",mqtt_user); 70 | Serial.println(" Cliend Id: "+mqtt_client_id); 71 | Serial.println(" MQTT configured!"); 72 | 73 | Serial.println("Setup completed! Running app..."); 74 | } 75 | 76 | 77 | void mqtt_reconnect() { 78 | // Loop until we're reconnected 79 | while (!mqtt_client.connected()) { 80 | Serial.print("Attempting MQTT connection..."); 81 | // Attempt to connect 82 | // If you do not want to use a username and password, change next line to 83 | // if (client.connect("ESP8266Client")) { 84 | if (mqtt_client.connect(mqtt_client_id.c_str(), mqtt_user, mqtt_password)) { 85 | Serial.println("connected"); 86 | } else { 87 | Serial.print("failed, rc="); 88 | Serial.print(mqtt_client.state()); 89 | Serial.println(" try again in 5 seconds"); 90 | // Wait 5 seconds before retrying 91 | delay(5000); 92 | } 93 | } 94 | } 95 | 96 | 97 | bool checkBound(float newValue, float prevValue, float maxDiff) { 98 | return(true); 99 | return newValue < prevValue - maxDiff || newValue > prevValue + maxDiff; 100 | } 101 | 102 | 103 | 104 | long now =0; //in ms 105 | long lastMsg = 0; 106 | float temp = 0.0; 107 | float hum = 0.0; 108 | float diff = 1.0; 109 | int min_timeout=2000; //in ms 110 | 111 | void loop() { 112 | 113 | ArduinoOTA.handle(); 114 | 115 | if (!mqtt_client.connected()) { 116 | mqtt_reconnect(); 117 | } 118 | mqtt_client.loop(); 119 | 120 | now = millis(); 121 | if (now - lastMsg > min_timeout) { 122 | lastMsg = now; 123 | now = millis(); 124 | float newTemp = temp+2;//hdc.readTemperature(); 125 | float newHum = hum+0.5;//hdc.readHumidity(); 126 | 127 | if (checkBound(newTemp, temp, diff)) { 128 | temp = newTemp; 129 | Serial.print("Sent "); 130 | Serial.print(String(temp).c_str()); 131 | Serial.println(" to "+mqtt_base_topic+temperature_topic); 132 | mqtt_client.publish((mqtt_base_topic+temperature_topic).c_str(), String(temp).c_str(), true); 133 | } 134 | 135 | if (checkBound(newHum, hum, diff)) { 136 | hum = newHum; 137 | Serial.print("Sent "); 138 | Serial.print(String(hum).c_str()); 139 | Serial.println(" to "+mqtt_base_topic+humidity_topic); 140 | mqtt_client.publish((mqtt_base_topic+humidity_topic).c_str(), String(hum).c_str(), true); 141 | } 142 | } 143 | } 144 | --------------------------------------------------------------------------------