Advertisement
Guest User

Untitled

a guest
May 3rd, 2019
135
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 6.76 KB | None | 0 0
  1. #include <ArduinoJson.h>
  2. #include <ESP8266WiFi.h>
  3. #include <PubSubClient.h>
  4. #include <ESP8266mDNS.h>
  5. #include <WiFiUdp.h>
  6. #include <ArduinoOTA.h>
  7. // la uso solo perchè mi da le funzioni EVERY_N_SECONDS che mi permette di ricevere lo stato ogni tot secondi si potrebbe levare?
  8. //#include "FastLED.h"
  9.  
  10. /************ WIFI and MQTT Information (CHANGE THESE FOR YOUR SETUP) ******************/
  11. const char* ssid = ""; //da configurare
  12. const char* password = "%%"; //da configurare
  13. const char* mqtt_server = "192.168.1.3"; //da configurare
  14. const char* mqtt_username = ""; //da configurare
  15. const char* mqtt_password = ""; //da configurare
  16. const int mqtt_port = 1883;
  17.  
  18.  
  19. /**************************** FOR OTA **************************************************/
  20. #define SENSORNAME "smartoled" //change this to whatever you want to call your device
  21. #define OTApassword "123StellaStella" //the password you will need to enter to upload remotely via the ArduinoIDE
  22. int OTAport = 8268;
  23.  
  24. #define serialRate 115200
  25.  
  26. /************* MQTT TOPICS (change these topics as you wish) **************************/
  27. const char* smartostat_sensor_state_topic = "tele/smartostat/SENSOR";
  28. const char* smartostat_furnance_state_topic = "stat/smartostat/POWER1";
  29. const char* smartostat_pir_state_topic = "stat/smartostat/POWER2";
  30.  
  31. bool stateOn = false;
  32. const char* on_cmd = "ON";
  33. const char* off_cmd = "OFF";
  34.  
  35.  
  36. /****************************************FOR JSON***************************************/
  37. const int BUFFER_SIZE = JSON_OBJECT_SIZE(50);
  38. #define MQTT_MAX_PACKET_SIZE 40096
  39.  
  40.  
  41. /*********************************** FastLED Defintions ********************************/
  42. #define DATA_PIN 5 // Su Wemos D1 Mini Lite sarebbe il PIN D5
  43.  
  44.  
  45. WiFiClient espClient;
  46. PubSubClient client(espClient);
  47.  
  48.  
  49. /********************************** START SETUP*****************************************/
  50. void setup() {
  51.  
  52. Serial.begin(serialRate);
  53.  
  54. setup_wifi();
  55. client.setServer(mqtt_server, mqtt_port);
  56. client.setCallback(callback);
  57.  
  58. //OTA SETUP
  59. ArduinoOTA.setPort(OTAport);
  60. // Hostname defaults to esp8266-[ChipID]
  61. ArduinoOTA.setHostname(SENSORNAME);
  62.  
  63. // No authentication by default
  64. ArduinoOTA.setPassword((const char *)OTApassword);
  65.  
  66. ArduinoOTA.onStart([]() {
  67. Serial.println("Starting");
  68. });
  69. ArduinoOTA.onEnd([]() {
  70. Serial.println("\nEnd");
  71. });
  72. ArduinoOTA.onProgress([](unsigned int progress, unsigned int total) {
  73. Serial.printf("Progress: %u%%\r", (progress / (total / 100)));
  74. });
  75. ArduinoOTA.onError([](ota_error_t error) {
  76. Serial.printf("Error[%u]: ", error);
  77. if (error == OTA_AUTH_ERROR) Serial.println("Auth Failed");
  78. else if (error == OTA_BEGIN_ERROR) Serial.println("Begin Failed");
  79. else if (error == OTA_CONNECT_ERROR) Serial.println("Connect Failed");
  80. else if (error == OTA_RECEIVE_ERROR) Serial.println("Receive Failed");
  81. else if (error == OTA_END_ERROR) Serial.println("End Failed");
  82. });
  83. ArduinoOTA.begin();
  84.  
  85. Serial.println("Ready");
  86. Serial.print("IP Address: ");
  87. Serial.println(WiFi.localIP());
  88.  
  89. pinMode(DATA_PIN, OUTPUT); // LED pin as output.
  90.  
  91. }
  92.  
  93. /********************************** START SETUP WIFI*****************************************/
  94. void setup_wifi() {
  95.  
  96. delay(10);
  97. // We start by connecting to a WiFi network
  98. Serial.println();
  99. Serial.print("Connecting to ");
  100. Serial.println(ssid);
  101.  
  102. WiFi.mode(WIFI_STA);
  103. WiFi.begin(ssid, password);
  104.  
  105. while (WiFi.status() != WL_CONNECTED) {
  106. delay(500);
  107. Serial.print(".");
  108. }
  109.  
  110. Serial.println("");
  111. Serial.println("WiFi connected");
  112. Serial.println("IP address: ");
  113. Serial.println(WiFi.localIP());
  114. }
  115.  
  116.  
  117. /********************************** START CALLBACK*****************************************/
  118. void callback(char* topic, byte* payload, unsigned int length) {
  119. Serial.print("Message arrived [");
  120. Serial.print(topic);
  121. Serial.print("] ");
  122.  
  123. char message[length + 1];
  124. for (int i = 0; i < length; i++) {
  125. message[i] = (char)payload[i];
  126. }
  127. message[length] = '\0';
  128. Serial.println(message);
  129.  
  130. if (!processJson(message)) {
  131. return;
  132. }
  133.  
  134. }
  135.  
  136.  
  137. /********************************** START PROCESS JSON*****************************************/
  138. bool processJson(char* message) {
  139. // in questo esempio in particolare il messaggio è semplice testo non json quindi bypasso il codice non necessario
  140. // StaticJsonBuffer<BUFFER_SIZE> jsonBuffer;
  141. // JsonObject& root = jsonBuffer.parseObject(message);
  142. // if (!root.success()) {
  143. // Serial.println("parseObject() failed");
  144. // Serial.println("dada");
  145. // Serial.println(message);
  146. // return false;
  147. // }
  148. // if (root.containsKey("state")) {
  149. // if (strcmp(root["state"], on_cmd) == 0) {
  150. // stateOn = true;
  151. // }
  152. // else if (strcmp(root["state"], off_cmd) == 0) {
  153. // stateOn = false;
  154. // }
  155. // }
  156. Serial.print("Messaggio MQTT: ");
  157. // Serial.println(message);
  158. //
  159. // if(strcmp(message, on_cmd) == 0) {
  160. // stateOn = true;
  161. // Serial.println("accendo");
  162. // } else if(strcmp(message, off_cmd) == 0) {
  163. // stateOn = false;
  164. // Serial.println("spengo");
  165. // }
  166.  
  167. return true;
  168. }
  169.  
  170.  
  171.  
  172.  
  173.  
  174.  
  175. /********************************** START RECONNECT*****************************************/
  176. void reconnect() {
  177. // variabile usata per tenere il conto di quanti tentativi di connessione al broker mqtt faccio
  178. int brokermqttcounter = 0;
  179. // Loop until we're reconnected
  180. while (!client.connected()) {
  181. Serial.print("Attempting MQTT connection...");
  182. // Attempt to connect
  183. if (client.connect(SENSORNAME, mqtt_username, mqtt_password)) {
  184. Serial.println("connected");
  185. client.subscribe(smartostat_sensor_state_topic);
  186. // ogni tanto quando HA smette di rispondere si disconnette per 10 secondi e mi spegne i led tolto il set state a 0
  187. brokermqttcounter = 0;
  188. } else {
  189. Serial.print("failed, rc=");
  190. Serial.print(client.state());
  191. Serial.println(" try again in 5 seconds");
  192. Serial.print("Numbers of retry=");
  193. Serial.println(brokermqttcounter);
  194. brokermqttcounter++;
  195. // se dopo 10 tentativi di connessione al broker mqtt non ottengo risposta, spengo i led forzatamente.
  196. if (brokermqttcounter == 10) {
  197. Serial.print("Max retry reached, powering off peripherals.");
  198. }
  199. // Wait 5 seconds before retrying
  200. delay(5000);
  201. }
  202. }
  203. }
  204.  
  205.  
  206.  
  207. /********************************** START MAIN LOOP*****************************************/
  208. void loop() {
  209.  
  210. if (!client.connected()) {
  211. reconnect();
  212. }
  213.  
  214. if (WiFi.status() != WL_CONNECTED) {
  215. delay(1);
  216. Serial.print("WIFI Disconnected. Attempting reconnection.");
  217. setup_wifi();
  218. return;
  219. }
  220. client.loop();
  221.  
  222.  
  223. ArduinoOTA.handle();
  224.  
  225. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement