Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <ArduinoJson.h>
- #include <ESP8266WiFi.h>
- #include <PubSubClient.h>
- #include <ESP8266mDNS.h>
- #include <WiFiUdp.h>
- #include <ArduinoOTA.h>
- // la uso solo perchè mi da le funzioni EVERY_N_SECONDS che mi permette di ricevere lo stato ogni tot secondi si potrebbe levare?
- //#include "FastLED.h"
- /************ WIFI and MQTT Information (CHANGE THESE FOR YOUR SETUP) ******************/
- const char* ssid = ""; //da configurare
- const char* password = "%%"; //da configurare
- const char* mqtt_server = "192.168.1.3"; //da configurare
- const char* mqtt_username = ""; //da configurare
- const char* mqtt_password = ""; //da configurare
- const int mqtt_port = 1883;
- /**************************** FOR OTA **************************************************/
- #define SENSORNAME "smartoled" //change this to whatever you want to call your device
- #define OTApassword "123StellaStella" //the password you will need to enter to upload remotely via the ArduinoIDE
- int OTAport = 8268;
- #define serialRate 115200
- /************* MQTT TOPICS (change these topics as you wish) **************************/
- const char* smartostat_sensor_state_topic = "tele/smartostat/SENSOR";
- const char* smartostat_furnance_state_topic = "stat/smartostat/POWER1";
- const char* smartostat_pir_state_topic = "stat/smartostat/POWER2";
- bool stateOn = false;
- const char* on_cmd = "ON";
- const char* off_cmd = "OFF";
- /****************************************FOR JSON***************************************/
- const int BUFFER_SIZE = JSON_OBJECT_SIZE(50);
- #define MQTT_MAX_PACKET_SIZE 40096
- /*********************************** FastLED Defintions ********************************/
- #define DATA_PIN 5 // Su Wemos D1 Mini Lite sarebbe il PIN D5
- WiFiClient espClient;
- PubSubClient client(espClient);
- /********************************** START SETUP*****************************************/
- void setup() {
- Serial.begin(serialRate);
- setup_wifi();
- client.setServer(mqtt_server, mqtt_port);
- client.setCallback(callback);
- //OTA SETUP
- ArduinoOTA.setPort(OTAport);
- // Hostname defaults to esp8266-[ChipID]
- ArduinoOTA.setHostname(SENSORNAME);
- // No authentication by default
- ArduinoOTA.setPassword((const char *)OTApassword);
- ArduinoOTA.onStart([]() {
- Serial.println("Starting");
- });
- ArduinoOTA.onEnd([]() {
- Serial.println("\nEnd");
- });
- ArduinoOTA.onProgress([](unsigned int progress, unsigned int total) {
- Serial.printf("Progress: %u%%\r", (progress / (total / 100)));
- });
- ArduinoOTA.onError([](ota_error_t error) {
- Serial.printf("Error[%u]: ", error);
- if (error == OTA_AUTH_ERROR) Serial.println("Auth Failed");
- else if (error == OTA_BEGIN_ERROR) Serial.println("Begin Failed");
- else if (error == OTA_CONNECT_ERROR) Serial.println("Connect Failed");
- else if (error == OTA_RECEIVE_ERROR) Serial.println("Receive Failed");
- else if (error == OTA_END_ERROR) Serial.println("End Failed");
- });
- ArduinoOTA.begin();
- Serial.println("Ready");
- Serial.print("IP Address: ");
- Serial.println(WiFi.localIP());
- pinMode(DATA_PIN, OUTPUT); // LED pin as output.
- }
- /********************************** START SETUP WIFI*****************************************/
- void setup_wifi() {
- delay(10);
- // We start by connecting to a WiFi network
- Serial.println();
- Serial.print("Connecting to ");
- Serial.println(ssid);
- WiFi.mode(WIFI_STA);
- WiFi.begin(ssid, password);
- while (WiFi.status() != WL_CONNECTED) {
- delay(500);
- Serial.print(".");
- }
- Serial.println("");
- Serial.println("WiFi connected");
- Serial.println("IP address: ");
- Serial.println(WiFi.localIP());
- }
- /********************************** START CALLBACK*****************************************/
- void callback(char* topic, byte* payload, unsigned int length) {
- Serial.print("Message arrived [");
- Serial.print(topic);
- Serial.print("] ");
- char message[length + 1];
- for (int i = 0; i < length; i++) {
- message[i] = (char)payload[i];
- }
- message[length] = '\0';
- Serial.println(message);
- if (!processJson(message)) {
- return;
- }
- }
- /********************************** START PROCESS JSON*****************************************/
- bool processJson(char* message) {
- // in questo esempio in particolare il messaggio è semplice testo non json quindi bypasso il codice non necessario
- // StaticJsonBuffer<BUFFER_SIZE> jsonBuffer;
- // JsonObject& root = jsonBuffer.parseObject(message);
- // if (!root.success()) {
- // Serial.println("parseObject() failed");
- // Serial.println("dada");
- // Serial.println(message);
- // return false;
- // }
- // if (root.containsKey("state")) {
- // if (strcmp(root["state"], on_cmd) == 0) {
- // stateOn = true;
- // }
- // else if (strcmp(root["state"], off_cmd) == 0) {
- // stateOn = false;
- // }
- // }
- Serial.print("Messaggio MQTT: ");
- // Serial.println(message);
- //
- // if(strcmp(message, on_cmd) == 0) {
- // stateOn = true;
- // Serial.println("accendo");
- // } else if(strcmp(message, off_cmd) == 0) {
- // stateOn = false;
- // Serial.println("spengo");
- // }
- return true;
- }
- /********************************** START RECONNECT*****************************************/
- void reconnect() {
- // variabile usata per tenere il conto di quanti tentativi di connessione al broker mqtt faccio
- int brokermqttcounter = 0;
- // Loop until we're reconnected
- while (!client.connected()) {
- Serial.print("Attempting MQTT connection...");
- // Attempt to connect
- if (client.connect(SENSORNAME, mqtt_username, mqtt_password)) {
- Serial.println("connected");
- client.subscribe(smartostat_sensor_state_topic);
- // ogni tanto quando HA smette di rispondere si disconnette per 10 secondi e mi spegne i led tolto il set state a 0
- brokermqttcounter = 0;
- } else {
- Serial.print("failed, rc=");
- Serial.print(client.state());
- Serial.println(" try again in 5 seconds");
- Serial.print("Numbers of retry=");
- Serial.println(brokermqttcounter);
- brokermqttcounter++;
- // se dopo 10 tentativi di connessione al broker mqtt non ottengo risposta, spengo i led forzatamente.
- if (brokermqttcounter == 10) {
- Serial.print("Max retry reached, powering off peripherals.");
- }
- // Wait 5 seconds before retrying
- delay(5000);
- }
- }
- }
- /********************************** START MAIN LOOP*****************************************/
- void loop() {
- if (!client.connected()) {
- reconnect();
- }
- if (WiFi.status() != WL_CONNECTED) {
- delay(1);
- Serial.print("WIFI Disconnected. Attempting reconnection.");
- setup_wifi();
- return;
- }
- client.loop();
- ArduinoOTA.handle();
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement